<commit_before>#include "fru.hpp"

#include "utils.hpp"

#include <systemd/sd-journal.h>

#include <boost/crc.hpp>
#include <iostream>
#include <sdbusplus/bus.hpp>
#include <set>

namespace pldm
{

namespace responder
{

FruImpl::FruImpl(const std::string& configPath)
{
    fru_parser::FruParser handle(configPath);

    fru_parser::DBusLookupInfo dbusInfo;
    // Read the all the inventory D-Bus objects
    auto& bus = pldm::utils::DBusHandler::getBus();
    dbus::ObjectValueTree objects;

    try
    {
        dbusInfo = handle.inventoryLookup();
        auto method = bus.new_method_call(
            std::get<0>(dbusInfo).c_str(), std::get<1>(dbusInfo).c_str(),
            "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
        auto reply = bus.call(method);
        reply.read(objects);
    }
    catch (const std::exception& e)
    {
        std::cerr << "Look up of inventory objects failed and PLDM FRU table "
                     "creation failed";
        return;
    }

    // Populate all the interested Item types to a map for easy lookup
    std::set<dbus::Interface> itemIntfsLookup;
    auto itemIntfs = std::get<2>(dbusInfo);
    std::transform(std::begin(itemIntfs), std::end(itemIntfs),
                   std::inserter(itemIntfsLookup, itemIntfsLookup.end()),
                   [](dbus::Interface intf) { return intf; });

    for (const auto& object : objects)
    {
        const auto& interfaces = object.second;

        for (const auto& interface : interfaces)
        {
            if (itemIntfsLookup.find(interface.first) != itemIntfsLookup.end())
            {
                // An exception will be thrown by getRecordInfo, if the item
                // D-Bus interface name specified in FRU_Master.json does
                // not have corresponding config jsons
                try
                {
                    auto recordInfos = handle.getRecordInfo(interface.first);
                    populateRecords(interfaces, recordInfos);
                }
                catch (const std::exception& e)
                {
                    std::cout << "Config JSONs missing for the item "
                                 "interface type, interface = "
                              << interface.first << "\n";
                    break;
                }
            }
        }
    }

    if (table.size())
    {
        padBytes = utils::getNumPadBytes(table.size());
        table.resize(table.size() + padBytes, 0);

        // Calculate the checksum
        boost::crc_32_type result;
        result.process_bytes(table.data(), table.size());
        checksum = result.checksum();
    }
}

void FruImpl::populateRecords(
    const pldm::responder::dbus::InterfaceMap& interfaces,
    const fru_parser::FruRecordInfos& recordInfos)
{
    // recordSetIdentifier for the FRU will be set when the first record gets
    // added for the FRU
    uint16_t recordSetIdentifier = 0;
    auto numRecsCount = numRecs;

    for (auto const& [recType, encType, fieldInfos] : recordInfos)
    {
        std::vector<uint8_t> tlvs;
        uint8_t numFRUFields = 0;
        for (auto const& [intf, prop, propType, fieldTypeNum] : fieldInfos)
        {
            try
            {
                auto propValue = interfaces.at(intf).at(prop);
                if (propType == "bytearray")
                {
                    auto byteArray = std::get<std::vector<uint8_t>>(propValue);
                    if (!byteArray.size())
                    {
                        continue;
                    }

                    numFRUFields++;
                    tlvs.emplace_back(fieldTypeNum);
                    tlvs.emplace_back(byteArray.size());
                    std::move(std::begin(byteArray), std::end(byteArray),
                              std::back_inserter(tlvs));
                }
                else if (propType == "string")
                {
                    auto str = std::get<std::string>(propValue);
                    if (!str.size())
                    {
                        continue;
                    }

                    numFRUFields++;
                    tlvs.emplace_back(fieldTypeNum);
                    tlvs.emplace_back(str.size());
                    std::move(std::begin(str), std::end(str),
                              std::back_inserter(tlvs));
                }
            }
            catch (const std::out_of_range& e)
            {
                std::cout << "Interface = " << intf
                          << " , and Property = " << prop
                          << " , in config json not present in D-Bus"
                          << "\n";
                continue;
            }
        }

        if (tlvs.size())
        {
            if (numRecs == numRecsCount)
            {
                recordSetIdentifier = nextRSI();
            }
            auto curSize = table.size();
            table.resize(curSize + recHeaderSize + tlvs.size());
            encode_fru_record(table.data(), table.size(), &curSize,
                              recordSetIdentifier, recType, numFRUFields,
                              encType, tlvs.data(), tlvs.size());
            numRecs++;
        }
    }
}

void FruImpl::getFRUTable(Response& response)
{
    auto hdrSize = response.size();

    response.resize(hdrSize + table.size() + sizeof(checksum), 0);
    std::copy(table.begin(), table.end(), response.begin() + hdrSize);

    // Copy the checksum to response data
    auto iter = response.begin() + hdrSize + table.size();
    std::copy_n(reinterpret_cast<const uint8_t*>(&checksum), sizeof(checksum),
                iter);
}

namespace fru
{

Response Handler::getFRURecordTableMetadata(const pldm_msg* request,
                                            size_t /*payloadLength*/)
{
    constexpr uint8_t major = 0x01;
    constexpr uint8_t minor = 0x00;
    constexpr uint32_t maxSize = 0xFFFFFFFF;

    Response response(sizeof(pldm_msg_hdr) +
                          PLDM_GET_FRU_RECORD_TABLE_METADATA_RESP_BYTES,
                      0);
    auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());

    auto rc = encode_get_fru_record_table_metadata_resp(
        request->hdr.instance_id, PLDM_SUCCESS, major, minor, maxSize,
        impl.size(), impl.numRSI(), impl.numRecords(), impl.checkSum(),
        responsePtr);
    if (rc != PLDM_SUCCESS)
    {
        return ccOnlyResponse(request, rc);
    }

    return response;
}

Response Handler::getFRURecordTable(const pldm_msg* request,
                                    size_t payloadLength)
{
    if (payloadLength != PLDM_GET_FRU_RECORD_TABLE_REQ_BYTES)
    {
        return ccOnlyResponse(request, PLDM_ERROR_INVALID_LENGTH);
    }

    Response response(
        sizeof(pldm_msg_hdr) + PLDM_GET_FRU_RECORD_TABLE_MIN_RESP_BYTES, 0);
    auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());

    auto rc =
        encode_get_fru_record_table_resp(request->hdr.instance_id, PLDM_SUCCESS,
                                         0, PLDM_START_AND_END, responsePtr);
    if (rc != PLDM_SUCCESS)
    {
        return ccOnlyResponse(request, rc);
    }

    impl.getFRUTable(response);

    return response;
}

} // namespace fru

} // namespace responder

} // namespace pldm
<commit_msg>fru: Remove verbose tracing<commit_after>#include "fru.hpp"

#include "utils.hpp"

#include <systemd/sd-journal.h>

#include <boost/crc.hpp>
#include <iostream>
#include <sdbusplus/bus.hpp>
#include <set>

namespace pldm
{

namespace responder
{

FruImpl::FruImpl(const std::string& configPath)
{
    fru_parser::FruParser handle(configPath);

    fru_parser::DBusLookupInfo dbusInfo;
    // Read the all the inventory D-Bus objects
    auto& bus = pldm::utils::DBusHandler::getBus();
    dbus::ObjectValueTree objects;

    try
    {
        dbusInfo = handle.inventoryLookup();
        auto method = bus.new_method_call(
            std::get<0>(dbusInfo).c_str(), std::get<1>(dbusInfo).c_str(),
            "org.freedesktop.DBus.ObjectManager", "GetManagedObjects");
        auto reply = bus.call(method);
        reply.read(objects);
    }
    catch (const std::exception& e)
    {
        std::cerr << "Look up of inventory objects failed and PLDM FRU table "
                     "creation failed";
        return;
    }

    // Populate all the interested Item types to a map for easy lookup
    std::set<dbus::Interface> itemIntfsLookup;
    auto itemIntfs = std::get<2>(dbusInfo);
    std::transform(std::begin(itemIntfs), std::end(itemIntfs),
                   std::inserter(itemIntfsLookup, itemIntfsLookup.end()),
                   [](dbus::Interface intf) { return intf; });

    for (const auto& object : objects)
    {
        const auto& interfaces = object.second;

        for (const auto& interface : interfaces)
        {
            if (itemIntfsLookup.find(interface.first) != itemIntfsLookup.end())
            {
                // An exception will be thrown by getRecordInfo, if the item
                // D-Bus interface name specified in FRU_Master.json does
                // not have corresponding config jsons
                try
                {
                    auto recordInfos = handle.getRecordInfo(interface.first);
                    populateRecords(interfaces, recordInfos);
                }
                catch (const std::exception& e)
                {
                    std::cout << "Config JSONs missing for the item "
                                 "interface type, interface = "
                              << interface.first << "\n";
                    break;
                }
            }
        }
    }

    if (table.size())
    {
        padBytes = utils::getNumPadBytes(table.size());
        table.resize(table.size() + padBytes, 0);

        // Calculate the checksum
        boost::crc_32_type result;
        result.process_bytes(table.data(), table.size());
        checksum = result.checksum();
    }
}

void FruImpl::populateRecords(
    const pldm::responder::dbus::InterfaceMap& interfaces,
    const fru_parser::FruRecordInfos& recordInfos)
{
    // recordSetIdentifier for the FRU will be set when the first record gets
    // added for the FRU
    uint16_t recordSetIdentifier = 0;
    auto numRecsCount = numRecs;

    for (auto const& [recType, encType, fieldInfos] : recordInfos)
    {
        std::vector<uint8_t> tlvs;
        uint8_t numFRUFields = 0;
        for (auto const& [intf, prop, propType, fieldTypeNum] : fieldInfos)
        {
            try
            {
                auto propValue = interfaces.at(intf).at(prop);
                if (propType == "bytearray")
                {
                    auto byteArray = std::get<std::vector<uint8_t>>(propValue);
                    if (!byteArray.size())
                    {
                        continue;
                    }

                    numFRUFields++;
                    tlvs.emplace_back(fieldTypeNum);
                    tlvs.emplace_back(byteArray.size());
                    std::move(std::begin(byteArray), std::end(byteArray),
                              std::back_inserter(tlvs));
                }
                else if (propType == "string")
                {
                    auto str = std::get<std::string>(propValue);
                    if (!str.size())
                    {
                        continue;
                    }

                    numFRUFields++;
                    tlvs.emplace_back(fieldTypeNum);
                    tlvs.emplace_back(str.size());
                    std::move(std::begin(str), std::end(str),
                              std::back_inserter(tlvs));
                }
            }
            catch (const std::out_of_range& e)
            {
                continue;
            }
        }

        if (tlvs.size())
        {
            if (numRecs == numRecsCount)
            {
                recordSetIdentifier = nextRSI();
            }
            auto curSize = table.size();
            table.resize(curSize + recHeaderSize + tlvs.size());
            encode_fru_record(table.data(), table.size(), &curSize,
                              recordSetIdentifier, recType, numFRUFields,
                              encType, tlvs.data(), tlvs.size());
            numRecs++;
        }
    }
}

void FruImpl::getFRUTable(Response& response)
{
    auto hdrSize = response.size();

    response.resize(hdrSize + table.size() + sizeof(checksum), 0);
    std::copy(table.begin(), table.end(), response.begin() + hdrSize);

    // Copy the checksum to response data
    auto iter = response.begin() + hdrSize + table.size();
    std::copy_n(reinterpret_cast<const uint8_t*>(&checksum), sizeof(checksum),
                iter);
}

namespace fru
{

Response Handler::getFRURecordTableMetadata(const pldm_msg* request,
                                            size_t /*payloadLength*/)
{
    constexpr uint8_t major = 0x01;
    constexpr uint8_t minor = 0x00;
    constexpr uint32_t maxSize = 0xFFFFFFFF;

    Response response(sizeof(pldm_msg_hdr) +
                          PLDM_GET_FRU_RECORD_TABLE_METADATA_RESP_BYTES,
                      0);
    auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());

    auto rc = encode_get_fru_record_table_metadata_resp(
        request->hdr.instance_id, PLDM_SUCCESS, major, minor, maxSize,
        impl.size(), impl.numRSI(), impl.numRecords(), impl.checkSum(),
        responsePtr);
    if (rc != PLDM_SUCCESS)
    {
        return ccOnlyResponse(request, rc);
    }

    return response;
}

Response Handler::getFRURecordTable(const pldm_msg* request,
                                    size_t payloadLength)
{
    if (payloadLength != PLDM_GET_FRU_RECORD_TABLE_REQ_BYTES)
    {
        return ccOnlyResponse(request, PLDM_ERROR_INVALID_LENGTH);
    }

    Response response(
        sizeof(pldm_msg_hdr) + PLDM_GET_FRU_RECORD_TABLE_MIN_RESP_BYTES, 0);
    auto responsePtr = reinterpret_cast<pldm_msg*>(response.data());

    auto rc =
        encode_get_fru_record_table_resp(request->hdr.instance_id, PLDM_SUCCESS,
                                         0, PLDM_START_AND_END, responsePtr);
    if (rc != PLDM_SUCCESS)
    {
        return ccOnlyResponse(request, rc);
    }

    impl.getFRUTable(response);

    return response;
}

} // namespace fru

} // namespace responder

} // namespace pldm
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Calculate Crc by calling CRC method in LZMA SDK

#include "courgette/crc.h"

extern "C" {
#include "third_party/lzma_sdk/7zCrc.h"
}

namespace courgette {

uint32 CalculateCrc(const uint8* buffer, size_t size) {
  CrcGenerateTable();
  uint32 crc = 0xffffffffL;
  crc = ~CrcCalc(buffer, size);
  return crc;
}

}  // namespace
<commit_msg>Use a different define to decide which CRC library to use.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "courgette/crc.h"

#ifdef COURGETTE_USE_CRC_LIB
#  include "zlib.h"
#else
extern "C" {
#  include "third_party/lzma_sdk/7zCrc.h"
}
#endif

#include "base/basictypes.h"

namespace courgette {

uint32 CalculateCrc(const uint8* buffer, size_t size) {
  uint32 crc;

#ifdef COURGETTE_USE_CRC_LIB
  // Calculate Crc by calling CRC method in zlib
  crc = crc32(0, buffer, size);
#else
  // Calculate Crc by calling CRC method in LZMA SDK
  CrcGenerateTable();
  crc = CrcCalc(buffer, size);
#endif

  return ~crc;
}

}  // namespace
<|endoftext|>


<commit_before>// Replaces latex labels and references
// Compile with g++ -std=c++11 -O3 cpptexnumber.cpp -o cpptexnumber
// Use the -DDO_NOT_IGNORE_COMMENTS flag
// if you do not want to ignore the comments (ignored by default)

#include <cstddef>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <regex>
#include <sstream>
#include <string>
#include <vector>

#define DEBUG_PRINT(x) std::cout << (x) << std::endl

using label_idx_map = std::map<std::string, std::size_t>;
using idx_label_map = std::map<std::size_t, std::string>;

// build a map sorted by value from a standard map sorted by key
idx_label_map by_value(const label_idx_map& labels)
{
    idx_label_map result;
    for (auto && elem : labels)
        result[elem.second] = elem.first;
    return result;
}

label_idx_map build_labels(std::ifstream& ifile,
                           const std::string& pattern_in)
{
    label_idx_map result;
    std::regex re{R"(\\label\{)" + pattern_in + R"(.*?\})"};
    std::smatch labels;
    std::string line;
    std::size_t line_no = 0, label_no = 1;
    while (std::getline(ifile, line))
    {
        ++line_no;
#ifndef DO_NOT_IGNORE_COMMENTS
        std::getline(std::istringstream {line}, line, '%');
#else
        std::getline(std::istringstream {line}, line);
#endif
        // search regex in current line
        while (std::regex_search (line, labels, re))
        {
            for (auto && label : labels) // matches
            {
                // strip "content" from \label{content}
                std::string label_content =
                    label.str().substr(7, label.str().size() - 8);
                if (result.find(label_content) != result.end())
                {
                    std::cout << "PARSING ERROR: Duplicate \\label{"
                              << label_content << "} on line "
                              << label_no << std::endl;
                    std::exit(EXIT_FAILURE);
                }
                result[label_content] = label_no++;
            }
            // continue with the remainder of the line
            line = labels.suffix().str();
        }
    }
    return result;
}

std::string replace_line(std::string line,
                         const std::string& pattern_in,
                         const std::string& pattern_out,
                         const label_idx_map& labels,
                         const std::vector<std::string>& refs,
                         std::size_t line_no)
{
    for (auto & elem : refs) // for all reference types
    {
        std::string::size_type start;
        std::string::size_type end = 0;
        while (true)
        {
            start = line.find(elem, end);
            if (start == std::string::npos)
                break;
            end = line.find("}", start);
            if (end == std::string::npos)
            {
                std::cout << "PARSING ERROR: No matching '}'"
                          << " on line " << line_no << std::endl;
                std::exit(EXIT_FAILURE);
            }

            auto start_replace = start + elem.size();
            auto count = end - (start + elem.size());
            std::string ref = line.substr(start_replace, count);
            auto found = labels.find(ref);
            if (found != labels.end())
            {
                // construct the new reference
                std::string new_ref = pattern_out +
                                      std::to_string(labels.at(ref));
                line.replace(start_replace, count, new_ref);
            }
            // the reference starts with pattern_in
            // but it is not in the labels map
            else if (ref.compare(0, pattern_in.size(), pattern_in) == 0)
            {
                std::cout << "PARSING WARNING: Undefined reference "
                          << elem << ref << "} on line " << line_no
                          << std::endl;
            }
        }
    }
    return line;
}

void replace_refs(std::ifstream& ifile,
                  std::ofstream& ofile,
                  const std::string& pattern_in,
                  const std::string& pattern_out,
                  const label_idx_map& labels,
                  const std::vector<std::string>& refs)
{
    std::string line, line_no_comments;
    std::size_t line_no = 0;

    while (std::getline(ifile, line))
    {
        ++line_no;
        auto ss = std::istringstream{line};
        // get the line without comments
#ifndef DO_NOT_IGNORE_COMMENTS
        std::getline(ss, line_no_comments, '%');
#else
        std::getline(ss, line_no_comments);
#endif
        if (line == line_no_comments) // no comments
        {
            line = {};
        }
        else // we have a comment
        {
            std::getline(ss, line);
            line = '%' + line;
        }
        line_no_comments = replace_line(line_no_comments, pattern_in,
                                        pattern_out, labels, refs, line_no);
        ofile << line_no_comments + line + '\n'; // write it to output

    }
}

int main(int argc, char* argv[])
{
    if (argc != 5)
    {
        std::cout << "Usage: " << argv[0]
                  << " <in.tex> <out.tex> <pattern> <replacement>"
                  << std::endl;
        std::cout << "(c) Vlad Gheorghiu 2015, vsoftco@gmail.com"
                  << std::endl;
        std::exit(EXIT_FAILURE);
    }

    std::ifstream ifile(argv[1]);
    if (!ifile)
    {
        std::cout << "SYSTEM ERROR: Can not open the input file "
                  << argv[1] << std::endl;
        std::exit(EXIT_FAILURE);

    }
    std::ofstream ofile(argv[2]);
    if (!ofile)
    {
        std::cout << "SYSTEM ERROR: Can not open the output file "
                  << argv[2] << std::endl;
        std::exit(EXIT_FAILURE);
    }
    std::string pattern_in = argv[3];
    std::string pattern_out = argv[4];

    std::vector<std::string> refs = {"\\label{",
                                     "\\eqref{",
                                     "\\ref{",
                                     "\\pageref{"
                                    };
    auto labels = build_labels(ifile, pattern_in);
    if (labels.size() == 0)
    {
        std::cout << "PARSING ERROR: pattern <" << pattern_in
                  << "> not found" << std::endl;
        std::exit(EXIT_FAILURE);
    }
    ifile.clear();
    ifile.seekg(0);
    replace_refs(ifile, ofile, pattern_in, pattern_out, labels, refs);

    std::cout << "REPLACED: " << std::endl;
    for (auto && elem : by_value(labels))
    {
        std::cout << elem.second << " -> " <<
                  (pattern_out + std::to_string(elem.first)) << std::endl;
    }
}
<commit_msg>commit<commit_after>// Replaces latex labels and references
// Compile with g++ -std=c++11 -O3 cpptexnumber.cpp -o cpptexnumber
// Use the -DDO_NOT_IGNORE_COMMENTS flag
// if you do not want to ignore the comments (ignored by default)

#include <cstddef>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <regex>
#include <sstream>
#include <string>
#include <vector>

#define DEBUG_PRINT(x) std::cout << (x) << std::endl

using label_idx_map = std::map<std::string, std::size_t>;
using idx_label_map = std::map<std::size_t, std::string>;

// build a map sorted by value from a standard map sorted by key
idx_label_map by_value(const label_idx_map& labels)
{
    idx_label_map result;
    for (auto && elem : labels)
        result[elem.second] = elem.first;
    return result;
}

label_idx_map build_labels(std::ifstream& ifile,
                           const std::string& pattern_in)
{
    label_idx_map result;
    std::regex re{R"(\\label\{)" + pattern_in + R"(.*?\})"};
    std::smatch labels;
    std::string line;
    std::size_t line_no = 0, label_no = 1;
    while (std::getline(ifile, line))
    {
        ++line_no;
#ifndef DO_NOT_IGNORE_COMMENTS
        std::getline(std::istringstream {line}, line, '%');
#else
        std::getline(std::istringstream {line}, line);
#endif
        // search regex in current line
        while (std::regex_search (line, labels, re))
        {
            for (auto && label : labels) // matches
            {
                // strip "content" from \label{content}
                std::string label_content =
                    label.str().substr(7, label.str().size() - 8);
                if (result.find(label_content) != result.end())
                {
                    std::cout << "PARSING ERROR: Duplicate \\label{"
                              << label_content << "} on line "
                              << label_no << std::endl;
                    std::exit(EXIT_FAILURE);
                }
                result[label_content] = label_no++;
            }
            // continue with the remainder of the line
            line = labels.suffix().str();
        }
    }
    return result;
}

std::string replace_line(std::string line,
                         const std::string& pattern_in,
                         const std::string& pattern_out,
                         const label_idx_map& labels,
                         const std::vector<std::string>& refs,
                         std::size_t line_no)
{
    for (auto & elem : refs) // for all reference types
    {
        std::string::size_type start;
        std::string::size_type end = 0;
        while (true)
        {
            start = line.find(elem, end);
            if (start == std::string::npos)
                break;
            end = line.find("}", start);
            if (end == std::string::npos)
            {
                std::cout << "PARSING ERROR: No matching '}'"
                          << " on line " << line_no << std::endl;
                std::exit(EXIT_FAILURE);
            }

            auto start_replace = start + elem.size();
            auto count = end - (start + elem.size());
            std::string ref = line.substr(start_replace, count);
            auto found = labels.find(ref);
            if (found != labels.end())
            {
                // construct the new reference
                std::string new_ref = pattern_out +
                                      std::to_string(labels.at(ref));
                line.replace(start_replace, count, new_ref);
            }
            // the reference starts with pattern_in
            // but it is not in the labels map
            else if (ref.compare(0, pattern_in.size(), pattern_in) == 0)
            {
                std::cout << "PARSING WARNING: Undefined reference "
                          << elem << ref << "} on line " << line_no
                          << std::endl;
            }
        }
    }
    return line;
}

void replace_refs(std::ifstream& ifile,
                  std::ofstream& ofile,
                  const std::string& pattern_in,
                  const std::string& pattern_out,
                  const label_idx_map& labels,
                  const std::vector<std::string>& refs)
{
    std::string line, line_no_comments;
    std::size_t line_no = 0;

    while (std::getline(ifile, line))
    {
        ++line_no;
        auto ss = std::istringstream{line};
        // get the line without comments
#ifndef DO_NOT_IGNORE_COMMENTS
        std::getline(ss, line_no_comments, '%');
#else
        std::getline(ss, line_no_comments);
#endif
        if (line == line_no_comments) // no comments
        {
            line = {};
        }
        else // we have a comment
        {
            std::getline(ss, line);
            line = '%' + line;
        }
        line_no_comments = replace_line(line_no_comments, pattern_in,
                                        pattern_out, labels, refs, line_no);
        ofile << line_no_comments + line + '\n'; // write it to output

    }
}

int main(int argc, char* argv[])
{
    if (argc != 5)
    {
        std::cout << "Usage: " << argv[0]
                  << " <in.tex> <out.tex> <pattern> <replacement>"
                  << std::endl;
        std::cout << "(c) Vlad Gheorghiu 2015, vsoftco@gmail.com"
                  << std::endl;
        std::exit(EXIT_FAILURE);
    }

    std::ifstream ifile(argv[1]);
    if (!ifile)
    {
        std::cout << "SYSTEM ERROR: Can not open the input file "
                  << argv[1] << std::endl;
        std::exit(EXIT_FAILURE);

    }
    if (std::string(argv[1]) == argv[2])
    {
        std::cout << "SYSTEM ERROR: "
                  << "The output file must be different from the input file!"
                  << std::endl;
        std::exit(EXIT_FAILURE);
    }
    std::ofstream ofile(argv[2]);
    if (!ofile)
    {
        std::cout << "SYSTEM ERROR: Can not open the output file "
                  << argv[2] << std::endl;
        std::exit(EXIT_FAILURE);
    }
    std::string pattern_in = argv[3];
    std::string pattern_out = argv[4];

    std::vector<std::string> refs = {"\\label{",
                                     "\\eqref{",
                                     "\\ref{",
                                     "\\pageref{"
                                    };
    auto labels = build_labels(ifile, pattern_in);
    if (labels.size() == 0)
    {
        std::cout << "PARSING ERROR: pattern <" << pattern_in
                  << "> not found" << std::endl;
        std::exit(EXIT_FAILURE);
    }
    ifile.clear();
    ifile.seekg(0);
    replace_refs(ifile, ofile, pattern_in, pattern_out, labels, refs);

    std::cout << "REPLACED: " << std::endl;
    for (auto && elem : by_value(labels))
    {
        std::cout << elem.second << " -> " <<
                  (pattern_out + std::to_string(elem.first)) << std::endl;
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include "Date.h"

using namespace std;

//ʣﲻҪıݣconstֲܼӣô죿
void print_dates(array<Date, DateCounts>& arrDates, bool use_overload)
{
	for (int i = 0; i < DateCounts; i++) {
		if (use_overload)
			arrDates[i].print(); //print
		else
			cout << arrDates[i] ; //<<
	}
}

int main(int argc, char** argv) {

	array<Date, DateCounts> arrDates;

	cout << "\n--------[ϸģʽ]Date------------\n";
	arrDates = CreatePoints(false);

	print_dates(arrDates,false);//Date::print()

	cout << "\n--------[ϸģʽ]Date------------\n";
	arrDates = Sort(arrDates);
	print_dates(arrDates, false);//Date::print()

	cout << "\n--------[ϸģʽ]Date------------\n";
	arrDates = CreatePoints(true);

	print_dates(arrDates, true);//<<
	cout << "\n--------[ϸģʽ]Date------------\n";

	arrDates = Sort(arrDates);
	print_dates(arrDates, true);//<<

	system("pause");

	return 0;
}

<commit_msg>是否重载参数修正<commit_after>#include <iostream>
#include "Date.h"

using namespace std;

//疑问：这里不需要改变内容，但是const又不能加，该怎么办？
void print_dates(array<Date, DateCounts>& arrDates, bool use_overload)
{
	for (int i = 0; i < DateCounts; i++) {
		if (use_overload)
			cout << arrDates[i] ; //重载<<输出
		else
			arrDates[i].print(); //print输出
	}
}

int main(int argc, char** argv) {

	array<Date, DateCounts> arrDates;

	cout << "\n--------[非严格模式]生成Date数组------------\n";
	arrDates = CreatePoints(false);

	print_dates(arrDates,false);//Date::print()

	cout << "\n--------[非严格模式]对Date数组排序------------\n";
	arrDates = Sort(arrDates);
	print_dates(arrDates, false);//Date::print()

	cout << "\n--------[严格模式]生成Date数组------------\n";
	arrDates = CreatePoints(true);

	print_dates(arrDates, true);//重载<<输出
	cout << "\n--------[严格模式]对Date数组排序------------\n";

	arrDates = Sort(arrDates);
	print_dates(arrDates, true);//重载<<输出

	system("pause");

	return 0;
}

<|endoftext|>


<commit_before>#include "../Include/CGotoSceneVisitor.h"
#include "../Include/CSceneNode.h"
#include "../Include/CSequenceNode.h"

#include "cocos2d.h"

using namespace cocos2d;

namespace LM
{

CGotoSceneVisitor::CGotoSceneVisitor(const std::string& a_sSceneID) :
    m_sSceneID(a_sSceneID)
{

}

Result CGotoSceneVisitor::ProcessNodeTopDown(CNode* a_pNode)
{
  CSceneNode* pSceneNode = dynamic_cast<CSceneNode*>(a_pNode);
  if (pSceneNode)
  {
    if (pSceneNode->GetSceneID() == m_sSceneID)
    {
		CSequenceNode* pSequence = dynamic_cast<CSequenceNode*>(pSceneNode->GetParent());
		pSequence->SetCurrentNode(pSceneNode);
      Scene* pNewScene = pSceneNode->CreateScene();
      pSceneNode->init();

      Director::getInstance()->replaceScene(TransitionMoveInT::create(1.5f, pNewScene));
      return RESULT_PRUNE;
    }
  }
  return RESULT_CONTINUE;
}

} // namespace LM
<commit_msg>changed animation in CGotoSceneVisitor<commit_after>#include "../Include/CGotoSceneVisitor.h"
#include "../Include/CSceneNode.h"
#include "../Include/CSequenceNode.h"

#include "cocos2d.h"

using namespace cocos2d;

namespace LM
{

CGotoSceneVisitor::CGotoSceneVisitor(const std::string& a_sSceneID) :
    m_sSceneID(a_sSceneID)
{

}

Result CGotoSceneVisitor::ProcessNodeTopDown(CNode* a_pNode)
{
  CSceneNode* pSceneNode = dynamic_cast<CSceneNode*>(a_pNode);
  if (pSceneNode)
  {
    if (pSceneNode->GetSceneID() == m_sSceneID)
    {
		CSequenceNode* pSequence = dynamic_cast<CSequenceNode*>(pSceneNode->GetParent());
		pSequence->SetCurrentNode(pSceneNode);
      Scene* pNewScene = pSceneNode->CreateScene();
      pSceneNode->init();

      Director::getInstance()->replaceScene(TransitionSlideInR::create(0.5f, pNewScene));
      return RESULT_PRUNE;
    }
  }
  return RESULT_CONTINUE;
}

} // namespace LM
<|endoftext|>


<commit_before>#include "DisplayGeometry.h"

//##ModelId=3E3AE9FD00C5
void mitk::DisplayGeometry::Zoom(float factor, const mitk::Vector2D& centerInDisplayUnits)
{
    assert(factor > 0);

    SetScaleFactor(m_ScaleFactorUnitsPerDisplayUnit/factor);
    SetOriginInUnits(m_OriginInUnits+(1-factor)*m_ScaleFactorUnitsPerDisplayUnit*centerInDisplayUnits);

    Modified();
}

//##ModelId=3E3AEE700380
void mitk::DisplayGeometry::MoveBy(const mitk::Vector2D& shiftInDisplayUnits)
{
    SetOriginInUnits(m_OriginInUnits+m_ScaleFactorUnitsPerDisplayUnit*shiftInDisplayUnits);

    Modified();
}

//##ModelId=3E3AEA5101A2
void mitk::DisplayGeometry::SetWorldGeometry(const mitk::Geometry2D* aWorldGeometry)
{
    m_WorldGeometry = aWorldGeometry;

    Modified();
}

//##ModelId=3E3AEB8F0286
void mitk::DisplayGeometry::DisplayToUnits(const mitk::Point2D &pt_display, mitk::Point2D &pt_units) const
{
    pt_units=m_ScaleFactorUnitsPerDisplayUnit*pt_display+m_OriginInUnits;
}

//##ModelId=3E3AEBEF039C
void mitk::DisplayGeometry::UnitsToDisplay(const mitk::Point2D &pt_units, mitk::Point2D &pt_display) const
{
    pt_display=(pt_units-m_OriginInUnits)*(1.0/m_ScaleFactorUnitsPerDisplayUnit);
}

//##ModelId=3E3B02710239
void mitk::DisplayGeometry::DisplayToUnits(const mitk::Vector2D &vec_display, mitk::Vector2D &vec_units) const
{
    vec_units=m_ScaleFactorUnitsPerDisplayUnit*vec_display;
}

//##ModelId=3E3B02760128
void mitk::DisplayGeometry::UnitsToDisplay(const mitk::Vector2D &vec_units, mitk::Vector2D &vec_display) const
{
    vec_display=vec_units*(1.0/m_ScaleFactorUnitsPerDisplayUnit);
}

//##ModelId=3E3AEB460259
void mitk::DisplayGeometry::Map(const mitk::Point3D &pt3d_mm, mitk::Point2D &pt2d_mm) const
{
    if(m_WorldGeometry!=NULL) return;

    m_WorldGeometry->Map(pt3d_mm, pt2d_mm);
}

//##ModelId=3E3AEB490380
void mitk::DisplayGeometry::Map(const mitk::Point2D &pt2d_mm, mitk::Point3D &pt3d_mm) const
{
    if(m_WorldGeometry!=NULL) return;

    m_WorldGeometry->Map(pt2d_mm, pt3d_mm);
}

//##ModelId=3E3AEB52008A
void mitk::DisplayGeometry::UnitsToMM(const mitk::Point2D &pt_units, mitk::Point2D &pt_mm) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(pt_units, pt_mm);
}

//##ModelId=3E3AEB54017D
void mitk::DisplayGeometry::MMToUnits(const mitk::Point2D &pt_mm, mitk::Point2D &pt_units) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->MMToUnits(pt_mm, pt_units);
}

//##ModelId=3E3B994802B6
void mitk::DisplayGeometry::UnitsToMM(const mitk::Vector2D &vec_units, mitk::Vector2D &vec_mm) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(vec_units, vec_mm);
}

//##ModelId=3E3B994B02A6
void mitk::DisplayGeometry::MMToUnits(const mitk::Vector2D &vec_mm, mitk::Vector2D &vec_units) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->MMToUnits(vec_mm, vec_units);
}

//##ModelId=3E48D5B40210
void mitk::DisplayGeometry::DisplayToMM(const mitk::Point2D &pt_display, mitk::Point2D &pt_mm) const
{
    DisplayToUnits(pt_display, pt_mm);

    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(pt_mm, pt_mm);
}

//##ModelId=3E48D5D7027E
void mitk::DisplayGeometry::MMToDisplay(const mitk::Point2D &pt_mm, mitk::Point2D &pt_display) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(pt_mm, pt_display);

    UnitsToDisplay(pt_display, pt_display);
}

//##ModelId=3E48E2AE03A7
void mitk::DisplayGeometry::DisplayToMM(const mitk::Vector2D &vec_display, mitk::Vector2D &vec_mm) const
{
    DisplayToUnits(vec_display, vec_mm);

    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(vec_mm, vec_mm);
}

//##ModelId=3E48E2B40374
void mitk::DisplayGeometry::MMToDisplay(const mitk::Vector2D &vec_mm, mitk::Vector2D &vec_display) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(vec_mm, vec_display);

    UnitsToDisplay(vec_display, vec_display);
}

//##ModelId=3E3AEB56037E
itk::Transform<float,3,2>::Pointer mitk::DisplayGeometry::GetTransfrom() const
{
	itkExceptionMacro("Transform not yet supported.");
	return NULL;
}

//##ModelId=3E3AEB620231
double mitk::DisplayGeometry::GetTime() const
{
    if(m_WorldGeometry==NULL) return NULL;;

    return m_WorldGeometry->GetTime();
}

//##ModelId=3E3AE91A035E
mitk::DisplayGeometry::DisplayGeometry() : Geometry2D(10.0, 10.0), m_OriginInUnits(0,0),
    m_ScaleFactorUnitsPerDisplayUnit(1.0), m_SizeInDisplayUnits(10,10), m_WorldGeometry(NULL)
{
}

//##ModelId=3E3AE91A037C
mitk::DisplayGeometry::~DisplayGeometry()
{
}
//##ModelId=3E3C36920345
void mitk::DisplayGeometry::SetSizeInDisplayUnits(unsigned int width, unsigned int height)
{
    m_SizeInDisplayUnits.set(width, height);

    if(m_SizeInDisplayUnits.x <= 0)
        m_SizeInDisplayUnits.x = 1;
    if(m_SizeInDisplayUnits.y <= 0)
        m_SizeInDisplayUnits.y = 1;

    DisplayToUnits(m_SizeInDisplayUnits, m_SizeInUnits);

    Modified();
}

//##ModelId=3E3C36CD02D2
void mitk::DisplayGeometry::SetOriginInUnits(const mitk::Point2D& origin_units)
{
    m_OriginInUnits=origin_units;
    UnitsToDisplay(m_OriginInUnits, m_OriginInDisplayUnits);

    Modified();
}

//##ModelId=3E3C38660226
void mitk::DisplayGeometry::Fit()
{
	// FIXME
		bool fixed=false;
    if(m_WorldGeometry==NULL || !fixed) return;

    float   x,y,w,h;

    int width, height;

    width=m_SizeInDisplayUnits.x;
    height=m_SizeInDisplayUnits.y;

// FIXME: "silly assignment" (IDEA)
	w = width;
	h = height;

    float aspRatio=((float)m_WorldGeometry->GetWidthInUnits())/m_WorldGeometry->GetHeightInUnits();

    x = (float)w/m_WorldGeometry->GetWidthInUnits();
    y = (float)h/m_WorldGeometry->GetHeightInUnits();
    if (x > y)
        w = (int) (aspRatio*h);
    else
        h = (int) (w/aspRatio);

    SetScaleFactor(m_WorldGeometry->GetWidthInUnits()/w);

    mitk::Point2D origin_display(-(width-w)/2.0,-(height-h)/2.0);
    SetOriginInUnits(origin_display*m_ScaleFactorUnitsPerDisplayUnit);

    Modified();
}

//##ModelId=3E3C516B0045
mitk::Point2D mitk::DisplayGeometry::GetOriginInUnits() const
{
    return m_OriginInUnits;
}

//##ModelId=3E3C51890107
mitk::Point2D mitk::DisplayGeometry::GetOriginInDisplayUnits() const
{
    return m_OriginInDisplayUnits;
}

//##ModelId=3E3C666E0299
unsigned int mitk::DisplayGeometry::GetDisplayWidth() const
{
    return m_SizeInDisplayUnits.x;
}

//##ModelId=3E3C668B0363
unsigned int mitk::DisplayGeometry::GetDisplayHeight() const
{
    return m_SizeInDisplayUnits.y;
}

//##ModelId=3E3D86CB0039
mitk::Vector2D mitk::DisplayGeometry::GetSizeInDisplayUnits() const
{
    return m_SizeInDisplayUnits;
}

//##ModelId=3E3D86E9015E
mitk::Vector2D mitk::DisplayGeometry::GetSizeInUnits() const
{
    return m_SizeInUnits;
}

//##ModelId=3E3D883B0132
void mitk::DisplayGeometry::SetScaleFactor(float unitsPerDisplayUnit)
{
    if(unitsPerDisplayUnit<0.0001) unitsPerDisplayUnit=0.0001;

    m_ScaleFactorUnitsPerDisplayUnit = unitsPerDisplayUnit;

    DisplayToUnits(m_SizeInDisplayUnits, m_SizeInUnits);
}

//##ModelId=3E3ED45900A1
float mitk::DisplayGeometry::GetScaleFactorUnitsPerDisplayUnit() const
{
    return m_ScaleFactorUnitsPerDisplayUnit;
}
<commit_msg>removed wrong FIXME<commit_after>#include "DisplayGeometry.h"

//##ModelId=3E3AE9FD00C5
void mitk::DisplayGeometry::Zoom(float factor, const mitk::Vector2D& centerInDisplayUnits)
{
    assert(factor > 0);

    SetScaleFactor(m_ScaleFactorUnitsPerDisplayUnit/factor);
    SetOriginInUnits(m_OriginInUnits+(1-factor)*m_ScaleFactorUnitsPerDisplayUnit*centerInDisplayUnits);

    Modified();
}

//##ModelId=3E3AEE700380
void mitk::DisplayGeometry::MoveBy(const mitk::Vector2D& shiftInDisplayUnits)
{
    SetOriginInUnits(m_OriginInUnits+m_ScaleFactorUnitsPerDisplayUnit*shiftInDisplayUnits);

    Modified();
}

//##ModelId=3E3AEA5101A2
void mitk::DisplayGeometry::SetWorldGeometry(const mitk::Geometry2D* aWorldGeometry)
{
    m_WorldGeometry = aWorldGeometry;

    Modified();
}

//##ModelId=3E3AEB8F0286
void mitk::DisplayGeometry::DisplayToUnits(const mitk::Point2D &pt_display, mitk::Point2D &pt_units) const
{
    pt_units=m_ScaleFactorUnitsPerDisplayUnit*pt_display+m_OriginInUnits;
}

//##ModelId=3E3AEBEF039C
void mitk::DisplayGeometry::UnitsToDisplay(const mitk::Point2D &pt_units, mitk::Point2D &pt_display) const
{
    pt_display=(pt_units-m_OriginInUnits)*(1.0/m_ScaleFactorUnitsPerDisplayUnit);
}

//##ModelId=3E3B02710239
void mitk::DisplayGeometry::DisplayToUnits(const mitk::Vector2D &vec_display, mitk::Vector2D &vec_units) const
{
    vec_units=m_ScaleFactorUnitsPerDisplayUnit*vec_display;
}

//##ModelId=3E3B02760128
void mitk::DisplayGeometry::UnitsToDisplay(const mitk::Vector2D &vec_units, mitk::Vector2D &vec_display) const
{
    vec_display=vec_units*(1.0/m_ScaleFactorUnitsPerDisplayUnit);
}

//##ModelId=3E3AEB460259
void mitk::DisplayGeometry::Map(const mitk::Point3D &pt3d_mm, mitk::Point2D &pt2d_mm) const
{
    if(m_WorldGeometry!=NULL) return;

    m_WorldGeometry->Map(pt3d_mm, pt2d_mm);
}

//##ModelId=3E3AEB490380
void mitk::DisplayGeometry::Map(const mitk::Point2D &pt2d_mm, mitk::Point3D &pt3d_mm) const
{
    if(m_WorldGeometry!=NULL) return;

    m_WorldGeometry->Map(pt2d_mm, pt3d_mm);
}

//##ModelId=3E3AEB52008A
void mitk::DisplayGeometry::UnitsToMM(const mitk::Point2D &pt_units, mitk::Point2D &pt_mm) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(pt_units, pt_mm);
}

//##ModelId=3E3AEB54017D
void mitk::DisplayGeometry::MMToUnits(const mitk::Point2D &pt_mm, mitk::Point2D &pt_units) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->MMToUnits(pt_mm, pt_units);
}

//##ModelId=3E3B994802B6
void mitk::DisplayGeometry::UnitsToMM(const mitk::Vector2D &vec_units, mitk::Vector2D &vec_mm) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(vec_units, vec_mm);
}

//##ModelId=3E3B994B02A6
void mitk::DisplayGeometry::MMToUnits(const mitk::Vector2D &vec_mm, mitk::Vector2D &vec_units) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->MMToUnits(vec_mm, vec_units);
}

//##ModelId=3E48D5B40210
void mitk::DisplayGeometry::DisplayToMM(const mitk::Point2D &pt_display, mitk::Point2D &pt_mm) const
{
    DisplayToUnits(pt_display, pt_mm);

    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(pt_mm, pt_mm);
}

//##ModelId=3E48D5D7027E
void mitk::DisplayGeometry::MMToDisplay(const mitk::Point2D &pt_mm, mitk::Point2D &pt_display) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(pt_mm, pt_display);

    UnitsToDisplay(pt_display, pt_display);
}

//##ModelId=3E48E2AE03A7
void mitk::DisplayGeometry::DisplayToMM(const mitk::Vector2D &vec_display, mitk::Vector2D &vec_mm) const
{
    DisplayToUnits(vec_display, vec_mm);

    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(vec_mm, vec_mm);
}

//##ModelId=3E48E2B40374
void mitk::DisplayGeometry::MMToDisplay(const mitk::Vector2D &vec_mm, mitk::Vector2D &vec_display) const
{
    if(m_WorldGeometry!=NULL) return;
    m_WorldGeometry->UnitsToMM(vec_mm, vec_display);

    UnitsToDisplay(vec_display, vec_display);
}

//##ModelId=3E3AEB56037E
itk::Transform<float,3,2>::Pointer mitk::DisplayGeometry::GetTransfrom() const
{
	itkExceptionMacro("Transform not yet supported.");
	return NULL;
}

//##ModelId=3E3AEB620231
double mitk::DisplayGeometry::GetTime() const
{
    if(m_WorldGeometry==NULL) return NULL;;

    return m_WorldGeometry->GetTime();
}

//##ModelId=3E3AE91A035E
mitk::DisplayGeometry::DisplayGeometry() : Geometry2D(10.0, 10.0), m_OriginInUnits(0,0),
    m_ScaleFactorUnitsPerDisplayUnit(1.0), m_SizeInDisplayUnits(10,10), m_WorldGeometry(NULL)
{
}

//##ModelId=3E3AE91A037C
mitk::DisplayGeometry::~DisplayGeometry()
{
}
//##ModelId=3E3C36920345
void mitk::DisplayGeometry::SetSizeInDisplayUnits(unsigned int width, unsigned int height)
{
    m_SizeInDisplayUnits.set(width, height);

    if(m_SizeInDisplayUnits.x <= 0)
        m_SizeInDisplayUnits.x = 1;
    if(m_SizeInDisplayUnits.y <= 0)
        m_SizeInDisplayUnits.y = 1;

    DisplayToUnits(m_SizeInDisplayUnits, m_SizeInUnits);

    Modified();
}

//##ModelId=3E3C36CD02D2
void mitk::DisplayGeometry::SetOriginInUnits(const mitk::Point2D& origin_units)
{
    m_OriginInUnits=origin_units;
    UnitsToDisplay(m_OriginInUnits, m_OriginInDisplayUnits);

    Modified();
}

//##ModelId=3E3C38660226
void mitk::DisplayGeometry::Fit()
{
    if(m_WorldGeometry==NULL) return;

    float   x,y,w,h;

    int width, height;

    width=m_SizeInDisplayUnits.x;
    height=m_SizeInDisplayUnits.y;

// FIXME: "silly assignment" (IDEA)
	w = width;
	h = height;

    float aspRatio=((float)m_WorldGeometry->GetWidthInUnits())/m_WorldGeometry->GetHeightInUnits();

    x = (float)w/m_WorldGeometry->GetWidthInUnits();
    y = (float)h/m_WorldGeometry->GetHeightInUnits();
    if (x > y)
        w = (int) (aspRatio*h);
    else
        h = (int) (w/aspRatio);

    SetScaleFactor(m_WorldGeometry->GetWidthInUnits()/w);

    mitk::Point2D origin_display(-(width-w)/2.0,-(height-h)/2.0);
    SetOriginInUnits(origin_display*m_ScaleFactorUnitsPerDisplayUnit);

    Modified();
}

//##ModelId=3E3C516B0045
mitk::Point2D mitk::DisplayGeometry::GetOriginInUnits() const
{
    return m_OriginInUnits;
}

//##ModelId=3E3C51890107
mitk::Point2D mitk::DisplayGeometry::GetOriginInDisplayUnits() const
{
    return m_OriginInDisplayUnits;
}

//##ModelId=3E3C666E0299
unsigned int mitk::DisplayGeometry::GetDisplayWidth() const
{
    return m_SizeInDisplayUnits.x;
}

//##ModelId=3E3C668B0363
unsigned int mitk::DisplayGeometry::GetDisplayHeight() const
{
    return m_SizeInDisplayUnits.y;
}

//##ModelId=3E3D86CB0039
mitk::Vector2D mitk::DisplayGeometry::GetSizeInDisplayUnits() const
{
    return m_SizeInDisplayUnits;
}

//##ModelId=3E3D86E9015E
mitk::Vector2D mitk::DisplayGeometry::GetSizeInUnits() const
{
    return m_SizeInUnits;
}

//##ModelId=3E3D883B0132
void mitk::DisplayGeometry::SetScaleFactor(float unitsPerDisplayUnit)
{
    if(unitsPerDisplayUnit<0.0001) unitsPerDisplayUnit=0.0001;

    m_ScaleFactorUnitsPerDisplayUnit = unitsPerDisplayUnit;

    DisplayToUnits(m_SizeInDisplayUnits, m_SizeInUnits);
}

//##ModelId=3E3ED45900A1
float mitk::DisplayGeometry::GetScaleFactorUnitsPerDisplayUnit() const
{
    return m_ScaleFactorUnitsPerDisplayUnit;
}
<|endoftext|>


<commit_before>/*
 *  Created on: 19 Jun 2014
 *      Author: Vladimir Ivan
 *
 * Copyright (c) 2016, University Of Edinburgh
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  * Neither the name of  nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <exotica/Problems/SamplingProblem.h>
#include <exotica/Setup.h>

REGISTER_PROBLEM_TYPE("SamplingProblem", exotica::SamplingProblem)

namespace exotica
{

  SamplingProblem::SamplingProblem()
  {
    Flags = KIN_FK;
  }

  SamplingProblem::~SamplingProblem()
  {
    // TODO Auto-generated destructor stub
  }

  std::vector<double>& SamplingProblem::getBounds()
  {
    return bounds_;
  }

  void SamplingProblem::Instantiate(SamplingProblemInitializer& init)
  {
      Parameters = init;

      if(init.LocalPlannerConfig!="")
      {
          local_planner_config_ = init.LocalPlannerConfig;
      }

      goal_ = init.Goal;

      if (scene_->getBaseType() != exotica::BASE_TYPE::FIXED)
        compound_ = true;
      else
        compound_ = false;
      std::vector<std::string> jnts;
      scene_->getJointNames(jnts);

      getBounds().resize(jnts.size() * 2);
      std::map<std::string, std::vector<double>> joint_limits = scene_->getSolver().getUsedJointLimits();
      for (int i = 0; i < jnts.size(); i++)
      {
        getBounds()[i] = joint_limits.at(jnts[i])[0];
        getBounds()[i + jnts.size()] = joint_limits.at(jnts[i])[1];
      }
  }

  void SamplingProblem::setGoalState(Eigen::VectorXdRefConst qT)
  {
      goal_ = qT;
  }

  void SamplingProblem::Update(Eigen::VectorXdRefConst x)
  {
      scene_->Update(x);
  }

  int SamplingProblem::getSpaceDim()
  {
    return N;
  }

  bool SamplingProblem::isCompoundStateSpace()
  {
    return compound_;
  }

} /* namespace exotica */
<commit_msg>SamplingProblem: use the variable directly instead of the getter<commit_after>/*
 *  Created on: 19 Jun 2014
 *      Author: Vladimir Ivan
 *
 * Copyright (c) 2016, University Of Edinburgh
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  * Neither the name of  nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <exotica/Problems/SamplingProblem.h>
#include <exotica/Setup.h>

REGISTER_PROBLEM_TYPE("SamplingProblem", exotica::SamplingProblem)

namespace exotica
{

  SamplingProblem::SamplingProblem()
  {
    Flags = KIN_FK;
  }

  SamplingProblem::~SamplingProblem()
  {
    // TODO Auto-generated destructor stub
  }

  std::vector<double>& SamplingProblem::getBounds()
  {
    return bounds_;
  }

  void SamplingProblem::Instantiate(SamplingProblemInitializer& init)
  {
      Parameters = init;

      if(init.LocalPlannerConfig!="")
      {
          local_planner_config_ = init.LocalPlannerConfig;
      }

      goal_ = init.Goal;

      if (scene_->getBaseType() != exotica::BASE_TYPE::FIXED)
        compound_ = true;
      else
        compound_ = false;
      std::vector<std::string> jnts;
      scene_->getJointNames(jnts);

      bounds_.resize(jnts.size() * 2);
      std::map<std::string, std::vector<double>> joint_limits = scene_->getSolver().getUsedJointLimits();
      for (int i = 0; i < jnts.size(); i++)
      {
        bounds_[i] = joint_limits.at(jnts[i])[0];
        bounds_[i + jnts.size()] = joint_limits.at(jnts[i])[1];
      }
  }

  void SamplingProblem::setGoalState(Eigen::VectorXdRefConst qT)
  {
      goal_ = qT;
  }

  void SamplingProblem::Update(Eigen::VectorXdRefConst x)
  {
      scene_->Update(x);
  }

  int SamplingProblem::getSpaceDim()
  {
    return N;
  }

  bool SamplingProblem::isCompoundStateSpace()
  {
    return compound_;
  }

} /* namespace exotica */
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <android/log.h>
#include <jni.h>

#include <array>
#include <cstdlib>
#include <cstring>

#include "include/flac_parser.h"

#define LOG_TAG "flac_jni"
#define ALOGE(...) \
  ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
#define ALOGV(...) \
  ((void)__android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__))

#define DECODER_FUNC(RETURN_TYPE, NAME, ...)                               \
  extern "C" {                                                             \
  JNIEXPORT RETURN_TYPE                                                    \
      Java_com_google_android_exoplayer2_ext_flac_FlacDecoderJni_##NAME( \
          JNIEnv *env, jobject thiz, ##__VA_ARGS__);                       \
  }                                                                        \
  JNIEXPORT RETURN_TYPE                                                    \
      Java_com_google_android_exoplayer2_ext_flac_FlacDecoderJni_##NAME( \
          JNIEnv *env, jobject thiz, ##__VA_ARGS__)

class JavaDataSource : public DataSource {
 public:
  void setFlacDecoderJni(JNIEnv *env, jobject flacDecoderJni) {
    this->env = env;
    this->flacDecoderJni = flacDecoderJni;
    if (mid == NULL) {
      jclass cls = env->GetObjectClass(flacDecoderJni);
      mid = env->GetMethodID(cls, "read", "(Ljava/nio/ByteBuffer;)I");
    }
  }

  ssize_t readAt(off64_t offset, void *const data, size_t size) {
    jobject byteBuffer = env->NewDirectByteBuffer(data, size);
    int result = env->CallIntMethod(flacDecoderJni, mid, byteBuffer);
    if (env->ExceptionCheck()) {
      // Exception is thrown in Java when returning from the native call.
      result = -1;
    }
    return result;
  }

 private:
  JNIEnv *env;
  jobject flacDecoderJni;
  jmethodID mid;
};

struct Context {
  JavaDataSource *source;
  FLACParser *parser;

  Context() {
    source = new JavaDataSource();
    parser = new FLACParser(source);
  }

  ~Context() {
    delete parser;
    delete source;
  }
};

DECODER_FUNC(jlong, flacInit) {
  Context *context = new Context;
  if (!context->parser->init()) {
    delete context;
    return 0;
  }
  return reinterpret_cast<intptr_t>(context);
}

DECODER_FUNC(jobject, flacDecodeMetadata, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  context->source->setFlacDecoderJni(env, thiz);
  if (!context->parser->decodeMetadata()) {
    return NULL;
  }

  jclass arrayListClass = env->FindClass("java/util/ArrayList");
  jmethodID arrayListConstructor =
      env->GetMethodID(arrayListClass, "<init>", "()V");
  jobject commentList = env->NewObject(arrayListClass, arrayListConstructor);
  jmethodID arrayListAddMethod =
      env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z");

  if (context->parser->areVorbisCommentsValid()) {
    std::vector<std::string> vorbisComments =
        context->parser->getVorbisComments();
    for (std::vector<std::string>::const_iterator vorbisComment =
             vorbisComments.begin();
         vorbisComment != vorbisComments.end(); ++vorbisComment) {
      jstring commentString = env->NewStringUTF((*vorbisComment).c_str());
      env->CallBooleanMethod(commentList, arrayListAddMethod, commentString);
      env->DeleteLocalRef(commentString);
    }
  }

  jobject pictureFrames = env->NewObject(arrayListClass, arrayListConstructor);
  bool picturesValid = context->parser->arePicturesValid();
  if (picturesValid) {
    std::vector<FlacPicture> pictures = context->parser->getPictures();
    jclass pictureFrameClass = env->FindClass(
        "com/google/android/exoplayer2/metadata/flac/PictureFrame");
    jmethodID pictureFrameConstructor =
        env->GetMethodID(pictureFrameClass, "<init>",
                         "(ILjava/lang/String;Ljava/lang/String;IIII[B)V");
    for (std::vector<FlacPicture>::const_iterator picture = pictures.begin();
         picture != pictures.end(); ++picture) {
      jstring mimeType = env->NewStringUTF(picture->mimeType.c_str());
      jstring description = env->NewStringUTF(picture->description.c_str());
      jbyteArray pictureData = env->NewByteArray(picture->data.size());
      env->SetByteArrayRegion(pictureData, 0, picture->data.size(),
                              (signed char *)&picture->data[0]);
      jobject pictureFrame = env->NewObject(
          pictureFrameClass, pictureFrameConstructor, picture->type, mimeType,
          description, picture->width, picture->height, picture->depth,
          picture->colors, pictureData);
      env->CallBooleanMethod(pictureFrames, arrayListAddMethod, pictureFrame);
      env->DeleteLocalRef(mimeType);
      env->DeleteLocalRef(description);
      env->DeleteLocalRef(pictureData);
    }
  }

  const FLAC__StreamMetadata_StreamInfo &streamInfo =
      context->parser->getStreamInfo();

  jclass flacStreamMetadataClass = env->FindClass(
      "com/google/android/exoplayer2/extractor/"
      "FlacStreamMetadata");
  jmethodID flacStreamMetadataConstructor =
      env->GetMethodID(flacStreamMetadataClass, "<init>",
                       "(IIIIIIIJLjava/util/ArrayList;Ljava/util/ArrayList;)V");

  return env->NewObject(flacStreamMetadataClass, flacStreamMetadataConstructor,
                        streamInfo.min_blocksize, streamInfo.max_blocksize,
                        streamInfo.min_framesize, streamInfo.max_framesize,
                        streamInfo.sample_rate, streamInfo.channels,
                        streamInfo.bits_per_sample, streamInfo.total_samples,
                        commentList, pictureFrames);
}

DECODER_FUNC(jint, flacDecodeToBuffer, jlong jContext, jobject jOutputBuffer) {
  Context *context = reinterpret_cast<Context *>(jContext);
  context->source->setFlacDecoderJni(env, thiz);
  void *outputBuffer = env->GetDirectBufferAddress(jOutputBuffer);
  jint outputSize = env->GetDirectBufferCapacity(jOutputBuffer);
  return context->parser->readBuffer(outputBuffer, outputSize);
}

DECODER_FUNC(jint, flacDecodeToArray, jlong jContext, jbyteArray jOutputArray) {
  Context *context = reinterpret_cast<Context *>(jContext);
  context->source->setFlacDecoderJni(env, thiz);
  jbyte *outputBuffer = env->GetByteArrayElements(jOutputArray, NULL);
  jint outputSize = env->GetArrayLength(jOutputArray);
  int count = context->parser->readBuffer(outputBuffer, outputSize);
  env->ReleaseByteArrayElements(jOutputArray, outputBuffer, 0);
  return count;
}

DECODER_FUNC(jlong, flacGetDecodePosition, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  return context->parser->getDecodePosition();
}

DECODER_FUNC(jlong, flacGetLastFrameTimestamp, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  return context->parser->getLastFrameTimestamp();
}

DECODER_FUNC(jlong, flacGetLastFrameFirstSampleIndex, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  return context->parser->getLastFrameFirstSampleIndex();
}

DECODER_FUNC(jlong, flacGetNextFrameFirstSampleIndex, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  return context->parser->getNextFrameFirstSampleIndex();
}

DECODER_FUNC(jboolean, flacGetSeekPoints, jlong jContext, jlong timeUs,
             jlongArray outSeekPoints) {
  Context *context = reinterpret_cast<Context *>(jContext);
  std::array<int64_t, 4> result;
  bool success = context->parser->getSeekPositions(timeUs, result);
  if (success) {
    env->SetLongArrayRegion(outSeekPoints, 0, result.size(), result.data());
  }
  return success;
}

DECODER_FUNC(jstring, flacGetStateString, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  const char *str = context->parser->getDecoderStateString();
  return env->NewStringUTF(str);
}

DECODER_FUNC(jboolean, flacIsDecoderAtEndOfStream, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  return context->parser->isDecoderAtEndOfStream();
}

DECODER_FUNC(void, flacFlush, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  context->parser->flush();
}

DECODER_FUNC(void, flacReset, jlong jContext, jlong newPosition) {
  Context *context = reinterpret_cast<Context *>(jContext);
  context->parser->reset(newPosition);
}

DECODER_FUNC(void, flacRelease, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  delete context;
}
<commit_msg>Restore DeleteLocalRef usage<commit_after>/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <android/log.h>
#include <jni.h>

#include <array>
#include <cstdlib>
#include <cstring>

#include "include/flac_parser.h"

#define LOG_TAG "flac_jni"
#define ALOGE(...) \
  ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
#define ALOGV(...) \
  ((void)__android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__))

#define DECODER_FUNC(RETURN_TYPE, NAME, ...)                               \
  extern "C" {                                                             \
  JNIEXPORT RETURN_TYPE                                                    \
      Java_com_google_android_exoplayer2_ext_flac_FlacDecoderJni_##NAME( \
          JNIEnv *env, jobject thiz, ##__VA_ARGS__);                       \
  }                                                                        \
  JNIEXPORT RETURN_TYPE                                                    \
      Java_com_google_android_exoplayer2_ext_flac_FlacDecoderJni_##NAME( \
          JNIEnv *env, jobject thiz, ##__VA_ARGS__)

class JavaDataSource : public DataSource {
 public:
  void setFlacDecoderJni(JNIEnv *env, jobject flacDecoderJni) {
    this->env = env;
    this->flacDecoderJni = flacDecoderJni;
    if (mid == NULL) {
      jclass cls = env->GetObjectClass(flacDecoderJni);
      mid = env->GetMethodID(cls, "read", "(Ljava/nio/ByteBuffer;)I");
      env->DeleteLocalRef(cls);
    }
  }

  ssize_t readAt(off64_t offset, void *const data, size_t size) {
    jobject byteBuffer = env->NewDirectByteBuffer(data, size);
    int result = env->CallIntMethod(flacDecoderJni, mid, byteBuffer);
    if (env->ExceptionCheck()) {
      // Exception is thrown in Java when returning from the native call.
      result = -1;
    }
    env->DeleteLocalRef(byteBuffer);
    return result;
  }

 private:
  JNIEnv *env;
  jobject flacDecoderJni;
  jmethodID mid;
};

struct Context {
  JavaDataSource *source;
  FLACParser *parser;

  Context() {
    source = new JavaDataSource();
    parser = new FLACParser(source);
  }

  ~Context() {
    delete parser;
    delete source;
  }
};

DECODER_FUNC(jlong, flacInit) {
  Context *context = new Context;
  if (!context->parser->init()) {
    delete context;
    return 0;
  }
  return reinterpret_cast<intptr_t>(context);
}

DECODER_FUNC(jobject, flacDecodeMetadata, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  context->source->setFlacDecoderJni(env, thiz);
  if (!context->parser->decodeMetadata()) {
    return NULL;
  }

  jclass arrayListClass = env->FindClass("java/util/ArrayList");
  jmethodID arrayListConstructor =
      env->GetMethodID(arrayListClass, "<init>", "()V");
  jobject commentList = env->NewObject(arrayListClass, arrayListConstructor);
  jmethodID arrayListAddMethod =
      env->GetMethodID(arrayListClass, "add", "(Ljava/lang/Object;)Z");

  if (context->parser->areVorbisCommentsValid()) {
    std::vector<std::string> vorbisComments =
        context->parser->getVorbisComments();
    for (std::vector<std::string>::const_iterator vorbisComment =
             vorbisComments.begin();
         vorbisComment != vorbisComments.end(); ++vorbisComment) {
      jstring commentString = env->NewStringUTF((*vorbisComment).c_str());
      env->CallBooleanMethod(commentList, arrayListAddMethod, commentString);
      env->DeleteLocalRef(commentString);
    }
  }

  jobject pictureFrames = env->NewObject(arrayListClass, arrayListConstructor);
  bool picturesValid = context->parser->arePicturesValid();
  if (picturesValid) {
    std::vector<FlacPicture> pictures = context->parser->getPictures();
    jclass pictureFrameClass = env->FindClass(
        "com/google/android/exoplayer2/metadata/flac/PictureFrame");
    jmethodID pictureFrameConstructor =
        env->GetMethodID(pictureFrameClass, "<init>",
                         "(ILjava/lang/String;Ljava/lang/String;IIII[B)V");
    for (std::vector<FlacPicture>::const_iterator picture = pictures.begin();
         picture != pictures.end(); ++picture) {
      jstring mimeType = env->NewStringUTF(picture->mimeType.c_str());
      jstring description = env->NewStringUTF(picture->description.c_str());
      jbyteArray pictureData = env->NewByteArray(picture->data.size());
      env->SetByteArrayRegion(pictureData, 0, picture->data.size(),
                              (signed char *)&picture->data[0]);
      jobject pictureFrame = env->NewObject(
          pictureFrameClass, pictureFrameConstructor, picture->type, mimeType,
          description, picture->width, picture->height, picture->depth,
          picture->colors, pictureData);
      env->CallBooleanMethod(pictureFrames, arrayListAddMethod, pictureFrame);
      env->DeleteLocalRef(mimeType);
      env->DeleteLocalRef(description);
      env->DeleteLocalRef(pictureData);
    }
  }

  const FLAC__StreamMetadata_StreamInfo &streamInfo =
      context->parser->getStreamInfo();

  jclass flacStreamMetadataClass = env->FindClass(
      "com/google/android/exoplayer2/extractor/"
      "FlacStreamMetadata");
  jmethodID flacStreamMetadataConstructor =
      env->GetMethodID(flacStreamMetadataClass, "<init>",
                       "(IIIIIIIJLjava/util/ArrayList;Ljava/util/ArrayList;)V");

  return env->NewObject(flacStreamMetadataClass, flacStreamMetadataConstructor,
                        streamInfo.min_blocksize, streamInfo.max_blocksize,
                        streamInfo.min_framesize, streamInfo.max_framesize,
                        streamInfo.sample_rate, streamInfo.channels,
                        streamInfo.bits_per_sample, streamInfo.total_samples,
                        commentList, pictureFrames);
}

DECODER_FUNC(jint, flacDecodeToBuffer, jlong jContext, jobject jOutputBuffer) {
  Context *context = reinterpret_cast<Context *>(jContext);
  context->source->setFlacDecoderJni(env, thiz);
  void *outputBuffer = env->GetDirectBufferAddress(jOutputBuffer);
  jint outputSize = env->GetDirectBufferCapacity(jOutputBuffer);
  return context->parser->readBuffer(outputBuffer, outputSize);
}

DECODER_FUNC(jint, flacDecodeToArray, jlong jContext, jbyteArray jOutputArray) {
  Context *context = reinterpret_cast<Context *>(jContext);
  context->source->setFlacDecoderJni(env, thiz);
  jbyte *outputBuffer = env->GetByteArrayElements(jOutputArray, NULL);
  jint outputSize = env->GetArrayLength(jOutputArray);
  int count = context->parser->readBuffer(outputBuffer, outputSize);
  env->ReleaseByteArrayElements(jOutputArray, outputBuffer, 0);
  return count;
}

DECODER_FUNC(jlong, flacGetDecodePosition, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  return context->parser->getDecodePosition();
}

DECODER_FUNC(jlong, flacGetLastFrameTimestamp, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  return context->parser->getLastFrameTimestamp();
}

DECODER_FUNC(jlong, flacGetLastFrameFirstSampleIndex, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  return context->parser->getLastFrameFirstSampleIndex();
}

DECODER_FUNC(jlong, flacGetNextFrameFirstSampleIndex, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  return context->parser->getNextFrameFirstSampleIndex();
}

DECODER_FUNC(jboolean, flacGetSeekPoints, jlong jContext, jlong timeUs,
             jlongArray outSeekPoints) {
  Context *context = reinterpret_cast<Context *>(jContext);
  std::array<int64_t, 4> result;
  bool success = context->parser->getSeekPositions(timeUs, result);
  if (success) {
    env->SetLongArrayRegion(outSeekPoints, 0, result.size(), result.data());
  }
  return success;
}

DECODER_FUNC(jstring, flacGetStateString, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  const char *str = context->parser->getDecoderStateString();
  return env->NewStringUTF(str);
}

DECODER_FUNC(jboolean, flacIsDecoderAtEndOfStream, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  return context->parser->isDecoderAtEndOfStream();
}

DECODER_FUNC(void, flacFlush, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  context->parser->flush();
}

DECODER_FUNC(void, flacReset, jlong jContext, jlong newPosition) {
  Context *context = reinterpret_cast<Context *>(jContext);
  context->parser->reset(newPosition);
}

DECODER_FUNC(void, flacRelease, jlong jContext) {
  Context *context = reinterpret_cast<Context *>(jContext);
  delete context;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: MasterScriptProviderFactory.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-10-22 14:07:27 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <rtl/ustring>
#include <cppuhelper/implbase2.hxx>

#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>

#include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
#include <com/sun/star/script/provider/XScriptProvider.hpp>

namespace func_provider
{
// for simplification
#define css ::com::sun::star

class MasterScriptProviderFactory :
    public ::cppu::WeakImplHelper2 <
        css::script::provider::XScriptProviderFactory,
        css::lang::XServiceInfo >
{
private:
    css::uno::Reference< css::uno::XComponentContext > m_xComponentContext;
protected:
    virtual ~MasterScriptProviderFactory();

public:
    MasterScriptProviderFactory(
        css::uno::Reference< css::uno::XComponentContext > const & xComponentContext );

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName()
        throw ( css::uno::RuntimeException );

    virtual sal_Bool SAL_CALL
        supportsService( ::rtl::OUString const & serviceName )
            throw ( css::uno::RuntimeException );

    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL
        getSupportedServiceNames()
            throw ( css::uno::RuntimeException );

    // XScriptProviderFactory
    virtual css::uno::Reference< css::script::provider::XScriptProvider >
        SAL_CALL createScriptProvider( const css::uno::Any& context )
            throw ( css::lang::IllegalArgumentException, css::uno::RuntimeException);
};

} // namespace func_provider
<commit_msg>INTEGRATION: CWS scriptingf9 (1.3.6); FILE MERGED 2004/11/12 11:37:25 toconnor 1.3.6.1: #i36913# make ActiveMSPList a member of fMasterScriptProviderFactory<commit_after>/*************************************************************************
 *
 *  $RCSfile: MasterScriptProviderFactory.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2004-12-23 11:50:41 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <rtl/ustring>
#include <cppuhelper/implbase2.hxx>

#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>

#include <com/sun/star/script/provider/XScriptProviderFactory.hpp>
#include <com/sun/star/script/provider/XScriptProvider.hpp>

#include "ActiveMSPList.hxx"

namespace func_provider
{
// for simplification
#define css ::com::sun::star

class MasterScriptProviderFactory :
    public ::cppu::WeakImplHelper2 <
        css::script::provider::XScriptProviderFactory,
        css::lang::XServiceInfo >
{
private:

    ActiveMSPList* m_MSPList;

    // need to not only hold a pointer to this object but also
    // keep it aqcuired
    css::uno::Reference< css::lang::XEventListener > m_MSPListHolder;

    css::uno::Reference< css::uno::XComponentContext > m_xComponentContext;

    ActiveMSPList& getActiveMSPList();

protected:
    virtual ~MasterScriptProviderFactory();

public:
    MasterScriptProviderFactory(
        css::uno::Reference< css::uno::XComponentContext > const & xComponentContext );

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName()
        throw ( css::uno::RuntimeException );

    virtual sal_Bool SAL_CALL
        supportsService( ::rtl::OUString const & serviceName )
            throw ( css::uno::RuntimeException );

    virtual css::uno::Sequence< ::rtl::OUString > SAL_CALL
        getSupportedServiceNames()
            throw ( css::uno::RuntimeException );

    // XScriptProviderFactory
    virtual css::uno::Reference< css::script::provider::XScriptProvider >
        SAL_CALL createScriptProvider( const css::uno::Any& context )
            throw ( css::lang::IllegalArgumentException, css::uno::RuntimeException);
};

} // namespace func_provider
<|endoftext|>