<commit_before>/* @file
 *
 *  Copyright (C) - Triton
 *
 *  This program is under the terms of the BSD License.
 */

#include <triton/pythonBindings.hpp>
#include <triton/pythonObjects.hpp>
#include <triton/pythonUtils.hpp>
#include <triton/pythonXFunctions.hpp>

/*! \page py_REG_page REG
    \brief [**python api**] All information about the REG python namespace.

\tableofcontents

\section REG_py_description Description

According to the CPU architecture, the REG namespace contains all kinds of register.

\section REG_py_api Python API - Items of the REG namespace

\subsection REG_X86_py_api x86 registers

\include x86_reg

\subsection REG_X8664_py_api x86-64 registers

\include x8664_reg

*/

namespace triton {
  namespace bindings {
    namespace python {

      void initRegNamespace(PyObject* registersDict) {
        PyDict_Clear(registersDict);

        PyObject* x86RegistersDict = xPyDict_New();
        PyObject* x86RegDictClass = xPyClass_New(nullptr, x86RegistersDict, xPyString_FromString("X86"));
        PyDict_SetItemString(registersDict, "X86", x86RegDictClass);

        // Init X86 REG namespace
        #define REG_SPEC(UPPER_NAME, LOWER_NAME, X86_64_UPPER, X86_64_LOWER, X86_64_PARENT, X86_UPPER, X86_LOWER, X86_PARENT, X86_AVAIL)\
          if(X86_AVAIL)                                                                                \
            PyDict_SetItemString(x86RegistersDict, #UPPER_NAME, PyLong_FromUint32(triton::arch::ID_REG_##UPPER_NAME));
        // Use REG not available in capstone as normal register
        #define REG_SPEC_NO_CAPSTONE REG_SPEC
        #include "triton/x86.spec"

        PyObject* x8664RegistersDict = xPyDict_New();
        PyObject* x8664RegDictClass = xPyClass_New(nullptr, x8664RegistersDict, xPyString_FromString("X86_64"));
        PyDict_SetItemString(registersDict, "X86_64", x8664RegDictClass);

        // Init X86_64 REG namespace
        #define REG_SPEC(UPPER_NAME, LOWER_NAME, X86_64_UPPER, X86_64_LOWER, X86_64_PARENT, X86_UPPER, X86_LOWER, X86_PARENT, X86_AVAIL)\
          PyDict_SetItemString(x8664RegistersDict, #UPPER_NAME, PyLong_FromUint32(triton::arch::ID_REG_##UPPER_NAME));
        // Use REG not available in capstone as normal register
        #define REG_SPEC_NO_CAPSTONE REG_SPEC
        #include "triton/x86.spec"
      }

    }; /* python namespace */
  }; /* bindings namespace */
}; /* triton namespace */
<commit_msg>Fix things 2<commit_after>/* @file
 *
 *  Copyright (C) - Triton
 *
 *  This program is under the terms of the BSD License.
 */

#include <triton/pythonBindings.hpp>
#include <triton/pythonObjects.hpp>
#include <triton/pythonUtils.hpp>
#include <triton/pythonXFunctions.hpp>

/*! \page py_REG_page REG
    \brief [**python api**] All information about the REG python namespace.

\tableofcontents

\section REG_py_description Description

According to the CPU architecture, the REG namespace contains all kinds of register.

\section REG_py_api Python API - Items of the REG namespace

\subsection REG_X86_py_api x86 registers

\include x86_reg

\subsection REG_X8664_py_api x86-64 registers

\include x8664_reg

*/

namespace triton {
  namespace bindings {
    namespace python {

      void initRegNamespace(PyObject* registersDict) {
        PyDict_Clear(registersDict);

        PyObject* x86RegistersDict      = xPyDict_New();
        PyObject* x86RegistersDictClass = xPyClass_New(nullptr, x86RegistersDict, xPyString_FromString("X86"));
        PyDict_SetItemString(registersDict, "X86", x86RegistersDictClass);

        // Init X86 REG namespace
        #define REG_SPEC(UPPER_NAME, LOWER_NAME, X86_64_UPPER, X86_64_LOWER, X86_64_PARENT, X86_UPPER, X86_LOWER, X86_PARENT, X86_AVAIL)  \
          if (X86_AVAIL)                                                                                \
            PyDict_SetItemString(x86RegistersDict, #UPPER_NAME, PyLong_FromUint32(triton::arch::ID_REG_##UPPER_NAME));
        // Use REG not available in capstone as normal register
        #define REG_SPEC_NO_CAPSTONE REG_SPEC
        #include "triton/x86.spec"

        PyObject* x8664RegistersDict      = xPyDict_New();
        PyObject* x8664RegistersDictClass = xPyClass_New(nullptr, x8664RegistersDict, xPyString_FromString("X86_64"));
        PyDict_SetItemString(registersDict, "X86_64", x8664RegistersDictClass);

        // Init X86_64 REG namespace
        #define REG_SPEC(UPPER_NAME, LOWER_NAME, X86_64_UPPER, X86_64_LOWER, X86_64_PARENT, X86_UPPER, X86_LOWER, X86_PARENT, X86_AVAIL)  \
          PyDict_SetItemString(x8664RegistersDict, #UPPER_NAME, PyLong_FromUint32(triton::arch::ID_REG_##UPPER_NAME));
        // Use REG not available in capstone as normal register
        #define REG_SPEC_NO_CAPSTONE REG_SPEC
        #include "triton/x86.spec"
      }

    }; /* python namespace */
  }; /* bindings namespace */
}; /* triton namespace */
<|endoftext|>


<commit_before>#pragma once
#include <iostream>
#include <stdexcept>
#include <cmath>
#include <lexical_eval.hpp>

class assertion_error : public std::runtime_error {
public:
  assertion_error(const std::string& s): std::runtime_error(s) {}
};

inline void
throw_exception(const char *file, int line, const std::string& msg) {
  throw assertion_error(std::string(file) + ":" + std::to_string(line) + ": " + msg);
}

template <typename T1>
inline void assert_equal(const T1& actual, const T1& expected) {
  if(actual != expected) {
    throw assertion_error(std::to_string(actual) + " is not equal to " + std::to_string(expected));
  }
}

template <typename T1>
inline void assert_close(const T1& actual, const T1& expected, const T1& delta) {
  if(std::abs(actual-expected) > std::abs(delta)) {
    throw assertion_error(std::to_string(actual) + " is not within " + std::to_string(expected)
      + " +/- " + std::to_string(delta)
    );
  }
}

template <typename T3, typename T1, typename T2>
inline void do_equal_test(const T1& input, const T2& expected) {
  assert_equal(lexical_eval<T3>(input), static_cast<T3>(expected));
}

template <typename T3, typename T1, typename T2>
inline void do_close_test(const T1& input, const T2& expected, const T3& delta) {
  assert_close(lexical_eval<T3>(input), static_cast<T3>(expected), delta);
}

template <typename T1, typename T2>
inline void do_integral_batch(const T1& input, const T2& expected) {
  do_equal_test<unsigned long>(input, expected);
  do_equal_test<unsigned long long>(input, expected);
  do_equal_test<unsigned int>(input, expected);
  do_equal_test<unsigned short>(input, expected);
  do_equal_test<unsigned char>(input, expected);
  do_equal_test<long long>(input, expected);
  do_equal_test<int>(input, expected);
  do_equal_test<short>(input, expected);
  do_equal_test<char>(input, expected);
}

template <typename T1, typename T2>
inline void do_real_batch(const T1& input, const T2& expected, const T2 delta = static_cast<T2>(1e-6)) {
  do_close_test<long double>(input, expected, delta);
  do_close_test<double>(input, expected, delta);
  do_close_test<float>(input, expected, delta);
}
<commit_msg>remove util.hpp<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2011 Google Inc. 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 Google Inc. 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 "config.h"
#include "platform/mhtml/MHTMLArchive.h"

#include "platform/DateComponents.h"
#include "platform/MIMETypeRegistry.h"
#include "platform/SerializedResource.h"
#include "platform/SharedBuffer.h"
#include "platform/mhtml/ArchiveResource.h"
#include "platform/mhtml/MHTMLParser.h"
#include "platform/text/QuotedPrintable.h"
#include "platform/weborigin/SchemeRegistry.h"
#include "wtf/CryptographicallyRandomNumber.h"
#include "wtf/DateMath.h"
#include "wtf/text/Base64.h"
#include "wtf/text/StringBuilder.h"

namespace blink {

const char* const quotedPrintable = "quoted-printable";
const char* const base64 = "base64";
const char* const binary = "binary";

static String generateRandomBoundary()
{
    // Trying to generate random boundaries similar to IE/UnMHT (ex: ----=_NextPart_000_001B_01CC157B.96F808A0).
    const size_t randomValuesLength = 10;
    char randomValues[randomValuesLength];
    cryptographicallyRandomValues(&randomValues, randomValuesLength);
    StringBuilder stringBuilder;
    stringBuilder.appendLiteral("----=_NextPart_000_");
    for (size_t i = 0; i < randomValuesLength; ++i) {
        if (i == 2)
            stringBuilder.append('_');
        else if (i == 6)
            stringBuilder.append('.');
        stringBuilder.append(lowerNibbleToASCIIHexDigit(randomValues[i]));
        stringBuilder.append(upperNibbleToASCIIHexDigit(randomValues[i]));
    }
    return stringBuilder.toString();
}

static String replaceNonPrintableCharacters(const String& text)
{
    StringBuilder stringBuilder;
    for (size_t i = 0; i < text.length(); ++i) {
        if (isASCIIPrintable(text[i]))
            stringBuilder.append(text[i]);
        else
            stringBuilder.append('?');
    }
    return stringBuilder.toString();
}

MHTMLArchive::MHTMLArchive()
{
}

MHTMLArchive::~MHTMLArchive()
{
#if !ENABLE(OILPAN)
    // Because all frames know about each other we need to perform a deep clearing of the archives graph.
    clearAllSubframeArchives();
#endif
}

PassRefPtrWillBeRawPtr<MHTMLArchive> MHTMLArchive::create()
{
    return adoptRefWillBeNoop(new MHTMLArchive);
}

PassRefPtrWillBeRawPtr<MHTMLArchive> MHTMLArchive::create(const KURL& url, SharedBuffer* data)
{
    // For security reasons we only load MHTML pages from local URLs.
    if (!SchemeRegistry::shouldTreatURLSchemeAsLocal(url.protocol()))
        return nullptr;

    MHTMLParser parser(data);
    RefPtrWillBeRawPtr<MHTMLArchive> mainArchive = parser.parseArchive();
    if (!mainArchive)
        return nullptr; // Invalid MHTML file.

    // Since MHTML is a flat format, we need to make all frames aware of all resources.
    for (size_t i = 0; i < parser.frameCount(); ++i) {
        RefPtrWillBeRawPtr<MHTMLArchive> archive = parser.frameAt(i);
        for (size_t j = 1; j < parser.frameCount(); ++j) {
            if (i != j)
                archive->addSubframeArchive(parser.frameAt(j));
        }
        for (size_t j = 0; j < parser.subResourceCount(); ++j)
            archive->addSubresource(parser.subResourceAt(j));
    }
    return mainArchive.release();
}

PassRefPtr<SharedBuffer> MHTMLArchive::generateMHTMLData(const Vector<SerializedResource>& resources, EncodingPolicy encodingPolicy, const String& title, const String& mimeType)
{
    String boundary = generateRandomBoundary();
    String endOfResourceBoundary = "--" + boundary + "\r\n";

    DateComponents now;
    now.setMillisecondsSinceEpochForDateTime(currentTimeMS());
    String dateString = makeRFC2822DateString(now.weekDay(), now.monthDay(), now.month(), now.fullYear(), now.hour(), now.minute(), now.second(), 0);

    StringBuilder stringBuilder;
    stringBuilder.appendLiteral("From: <Saved by WebKit>\r\n");
    stringBuilder.appendLiteral("Subject: ");
    // We replace non ASCII characters with '?' characters to match IE's behavior.
    stringBuilder.append(replaceNonPrintableCharacters(title));
    stringBuilder.appendLiteral("\r\nDate: ");
    stringBuilder.append(dateString);
    stringBuilder.appendLiteral("\r\nMIME-Version: 1.0\r\n");
    stringBuilder.appendLiteral("Content-Type: multipart/related;\r\n");
    stringBuilder.appendLiteral("\ttype=\"");
    stringBuilder.append(mimeType);
    stringBuilder.appendLiteral("\";\r\n");
    stringBuilder.appendLiteral("\tboundary=\"");
    stringBuilder.append(boundary);
    stringBuilder.appendLiteral("\"\r\n\r\n");

    // We use utf8() below instead of ascii() as ascii() replaces CRLFs with ?? (we still only have put ASCII characters in it).
    ASSERT(stringBuilder.toString().containsOnlyASCII());
    CString asciiString = stringBuilder.toString().utf8();
    RefPtr<SharedBuffer> mhtmlData = SharedBuffer::create();
    mhtmlData->append(asciiString.data(), asciiString.length());

    for (size_t i = 0; i < resources.size(); ++i) {
        const SerializedResource& resource = resources[i];

        stringBuilder.clear();
        stringBuilder.append(endOfResourceBoundary);
        stringBuilder.appendLiteral("Content-Type: ");
        stringBuilder.append(resource.mimeType);

        const char* contentEncoding = 0;
        if (encodingPolicy == UseBinaryEncoding)
            contentEncoding = binary;
        else if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(resource.mimeType) || MIMETypeRegistry::isSupportedNonImageMIMEType(resource.mimeType))
            contentEncoding = quotedPrintable;
        else
            contentEncoding = base64;

        stringBuilder.appendLiteral("\r\nContent-Transfer-Encoding: ");
        stringBuilder.append(contentEncoding);
        stringBuilder.appendLiteral("\r\nContent-Location: ");
        stringBuilder.append(resource.url);
        stringBuilder.appendLiteral("\r\n\r\n");

        asciiString = stringBuilder.toString().utf8();
        mhtmlData->append(asciiString.data(), asciiString.length());

        if (!strcmp(contentEncoding, binary)) {
            const char* data;
            size_t position = 0;
            while (size_t length = resource.data->getSomeData(data, position)) {
                mhtmlData->append(data, length);
                position += length;
            }
        } else {
            // FIXME: ideally we would encode the content as a stream without having to fetch it all.
            const char* data = resource.data->data();
            size_t dataLength = resource.data->size();
            Vector<char> encodedData;
            if (!strcmp(contentEncoding, quotedPrintable)) {
                quotedPrintableEncode(data, dataLength, encodedData);
                mhtmlData->append(encodedData.data(), encodedData.size());
                mhtmlData->append("\r\n", 2);
            } else {
                ASSERT(!strcmp(contentEncoding, base64));
                // We are not specifying insertLFs = true below as it would cut the lines with LFs and MHTML requires CRLFs.
                base64Encode(data, dataLength, encodedData);
                const size_t maximumLineLength = 76;
                size_t index = 0;
                size_t encodedDataLength = encodedData.size();
                do {
                    size_t lineLength = std::min(encodedDataLength - index, maximumLineLength);
                    mhtmlData->append(encodedData.data() + index, lineLength);
                    mhtmlData->append("\r\n", 2);
                    index += maximumLineLength;
                } while (index < encodedDataLength);
            }
        }
    }

    asciiString = String("--" + boundary + "--\r\n").utf8();
    mhtmlData->append(asciiString.data(), asciiString.length());

    return mhtmlData.release();
}

#if !ENABLE(OILPAN)
void MHTMLArchive::clearAllSubframeArchives()
{
    SubFrameArchives clearedArchives;
    clearAllSubframeArchivesImpl(&clearedArchives);
}

void MHTMLArchive::clearAllSubframeArchivesImpl(SubFrameArchives* clearedArchives)
{
    for (SubFrameArchives::iterator it = m_subframeArchives.begin(); it != m_subframeArchives.end(); ++it) {
        if (!clearedArchives->contains(*it)) {
            clearedArchives->append(*it);
            (*it)->clearAllSubframeArchivesImpl(clearedArchives);
        }
    }
    m_subframeArchives.clear();
}
#endif

void MHTMLArchive::setMainResource(PassRefPtrWillBeRawPtr<ArchiveResource> mainResource)
{
    m_mainResource = mainResource;
}

void MHTMLArchive::addSubresource(PassRefPtrWillBeRawPtr<ArchiveResource> subResource)
{
    m_subresources.append(subResource);
}

void MHTMLArchive::addSubframeArchive(PassRefPtrWillBeRawPtr<MHTMLArchive> subframeArchive)
{
    m_subframeArchives.append(subframeArchive);
}

void MHTMLArchive::trace(Visitor* visitor)
{
    visitor->trace(m_mainResource);
    visitor->trace(m_subresources);
    visitor->trace(m_subframeArchives);
}

}
<commit_msg>Update mhtml saved page header to "Saved by Blink"<commit_after>/*
 * Copyright (C) 2011 Google Inc. 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 Google Inc. 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 "config.h"
#include "platform/mhtml/MHTMLArchive.h"

#include "platform/DateComponents.h"
#include "platform/MIMETypeRegistry.h"
#include "platform/SerializedResource.h"
#include "platform/SharedBuffer.h"
#include "platform/mhtml/ArchiveResource.h"
#include "platform/mhtml/MHTMLParser.h"
#include "platform/text/QuotedPrintable.h"
#include "platform/weborigin/SchemeRegistry.h"
#include "wtf/CryptographicallyRandomNumber.h"
#include "wtf/DateMath.h"
#include "wtf/text/Base64.h"
#include "wtf/text/StringBuilder.h"

namespace blink {

const char* const quotedPrintable = "quoted-printable";
const char* const base64 = "base64";
const char* const binary = "binary";

static String generateRandomBoundary()
{
    // Trying to generate random boundaries similar to IE/UnMHT (ex: ----=_NextPart_000_001B_01CC157B.96F808A0).
    const size_t randomValuesLength = 10;
    char randomValues[randomValuesLength];
    cryptographicallyRandomValues(&randomValues, randomValuesLength);
    StringBuilder stringBuilder;
    stringBuilder.appendLiteral("----=_NextPart_000_");
    for (size_t i = 0; i < randomValuesLength; ++i) {
        if (i == 2)
            stringBuilder.append('_');
        else if (i == 6)
            stringBuilder.append('.');
        stringBuilder.append(lowerNibbleToASCIIHexDigit(randomValues[i]));
        stringBuilder.append(upperNibbleToASCIIHexDigit(randomValues[i]));
    }
    return stringBuilder.toString();
}

static String replaceNonPrintableCharacters(const String& text)
{
    StringBuilder stringBuilder;
    for (size_t i = 0; i < text.length(); ++i) {
        if (isASCIIPrintable(text[i]))
            stringBuilder.append(text[i]);
        else
            stringBuilder.append('?');
    }
    return stringBuilder.toString();
}

MHTMLArchive::MHTMLArchive()
{
}

MHTMLArchive::~MHTMLArchive()
{
#if !ENABLE(OILPAN)
    // Because all frames know about each other we need to perform a deep clearing of the archives graph.
    clearAllSubframeArchives();
#endif
}

PassRefPtrWillBeRawPtr<MHTMLArchive> MHTMLArchive::create()
{
    return adoptRefWillBeNoop(new MHTMLArchive);
}

PassRefPtrWillBeRawPtr<MHTMLArchive> MHTMLArchive::create(const KURL& url, SharedBuffer* data)
{
    // For security reasons we only load MHTML pages from local URLs.
    if (!SchemeRegistry::shouldTreatURLSchemeAsLocal(url.protocol()))
        return nullptr;

    MHTMLParser parser(data);
    RefPtrWillBeRawPtr<MHTMLArchive> mainArchive = parser.parseArchive();
    if (!mainArchive)
        return nullptr; // Invalid MHTML file.

    // Since MHTML is a flat format, we need to make all frames aware of all resources.
    for (size_t i = 0; i < parser.frameCount(); ++i) {
        RefPtrWillBeRawPtr<MHTMLArchive> archive = parser.frameAt(i);
        for (size_t j = 1; j < parser.frameCount(); ++j) {
            if (i != j)
                archive->addSubframeArchive(parser.frameAt(j));
        }
        for (size_t j = 0; j < parser.subResourceCount(); ++j)
            archive->addSubresource(parser.subResourceAt(j));
    }
    return mainArchive.release();
}

PassRefPtr<SharedBuffer> MHTMLArchive::generateMHTMLData(const Vector<SerializedResource>& resources, EncodingPolicy encodingPolicy, const String& title, const String& mimeType)
{
    String boundary = generateRandomBoundary();
    String endOfResourceBoundary = "--" + boundary + "\r\n";

    DateComponents now;
    now.setMillisecondsSinceEpochForDateTime(currentTimeMS());
    String dateString = makeRFC2822DateString(now.weekDay(), now.monthDay(), now.month(), now.fullYear(), now.hour(), now.minute(), now.second(), 0);

    StringBuilder stringBuilder;
    stringBuilder.appendLiteral("From: <Saved by Blink>\r\n");
    stringBuilder.appendLiteral("Subject: ");
    // We replace non ASCII characters with '?' characters to match IE's behavior.
    stringBuilder.append(replaceNonPrintableCharacters(title));
    stringBuilder.appendLiteral("\r\nDate: ");
    stringBuilder.append(dateString);
    stringBuilder.appendLiteral("\r\nMIME-Version: 1.0\r\n");
    stringBuilder.appendLiteral("Content-Type: multipart/related;\r\n");
    stringBuilder.appendLiteral("\ttype=\"");
    stringBuilder.append(mimeType);
    stringBuilder.appendLiteral("\";\r\n");
    stringBuilder.appendLiteral("\tboundary=\"");
    stringBuilder.append(boundary);
    stringBuilder.appendLiteral("\"\r\n\r\n");

    // We use utf8() below instead of ascii() as ascii() replaces CRLFs with ?? (we still only have put ASCII characters in it).
    ASSERT(stringBuilder.toString().containsOnlyASCII());
    CString asciiString = stringBuilder.toString().utf8();
    RefPtr<SharedBuffer> mhtmlData = SharedBuffer::create();
    mhtmlData->append(asciiString.data(), asciiString.length());

    for (size_t i = 0; i < resources.size(); ++i) {
        const SerializedResource& resource = resources[i];

        stringBuilder.clear();
        stringBuilder.append(endOfResourceBoundary);
        stringBuilder.appendLiteral("Content-Type: ");
        stringBuilder.append(resource.mimeType);

        const char* contentEncoding = 0;
        if (encodingPolicy == UseBinaryEncoding)
            contentEncoding = binary;
        else if (MIMETypeRegistry::isSupportedJavaScriptMIMEType(resource.mimeType) || MIMETypeRegistry::isSupportedNonImageMIMEType(resource.mimeType))
            contentEncoding = quotedPrintable;
        else
            contentEncoding = base64;

        stringBuilder.appendLiteral("\r\nContent-Transfer-Encoding: ");
        stringBuilder.append(contentEncoding);
        stringBuilder.appendLiteral("\r\nContent-Location: ");
        stringBuilder.append(resource.url);
        stringBuilder.appendLiteral("\r\n\r\n");

        asciiString = stringBuilder.toString().utf8();
        mhtmlData->append(asciiString.data(), asciiString.length());

        if (!strcmp(contentEncoding, binary)) {
            const char* data;
            size_t position = 0;
            while (size_t length = resource.data->getSomeData(data, position)) {
                mhtmlData->append(data, length);
                position += length;
            }
        } else {
            // FIXME: ideally we would encode the content as a stream without having to fetch it all.
            const char* data = resource.data->data();
            size_t dataLength = resource.data->size();
            Vector<char> encodedData;
            if (!strcmp(contentEncoding, quotedPrintable)) {
                quotedPrintableEncode(data, dataLength, encodedData);
                mhtmlData->append(encodedData.data(), encodedData.size());
                mhtmlData->append("\r\n", 2);
            } else {
                ASSERT(!strcmp(contentEncoding, base64));
                // We are not specifying insertLFs = true below as it would cut the lines with LFs and MHTML requires CRLFs.
                base64Encode(data, dataLength, encodedData);
                const size_t maximumLineLength = 76;
                size_t index = 0;
                size_t encodedDataLength = encodedData.size();
                do {
                    size_t lineLength = std::min(encodedDataLength - index, maximumLineLength);
                    mhtmlData->append(encodedData.data() + index, lineLength);
                    mhtmlData->append("\r\n", 2);
                    index += maximumLineLength;
                } while (index < encodedDataLength);
            }
        }
    }

    asciiString = String("--" + boundary + "--\r\n").utf8();
    mhtmlData->append(asciiString.data(), asciiString.length());

    return mhtmlData.release();
}

#if !ENABLE(OILPAN)
void MHTMLArchive::clearAllSubframeArchives()
{
    SubFrameArchives clearedArchives;
    clearAllSubframeArchivesImpl(&clearedArchives);
}

void MHTMLArchive::clearAllSubframeArchivesImpl(SubFrameArchives* clearedArchives)
{
    for (SubFrameArchives::iterator it = m_subframeArchives.begin(); it != m_subframeArchives.end(); ++it) {
        if (!clearedArchives->contains(*it)) {
            clearedArchives->append(*it);
            (*it)->clearAllSubframeArchivesImpl(clearedArchives);
        }
    }
    m_subframeArchives.clear();
}
#endif

void MHTMLArchive::setMainResource(PassRefPtrWillBeRawPtr<ArchiveResource> mainResource)
{
    m_mainResource = mainResource;
}

void MHTMLArchive::addSubresource(PassRefPtrWillBeRawPtr<ArchiveResource> subResource)
{
    m_subresources.append(subResource);
}

void MHTMLArchive::addSubframeArchive(PassRefPtrWillBeRawPtr<MHTMLArchive> subframeArchive)
{
    m_subframeArchives.append(subframeArchive);
}

void MHTMLArchive::trace(Visitor* visitor)
{
    visitor->trace(m_mainResource);
    visitor->trace(m_subresources);
    visitor->trace(m_subframeArchives);
}

}
<|endoftext|>


<commit_before>#ifdef dynodbc

#include "dynodbc.h"
#include <stdio.h>

#ifdef _WIN32
  #include <windows.h>
#elif defined(__GNUC__) // GNU compiler
  #include <dlfcn.h>
#else
#error define your copiler
#endif

#include<string>
/*
#define RTLD_LAZY   1
#define RTLD_NOW    2
#define RTLD_GLOBAL 4
*/

void* LoadSharedLibrary(char *pcDllname, int iMode = 2)
{
  std::string sDllName = pcDllname;
#ifdef _WIN32
  sDllName += ".dll";
  return (void*)LoadLibraryA(pcDllname);
#elif defined(__GNUC__) // GNU compiler
  sDllName += ".so";
  void* handle = dlopen(sDllName.c_str(),iMode);

  if (!handle) {
    printf("node-odbc: error loading ODBC library: %s\n", dlerror());
  }

  return handle;
#endif
}

void* GetFunction(void *Lib, char *Fnname)
{
#if defined(_MSC_VER) // Microsoft compiler
  return (void*)GetProcAddress((HINSTANCE)Lib,Fnname);
#elif defined(__GNUC__) // GNU compiler
  return dlsym(Lib,Fnname);
#endif
}

bool FreeSharedLibrary(void *hDLL)
{
#if defined(_MSC_VER) // Microsoft compiler
  return (FreeLibrary((HINSTANCE)hDLL)!=0);
#elif defined(__GNUC__) // GNU compiler
  return dlclose(hDLL);
#endif
}

pfnSQLGetData           pSQLGetData;
pfnSQLGetFunctions      pSQLGetFunctions;
pfnSQLAllocConnect      pSQLAllocConnect;
pfnSQLAllocEnv          pSQLAllocEnv;
pfnSQLAllocStmt         pSQLAllocStmt;
pfnSQLBindCol           pSQLBindCol;
pfnSQLCancel            pSQLCancel;
pfnSQLColAttributes     pSQLColAttributes;
pfnSQLConnect           pSQLConnect;
pfnSQLDescribeCol       pSQLDescribeCol;
pfnSQLDisconnect        pSQLDisconnect;
pfnSQLError             pSQLError;
pfnSQLExecDirect        pSQLExecDirect;
pfnSQLExecute           pSQLExecute;
pfnSQLFetch             pSQLFetch;
pfnSQLGetDiagRec        pSQLGetDiagRec;
pfnSQLFreeHandle        pSQLFreeHandle;
pfnSQLFetchScroll       pSQLFetchScroll;
pfnSQLColAttribute      pSQLColAttribute;
pfnSQLSetConnectAttr    pSQLSetConnectAttr;
pfnSQLDriverConnect     pSQLDriverConnect;
pfnSQLAllocHandle       pSQLAllocHandle;
pfnSQLRowCount          pSQLRowCount;
pfnSQLNumResultCols     pSQLNumResultCols;
pfnSQLEndTran           pSQLEndTran;
pfnSQLTables            pSQLTables;
pfnSQLColumns           pSQLColumns;
pfnSQLBindParameter     pSQLBindParameter;
pfnSQLPrimaryKeys       pSQLPrimaryKeys;
pfnSQLSetEnvAttr        pSQLSetEnvAttr  ;
pfnSQLFreeConnect       pSQLFreeConnect;
pfnSQLFreeEnv           pSQLFreeEnv;
pfnSQLFreeStmt          pSQLFreeStmt;
pfnSQLGetCursorName     pSQLGetCursorName;
pfnSQLPrepare           pSQLPrepare;
pfnSQLSetCursorName     pSQLSetCursorName;
pfnSQLTransact          pSQLTransact;
pfnSQLSetConnectOption  pSQLSetConnectOption;
pfnSQLDrivers           pSQLDrivers;
pfnSQLDataSources       pSQLDataSources;
pfnSQLGetInfo           pSQLGetInfo;
pfnSQLMoreResults       pSQLMoreResults;

//#define LOAD_ENTRY( hMod, Name ) (p##Name = (pfn##Name) GetProcAddress( (hMod), #Name ))
#define LOAD_ENTRY( hMod, Name ) (p##Name = (pfn##Name) GetFunction( (hMod), #Name ))

static BOOL  s_fODBCLoaded = false;

BOOL DynLoadODBC( char* odbcModuleName )
{
#ifdef _WIN32
    HMODULE hMod;
#elif defined(__GNUC__) // GNU compiler
    void* hMod;
#endif

    if ( s_fODBCLoaded )
      return true;

 //   if ( (hMod = (HMODULE) LoadLibrary( odbcModuleName ))) {
#ifdef _WIN32
  if ( (hMod = (HMODULE) LoadSharedLibrary( odbcModuleName ))) {
#elif defined(__GNUC__) // GNU compiler
  if ( (hMod = (void *) LoadSharedLibrary( odbcModuleName ))) {
#endif

//#if (ODBCVER < 0x0300)
  if (LOAD_ENTRY( hMod, SQLGetData   )  )
  if (LOAD_ENTRY( hMod, SQLGetFunctions   )  )
  if (LOAD_ENTRY( hMod, SQLAllocConnect   )  )
  if (LOAD_ENTRY( hMod, SQLAllocEnv       )  )
  if (LOAD_ENTRY( hMod, SQLAllocStmt      )  )
  if (LOAD_ENTRY( hMod, SQLColAttributes  )  )
  if (LOAD_ENTRY( hMod, SQLError          )  )
  if (LOAD_ENTRY( hMod, SQLFreeConnect    )  )
  if (LOAD_ENTRY( hMod, SQLFreeEnv        )  )
  if (LOAD_ENTRY( hMod, SQLTransact       )  )
  if (LOAD_ENTRY( hMod, SQLSetConnectOption )  )
  if (LOAD_ENTRY( hMod, SQLDrivers        )  )
  if (LOAD_ENTRY( hMod, SQLDataSources    )  )
//#endif
  if (LOAD_ENTRY( hMod, SQLBindCol        )  )
  if (LOAD_ENTRY( hMod, SQLCancel         )  )
  if (LOAD_ENTRY( hMod, SQLConnect       )  )
  if (LOAD_ENTRY( hMod, SQLDescribeCol    )  )
  if (LOAD_ENTRY( hMod, SQLDisconnect     )  )
  if (LOAD_ENTRY( hMod, SQLExecDirect     )  )
  if (LOAD_ENTRY( hMod, SQLExecute        )  )
  if (LOAD_ENTRY( hMod, SQLFetch          )  )
  if (LOAD_ENTRY( hMod, SQLGetDiagRec     )  )
  if (LOAD_ENTRY( hMod, SQLFreeHandle     )  )
  if (LOAD_ENTRY( hMod, SQLFetchScroll    )  )
  if (LOAD_ENTRY( hMod, SQLColAttribute   )  )
  if (LOAD_ENTRY( hMod, SQLSetConnectAttr )  )
  if (LOAD_ENTRY( hMod, SQLDriverConnect   )  )
  if (LOAD_ENTRY( hMod, SQLAllocHandle   )  )
  if (LOAD_ENTRY( hMod, SQLRowCount     )  )
  if (LOAD_ENTRY( hMod, SQLNumResultCols   )  )
  if (LOAD_ENTRY( hMod, SQLEndTran     )  )
  if (LOAD_ENTRY( hMod, SQLTables)  )
  if (LOAD_ENTRY( hMod, SQLColumns)  )
  if (LOAD_ENTRY( hMod, SQLBindParameter)  )
  if (LOAD_ENTRY( hMod, SQLPrimaryKeys)  )
  if (LOAD_ENTRY( hMod, SQLSetEnvAttr)  )
  if (LOAD_ENTRY( hMod, SQLFreeStmt       )  )
  if (LOAD_ENTRY( hMod, SQLNumResultCols  )  )
  if (LOAD_ENTRY( hMod, SQLPrepare        )  )
  if (LOAD_ENTRY( hMod, SQLRowCount       )  )
  if (LOAD_ENTRY( hMod, SQLGetInfo        )  )
  if (LOAD_ENTRY( hMod, SQLBindParameter  )  )
  if (LOAD_ENTRY( hMod, SQLMoreResults    )
          ) {

          s_fODBCLoaded = true;
      }
  }

  return (s_fODBCLoaded);
}
#endif<commit_msg>dynodbc: if dlsym fails, printf the function not loaded<commit_after>#ifdef dynodbc

#include "dynodbc.h"
#include <stdio.h>

#ifdef _WIN32
  #include <windows.h>
#elif defined(__GNUC__) // GNU compiler
  #include <dlfcn.h>
#else
#error define your copiler
#endif

#include<string>
/*
#define RTLD_LAZY   1
#define RTLD_NOW    2
#define RTLD_GLOBAL 4
*/

void* LoadSharedLibrary(char *pcDllname, int iMode = 2)
{
  std::string sDllName = pcDllname;
#ifdef _WIN32
  sDllName += ".dll";
  return (void*)LoadLibraryA(pcDllname);
#elif defined(__GNUC__) // GNU compiler
  sDllName += ".so";
  void* handle = dlopen(sDllName.c_str(),iMode);

  if (!handle) {
    printf("node-odbc: error loading ODBC library: %s\n", dlerror());
  }

  return handle;
#endif
}

void* GetFunction(void *Lib, char *Fnname)
{
#if defined(_MSC_VER) // Microsoft compiler
  return (void*)GetProcAddress((HINSTANCE)Lib,Fnname);
#elif defined(__GNUC__) // GNU compiler
  void * tmp = dlsym(Lib, Fnname);
  if (!tmp) {
    printf("node-odbc: error loading function: %s\n", Fnname);
  }
  return tmp;
#endif
}

bool FreeSharedLibrary(void *hDLL)
{
#if defined(_MSC_VER) // Microsoft compiler
  return (FreeLibrary((HINSTANCE)hDLL)!=0);
#elif defined(__GNUC__) // GNU compiler
  return dlclose(hDLL);
#endif
}

pfnSQLGetData           pSQLGetData;
pfnSQLGetFunctions      pSQLGetFunctions;
pfnSQLAllocConnect      pSQLAllocConnect;
pfnSQLAllocEnv          pSQLAllocEnv;
pfnSQLAllocStmt         pSQLAllocStmt;
pfnSQLBindCol           pSQLBindCol;
pfnSQLCancel            pSQLCancel;
pfnSQLColAttributes     pSQLColAttributes;
pfnSQLConnect           pSQLConnect;
pfnSQLDescribeCol       pSQLDescribeCol;
pfnSQLDisconnect        pSQLDisconnect;
pfnSQLError             pSQLError;
pfnSQLExecDirect        pSQLExecDirect;
pfnSQLExecute           pSQLExecute;
pfnSQLFetch             pSQLFetch;
pfnSQLGetDiagRec        pSQLGetDiagRec;
pfnSQLFreeHandle        pSQLFreeHandle;
pfnSQLFetchScroll       pSQLFetchScroll;
pfnSQLColAttribute      pSQLColAttribute;
pfnSQLSetConnectAttr    pSQLSetConnectAttr;
pfnSQLDriverConnect     pSQLDriverConnect;
pfnSQLAllocHandle       pSQLAllocHandle;
pfnSQLRowCount          pSQLRowCount;
pfnSQLNumResultCols     pSQLNumResultCols;
pfnSQLEndTran           pSQLEndTran;
pfnSQLTables            pSQLTables;
pfnSQLColumns           pSQLColumns;
pfnSQLBindParameter     pSQLBindParameter;
pfnSQLPrimaryKeys       pSQLPrimaryKeys;
pfnSQLSetEnvAttr        pSQLSetEnvAttr  ;
pfnSQLFreeConnect       pSQLFreeConnect;
pfnSQLFreeEnv           pSQLFreeEnv;
pfnSQLFreeStmt          pSQLFreeStmt;
pfnSQLGetCursorName     pSQLGetCursorName;
pfnSQLPrepare           pSQLPrepare;
pfnSQLSetCursorName     pSQLSetCursorName;
pfnSQLTransact          pSQLTransact;
pfnSQLSetConnectOption  pSQLSetConnectOption;
pfnSQLDrivers           pSQLDrivers;
pfnSQLDataSources       pSQLDataSources;
pfnSQLGetInfo           pSQLGetInfo;
pfnSQLMoreResults       pSQLMoreResults;

//#define LOAD_ENTRY( hMod, Name ) (p##Name = (pfn##Name) GetProcAddress( (hMod), #Name ))
#define LOAD_ENTRY( hMod, Name ) (p##Name = (pfn##Name) GetFunction( (hMod), #Name ))

static BOOL  s_fODBCLoaded = false;

BOOL DynLoadODBC( char* odbcModuleName )
{
#ifdef _WIN32
    HMODULE hMod;
#elif defined(__GNUC__) // GNU compiler
    void* hMod;
#endif

    if ( s_fODBCLoaded )
      return true;

 //   if ( (hMod = (HMODULE) LoadLibrary( odbcModuleName ))) {
#ifdef _WIN32
  if ( (hMod = (HMODULE) LoadSharedLibrary( odbcModuleName ))) {
#elif defined(__GNUC__) // GNU compiler
  if ( (hMod = (void *) LoadSharedLibrary( odbcModuleName ))) {
#endif

//#if (ODBCVER < 0x0300)
  if (LOAD_ENTRY( hMod, SQLGetData   )  )
  if (LOAD_ENTRY( hMod, SQLGetFunctions   )  )
  if (LOAD_ENTRY( hMod, SQLAllocConnect   )  )
  if (LOAD_ENTRY( hMod, SQLAllocEnv       )  )
  if (LOAD_ENTRY( hMod, SQLAllocStmt      )  )
  if (LOAD_ENTRY( hMod, SQLColAttributes  )  )
  if (LOAD_ENTRY( hMod, SQLError          )  )
  if (LOAD_ENTRY( hMod, SQLFreeConnect    )  )
  if (LOAD_ENTRY( hMod, SQLFreeEnv        )  )
  if (LOAD_ENTRY( hMod, SQLTransact       )  )
  if (LOAD_ENTRY( hMod, SQLSetConnectOption )  )
  if (LOAD_ENTRY( hMod, SQLDrivers        )  )
  if (LOAD_ENTRY( hMod, SQLDataSources    )  )
//#endif
  if (LOAD_ENTRY( hMod, SQLBindCol        )  )
  if (LOAD_ENTRY( hMod, SQLCancel         )  )
  if (LOAD_ENTRY( hMod, SQLConnect       )  )
  if (LOAD_ENTRY( hMod, SQLDescribeCol    )  )
  if (LOAD_ENTRY( hMod, SQLDisconnect     )  )
  if (LOAD_ENTRY( hMod, SQLExecDirect     )  )
  if (LOAD_ENTRY( hMod, SQLExecute        )  )
  if (LOAD_ENTRY( hMod, SQLFetch          )  )
  if (LOAD_ENTRY( hMod, SQLGetDiagRec     )  )
  if (LOAD_ENTRY( hMod, SQLFreeHandle     )  )
  if (LOAD_ENTRY( hMod, SQLFetchScroll    )  )
  if (LOAD_ENTRY( hMod, SQLColAttribute   )  )
  if (LOAD_ENTRY( hMod, SQLSetConnectAttr )  )
  if (LOAD_ENTRY( hMod, SQLDriverConnect   )  )
  if (LOAD_ENTRY( hMod, SQLAllocHandle   )  )
  if (LOAD_ENTRY( hMod, SQLRowCount     )  )
  if (LOAD_ENTRY( hMod, SQLNumResultCols   )  )
  if (LOAD_ENTRY( hMod, SQLEndTran     )  )
  if (LOAD_ENTRY( hMod, SQLTables)  )
  if (LOAD_ENTRY( hMod, SQLColumns)  )
  if (LOAD_ENTRY( hMod, SQLBindParameter)  )
  if (LOAD_ENTRY( hMod, SQLPrimaryKeys)  )
  if (LOAD_ENTRY( hMod, SQLSetEnvAttr)  )
  if (LOAD_ENTRY( hMod, SQLFreeStmt       )  )
  if (LOAD_ENTRY( hMod, SQLNumResultCols  )  )
  if (LOAD_ENTRY( hMod, SQLPrepare        )  )
  if (LOAD_ENTRY( hMod, SQLRowCount       )  )
  if (LOAD_ENTRY( hMod, SQLGetInfo        )  )
  if (LOAD_ENTRY( hMod, SQLBindParameter  )  )
  if (LOAD_ENTRY( hMod, SQLMoreResults    )
          ) {

          s_fODBCLoaded = true;
      }
  }

  return (s_fODBCLoaded);
}
#endif
<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include "GeocastBroadcastFilter.h"

#include <string>

#include <boost/geometry.hpp>

#include "joynr/serializer/Serializer.h"

GeocastBroadcastFilter::GeocastBroadcastFilter()
{
}

bool GeocastBroadcastFilter::filter(
        const joynr::vehicle::RadioStation& discoveredStation,
        const joynr::vehicle::GeoPosition& geoPosition,
        const vehicle::RadioNewStationDiscoveredBroadcastFilterParameters& filterParameters)
{
    if (filterParameters.getPositionOfInterest().empty() ||
        filterParameters.getRadiusOfInterestArea().empty()) {
        // filter parameter not set, so we do no filtering
        return true;
    }

    joynr::vehicle::GeoPosition positionOfInterest;
    try {
        joynr::serializer::deserializeFromJson(
                positionOfInterest, filterParameters.getPositionOfInterest());
    } catch (const std::invalid_argument& e) {
        JOYNR_LOG_ERROR(logger(),
                        "Unable to deserialize geo position object from: {} - error: {}",
                        filterParameters.getPositionOfInterest(),
                        e.what());
        return true;
    }
    int radiusOfInterestArea = std::stoi(filterParameters.getRadiusOfInterestArea());

    // calculate distance between two geo positions using the haversine formula
    // (cf. http://en.wikipedia.org/wiki/Haversine_formula)
    double earthRadius = 6371000.0; // in meters

    typedef boost::geometry::model::point<
            double,
            2,
            boost::geometry::cs::spherical_equatorial<boost::geometry::degree>> BoostGeoPosition;

    BoostGeoPosition boostGeoPosition(geoPosition.getLatitude(), geoPosition.getLongitude());
    BoostGeoPosition boostPositionOfInterest(
            positionOfInterest.getLatitude(), positionOfInterest.getLongitude());

    double distance = boost::geometry::distance(
            boostGeoPosition,
            boostPositionOfInterest,
            boost::geometry::strategy::distance::haversine<double>(earthRadius));

    return distance < radiusOfInterestArea;
}
<commit_msg>[C++] Ignore unused parameter in GeocastBroadcastFilter<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
#include "GeocastBroadcastFilter.h"

#include <string>

#include <boost/geometry.hpp>

#include "joynr/serializer/Serializer.h"

GeocastBroadcastFilter::GeocastBroadcastFilter()
{
}

bool GeocastBroadcastFilter::filter(
        const joynr::vehicle::RadioStation& discoveredStation,
        const joynr::vehicle::GeoPosition& geoPosition,
        const vehicle::RadioNewStationDiscoveredBroadcastFilterParameters& filterParameters)
{
    std::ignore = discoveredStation;

    if (filterParameters.getPositionOfInterest().empty() ||
        filterParameters.getRadiusOfInterestArea().empty()) {
        // filter parameter not set, so we do no filtering
        return true;
    }

    joynr::vehicle::GeoPosition positionOfInterest;
    try {
        joynr::serializer::deserializeFromJson(
                positionOfInterest, filterParameters.getPositionOfInterest());
    } catch (const std::invalid_argument& e) {
        JOYNR_LOG_ERROR(logger(),
                        "Unable to deserialize geo position object from: {} - error: {}",
                        filterParameters.getPositionOfInterest(),
                        e.what());
        return true;
    }
    int radiusOfInterestArea = std::stoi(filterParameters.getRadiusOfInterestArea());

    // calculate distance between two geo positions using the haversine formula
    // (cf. http://en.wikipedia.org/wiki/Haversine_formula)
    double earthRadius = 6371000.0; // in meters

    typedef boost::geometry::model::point<
            double,
            2,
            boost::geometry::cs::spherical_equatorial<boost::geometry::degree>> BoostGeoPosition;

    BoostGeoPosition boostGeoPosition(geoPosition.getLatitude(), geoPosition.getLongitude());
    BoostGeoPosition boostPositionOfInterest(
            positionOfInterest.getLatitude(), positionOfInterest.getLongitude());

    double distance = boost::geometry::distance(
            boostGeoPosition,
            boostPositionOfInterest,
            boost::geometry::strategy::distance::haversine<double>(earthRadius));

    return distance < radiusOfInterestArea;
}
<|endoftext|>


<commit_before>/**
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 <utility>
#include <memory>
#include <string>
#include <vector>
#include <set>
#include <fstream>

#include "TestBase.h"
#include "LogAttribute.h"
#include "GetFile.h"

#ifdef WIN32
#include <fileapi.h>
#endif

/**
 * This is an invalidly named test as we can't guarantee order, nor shall we.
 */
TEST_CASE("GetFile: MaxSize", "[getFileFifo]") {  // NOLINT
  TestController testController;

  LogTestController::getInstance().setTrace<TestPlan>();
  LogTestController::getInstance().setTrace<processors::GetFile>();
  LogTestController::getInstance().setTrace<processors::LogAttribute>();

  auto plan = testController.createPlan();
  auto repo = std::make_shared<TestRepository>();

  // Define directory for input
  char in_dir[] = "/tmp/gt.XXXXXX";
  auto temp_path = testController.createTempDirectory(in_dir);
  REQUIRE(!temp_path.empty());

  // Define test input file
  std::string in_file = temp_path + utils::file::FileUtils::get_separator() + "testfifo";

  // Define test input file
  std::string hidden_in_file(in_dir);
  hidden_in_file.append("/.testfifo");  // hidden

  // Build MiNiFi processing graph

  auto get_file = plan->addProcessor("GetFile", "Get");
  plan->setProperty(get_file, processors::GetFile::Directory.getName(), temp_path);
  plan->setProperty(get_file, processors::GetFile::KeepSourceFile.getName(), "true");
  plan->setProperty(get_file, processors::GetFile::MaxSize.getName(), "50 B");
  plan->setProperty(get_file, processors::GetFile::IgnoreHiddenFile.getName(), "true");
  auto log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
  plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");

  // Write test input.
  std::ofstream in_file_stream(in_file);
  in_file_stream << "The quick brown fox jumps over the lazy dog" << std::endl;
  in_file_stream.close();

  std::this_thread::sleep_for(std::chrono::seconds(2));

  in_file_stream.open(in_file + "2");
  in_file_stream << "The quick brown fox jumps over the lazy dog who is 2 legit to quit" << std::endl;
  in_file_stream.close();

  std::ofstream hidden_in_file_stream(hidden_in_file);
  hidden_in_file_stream << "But noone has ever seen it" << std::endl;
  hidden_in_file_stream.close();
#ifdef WIN32
  REQUIRE(SetFileAttributesA(hidden_in_file.c_str(), FILE_ATTRIBUTE_HIDDEN));
#endif
  plan->runNextProcessor();  // Get
  plan->runNextProcessor();  // Log

  REQUIRE(LogTestController::getInstance().contains("Logged 1 flow files"));  // The hidden and the too big files should be ignored
  // Check log output on windows std::endl; will produce \r\n can write manually but might as well just
  // account for the size difference here
  REQUIRE(LogTestController::getInstance().contains("key:flow.id"));
#ifdef WIN32
  REQUIRE(LogTestController::getInstance().contains("Size:45 Offset:0"));
#else
  REQUIRE(LogTestController::getInstance().contains("Size:44 Offset:0"));
#endif
}

<commit_msg>MINIFICPP-1072 - Fixed temporary path for GetFileTests on Windows<commit_after>/**
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 <utility>
#include <memory>
#include <string>
#include <vector>
#include <set>
#include <fstream>

#include "TestBase.h"
#include "LogAttribute.h"
#include "GetFile.h"

#ifdef WIN32
#include <fileapi.h>
#endif

/**
 * This is an invalidly named test as we can't guarantee order, nor shall we.
 */
TEST_CASE("GetFile: MaxSize", "[getFileFifo]") {  // NOLINT
  TestController testController;

  LogTestController::getInstance().setTrace<TestPlan>();
  LogTestController::getInstance().setTrace<processors::GetFile>();
  LogTestController::getInstance().setTrace<processors::LogAttribute>();

  auto plan = testController.createPlan();
  auto repo = std::make_shared<TestRepository>();

  // Define directory for input
  char in_dir[] = "/tmp/gt.XXXXXX";
  auto temp_path = testController.createTempDirectory(in_dir);
  REQUIRE(!temp_path.empty());

  // Define test input file
  std::string in_file(temp_path + utils::file::FileUtils::get_separator() + "testfifo");
  std::string hidden_in_file(temp_path + utils::file::FileUtils::get_separator() + ".testfifo");

  // Build MiNiFi processing graph

  auto get_file = plan->addProcessor("GetFile", "Get");
  plan->setProperty(get_file, processors::GetFile::Directory.getName(), temp_path);
  plan->setProperty(get_file, processors::GetFile::KeepSourceFile.getName(), "true");
  plan->setProperty(get_file, processors::GetFile::MaxSize.getName(), "50 B");
  plan->setProperty(get_file, processors::GetFile::IgnoreHiddenFile.getName(), "true");
  auto log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true);
  plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0");

  // Write test input.
  std::ofstream in_file_stream(in_file);
  in_file_stream << "The quick brown fox jumps over the lazy dog" << std::endl;
  in_file_stream.close();

  std::this_thread::sleep_for(std::chrono::seconds(2));

  in_file_stream.open(in_file + "2");
  in_file_stream << "The quick brown fox jumps over the lazy dog who is 2 legit to quit" << std::endl;
  in_file_stream.close();

  std::ofstream hidden_in_file_stream(hidden_in_file);
  hidden_in_file_stream << "But noone has ever seen it" << std::endl;
  hidden_in_file_stream.close();
#ifdef WIN32
  REQUIRE(SetFileAttributesA(hidden_in_file.c_str(), FILE_ATTRIBUTE_HIDDEN));
#endif
  plan->runNextProcessor();  // Get
  plan->runNextProcessor();  // Log

  REQUIRE(LogTestController::getInstance().contains("Logged 1 flow files"));  // The hidden and the too big files should be ignored
  // Check log output on windows std::endl; will produce \r\n can write manually but might as well just
  // account for the size difference here
  REQUIRE(LogTestController::getInstance().contains("key:flow.id"));
#ifdef WIN32
  REQUIRE(LogTestController::getInstance().contains("Size:45 Offset:0"));
#else
  REQUIRE(LogTestController::getInstance().contains("Size:44 Offset:0"));
#endif
}

<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef __itkDiffusionTensor3D_hxx
#define __itkDiffusionTensor3D_hxx

#include "itkDiffusionTensor3D.h"
#include "itkNumericTraits.h"

namespace itk
{
/**
 * Default Constructor
 */
template< class T >
DiffusionTensor3D< T >
::DiffusionTensor3D()
{}

/**
 * Constructor with initialization
 */
template< class T >
DiffusionTensor3D< T >
::DiffusionTensor3D(const Superclass & r):SymmetricSecondRankTensor< T, 3 >(r)
{}

/**
 * Constructor with initialization
 */
template< class T >
DiffusionTensor3D< T >
::DiffusionTensor3D(const ComponentType & r):SymmetricSecondRankTensor< T, 3 >(r)
{}

/**
 * Constructor with initialization
 */
template< class T >
DiffusionTensor3D< T >
::DiffusionTensor3D(const ComponentArrayType r):SymmetricSecondRankTensor< T, 3 >(r)
{}

/**
 * Assignment Operator
 */
template< class T >
DiffusionTensor3D< T > &
DiffusionTensor3D< T >
::operator=(const ComponentType & r)
{
  Superclass::operator=(r);
  return *this;
}

/**
 * Assignment Operator
 */
template< class T >
DiffusionTensor3D< T > &
DiffusionTensor3D< T >
::operator=(const ComponentArrayType r)
{
  Superclass::operator=(r);
  return *this;
}

/**
 * Assignment Operator
 */
template< class T >
DiffusionTensor3D< T > &
DiffusionTensor3D< T >
::operator=(const Superclass & r)
{
  Superclass::operator=(r);
  return *this;
}

/**
 * Get the Trace, specialized version for 3D.
 *
 * Note that the indices are related to the fact
 * that we store only the upper-right triangle of
 * the matrix. Like
 *
 *       | 0  1  2  |
 *       | X  3  4  |
 *       | X  X  5  |
 *
 * The trace is therefore the sum of the components
 * M[0], M[3] and M[5].
 *
 */
template< class T >
typename DiffusionTensor3D< T >::AccumulateValueType
DiffusionTensor3D< T >
::GetTrace() const
{
  AccumulateValueType trace = ( *this )[0];

  trace += ( *this )[3];
  trace += ( *this )[5];
  return trace;
}

/**
 *  Compute the value of fractional anisotropy
 */
template< class T >
typename DiffusionTensor3D< T >::RealValueType
DiffusionTensor3D< T >
::GetFractionalAnisotropy() const
{
  // Computed as
  // FA = vcl_sqrt(1.5*sum(sum(N.*N))/sum((sum(D.*D))))
  // where N = D - ((1/3)*trace(D)*eye(3,3))
  // equation (28) in
  // http://lmi.bwh.harvard.edu/papers/pdfs/2002/westinMEDIA02.pdf
  const RealValueType isp   = this->GetInnerScalarProduct();

  if ( isp > 0.0 )
    {
    const RealValueType trace = this->GetTrace();
    const RealValueType anisotropy = 3.0 * isp - trace * trace;
    const RealValueType fractionalAnisotropy =
      static_cast< RealValueType >( vcl_sqrt( anisotropy / ( 2.0 * isp ) ) );
    return fractionalAnisotropy;
    }

  return 0.0;
}

/**
 *  Compute the value of relative anisotropy
 */
template< class T >
typename DiffusionTensor3D< T >::RealValueType
DiffusionTensor3D< T >
::GetRelativeAnisotropy() const
{
  const RealValueType trace = this->GetTrace();
  const RealValueType isp   = this->GetInnerScalarProduct();

  // Avoid negative trace and traces small enough to look like a division by
  // zero.
  if ( trace < NumericTraits< RealValueType >::min() )
    {
    return NumericTraits< RealValueType >::Zero;
    }

  const RealValueType anisotropy = 3.0 * isp - trace * trace;

  if ( anisotropy  < NumericTraits< RealValueType >::Zero )
    {
    return NumericTraits< RealValueType >::Zero;
    }

  const RealValueType relativeAnisotropySquared =
    static_cast< RealValueType >( anisotropy / ( vcl_sqrt(3.0) * trace ) );

  const RealValueType relativeAnisotropy =
    static_cast< RealValueType >( vcl_sqrt(relativeAnisotropySquared) );

  return relativeAnisotropy;
}

/**
 *  Compute the inner scalar product
 */
template< class T >
typename DiffusionTensor3D< T >::RealValueType
DiffusionTensor3D< T >
::GetInnerScalarProduct() const
{
  const RealValueType xx = ( *this )[0];
  const RealValueType xy = ( *this )[1];
  const RealValueType xz = ( *this )[2];
  const RealValueType yy = ( *this )[3];
  const RealValueType yz = ( *this )[4];
  const RealValueType zz = ( *this )[5];

  return ( xx * xx + yy * yy + zz * zz + 2.0 * ( xy * xy + xz * xz + yz * yz ) );
}
} // end namespace itk

#endif
<commit_msg>BUG: Return of NaN by DiffusionTensor3D::GetFractionalAnisotropy<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef __itkDiffusionTensor3D_hxx
#define __itkDiffusionTensor3D_hxx

#include "itkDiffusionTensor3D.h"
#include "itkNumericTraits.h"

namespace itk
{
/**
 * Default Constructor
 */
template< class T >
DiffusionTensor3D< T >
::DiffusionTensor3D()
{}

/**
 * Constructor with initialization
 */
template< class T >
DiffusionTensor3D< T >
::DiffusionTensor3D(const Superclass & r):SymmetricSecondRankTensor< T, 3 >(r)
{}

/**
 * Constructor with initialization
 */
template< class T >
DiffusionTensor3D< T >
::DiffusionTensor3D(const ComponentType & r):SymmetricSecondRankTensor< T, 3 >(r)
{}

/**
 * Constructor with initialization
 */
template< class T >
DiffusionTensor3D< T >
::DiffusionTensor3D(const ComponentArrayType r):SymmetricSecondRankTensor< T, 3 >(r)
{}

/**
 * Assignment Operator
 */
template< class T >
DiffusionTensor3D< T > &
DiffusionTensor3D< T >
::operator=(const ComponentType & r)
{
  Superclass::operator=(r);
  return *this;
}

/**
 * Assignment Operator
 */
template< class T >
DiffusionTensor3D< T > &
DiffusionTensor3D< T >
::operator=(const ComponentArrayType r)
{
  Superclass::operator=(r);
  return *this;
}

/**
 * Assignment Operator
 */
template< class T >
DiffusionTensor3D< T > &
DiffusionTensor3D< T >
::operator=(const Superclass & r)
{
  Superclass::operator=(r);
  return *this;
}

/**
 * Get the Trace, specialized version for 3D.
 *
 * Note that the indices are related to the fact
 * that we store only the upper-right triangle of
 * the matrix. Like
 *
 *       | 0  1  2  |
 *       | X  3  4  |
 *       | X  X  5  |
 *
 * The trace is therefore the sum of the components
 * M[0], M[3] and M[5].
 *
 */
template< class T >
typename DiffusionTensor3D< T >::AccumulateValueType
DiffusionTensor3D< T >
::GetTrace() const
{
  AccumulateValueType trace = ( *this )[0];

  trace += ( *this )[3];
  trace += ( *this )[5];
  return trace;
}

/**
 *  Compute the value of fractional anisotropy
 */
template< class T >
typename DiffusionTensor3D< T >::RealValueType
DiffusionTensor3D< T >
::GetFractionalAnisotropy() const
{
  // Computed as
  // FA = vcl_sqrt(1.5*sum(sum(N.*N))/sum((sum(D.*D))))
  // where N = D - ((1/3)*trace(D)*eye(3,3))
  // equation (28) in
  // http://lmi.bwh.harvard.edu/papers/pdfs/2002/westinMEDIA02.pdf
  const RealValueType isp   = this->GetInnerScalarProduct();

  if ( isp > 0.0 )
    {
    const RealValueType trace = this->GetTrace();
    const RealValueType anisotropy = 3.0 * isp - trace * trace;
    // sometimes anisotropy has been reported to be a small negative
    // number, and then vcl_sqrt returns NaN.  If it is a small
    // negative number, the obvious thing is to round to zero. If
    // it is a larger negative number, I'm not sure what the proper
    // result would be.  In either case, returning zero makes as much
    // sense in those cases as any other number.
    if(anisotropy > 0.0)
      {
      const RealValueType fractionalAnisotropy =
        static_cast< RealValueType >( vcl_sqrt( anisotropy / ( 2.0 * isp ) ) );
      return fractionalAnisotropy;
      }
    }

  return 0.0;
}

/**
 *  Compute the value of relative anisotropy
 */
template< class T >
typename DiffusionTensor3D< T >::RealValueType
DiffusionTensor3D< T >
::GetRelativeAnisotropy() const
{
  const RealValueType trace = this->GetTrace();
  const RealValueType isp   = this->GetInnerScalarProduct();

  // Avoid negative trace and traces small enough to look like a division by
  // zero.
  if ( trace < NumericTraits< RealValueType >::min() )
    {
    return NumericTraits< RealValueType >::Zero;
    }

  const RealValueType anisotropy = 3.0 * isp - trace * trace;

  if ( anisotropy  < NumericTraits< RealValueType >::Zero )
    {
    return NumericTraits< RealValueType >::Zero;
    }

  const RealValueType relativeAnisotropySquared =
    static_cast< RealValueType >( anisotropy / ( vcl_sqrt(3.0) * trace ) );

  const RealValueType relativeAnisotropy =
    static_cast< RealValueType >( vcl_sqrt(relativeAnisotropySquared) );

  return relativeAnisotropy;
}

/**
 *  Compute the inner scalar product
 */
template< class T >
typename DiffusionTensor3D< T >::RealValueType
DiffusionTensor3D< T >
::GetInnerScalarProduct() const
{
  const RealValueType xx = ( *this )[0];
  const RealValueType xy = ( *this )[1];
  const RealValueType xz = ( *this )[2];
  const RealValueType yy = ( *this )[3];
  const RealValueType yz = ( *this )[4];
  const RealValueType zz = ( *this )[5];

  return ( xx * xx + yy * yy + zz * zz + 2.0 * ( xy * xy + xz * xz + yz * yz ) );
}
} // end namespace itk

#endif
<|endoftext|>


<commit_before>#include "mgdFunc.hpp"
#include "../obj.hpp"
#include "../../builtin/container/native/tnchain.inl"
#include "../../frame/thread.hpp"
#include "../../loader/interpreter/tverification.hpp"
#include "../params.hpp"
#include "../../builtin/primitive/wVoid.hpp"

namespace wrd {

    WRD_DEF_ME(mgdFunc)

    str me::run(const ucontainable& args) {
        if(!_inFrame(*_evalArgs(args)))
            return str();

        str ret = _blk->run();
        _outFrame();
        return ret;
    }

    scope* me::_evalArgs(const ucontainable& args) {
        const params& ps = getParams();
        if(args.len() != ps.len())
            return WRD_E("length of args(%d) and typs(%d) doesn't match.", args.len(), ps.len()), nullptr;

        scope* ret = new scope();
        int n = 0;
        for(const node& e: args) {
            const param& p = ps[n++];
            str evaluated = e.as(p.getOrigin());
            if(!evaluated) return nullptr;

            ret->add(p.getName(), *evaluated);
        }
        return ret;
    }

    wbool me::_inFrame(scope& s) {
        frame& fr = thread::get()._getNowFrame();
        if(nul(fr)) return WRD_E("fr == null"), false;
        if(nul(s)) return WRD_E("s == null"), false;

        WRD_DI("%s._onInFrame()", getType().getName().c_str());
        fr.pushLocal(subs());
        fr.setFunc(*this);
        return fr.pushLocal(s);
    }

    void me::_outFrame() {
        frame& fr = thread::get()._getNowFrame();
        WRD_DI("%s._onOutFrame()", getType().getName().c_str());
        fr.setFunc(nulOf<func>());
        fr.popLocal();
        fr.popLocal();
    }

    WRD_VERIFY({
        WRD_DI("verify: retType exists and stmts exist one at least");

        const wtype& retType = it.getRetType();
        if(nul(retType)) return _err(errCode::NO_RET_TYPE);
        if(!retType.isSub(ttype<node>::get()))
            return _err(errCode::WRONG_RET_TYPE, retType.getName().c_str());

        const blockExpr& blk = it.getBlock();
        if(nul(blk) || blk.getStmts().len() <= 0)
            return _err(errCode::NO_STMT_IN_FUNC);
    })

    namespace {
        void _prepareArgsAlongParam(const params& ps, scope& s) {
            for(const auto& p : ps)
                s.add(p.getName(), *p.getOrigin());
        }
    }

    // TODO: verify arguments

    WRD_VERIFY(mgdFunc, subNodes, {
        WRD_DI("verify: mgdFunc: %s iterateBlock[%d]", it.getType().getName().c_str(), it._blk->subs().len());
        scope s;
        _prepareArgsAlongParam(it.getParams(), s);

        it._inFrame(s);

        {
            WRD_DI("last stmt should match to ret type");

            const narr& stmts = it.getBlock().getStmts();
            if(nul(stmts) || stmts.len() <= 0) return; // will be catched to another verification.

            const wtype& retType = it.getRetType();
            const node& lastStmt = *stmts.last();
            if(!lastStmt.isSub<returnExpr>() && retType == ttype<wVoid>::get()) {
                WRD_DI("implicit return won't verify when retType is void.");
                return;
            }
            const wtype& lastType = lastStmt.getEvalType(); // to get type of expr, always uses evalType.
            if(nul(lastType)) return _err(NO_RET_TYPE);
            if(!lastType.isSub(retType)) return _err(errCode::RET_TYPE_NOT_MATCH, lastType.getName().c_str(),
                    retType.getName().c_str());
        }

        verify(*it._blk);
        it._outFrame();
    })
}
<commit_msg>wrd: refactor: let wrdSyntaxTest uses interpreter<commit_after>#include "mgdFunc.hpp"
#include "../obj.hpp"
#include "../../builtin/container/native/tnchain.inl"
#include "../../frame/thread.hpp"
#include "../../loader/interpreter/tverification.hpp"
#include "../params.hpp"
#include "../../builtin/primitive/wVoid.hpp"

namespace wrd {

    WRD_DEF_ME(mgdFunc)

    str me::run(const ucontainable& args) {
        if(!_inFrame(*_evalArgs(args)))
            return str();

        str ret = _blk->run();
        _outFrame();
        return ret;
    }

    scope* me::_evalArgs(const ucontainable& args) {
        const params& ps = getParams();
        if(args.len() != ps.len())
            return WRD_E("length of args(%d) and typs(%d) doesn't match.", args.len(), ps.len()), nullptr;

        scope* ret = new scope();
        int n = 0;
        for(const node& e: args) {
            const param& p = ps[n++];
            str evaluated = e.as(p.getOrigin());
            if(!evaluated) return nullptr;

            ret->add(p.getName(), *evaluated);
        }
        return ret;
    }

    wbool me::_inFrame(scope& s) {
        frame& fr = thread::get()._getNowFrame();
        if(nul(fr)) return WRD_E("fr == null"), false;
        if(nul(s)) return WRD_E("s == null"), false;

        WRD_DI("%s._onInFrame()", getType().getName().c_str());
        fr.pushLocal(subs());
        fr.setFunc(*this);
        return fr.pushLocal(s);
    }

    void me::_outFrame() {
        frame& fr = thread::get()._getNowFrame();
        WRD_DI("%s._onOutFrame()", getType().getName().c_str());
        fr.setFunc(nulOf<func>());
        fr.popLocal();
        fr.popLocal();
    }

    WRD_VERIFY({
        WRD_DI("verify: retType exists and stmts exist one at least");

        const wtype& retType = it.getRetType();
        if(nul(retType)) return _err(errCode::NO_RET_TYPE);
        if(!retType.isSub(ttype<node>::get()))
            return _err(errCode::WRONG_RET_TYPE, retType.getName().c_str());

        const blockExpr& blk = it.getBlock();
        if(nul(blk) || blk.getStmts().len() <= 0)
            return _err(errCode::NO_STMT_IN_FUNC);
    })

    namespace {
        void _prepareArgsAlongParam(const params& ps, scope& s) {
            for(const auto& p : ps)
                s.add(p.getName(), *p.getOrigin());
        }
    }

    // TODO: verify arguments

    WRD_VERIFY(mgdFunc, subNodes, {
        WRD_DI("verify: mgdFunc: %s iterateBlock[%d]", it.getType().getName().c_str(), it._blk->subs().len());
        scope* s = new scope();
        _prepareArgsAlongParam(it.getParams(), *s);

        it._inFrame(*s);

        {
            WRD_DI("last stmt should match to ret type");

            const narr& stmts = it.getBlock().getStmts();
            if(nul(stmts) || stmts.len() <= 0) return; // will be catched to another verification.

            const wtype& retType = it.getRetType();
            const node& lastStmt = *stmts.last();
            if(!lastStmt.isSub<returnExpr>() && retType == ttype<wVoid>::get()) {
                WRD_DI("implicit return won't verify when retType is void.");
                return;
            }
            const wtype& lastType = lastStmt.getEvalType(); // to get type of expr, always uses evalType.
            if(nul(lastType)) return _err(NO_RET_TYPE);
            if(!lastType.isSub(retType)) return _err(errCode::RET_TYPE_NOT_MATCH, lastType.getName().c_str(),
                    retType.getName().c_str());
        }

        verify(*it._blk);
        it._outFrame();
    })
}
<|endoftext|>


<commit_before>/**************************************************************************
 * The MIT License                                                        *
 * Copyright (c) 2013 Antony Arciuolo.                                    *
 * arciuolo@gmail.com                                                     *
 *                                                                        *
 * Permission is hereby granted, free of charge, to any person obtaining  *
 * a copy of this software and associated documentation files (the        *
 * "Software"), to deal in the Software without restriction, including    *
 * without limitation the rights to use, copy, modify, merge, publish,    *
 * distribute, sublicense, and/or sell copies of the Software, and to     *
 * permit persons to whom the Software is furnished to do so, subject to  *
 * the following conditions:                                              *
 *                                                                        *
 * The above copyright notice and this permission notice shall be         *
 * included in all copies or substantial portions of the Software.        *
 *                                                                        *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,        *
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF     *
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND                  *
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE *
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION *
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  *
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.        *
 **************************************************************************/
#include <oSurface/fill.h>
#include <oGUI/Windows/oGDI.h>
#include <oPlatform/oTest.h>
#include <oGUI/Windows/oWinRect.h>

namespace ouro
{

void core_fill_grid_numbers(surface::buffer* _pBuffer, const int2& _GridDimensions, color _NumberColor)
{
	surface::info si = _pBuffer->get_info();

	if (si.format != surface::b8g8r8a8_unorm)
		throw std::invalid_argument("only b8g8r8a8_unorm currently supported");

	oGDIScopedObject<HBITMAP> hBmp = windows::gdi::make_bitmap(_pBuffer);
	oGDIScopedGetDC hScreenDC(0);
	oGDIScopedDC hDC(CreateCompatibleDC(hScreenDC));

	font_info fd;
	fd.name = "Tahoma";
	fd.point_size = (oGDILogicalHeightToPoint(hDC, _GridDimensions.y) * 0.33f);
	fd.bold = fd.point_size < 15;
	oGDIScopedObject<HFONT> hFont(oGDICreateFont(fd));

	oGDIScopedSelect ScopedSelectBmp(hDC, hBmp);
	oGDIScopedSelect ScopedSelectFont(hDC, hFont);

	text_info td;
	td.alignment = alignment::middle_center;
	td.shadow = color(0);
	td.single_line = true;

	surface::fill_grid_numbers(si.dimensions.xy(), _GridDimensions,
		[&](const int2& _DrawBoxPosition, const int2& _DrawBoxSize, const char* _Text)->bool
	{
		td.position = _DrawBoxPosition;
		td.size = _DrawBoxSize;
		td.foreground = _NumberColor;
		return oGDIDrawText(hDC, td, _Text);
	});

	surface::lock_guard lock(_pBuffer);
	windows::gdi::memcpy2d(lock.mapped.data, lock.mapped.row_pitch, hBmp, si.dimensions.y, true);
}

} // namespace ouro
<commit_msg>Remove unnecessary headers<commit_after>/**************************************************************************
 * The MIT License                                                        *
 * Copyright (c) 2013 Antony Arciuolo.                                    *
 * arciuolo@gmail.com                                                     *
 *                                                                        *
 * Permission is hereby granted, free of charge, to any person obtaining  *
 * a copy of this software and associated documentation files (the        *
 * "Software"), to deal in the Software without restriction, including    *
 * without limitation the rights to use, copy, modify, merge, publish,    *
 * distribute, sublicense, and/or sell copies of the Software, and to     *
 * permit persons to whom the Software is furnished to do so, subject to  *
 * the following conditions:                                              *
 *                                                                        *
 * The above copyright notice and this permission notice shall be         *
 * included in all copies or substantial portions of the Software.        *
 *                                                                        *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,        *
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF     *
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND                  *
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE *
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION *
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION  *
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.        *
 **************************************************************************/
#include <oSurface/fill.h>
#include <oGUI/Windows/oGDI.h>

namespace ouro
{

void core_fill_grid_numbers(surface::buffer* _pBuffer, const int2& _GridDimensions, color _NumberColor)
{
	surface::info si = _pBuffer->get_info();

	if (si.format != surface::b8g8r8a8_unorm)
		throw std::invalid_argument("only b8g8r8a8_unorm currently supported");

	oGDIScopedObject<HBITMAP> hBmp = windows::gdi::make_bitmap(_pBuffer);
	oGDIScopedGetDC hScreenDC(0);
	oGDIScopedDC hDC(CreateCompatibleDC(hScreenDC));

	font_info fd;
	fd.name = "Tahoma";
	fd.point_size = (oGDILogicalHeightToPoint(hDC, _GridDimensions.y) * 0.33f);
	fd.bold = fd.point_size < 15;
	oGDIScopedObject<HFONT> hFont(oGDICreateFont(fd));

	oGDIScopedSelect ScopedSelectBmp(hDC, hBmp);
	oGDIScopedSelect ScopedSelectFont(hDC, hFont);

	text_info td;
	td.alignment = alignment::middle_center;
	td.shadow = color(0);
	td.single_line = true;

	surface::fill_grid_numbers(si.dimensions.xy(), _GridDimensions,
		[&](const int2& _DrawBoxPosition, const int2& _DrawBoxSize, const char* _Text)->bool
	{
		td.position = _DrawBoxPosition;
		td.size = _DrawBoxSize;
		td.foreground = _NumberColor;
		return oGDIDrawText(hDC, td, _Text);
	});

	surface::lock_guard lock(_pBuffer);
	windows::gdi::memcpy2d(lock.mapped.data, lock.mapped.row_pitch, hBmp, si.dimensions.y, true);
}

} // namespace ouro
<|endoftext|>


<commit_before>// now in options
//=============================================//
//const char* centralityEstimator = "V0M";
//const char* centralityEstimator = "CL1";
//const char* centralityEstimator = "TRK";
//=============================================//
//Bool_t gRunShuffling = kFALSE;
//Bool_t gRunShuffling = kTRUE;
//=============================================//

//PID config
Bool_t kUseNSigmaPID = kFALSE;
Double_t nSigmaMax = 3.0;
Bool_t kUseBayesianPID = kTRUE;
Double_t gMinAcceptedProbability = 0.7;

//_________________________________________________________//
AliAnalysisTaskBFPsi *AddTaskBalancePsiCentralityTrain(Double_t centrMin=0.,
						       Double_t centrMax=100.,
						       Bool_t gRunShuffling=kFALSE,
						       Bool_t gRunMixing=kTRUE,
						       Bool_t gRunMixingWithEventPlane=kFALSE,
						       TString centralityEstimator="V0M",
						       Double_t vertexZ=10.,
						       Double_t DCAxy=-1,
						       Double_t DCAz=-1,
						       Double_t ptMin=0.3,
						       Double_t ptMax=1.5,
						       Double_t etaMin=-0.8,
						       Double_t etaMax=0.8,
						       Double_t maxTPCchi2 = -1,
						       Int_t minNClustersTPC = -1,
						       Bool_t kUsePID = kFALSE,
						       Bool_t bResonancesCut = kTRUE,
						       Bool_t bHBTcut = kTRUE,
						       Bool_t bConversionCut = kTRUE,
						       Bool_t bMomentumDifferenceCut = kTRUE,
						       Int_t AODfilterBit = 128,
						       Bool_t bCentralTrigger = kFALSE,
						       TString fileNameBase="AnalysisResults",
						       TString fArgEventClass="Centrality",
						       TString analysisTypeUser="AOD",
						       Bool_t bVertexBinning=kTRUE) {
  // Creates a balance function analysis task and adds it to the analysis manager.
  // Get the pointer to the existing analysis manager via the static access method.
  TString outputFileName(fileNameBase);
  outputFileName.Append(".root");

  //===========================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskBF", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //===========================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskBF", "This task requires an input event handler");
    return NULL;
  }
  TString analysisType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  if(dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler())) analysisType = "MC";

  // to set the analysis type manually
  if(analysisTypeUser != ""){
    analysisType = analysisTypeUser;
    ::Info("AddTaskBF",Form("Analysis Type manually set to %s",analysisType.Data()));
  }

  // for local changed BF configuration
  //gROOT->LoadMacro("./configBalanceFunctionPsiAnalysis.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGCF/EBYE/macros/configBalanceFunctionPsiAnalysis.C");
  AliBalancePsi *bf  = 0;  // Balance Function object
  AliBalancePsi *bfs = 0;  // shuffled Balance function object
  AliBalancePsi *bfm = 0;  // mixing Balance function object

  //maximum Delta eta range
  Double_t deltaEtaMax=TMath::Abs(etaMax-etaMin);

  if (analysisType=="ESD"){
    bf  = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
  }
  else if (analysisType=="AOD"){
    bf  = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
  }
  else if (analysisType=="MC"){
    bf  = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
  }
  else if (analysisType=="MCAOD"){
    bf  = GetBalanceFunctionObject("MCAOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("MCAOD",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("MCAOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
  }
  else{
    ::Error("AddTaskBF", "analysis type NOT known.");
    return NULL;
  }

  // Create the task, add it to manager and configure it.
  //===========================================================================
  AliAnalysisTaskBFPsi *taskBF = new AliAnalysisTaskBFPsi("TaskBFPsi");

  //Event characteristics scheme
  taskBF->SetEventClass(fArgEventClass);

  //++++++++++++++++++++++
  TString correctionFileName = "$ALICE_ROOT/PWGCF/EBYE/BalanceFunctions/Corrections/CorrectionMaps.root"; //to put the path for the correction maps
  TFile *fCorrectionMatrix  = TFile::Open(correctionFileName.Data());
  if(!fCorrectionMatrix){
    Printf("WARNING CORRECTION histogram file not found");
    return NULL;
  }

  taskBF->SetInputCorrection(correctionFileName.Data(),"");

  //+++++++++++++++++++++

  taskBF->SetAnalysisObject(bf);
  if(gRunShuffling) taskBF->SetShufflingObject(bfs);
  if(gRunMixing){
    taskBF->SetMixingObject(bfm);
    taskBF->SetMixingTracks(50000);
    if(gRunMixingWithEventPlane){
      taskBF->SetMixingWithEventPlane(gRunMixingWithEventPlane);
    }
  }

  taskBF->SetCentralityPercentileRange(centrMin,centrMax);
  if(analysisType == "ESD") {
    AliESDtrackCuts *trackCuts = GetTrackCutsObject(ptMin,ptMax,etaMin,etaMax,maxTPCchi2,DCAxy,DCAz,minNClustersTPC);
    taskBF->SetAnalysisCutObject(trackCuts);
    if(kUsePID) {
      if(kUseBayesianPID)
	taskBF->SetUseBayesianPID(gMinAcceptedProbability);
      else if(kUseNSigmaPID)
	taskBF->SetUseNSigmaPID(nSigmaMax);
      taskBF->SetParticleOfInterest(AliAnalysistaskBFPsi::kProton);
      taskBF->SetDetectorUsedForPID(AliAnalysisTaskBFPsi::kTOFpid);
    }
  }
  else if(analysisType == "AOD") {
    // pt and eta cut (pt_min, pt_max, eta_min, eta_max)
    taskBF->SetAODtrackCutBit(AODfilterBit);
    taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax);

    // set extra DCA cuts (-1 no extra cut)
    taskBF->SetExtraDCACutsAOD(DCAxy,DCAz);

    // set extra TPC chi2 / nr of clusters cut
    taskBF->SetExtraTPCCutsAOD(maxTPCchi2, minNClustersTPC);

  }
  else if(analysisType == "MC") {
    taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax);
    taskBF->SetImpactParameterRange(centrMin,centrMax);
  }
  else if(analysisType == "MCAOD") {
    // pt and eta cut (pt_min, pt_max, eta_min, eta_max)
    taskBF->SetAODtrackCutBit(AODfilterBit);
    taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax);
  }

  // offline trigger selection (AliVEvent.h)
  // taskBF->UseOfflineTrigger(); // NOT used (selection is done with the AliAnalysisTaskSE::SelectCollisionCandidates())
  // with this only selected events are analyzed (first 2 bins in event QA histogram are the same))
  // documentation in https://twiki.cern.ch/twiki/bin/viewauth/ALICE/PWG1EvSelDocumentation
  if(bCentralTrigger) taskBF->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral);
  else                taskBF->SelectCollisionCandidates(AliVEvent::kMB);

  // centrality estimator (default = V0M)
  taskBF->SetCentralityEstimator(centralityEstimator);

  // vertex cut (x,y,z)
  taskBF->SetVertexDiamond(3.,3.,vertexZ);

  //bf->PrintAnalysisSettings();
  mgr->AddTask(taskBF);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  outputFileName += ":PWGCFEbyE.outputBalanceFunctionPsiAnalysis";
  AliAnalysisDataContainer *coutQA = mgr->CreateContainer(Form("listQAPsi_%.0f-%.0f_Bit%d_%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  AliAnalysisDataContainer *coutBF = mgr->CreateContainer(Form("listBFPsi_%.0f-%.0f_Bit%d_%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  if(gRunShuffling) AliAnalysisDataContainer *coutBFS = mgr->CreateContainer(Form("listBFPsiShuffled_%.0f-%.0f_Bit%d_%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  if(gRunMixing) AliAnalysisDataContainer *coutBFM = mgr->CreateContainer(Form("listBFPsiMixed_%.0f-%.0f_Bit%d_%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  if(kUsePID) AliAnalysisDataContainer *coutQAPID = mgr->CreateContainer(Form("listQAPIDPsi_%.0f-%.0f_Bit%d_%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());

  mgr->ConnectInput(taskBF, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskBF, 1, coutQA);
  mgr->ConnectOutput(taskBF, 2, coutBF);
  if(gRunShuffling) mgr->ConnectOutput(taskBF, 3, coutBFS);
  if(gRunMixing) mgr->ConnectOutput(taskBF, 4, coutBFM);
  if(kUsePID && analysisType == "ESD") mgr->ConnectOutput(taskBF, 5, coutQAPID);

  return taskBF;
}
<commit_msg>1) adding also the change in the AddTask macro for the efficiency correction file<commit_after>// now in options
//=============================================//
//const char* centralityEstimator = "V0M";
//const char* centralityEstimator = "CL1";
//const char* centralityEstimator = "TRK";
//=============================================//
//Bool_t gRunShuffling = kFALSE;
//Bool_t gRunShuffling = kTRUE;
//=============================================//

//PID config
Bool_t kUseNSigmaPID = kFALSE;
Double_t nSigmaMax = 3.0;
Bool_t kUseBayesianPID = kTRUE;
Double_t gMinAcceptedProbability = 0.7;

//_________________________________________________________//
AliAnalysisTaskBFPsi *AddTaskBalancePsiCentralityTrain(Double_t centrMin=0.,
						       Double_t centrMax=100.,
						       Bool_t gRunShuffling=kFALSE,
						       Bool_t gRunMixing=kTRUE,
						       Bool_t gRunMixingWithEventPlane=kFALSE,
						       TString centralityEstimator="V0M",
						       Double_t vertexZ=10.,
						       Double_t DCAxy=-1,
						       Double_t DCAz=-1,
						       Double_t ptMin=0.3,
						       Double_t ptMax=1.5,
						       Double_t etaMin=-0.8,
						       Double_t etaMax=0.8,
						       Double_t maxTPCchi2 = -1,
						       Int_t minNClustersTPC = -1,
						       Bool_t kUsePID = kFALSE,
						       Bool_t bResonancesCut = kTRUE,
						       Bool_t bHBTcut = kTRUE,
						       Bool_t bConversionCut = kTRUE,
						       Bool_t bMomentumDifferenceCut = kTRUE,
						       Int_t AODfilterBit = 128,
						       Bool_t bCentralTrigger = kFALSE,
						       TString fileNameBase="AnalysisResults",
						       TString fArgEventClass="Centrality",
						       TString analysisTypeUser="AOD",
						       Bool_t bVertexBinning=kTRUE,
						       TString correctionFileName = "$ALICE_ROOT/PWGCF/EBYE/BalanceFunctions/Corrections/CorrectionMaps.root") {
  // Creates a balance function analysis task and adds it to the analysis manager.
  // Get the pointer to the existing analysis manager via the static access method.
  TString outputFileName(fileNameBase);
  outputFileName.Append(".root");

  //===========================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskBF", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //===========================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskBF", "This task requires an input event handler");
    return NULL;
  }
  TString analysisType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  if(dynamic_cast<AliMCEventHandler*> (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler())) analysisType = "MC";

  // to set the analysis type manually
  if(analysisTypeUser != ""){
    analysisType = analysisTypeUser;
    ::Info("AddTaskBF",Form("Analysis Type manually set to %s",analysisType.Data()));
  }

  // for local changed BF configuration
  //gROOT->LoadMacro("./configBalanceFunctionPsiAnalysis.C");
  gROOT->LoadMacro("$ALICE_ROOT/PWGCF/EBYE/macros/configBalanceFunctionPsiAnalysis.C");
  AliBalancePsi *bf  = 0;  // Balance Function object
  AliBalancePsi *bfs = 0;  // shuffled Balance function object
  AliBalancePsi *bfm = 0;  // mixing Balance function object

  //maximum Delta eta range
  Double_t deltaEtaMax=TMath::Abs(etaMax-etaMin);

  if (analysisType=="ESD"){
    bf  = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("ESD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
  }
  else if (analysisType=="AOD"){
    bf  = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("AOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
  }
  else if (analysisType=="MC"){
    bf  = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("MC",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
  }
  else if (analysisType=="MCAOD"){
    bf  = GetBalanceFunctionObject("MCAOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunShuffling) bfs = GetBalanceFunctionObject("MCAOD",centralityEstimator,centrMin,centrMax,kTRUE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
    if(gRunMixing)    bfm = GetBalanceFunctionObject("MCAOD",centralityEstimator,centrMin,centrMax,kFALSE,bResonancesCut,bHBTcut,bConversionCut,bMomentumDifferenceCut,fArgEventClass,deltaEtaMax,bVertexBinning);
  }
  else{
    ::Error("AddTaskBF", "analysis type NOT known.");
    return NULL;
  }

  // Create the task, add it to manager and configure it.
  //===========================================================================
  AliAnalysisTaskBFPsi *taskBF = new AliAnalysisTaskBFPsi("TaskBFPsi");

  //Event characteristics scheme
  taskBF->SetEventClass(fArgEventClass);

  //++++++++++++++++++++++
  // Efficiency + Contamination corrections
  // If correctionFileName = "", do not use corrections
  taskBF->SetInputCorrection(correctionFileName.Data(),"");
  //+++++++++++++++++++++

  taskBF->SetAnalysisObject(bf);
  if(gRunShuffling) taskBF->SetShufflingObject(bfs);
  if(gRunMixing){
    taskBF->SetMixingObject(bfm);
    taskBF->SetMixingTracks(50000);
    if(gRunMixingWithEventPlane){
      taskBF->SetMixingWithEventPlane(gRunMixingWithEventPlane);
    }
  }

  taskBF->SetCentralityPercentileRange(centrMin,centrMax);
  if(analysisType == "ESD") {
    AliESDtrackCuts *trackCuts = GetTrackCutsObject(ptMin,ptMax,etaMin,etaMax,maxTPCchi2,DCAxy,DCAz,minNClustersTPC);
    taskBF->SetAnalysisCutObject(trackCuts);
    if(kUsePID) {
      if(kUseBayesianPID)
	taskBF->SetUseBayesianPID(gMinAcceptedProbability);
      else if(kUseNSigmaPID)
	taskBF->SetUseNSigmaPID(nSigmaMax);
      taskBF->SetParticleOfInterest(AliAnalysistaskBFPsi::kProton);
      taskBF->SetDetectorUsedForPID(AliAnalysisTaskBFPsi::kTOFpid);
    }
  }
  else if(analysisType == "AOD") {
    // pt and eta cut (pt_min, pt_max, eta_min, eta_max)
    taskBF->SetAODtrackCutBit(AODfilterBit);
    taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax);

    // set extra DCA cuts (-1 no extra cut)
    taskBF->SetExtraDCACutsAOD(DCAxy,DCAz);

    // set extra TPC chi2 / nr of clusters cut
    taskBF->SetExtraTPCCutsAOD(maxTPCchi2, minNClustersTPC);

  }
  else if(analysisType == "MC") {
    taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax);
    taskBF->SetImpactParameterRange(centrMin,centrMax);
  }
  else if(analysisType == "MCAOD") {
    // pt and eta cut (pt_min, pt_max, eta_min, eta_max)
    taskBF->SetAODtrackCutBit(AODfilterBit);
    taskBF->SetKinematicsCutsAOD(ptMin,ptMax,etaMin,etaMax);
  }

  // offline trigger selection (AliVEvent.h)
  // taskBF->UseOfflineTrigger(); // NOT used (selection is done with the AliAnalysisTaskSE::SelectCollisionCandidates())
  // with this only selected events are analyzed (first 2 bins in event QA histogram are the same))
  // documentation in https://twiki.cern.ch/twiki/bin/viewauth/ALICE/PWG1EvSelDocumentation
  if(bCentralTrigger) taskBF->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kCentral | AliVEvent::kSemiCentral);
  else                taskBF->SelectCollisionCandidates(AliVEvent::kMB);

  // centrality estimator (default = V0M)
  taskBF->SetCentralityEstimator(centralityEstimator);

  // vertex cut (x,y,z)
  taskBF->SetVertexDiamond(3.,3.,vertexZ);

  //bf->PrintAnalysisSettings();
  mgr->AddTask(taskBF);

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  TString outputFileName = AliAnalysisManager::GetCommonFileName();
  outputFileName += ":PWGCFEbyE.outputBalanceFunctionPsiAnalysis";
  AliAnalysisDataContainer *coutQA = mgr->CreateContainer(Form("listQAPsi_%.0f-%.0f_Bit%d_%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  AliAnalysisDataContainer *coutBF = mgr->CreateContainer(Form("listBFPsi_%.0f-%.0f_Bit%d_%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  if(gRunShuffling) AliAnalysisDataContainer *coutBFS = mgr->CreateContainer(Form("listBFPsiShuffled_%.0f-%.0f_Bit%d_%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  if(gRunMixing) AliAnalysisDataContainer *coutBFM = mgr->CreateContainer(Form("listBFPsiMixed_%.0f-%.0f_Bit%d_%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());
  if(kUsePID) AliAnalysisDataContainer *coutQAPID = mgr->CreateContainer(Form("listQAPIDPsi_%.0f-%.0f_Bit%d_%s",centrMin,centrMax,AODfilterBit,centralityEstimator.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,outputFileName.Data());

  mgr->ConnectInput(taskBF, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(taskBF, 1, coutQA);
  mgr->ConnectOutput(taskBF, 2, coutBF);
  if(gRunShuffling) mgr->ConnectOutput(taskBF, 3, coutBFS);
  if(gRunMixing) mgr->ConnectOutput(taskBF, 4, coutBFM);
  if(kUsePID && analysisType == "ESD") mgr->ConnectOutput(taskBF, 5, coutQAPID);

  return taskBF;
}
<|endoftext|>