<commit_before>// Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// CPU specific code for arm independent of OS goes here.

#include "v8.h"

#if V8_TARGET_ARCH_ARM64

#include "arm64/cpu-arm64.h"
#include "arm64/utils-arm64.h"

namespace v8 {
namespace internal {

#ifdef DEBUG
bool CpuFeatures::initialized_ = false;
#endif
unsigned CpuFeatures::supported_ = 0;
unsigned CpuFeatures::found_by_runtime_probing_only_ = 0;
unsigned CpuFeatures::cross_compile_ = 0;

class CacheLineSizes {
 public:
  CacheLineSizes() {
#ifdef USE_SIMULATOR
    cache_type_register_ = 0;
#else
    // Copy the content of the cache type register to a core register.
    __asm__ __volatile__ ("mrs %[ctr], ctr_el0"  // NOLINT
                          : [ctr] "=r" (cache_type_register_));
#endif
  }

  uint32_t icache_line_size() const { return ExtractCacheLineSize(0); }
  uint32_t dcache_line_size() const { return ExtractCacheLineSize(16); }

 private:
  uint32_t ExtractCacheLineSize(int cache_line_size_shift) const {
    // The cache type register holds the size of the caches as a power of two.
    return 1 << ((cache_type_register_ >> cache_line_size_shift) & 0xf);
  }

  uint32_t cache_type_register_;
};

void CPU::FlushICache(void* address, size_t length) {
  if (length == 0) return;

#ifdef USE_SIMULATOR
  // TODO(all): consider doing some cache simulation to ensure every address
  // run has been synced.
  USE(address);
  USE(length);
#else
  // The code below assumes user space cache operations are allowed. The goal
  // of this routine is to make sure the code generated is visible to the I
  // side of the CPU.

  uintptr_t start = reinterpret_cast<uintptr_t>(address);
  // Sizes will be used to generate a mask big enough to cover a pointer.
  CacheLineSizes sizes;
  uintptr_t dsize = sizes.dcache_line_size();
  uintptr_t isize = sizes.icache_line_size();
  // Cache line sizes are always a power of 2.
  ASSERT(CountSetBits(dsize, 64) == 1);
  ASSERT(CountSetBits(isize, 64) == 1);
  uintptr_t dstart = start & ~(dsize - 1);
  uintptr_t istart = start & ~(isize - 1);
  uintptr_t end = start + length;

  __asm__ __volatile__ (  // NOLINT
    // Clean every line of the D cache containing the target data.
    "0:                                \n\t"
    // dc      : Data Cache maintenance
    //    c    : Clean
    //     va  : by (Virtual) Address
    //       u : to the point of Unification
    // The point of unification for a processor is the point by which the
    // instruction and data caches are guaranteed to see the same copy of a
    // memory location. See ARM DDI 0406B page B2-12 for more information.
    "dc   cvau, %[dline]                \n\t"
    "add  %[dline], %[dline], %[dsize]  \n\t"
    "cmp  %[dline], %[end]              \n\t"
    "b.lt 0b                            \n\t"
    // Barrier to make sure the effect of the code above is visible to the rest
    // of the world.
    // dsb    : Data Synchronisation Barrier
    //    ish : Inner SHareable domain
    // The point of unification for an Inner Shareable shareability domain is
    // the point by which the instruction and data caches of all the processors
    // in that Inner Shareable shareability domain are guaranteed to see the
    // same copy of a memory location.  See ARM DDI 0406B page B2-12 for more
    // information.
    "dsb  ish                           \n\t"
    // Invalidate every line of the I cache containing the target data.
    "1:                                 \n\t"
    // ic      : instruction cache maintenance
    //    i    : invalidate
    //     va  : by address
    //       u : to the point of unification
    "ic   ivau, %[iline]                \n\t"
    "add  %[iline], %[iline], %[isize]  \n\t"
    "cmp  %[iline], %[end]              \n\t"
    "b.lt 1b                            \n\t"
    // Barrier to make sure the effect of the code above is visible to the rest
    // of the world.
    "dsb  ish                           \n\t"
    // Barrier to ensure any prefetching which happened before this code is
    // discarded.
    // isb : Instruction Synchronisation Barrier
    "isb                                \n\t"
    : [dline] "+r" (dstart),
      [iline] "+r" (istart)
    : [dsize] "r"  (dsize),
      [isize] "r"  (isize),
      [end]   "r"  (end)
    // This code does not write to memory but without the dependency gcc might
    // move this code before the code is generated.
    : "cc", "memory"
  );  // NOLINT
#endif
}

void CpuFeatures::Probe(bool serializer_enabled) {
  ASSERT(supported_ == 0);

  if (serializer_enabled && FLAG_enable_always_align_csp) {
    // Always align csp in snapshot code - this is safe and ensures that csp
    // will always be aligned if it is enabled by probing at runtime.
    supported_ |= static_cast<uint64_t>(1) << ALWAYS_ALIGN_CSP;
  }

  if (!serializer_enabled) {
    CPU cpu;
    // Always align csp on Nvidia cores or when debug_code is enabled.
    if (FLAG_enable_always_align_csp &&
        (cpu.implementer() == CPU::NVIDIA || FLAG_debug_code)) {
      found_by_runtime_probing_only_ |=
          static_cast<uint64_t>(1) << ALWAYS_ALIGN_CSP;
    }

    supported_ |= found_by_runtime_probing_only_;
  }

#ifdef DEBUG
  initialized_ = true;
#endif
}

} }  // namespace v8::internal

#endif  // V8_TARGET_ARCH_ARM64
<commit_msg>ARM64: Fix cache line size computation.<commit_after>// Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// CPU specific code for arm independent of OS goes here.

#include "v8.h"

#if V8_TARGET_ARCH_ARM64

#include "arm64/cpu-arm64.h"
#include "arm64/utils-arm64.h"

namespace v8 {
namespace internal {

#ifdef DEBUG
bool CpuFeatures::initialized_ = false;
#endif
unsigned CpuFeatures::supported_ = 0;
unsigned CpuFeatures::found_by_runtime_probing_only_ = 0;
unsigned CpuFeatures::cross_compile_ = 0;

class CacheLineSizes {
 public:
  CacheLineSizes() {
#ifdef USE_SIMULATOR
    cache_type_register_ = 0;
#else
    // Copy the content of the cache type register to a core register.
    __asm__ __volatile__ ("mrs %[ctr], ctr_el0"  // NOLINT
                          : [ctr] "=r" (cache_type_register_));
#endif
  }

  uint32_t icache_line_size() const { return ExtractCacheLineSize(0); }
  uint32_t dcache_line_size() const { return ExtractCacheLineSize(16); }

 private:
  uint32_t ExtractCacheLineSize(int cache_line_size_shift) const {
    // The cache type register holds the size of cache lines in words as a
    // power of two.
    return 4 << ((cache_type_register_ >> cache_line_size_shift) & 0xf);
  }

  uint32_t cache_type_register_;
};

void CPU::FlushICache(void* address, size_t length) {
  if (length == 0) return;

#ifdef USE_SIMULATOR
  // TODO(all): consider doing some cache simulation to ensure every address
  // run has been synced.
  USE(address);
  USE(length);
#else
  // The code below assumes user space cache operations are allowed. The goal
  // of this routine is to make sure the code generated is visible to the I
  // side of the CPU.

  uintptr_t start = reinterpret_cast<uintptr_t>(address);
  // Sizes will be used to generate a mask big enough to cover a pointer.
  CacheLineSizes sizes;
  uintptr_t dsize = sizes.dcache_line_size();
  uintptr_t isize = sizes.icache_line_size();
  // Cache line sizes are always a power of 2.
  ASSERT(CountSetBits(dsize, 64) == 1);
  ASSERT(CountSetBits(isize, 64) == 1);
  uintptr_t dstart = start & ~(dsize - 1);
  uintptr_t istart = start & ~(isize - 1);
  uintptr_t end = start + length;

  __asm__ __volatile__ (  // NOLINT
    // Clean every line of the D cache containing the target data.
    "0:                                \n\t"
    // dc      : Data Cache maintenance
    //    c    : Clean
    //     va  : by (Virtual) Address
    //       u : to the point of Unification
    // The point of unification for a processor is the point by which the
    // instruction and data caches are guaranteed to see the same copy of a
    // memory location. See ARM DDI 0406B page B2-12 for more information.
    "dc   cvau, %[dline]                \n\t"
    "add  %[dline], %[dline], %[dsize]  \n\t"
    "cmp  %[dline], %[end]              \n\t"
    "b.lt 0b                            \n\t"
    // Barrier to make sure the effect of the code above is visible to the rest
    // of the world.
    // dsb    : Data Synchronisation Barrier
    //    ish : Inner SHareable domain
    // The point of unification for an Inner Shareable shareability domain is
    // the point by which the instruction and data caches of all the processors
    // in that Inner Shareable shareability domain are guaranteed to see the
    // same copy of a memory location.  See ARM DDI 0406B page B2-12 for more
    // information.
    "dsb  ish                           \n\t"
    // Invalidate every line of the I cache containing the target data.
    "1:                                 \n\t"
    // ic      : instruction cache maintenance
    //    i    : invalidate
    //     va  : by address
    //       u : to the point of unification
    "ic   ivau, %[iline]                \n\t"
    "add  %[iline], %[iline], %[isize]  \n\t"
    "cmp  %[iline], %[end]              \n\t"
    "b.lt 1b                            \n\t"
    // Barrier to make sure the effect of the code above is visible to the rest
    // of the world.
    "dsb  ish                           \n\t"
    // Barrier to ensure any prefetching which happened before this code is
    // discarded.
    // isb : Instruction Synchronisation Barrier
    "isb                                \n\t"
    : [dline] "+r" (dstart),
      [iline] "+r" (istart)
    : [dsize] "r"  (dsize),
      [isize] "r"  (isize),
      [end]   "r"  (end)
    // This code does not write to memory but without the dependency gcc might
    // move this code before the code is generated.
    : "cc", "memory"
  );  // NOLINT
#endif
}

void CpuFeatures::Probe(bool serializer_enabled) {
  ASSERT(supported_ == 0);

  if (serializer_enabled && FLAG_enable_always_align_csp) {
    // Always align csp in snapshot code - this is safe and ensures that csp
    // will always be aligned if it is enabled by probing at runtime.
    supported_ |= static_cast<uint64_t>(1) << ALWAYS_ALIGN_CSP;
  }

  if (!serializer_enabled) {
    CPU cpu;
    // Always align csp on Nvidia cores or when debug_code is enabled.
    if (FLAG_enable_always_align_csp &&
        (cpu.implementer() == CPU::NVIDIA || FLAG_debug_code)) {
      found_by_runtime_probing_only_ |=
          static_cast<uint64_t>(1) << ALWAYS_ALIGN_CSP;
    }

    supported_ |= found_by_runtime_probing_only_;
  }

#ifdef DEBUG
  initialized_ = true;
#endif
}

} }  // namespace v8::internal

#endif  // V8_TARGET_ARCH_ARM64
<|endoftext|>


<commit_before>#include "messages/messageelement.hpp"
#include "messages/layouts/messagelayoutcontainer.hpp"
#include "messages/layouts/messagelayoutelement.hpp"
#include "singletons/settingsmanager.hpp"
#include "util/benchmark.hpp"
#include "util/emotemap.hpp"

namespace chatterino {
namespace messages {

MessageElement::MessageElement(Flags _flags)
    : flags(_flags)
{
    util::DebugCount::increase("message elements");
}

MessageElement::~MessageElement()
{
    util::DebugCount::decrease("message elements");
}

MessageElement *MessageElement::setLink(const Link &_link)
{
    this->link = _link;
    return this;
}

MessageElement *MessageElement::setTooltip(const QString &_tooltip)
{
    this->tooltip = _tooltip;
    return this;
}

MessageElement *MessageElement::setTrailingSpace(bool value)
{
    this->trailingSpace = value;
    return this;
}

const QString &MessageElement::getTooltip() const
{
    return this->tooltip;
}

const Link &MessageElement::getLink() const
{
    return this->link;
}

bool MessageElement::hasTrailingSpace() const
{
    return this->trailingSpace;
}

MessageElement::Flags MessageElement::getFlags() const
{
    return this->flags;
}

// IMAGE
ImageElement::ImageElement(Image *_image, MessageElement::Flags flags)
    : MessageElement(flags)
    , image(_image)
{
    this->setTooltip(_image->getTooltip());
}

void ImageElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags _flags)
{
    if (_flags & this->getFlags()) {
        QSize size(this->image->getWidth() * this->image->getScale() * container.getScale(),
                   this->image->getHeight() * this->image->getScale() * container.getScale());

        container.addElement(
            (new ImageLayoutElement(*this, this->image, size))->setLink(this->getLink()));
    }
}

// EMOTE
EmoteElement::EmoteElement(const util::EmoteData &_data, MessageElement::Flags flags)
    : MessageElement(flags)
    , data(_data)
{
    if (_data.isValid()) {
        this->setTooltip(data.image1x->getTooltip());
        this->textElement.reset(new TextElement(_data.image1x->getName(), MessageElement::Misc));
    }
}

void EmoteElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags _flags)
{
    if (_flags & this->getFlags()) {
        if (_flags & MessageElement::EmoteImages) {
            if (!this->data.isValid()) {
                return;
            }

            int quality = singletons::SettingManager::getInstance().preferredEmoteQuality;

            Image *_image;
            if (quality == 3 && this->data.image3x != nullptr) {
                _image = this->data.image3x;
            } else if (quality >= 2 && this->data.image2x != nullptr) {
                _image = this->data.image2x;
            } else {
                _image = this->data.image1x;
            }

            QSize size((int)(container.getScale() * _image->getScaledWidth()),
                       (int)(container.getScale() * _image->getScaledHeight()));

            container.addElement(
                (new ImageLayoutElement(*this, _image, size))->setLink(this->getLink()));
        } else {
            if (this->textElement) {
                this->textElement->addToContainer(container, MessageElement::Misc);
            }
        }
    }
}

// TEXT
TextElement::TextElement(const QString &text, MessageElement::Flags flags,
                         const MessageColor &_color, FontStyle _style)
    : MessageElement(flags)
    , color(_color)
    , style(_style)
{
    for (QString word : text.split(' ')) {
        this->words.push_back({word, -1});
        // fourtf: add logic to store multiple spaces after message
    }
}

void TextElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags _flags)
{
    if (_flags & this->getFlags()) {
        QFontMetrics &metrics = singletons::FontManager::getInstance().getFontMetrics(
            this->style, container.getScale());
        singletons::ThemeManager &themeManager =
            singletons::ThemeManager::ThemeManager::getInstance();

        for (Word &word : this->words) {
            auto getTextLayoutElement = [&](QString text, int width, bool trailingSpace) {
                QColor color = this->color.getColor(themeManager);
                themeManager.normalizeColor(color);

                auto e = (new TextLayoutElement(*this, text, QSize(width, metrics.height()), color,
                                                this->style, container.getScale()))
                             ->setLink(this->getLink());
                e->setTrailingSpace(trailingSpace);
                return e;
            };

            // fourtf: add again
            //            if (word.width == -1) {
            word.width = metrics.width(word.text);
            //            }

            // see if the text fits in the current line
            if (container.fitsInLine(word.width)) {
                container.addElementNoLineBreak(
                    getTextLayoutElement(word.text, word.width, this->hasTrailingSpace()));
                continue;
            }

            // see if the text fits in the next line
            if (!container.atStartOfLine()) {
                container.breakLine();

                if (container.fitsInLine(word.width)) {
                    container.addElementNoLineBreak(
                        getTextLayoutElement(word.text, word.width, this->hasTrailingSpace()));
                    continue;
                }
            }

            // we done goofed, we need to wrap the text
            QString text = word.text;
            int textLength = text.length();
            int wordStart = 0;
            int width = metrics.width(text[0]);
            int lastWidth = 0;

            for (int i = 1; i < textLength; i++) {
                int charWidth = metrics.width(text[i]);

                if (!container.fitsInLine(width + charWidth)) {
                    container.addElementNoLineBreak(
                        getTextLayoutElement(text.mid(wordStart, i - wordStart), width, false));
                    container.breakLine();

                    wordStart = i;
                    lastWidth = width;
                    width = 0;
                    if (textLength > i + 2) {
                        width += metrics.width(text[i]);
                        width += metrics.width(text[i + 1]);
                        i += 1;
                    }
                    continue;
                }
                width += charWidth;
            }

            container.addElement(getTextLayoutElement(text.mid(wordStart), word.width - lastWidth,
                                                      this->hasTrailingSpace()));
            container.breakLine();
        }
    }
}

// TIMESTAMP
TimestampElement::TimestampElement(QTime _time)
    : MessageElement(MessageElement::Timestamp)
    , time(_time)
    , element(this->formatTime(_time))
{
    assert(this->element != nullptr);
}

void TimestampElement::addToContainer(MessageLayoutContainer &container,
                                      MessageElement::Flags _flags)
{
    if (_flags & this->getFlags()) {
        if (singletons::SettingManager::getInstance().timestampFormat != this->format) {
            this->format = singletons::SettingManager::getInstance().timestampFormat.getValue();
            this->element.reset(this->formatTime(this->time));
        }

        this->element->addToContainer(container, _flags);
    }
}

TextElement *TimestampElement::formatTime(const QTime &time)
{
    static QLocale locale("en_US");

    QString format =
        locale.toString(time, singletons::SettingManager::getInstance().timestampFormat);

    return new TextElement(format, Flags::Timestamp, MessageColor::System, FontStyle::Medium);
}

// TWITCH MODERATION
TwitchModerationElement::TwitchModerationElement()
    : MessageElement(MessageElement::ModeratorTools)
{
}

void TwitchModerationElement::addToContainer(MessageLayoutContainer &container,
                                             MessageElement::Flags _flags)
{
    if (_flags & MessageElement::ModeratorTools) {
        QSize size((int)(container.getScale() * 16), (int)(container.getScale() * 16));

        for (const singletons::ModerationAction &m :
             singletons::SettingManager::getInstance().getModerationActions()) {
            if (m.isImage()) {
                container.addElement((new ImageLayoutElement(*this, m.getImage(), size))
                                         ->setLink(Link(Link::UserAction, m.getAction())));
            } else {
                container.addElement((new TextIconLayoutElement(*this, m.getLine1(), m.getLine2(),
                                                                container.getScale(), size))
                                         ->setLink(Link(Link::UserAction, m.getAction())));
            }
        }
    }
}

}  // namespace messages
}  // namespace chatterino
<commit_msg>fixed issue with selecting text and word wrapping<commit_after>#include "messages/messageelement.hpp"
#include "messages/layouts/messagelayoutcontainer.hpp"
#include "messages/layouts/messagelayoutelement.hpp"
#include "singletons/settingsmanager.hpp"
#include "util/benchmark.hpp"
#include "util/emotemap.hpp"

namespace chatterino {
namespace messages {

MessageElement::MessageElement(Flags _flags)
    : flags(_flags)
{
    util::DebugCount::increase("message elements");
}

MessageElement::~MessageElement()
{
    util::DebugCount::decrease("message elements");
}

MessageElement *MessageElement::setLink(const Link &_link)
{
    this->link = _link;
    return this;
}

MessageElement *MessageElement::setTooltip(const QString &_tooltip)
{
    this->tooltip = _tooltip;
    return this;
}

MessageElement *MessageElement::setTrailingSpace(bool value)
{
    this->trailingSpace = value;
    return this;
}

const QString &MessageElement::getTooltip() const
{
    return this->tooltip;
}

const Link &MessageElement::getLink() const
{
    return this->link;
}

bool MessageElement::hasTrailingSpace() const
{
    return this->trailingSpace;
}

MessageElement::Flags MessageElement::getFlags() const
{
    return this->flags;
}

// IMAGE
ImageElement::ImageElement(Image *_image, MessageElement::Flags flags)
    : MessageElement(flags)
    , image(_image)
{
    this->setTooltip(_image->getTooltip());
}

void ImageElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags _flags)
{
    if (_flags & this->getFlags()) {
        QSize size(this->image->getWidth() * this->image->getScale() * container.getScale(),
                   this->image->getHeight() * this->image->getScale() * container.getScale());

        container.addElement(
            (new ImageLayoutElement(*this, this->image, size))->setLink(this->getLink()));
    }
}

// EMOTE
EmoteElement::EmoteElement(const util::EmoteData &_data, MessageElement::Flags flags)
    : MessageElement(flags)
    , data(_data)
{
    if (_data.isValid()) {
        this->setTooltip(data.image1x->getTooltip());
        this->textElement.reset(new TextElement(_data.image1x->getName(), MessageElement::Misc));
    }
}

void EmoteElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags _flags)
{
    if (_flags & this->getFlags()) {
        if (_flags & MessageElement::EmoteImages) {
            if (!this->data.isValid()) {
                return;
            }

            int quality = singletons::SettingManager::getInstance().preferredEmoteQuality;

            Image *_image;
            if (quality == 3 && this->data.image3x != nullptr) {
                _image = this->data.image3x;
            } else if (quality >= 2 && this->data.image2x != nullptr) {
                _image = this->data.image2x;
            } else {
                _image = this->data.image1x;
            }

            QSize size((int)(container.getScale() * _image->getScaledWidth()),
                       (int)(container.getScale() * _image->getScaledHeight()));

            container.addElement(
                (new ImageLayoutElement(*this, _image, size))->setLink(this->getLink()));
        } else {
            if (this->textElement) {
                this->textElement->addToContainer(container, MessageElement::Misc);
            }
        }
    }
}

// TEXT
TextElement::TextElement(const QString &text, MessageElement::Flags flags,
                         const MessageColor &_color, FontStyle _style)
    : MessageElement(flags)
    , color(_color)
    , style(_style)
{
    for (QString word : text.split(' ')) {
        this->words.push_back({word, -1});
        // fourtf: add logic to store multiple spaces after message
    }
}

void TextElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags _flags)
{
    if (_flags & this->getFlags()) {
        QFontMetrics &metrics = singletons::FontManager::getInstance().getFontMetrics(
            this->style, container.getScale());
        singletons::ThemeManager &themeManager =
            singletons::ThemeManager::ThemeManager::getInstance();

        for (Word &word : this->words) {
            auto getTextLayoutElement = [&](QString text, int width, bool trailingSpace) {
                QColor color = this->color.getColor(themeManager);
                themeManager.normalizeColor(color);

                auto e = (new TextLayoutElement(*this, text, QSize(width, metrics.height()), color,
                                                this->style, container.getScale()))
                             ->setLink(this->getLink());
                e->setTrailingSpace(trailingSpace);
                return e;
            };

            // fourtf: add again
            //            if (word.width == -1) {
            word.width = metrics.width(word.text);
            //            }

            // see if the text fits in the current line
            if (container.fitsInLine(word.width)) {
                container.addElementNoLineBreak(
                    getTextLayoutElement(word.text, word.width, this->hasTrailingSpace()));
                continue;
            }

            // see if the text fits in the next line
            if (!container.atStartOfLine()) {
                container.breakLine();

                if (container.fitsInLine(word.width)) {
                    container.addElementNoLineBreak(
                        getTextLayoutElement(word.text, word.width, this->hasTrailingSpace()));
                    continue;
                }
            }

            // we done goofed, we need to wrap the text
            QString text = word.text;
            int textLength = text.length();
            int wordStart = 0;
            int width = metrics.width(text[0]);
            int lastWidth = 0;

            for (int i = 1; i < textLength; i++) {
                int charWidth = metrics.width(text[i]);

                if (!container.fitsInLine(width + charWidth)) {
                    container.addElementNoLineBreak(
                        getTextLayoutElement(text.mid(wordStart, i - wordStart), width, false));
                    container.breakLine();

                    wordStart = i;
                    lastWidth = width;
                    width = 0;
                    if (textLength > i + 2) {
                        width += metrics.width(text[i]);
                        width += metrics.width(text[i + 1]);
                        i += 1;
                    }
                    continue;
                }
                width += charWidth;
            }

            container.addElement(
                getTextLayoutElement(text.mid(wordStart), width, this->hasTrailingSpace()));
            container.breakLine();
        }
    }
}

// TIMESTAMP
TimestampElement::TimestampElement(QTime _time)
    : MessageElement(MessageElement::Timestamp)
    , time(_time)
    , element(this->formatTime(_time))
{
    assert(this->element != nullptr);
}

void TimestampElement::addToContainer(MessageLayoutContainer &container,
                                      MessageElement::Flags _flags)
{
    if (_flags & this->getFlags()) {
        if (singletons::SettingManager::getInstance().timestampFormat != this->format) {
            this->format = singletons::SettingManager::getInstance().timestampFormat.getValue();
            this->element.reset(this->formatTime(this->time));
        }

        this->element->addToContainer(container, _flags);
    }
}

TextElement *TimestampElement::formatTime(const QTime &time)
{
    static QLocale locale("en_US");

    QString format =
        locale.toString(time, singletons::SettingManager::getInstance().timestampFormat);

    return new TextElement(format, Flags::Timestamp, MessageColor::System, FontStyle::Medium);
}

// TWITCH MODERATION
TwitchModerationElement::TwitchModerationElement()
    : MessageElement(MessageElement::ModeratorTools)
{
}

void TwitchModerationElement::addToContainer(MessageLayoutContainer &container,
                                             MessageElement::Flags _flags)
{
    if (_flags & MessageElement::ModeratorTools) {
        QSize size((int)(container.getScale() * 16), (int)(container.getScale() * 16));

        for (const singletons::ModerationAction &m :
             singletons::SettingManager::getInstance().getModerationActions()) {
            if (m.isImage()) {
                container.addElement((new ImageLayoutElement(*this, m.getImage(), size))
                                         ->setLink(Link(Link::UserAction, m.getAction())));
            } else {
                container.addElement((new TextIconLayoutElement(*this, m.getLine1(), m.getLine2(),
                                                                container.getScale(), size))
                                         ->setLink(Link(Link::UserAction, m.getAction())));
            }
        }
    }
}

}  // namespace messages
}  // namespace chatterino
<|endoftext|>


<commit_before>#ifndef IMPORTER_NODESTORE_HPP
#define IMPORTER_NODESTORE_HPP

class Nodestore {
public:
    struct Nodeinfo {
        osm_version_t version;
        double lat;
        double lon;
    };

private:
    typedef std::map< time_t, Nodeinfo > timemap;
    typedef std::pair< time_t, Nodeinfo > timepair;
    typedef std::map< time_t, Nodeinfo >::iterator timemap_it;
    typedef std::map< time_t, Nodeinfo >::const_iterator timemap_cit;

    typedef std::map< osm_object_id_t, timemap* > nodemap;
    typedef std::pair< osm_object_id_t, timemap* > nodepair;
    typedef std::map< osm_object_id_t, timemap* >::iterator nodemap_it;
    typedef std::map< osm_object_id_t, timemap* >::const_iterator nodemap_cit;
    nodemap m_nodemap;

public:
    Nodestore() : m_nodemap() {}
    ~Nodestore() {
        nodemap_cit end = m_nodemap.end();
        for(nodemap_cit it = m_nodemap.begin(); it != end; ++it) {
            delete it->second;
        }
    }

    void record(osm_object_id_t id, osm_version_t v, time_t t, double lon, double lat) {
        Nodeinfo info = {v, lon, lat};

        nodemap_it it = m_nodemap.find(id);
        timemap *tmap;

        if(it == m_nodemap.end()) {
            if(Osmium::debug()) {
                std::cerr << "no timemap for node #" << id << ", creating new" << std::endl;
            }

            tmap = new timemap();
            m_nodemap.insert(nodepair(id, tmap));
        } else {
            tmap = it->second;
        }

        tmap->insert(timepair(t, info));
        if(Osmium::debug()) {
            std::cerr << "adding timepair for node #" << id << " v" << v << " at tstamp " << t << std::endl;
        }
    }

    Nodeinfo lookup(osm_object_id_t id, time_t t) {
        Nodeinfo nullinfo = {0, 0, 0};

        if(Osmium::debug()) {
            std::cerr << "looking up information of node #" << id << " at tstamp " << t << std::endl;
        }

        nodemap_it nit = m_nodemap.find(id);
        if(nit == m_nodemap.end()) {
            std::cerr << "no timemap for node #" << id << ", skipping node" << std::endl;
            return nullinfo;
        }

        timemap *tmap = nit->second;
        timemap_it tit = tmap->upper_bound(t);

        if(tit == tmap->begin()) {
            std::cerr << "reference to node #" << id << " at tstamp " << t << " which is before the youngest available version of that node, using version " << tit->second.version << std::endl;
        } else {
            tit--;
        }

        return tit->second;
    }

    geos::geom::Geometry* mkgeom(Osmium::OSM::WayNodeList &nodes, time_t t, bool looksLikePolygon) {
        // shorthand to the geometry factory
        geos::geom::GeometryFactory *f = Osmium::Geometry::geos_geometry_factory();

        // pointer to coordinate vector
        std::vector<geos::geom::Coordinate> *c = new std::vector<geos::geom::Coordinate>();

        Osmium::OSM::WayNodeList::const_iterator end = nodes.end();
        for(Osmium::OSM::WayNodeList::const_iterator it = nodes.begin(); it != end; ++it) {
            osm_object_id_t id = it->ref();

            Nodeinfo info = lookup(id, t);
            if(info.version == 0)
                continue;

            if(Osmium::debug()) {
                std::cerr << "node #" << id << " at tstamp " << t << " references version " << info.version << std::endl;
            }

            c->push_back(geos::geom::Coordinate(info.lat, info.lon, DoubleNotANumber));
        }

        if(c->size() < 2) {
			std::cerr << "found only " << c->size() << " valid coordinates, skipping way" << std::endl;
			return NULL;
		}

        geos::geom::Geometry* geom;

        try {
            // tags say it could be a polygon and the way is closed
            if(looksLikePolygon && c->front() == c->back()) {
                // build a polygon
                geom = f->createPolygon(
                    f->createLinearRing(
                        f->getCoordinateSequenceFactory()->create(c)
                    ),
                    NULL
                );
            } else {
                // build a linestring
                geom = f->createLineString(
                    f->getCoordinateSequenceFactory()->create(c)
                );
            }
        } catch(geos::util::GEOSException e) {
            std::cerr << "error creating polygon: " << e.what() << std::endl;
            return NULL;
        }

        geom->setSRID(900913);
        return geom;
    }
};

#endif // IMPORTER_NODESTORE_HPP
<commit_msg>whitespace IS important<commit_after>#ifndef IMPORTER_NODESTORE_HPP
#define IMPORTER_NODESTORE_HPP

class Nodestore {
public:
    struct Nodeinfo {
        osm_version_t version;
        double lat;
        double lon;
    };

private:
    typedef std::map< time_t, Nodeinfo > timemap;
    typedef std::pair< time_t, Nodeinfo > timepair;
    typedef std::map< time_t, Nodeinfo >::iterator timemap_it;
    typedef std::map< time_t, Nodeinfo >::const_iterator timemap_cit;

    typedef std::map< osm_object_id_t, timemap* > nodemap;
    typedef std::pair< osm_object_id_t, timemap* > nodepair;
    typedef std::map< osm_object_id_t, timemap* >::iterator nodemap_it;
    typedef std::map< osm_object_id_t, timemap* >::const_iterator nodemap_cit;
    nodemap m_nodemap;

public:
    Nodestore() : m_nodemap() {}
    ~Nodestore() {
        nodemap_cit end = m_nodemap.end();
        for(nodemap_cit it = m_nodemap.begin(); it != end; ++it) {
            delete it->second;
        }
    }

    void record(osm_object_id_t id, osm_version_t v, time_t t, double lon, double lat) {
        Nodeinfo info = {v, lon, lat};

        nodemap_it it = m_nodemap.find(id);
        timemap *tmap;

        if(it == m_nodemap.end()) {
            if(Osmium::debug()) {
                std::cerr << "no timemap for node #" << id << ", creating new" << std::endl;
            }

            tmap = new timemap();
            m_nodemap.insert(nodepair(id, tmap));
        } else {
            tmap = it->second;
        }

        tmap->insert(timepair(t, info));
        if(Osmium::debug()) {
            std::cerr << "adding timepair for node #" << id << " v" << v << " at tstamp " << t << std::endl;
        }
    }

    Nodeinfo lookup(osm_object_id_t id, time_t t) {
        Nodeinfo nullinfo = {0, 0, 0};

        if(Osmium::debug()) {
            std::cerr << "looking up information of node #" << id << " at tstamp " << t << std::endl;
        }

        nodemap_it nit = m_nodemap.find(id);
        if(nit == m_nodemap.end()) {
            std::cerr << "no timemap for node #" << id << ", skipping node" << std::endl;
            return nullinfo;
        }

        timemap *tmap = nit->second;
        timemap_it tit = tmap->upper_bound(t);

        if(tit == tmap->begin()) {
            std::cerr << "reference to node #" << id << " at tstamp " << t << " which is before the youngest available version of that node, using version " << tit->second.version << std::endl;
        } else {
            tit--;
        }

        return tit->second;
    }

    geos::geom::Geometry* mkgeom(Osmium::OSM::WayNodeList &nodes, time_t t, bool looksLikePolygon) {
        // shorthand to the geometry factory
        geos::geom::GeometryFactory *f = Osmium::Geometry::geos_geometry_factory();

        // pointer to coordinate vector
        std::vector<geos::geom::Coordinate> *c = new std::vector<geos::geom::Coordinate>();

        Osmium::OSM::WayNodeList::const_iterator end = nodes.end();
        for(Osmium::OSM::WayNodeList::const_iterator it = nodes.begin(); it != end; ++it) {
            osm_object_id_t id = it->ref();

            Nodeinfo info = lookup(id, t);
            if(info.version == 0)
                continue;

            if(Osmium::debug()) {
                std::cerr << "node #" << id << " at tstamp " << t << " references version " << info.version << std::endl;
            }

            c->push_back(geos::geom::Coordinate(info.lat, info.lon, DoubleNotANumber));
        }

        if(c->size() < 2) {
            std::cerr << "found only " << c->size() << " valid coordinates, skipping way" << std::endl;
            return NULL;
        }

        geos::geom::Geometry* geom;

        try {
            // tags say it could be a polygon and the way is closed
            if(looksLikePolygon && c->front() == c->back()) {
                // build a polygon
                geom = f->createPolygon(
                    f->createLinearRing(
                        f->getCoordinateSequenceFactory()->create(c)
                    ),
                    NULL
                );
            } else {
                // build a linestring
                geom = f->createLineString(
                    f->getCoordinateSequenceFactory()->create(c)
                );
            }
        } catch(geos::util::GEOSException e) {
            std::cerr << "error creating polygon: " << e.what() << std::endl;
            return NULL;
        }

        geom->setSRID(900913);
        return geom;
    }
};

#endif // IMPORTER_NODESTORE_HPP
<|endoftext|>


<commit_before>#include "variant/platform.hpp"

#include "hal.h"

#include "variant/i2c_platform.hpp"
#include "variant/pwm_platform.hpp"
#include "variant/spi_platform.hpp"
#include "variant/usart_platform.hpp"

Platform::Platform() {
}

template <>
I2CPlatform& Platform::get() {
  static I2CPlatform i2cPlatform;
  return i2cPlatform;
}

template <>
PWMPlatform& Platform::get() {
  static PWMPlatform pwmPlatform;
  return pwmPlatform;
}

template <>
SPIPlatform& Platform::get() {
  static SPIPlatform spiPlatform;
  return spiPlatform;
}

template <>
USARTPlatform& Platform::get() {
  static USARTPlatform usartPlatform;
  return usartPlatform;
}

void Platform::init() {
  get<I2CPlatform>();
  get<PWMPlatform>();
  get<SPIPlatform>();
  get<USARTPlatform>();

  get<ICUPlatform>().init();
}
<commit_msg>Make all platforms singletons.<commit_after>#include "variant/platform.hpp"

#include "hal.h"

#include "variant/i2c_platform.hpp"
#include "variant/pwm_platform.hpp"
#include "variant/spi_platform.hpp"
#include "variant/usart_platform.hpp"

Platform::Platform() {
}

template <>
I2CPlatform& Platform::get() {
  return I2CPlatform::getInstance();
}

template <>
PWMPlatform& Platform::get() {
  return PWMPlatform::getInstance();
}

template <>
SPIPlatform& Platform::get() {
  return SPIPlatform::getInstance();
}

template <>
USARTPlatform& Platform::get() {
  return USARTPlatform::getInstance();
}

void Platform::init() {
  get<I2CPlatform>();
  get<PWMPlatform>();
  get<SPIPlatform>();
  get<USARTPlatform>();

  get<ICUPlatform>().init();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <stdlib.h>

#include <iostream>
#include <corecrt_io.h>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <filesystem>

using namespace std;

#if GLOG
#include "glog/logging.h"

enum level
{
    INFO=0,
    WARINIG=1,
    ERROR=2,
    FATAL=3
};

void test_glog()
{
    for(int i = 1; i < 101; i++)
    {
        //满足i==100才会打印
        LOG_IF(INFO,i==100)<<"LOG_IF(INFO,I==100),google::COUNTER=" << google::COUNTER << " i=" << i << endl;

        //每隔10次打印一次，对于刷屏的日志控制很好
        LOG_EVERY_N(INFO,10)<<"LOG_EVERY_N(INFO,10) google::COUNTER=" << google::COUNTER << " i=" << i;

        //满足i > 50的条件后，每隔10次打印一次，对于刷屏的日志控制很好
        LOG_IF_EVERY_N(WARNING,(i>50),10) << "LOG_IF_ERVER_N(INFO,(I>50),10) google::COUNTER="<<google::COUNTER<< " i=" << i;

        //只打印前5次
        LOG_FIRST_N(ERROR,5) << "LOG_FIRST_N(error,5) google::COUNTER=" << " i=" << i;

        //每次都打印
        LOG(ERROR) << "TEST BY TOPSLUO" << endl;
    }
}

int test_glog_main(int argc)
{
    google::InitGoogleLogging("vsc2");
    FLAGS_stderrthreshold=INFO;
    FLAGS_colorlogtostderr=true;
    google::SetStderrLogging(INFO);//设置级别高于google::INFO的日志同时输出到屏幕
    google::SetLogDestination(ERROR,"./log/error_");//设置google::ERROR级别的日志存储路径和文件名前缀
    google::SetLogDestination(WARINIG,"./log/warning_");
    google::SetLogDestination(INFO,"./log/info_");
    FLAGS_logbufsecs = 0;//缓冲日志输出，默认为30秒，此处改为立刻
    FLAGS_max_log_size = 100;//最大日志大小为100M
    FLAGS_stop_logging_if_full_disk = true;//当磁盘被写满时，停止日志输出
    google::SetLogFilenameExtension("91_");//设置文件名扩展，如平台，或者其它需要区分的信息
    google::InstallFailureSignalHandler();//捕捉core dumped
    //google::InstallFailureWriter(&SignalHandle);//默认捕捉SIGSEGV信息输出会输出到sdtdrr

    test_glog();

    google::ShutdownGoogleLogging();//GLOG内存清理，一般与  google::InitGoogleLogging配对使用
    return 0;
}

int test_dir_main()
{
	string folderPath = "y:\\temp\\database\\testFolder";

	if (0 != _access(folderPath.c_str(), 0))
	{
        // if this folder not exist, create a new one. 换成 ::_mkdir  ::_access 也行，不知道什么意思
		mkdir(folderPath.c_str());   // 返回 0 表示创建成功，-1 表示失败
	}

	return 0;
}
#endif
int main(int, char**) {
	int kk = 1;
	kk++;
    std::cout << "Hello, world!\n";
    test_dir_main();
    //test_glog_main(1);

#if __LINUX__
    char path[256];
    sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", 0);
    FILE* fp = fopen(path, "rb");
    if (!fp)
        return -1;

    int max_freq_khz = -1;
    int nscan = fscanf(fp, "%d", &max_freq_khz);

    std::cout << "fscanf, world! " << nscan << std::endl;

    sprintf(path, "/sys/devices/system/cpu/cpufreq/stats/cpu%d/time_in_state", 0);
    sprintf(path, "/home/sf/time_in_state.txt");
    FILE* fp1 = fopen(path, "rb");
    max_freq_khz = 0;
    while (!feof(fp1))
    {
        int freq_khz = 0;
        int nscan = fscanf(fp1, "%d %*d", &freq_khz);
        std::cout << "fscanf, freq_khz! " << nscan << std::endl;
        if (nscan != 1)
            break;

        if (freq_khz > max_freq_khz)
            max_freq_khz = freq_khz;
    }
#endif
    std::cout << "fscanf end \n";
}
<commit_msg>PREF c++ vscode test main 注释非跨平台dir<commit_after>#include <iostream>
#include <stdlib.h>

using namespace std;

#if GLOG
#include "glog/logging.h"
#include <iostream>
#include <corecrt_io.h>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <filesystem>

enum level
{
    INFO=0,
    WARINIG=1,
    ERROR=2,
    FATAL=3
};

void test_glog()
{
    for(int i = 1; i < 101; i++)
    {
        //满足i==100才会打印
        LOG_IF(INFO,i==100)<<"LOG_IF(INFO,I==100),google::COUNTER=" << google::COUNTER << " i=" << i << endl;

        //每隔10次打印一次，对于刷屏的日志控制很好
        LOG_EVERY_N(INFO,10)<<"LOG_EVERY_N(INFO,10) google::COUNTER=" << google::COUNTER << " i=" << i;

        //满足i > 50的条件后，每隔10次打印一次，对于刷屏的日志控制很好
        LOG_IF_EVERY_N(WARNING,(i>50),10) << "LOG_IF_ERVER_N(INFO,(I>50),10) google::COUNTER="<<google::COUNTER<< " i=" << i;

        //只打印前5次
        LOG_FIRST_N(ERROR,5) << "LOG_FIRST_N(error,5) google::COUNTER=" << " i=" << i;

        //每次都打印
        LOG(ERROR) << "TEST BY TOPSLUO" << endl;
    }
}

int test_glog_main(int argc)
{
    google::InitGoogleLogging("vsc2");
    FLAGS_stderrthreshold=INFO;
    FLAGS_colorlogtostderr=true;
    google::SetStderrLogging(INFO);//设置级别高于google::INFO的日志同时输出到屏幕
    google::SetLogDestination(ERROR,"./log/error_");//设置google::ERROR级别的日志存储路径和文件名前缀
    google::SetLogDestination(WARINIG,"./log/warning_");
    google::SetLogDestination(INFO,"./log/info_");
    FLAGS_logbufsecs = 0;//缓冲日志输出，默认为30秒，此处改为立刻
    FLAGS_max_log_size = 100;//最大日志大小为100M
    FLAGS_stop_logging_if_full_disk = true;//当磁盘被写满时，停止日志输出
    google::SetLogFilenameExtension("91_");//设置文件名扩展，如平台，或者其它需要区分的信息
    google::InstallFailureSignalHandler();//捕捉core dumped
    //google::InstallFailureWriter(&SignalHandle);//默认捕捉SIGSEGV信息输出会输出到sdtdrr

    test_glog();

    google::ShutdownGoogleLogging();//GLOG内存清理，一般与  google::InitGoogleLogging配对使用
    return 0;
}

int test_dir_main()
{
	string folderPath = "y:\\temp\\database\\testFolder";

	if (0 != _access(folderPath.c_str(), 0))
	{
        // if this folder not exist, create a new one. 换成 ::_mkdir  ::_access 也行，不知道什么意思
		mkdir(folderPath.c_str());   // 返回 0 表示创建成功，-1 表示失败
	}

	return 0;
}
#endif
int main(int, char**) {
	int kk = 1;
	kk++;
    std::cout << "Hello, world!\n";
    //test_dir_main();
    //test_glog_main(1);

#if __LINUX__
    char path[256];
    sprintf(path, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", 0);
    FILE* fp = fopen(path, "rb");
    if (!fp)
        return -1;

    int max_freq_khz = -1;
    int nscan = fscanf(fp, "%d", &max_freq_khz);

    std::cout << "fscanf, world! " << nscan << std::endl;

    sprintf(path, "/sys/devices/system/cpu/cpufreq/stats/cpu%d/time_in_state", 0);
    sprintf(path, "/home/sf/time_in_state.txt");
    FILE* fp1 = fopen(path, "rb");
    max_freq_khz = 0;
    while (!feof(fp1))
    {
        int freq_khz = 0;
        int nscan = fscanf(fp1, "%d %*d", &freq_khz);
        std::cout << "fscanf, freq_khz! " << nscan << std::endl;
        if (nscan != 1)
            break;

        if (freq_khz > max_freq_khz)
            max_freq_khz = freq_khz;
    }
#endif
    std::cout << "fscanf end \n";
}
<|endoftext|>


<commit_before>#include <bits/stdc++.h>

using namespace std;

// https://cp-algorithms.com/geometry/convex_hull_trick.html

using ftype = int;
using point = complex<ftype>;

ftype dot(point a, point b) {
    return (conj(a) * b).real();
}

ftype f(point a, ftype x) {
    return dot(a, {x, 1});
}

const int maxn = 2e5;

point lines[4 * maxn];

void add_line(point line, int node = 1, int l = 0, int r = maxn) {
    int m = (l + r) / 2;
    bool left = f(line, l) < f(lines[node], l);
    bool mid = f(line, m) < f(lines[node], m);
    if (mid) {
        swap(lines[node], line);
    }
    if (r - l == 1) {
        return;
    } else if (left != mid) {
        add_line(line, 2 * node, l, m);
    } else {
        add_line(line, 2 * node + 1, m, r);
    }
}

int get_min(int x, int node = 1, int l = 0, int r = maxn) {
    int m = (l + r) / 2;
    if (r - l == 1) {
        return f(lines[node], x);
    } else if (x < m) {
        return min(f(lines[node], x), get_min(x, 2 * node, l, m));
    } else {
        return min(f(lines[node], x), get_min(x, 2 * node + 1, m, r));
    }
}

// usage example
int main() {
    fill(lines, lines + 4 * maxn, point(0, numeric_limits<int>::max()));
    add_line({1, 3});
    add_line({2, 1});
    cout << get_min(1) << endl;
}
<commit_msg>update<commit_after>#include <bits/stdc++.h>

using namespace std;

// https://cp-algorithms.com/geometry/convex_hull_trick.html

using ftype = long long;

struct Line {
    ftype k, d;

    ftype eval(ftype x) {
        return k * x + d;
    }
};

struct Node {
    Line line;
    Node *left = nullptr;
    Node *right = nullptr;

    Node(Line line) : line(line) {}

    void add_line(Line nline, ftype l, ftype r) {
        ftype m = (l + r) / 2;
        bool left_smaller = nline.eval(l) < line.eval(l);
        bool mid_smaller = nline.eval(m) < line.eval(m);
        if (mid_smaller) {
            swap(line, nline);
        }
        if (r - l == 1) {
            return;
        }
        if (left_smaller != mid_smaller) {
            if (left == nullptr)
                left = new Node(nline);
            else
                left->add_line(nline, l, m);
        } else {
            if (right == nullptr)
                right = new Node(nline);
            else
                right->add_line(nline, m, r);
        }
    }

    ftype get_min(ftype x, ftype l, ftype r) {
        if (r - l > 1) {
            ftype m = (l + r) / 2;
            if (x < m && left != nullptr) {
                return min(line.eval(x), left->get_min(x, l, m));
            }
            if (x >= m && right != nullptr) {
                return min(line.eval(x), right->get_min(x, m, r));
            }
        }
        return line.eval(x);
    }
};

struct LiChaoTree {
    ftype minx;
    ftype maxx;
    Node *root;

    LiChaoTree(ftype minx, ftype maxx) : minx(minx), maxx(maxx) {
        root = new Node({0, std::numeric_limits<ftype>::max() / 2});
    }

    void add_line(Line line) {
        root->add_line(line, minx, maxx + 1);
    }

    ftype get_min(ftype x) {
        return root->get_min(x, minx, maxx + 1);
    }
};

// usage example
int main() {
    LiChaoTree t = LiChaoTree(1, 1e9);
    t.add_line({1, 3});
    t.add_line({2, 1});
    cout << t.get_min(1) << endl;
}
<|endoftext|>


<commit_before>/// HEADER
#include "hog_extractor.h"

/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex_core_plugins/vector_message.h>
#include <csapex_vision/roi_message.h>
#include <csapex_vision/cv_mat_message.h>
#include <csapex_ml/features_message.h>

/// SYSTEM
#include <boost/assign.hpp>
#include <opencv2/objdetect/objdetect.hpp>

CSAPEX_REGISTER_CLASS(vision_plugins::HOGExtractor, csapex::Node)
/// TODO : L2HysThreshold - derivAperture

using namespace csapex;
using namespace csapex::connection_types;
using namespace vision_plugins;

HOGExtractor::HOGExtractor()
{
}

void HOGExtractor::setupParameters(Parameterizable& parameters)
{
    parameters.addParameter(param::ParameterFactory::declareRange("hog/sigma",
                                                                  param::ParameterDescription("Standard deviation for Gaussian blur."),
                                                                  0.0, 10.0, 0.0, 0.1),
                            hog_.winSigma);

    parameters.addParameter(param::ParameterFactory::declareBool("hog/gamma_correction",
                                                                 param::ParameterDescription("Enable the gamma correction."),
                                                                 true),
                            hog_.gammaCorrection);
    parameters.addParameter(param::ParameterFactory::declareBool("hog/signed_gradient",
                                                                 param::ParameterDescription("Un-/directed gradients."),
                                                                 hog_.signedGradient),
                            hog_.signedGradient);

    addParameter(param::ParameterFactory::declareRange("hog/gradient_bins",
                                                       param::ParameterDescription("Amount of gradient bins."),
                                                       2, 18, hog_.nbins, 1),
                 hog_.nbins);

    parameters.addParameter(param::ParameterFactory::declareRange("hog/cells_x",
                                                                  param::ParameterDescription("Cells in x direction."),
                                                                  2, 16, 8, 1),
                            cells_x_);

    parameters.addParameter(param::ParameterFactory::declareRange("hog/cells_y",
                                                                  param::ParameterDescription("Cells in x direction."),
                                                                  2, 16, 16, 1),
                            cells_y_);

    parameters.addParameter(param::ParameterFactory::declareRange("hog/cell_size",
                                                                  param::ParameterDescription("Size of the cells."),
                                                                  4, 16, 8, 1),
                            cell_size_);
    parameters.addParameter(param::ParameterFactory::declareRange("hog/block size",
                                                                  param::ParameterDescription("Cell count in both dimension of a block."),
                                                                  1, 4, 2, 1),
                            block_size_);
    parameters.addParameter(param::ParameterFactory::declareRange("hog/bock_stride",
                                                                  param::ParameterDescription("Overlap of each block in cells."),
                                                                  1, 3, 1, 1),
                            block_stride_);

    std::map<std::string, int> adpation_types =
            boost::assign::map_list_of("Scale", SCALE)("TryGrow", TRY_GROW)("GrowStrict", GROW_STRICT);
    parameters.addParameter(param::ParameterFactory::declareParameterSet("hog/adaption_mode",
                                                                         param::ParameterDescription("Adaption of rois to window size of hog."),
                                                                         adpation_types,
                                                                         (int) SCALE),
                            adaption_type_);
}

void HOGExtractor::setup(NodeModifier& node_modifier)
{
    in_img_     = node_modifier.addInput<CvMatMessage>("image");
    in_rois_    = node_modifier.addInput<VectorMessage, RoiMessage>("rois");
    out_        = node_modifier.addOutput<VectorMessage, FeaturesMessage>("features");
}

void HOGExtractor::process()
{
    CvMatMessage::ConstPtr  in = msg::getMessage<CvMatMessage>(in_img_);
    VectorMessage::ConstPtr in_rois = msg::getMessage<VectorMessage>(in_rois_);
    VectorMessage::Ptr      out(VectorMessage::make<FeaturesMessage>());

    /// update HOG parameters
    hog_.cellSize.width  = cell_size_;
    hog_.cellSize.height = cell_size_;
    hog_.winSize.height  = cell_size_ * cells_y_;
    hog_.winSize.width   = cell_size_ * cells_x_;
    hog_.blockSize       = hog_.cellSize * block_size_;
    hog_.blockStride     = hog_.cellSize * block_stride_;
    ratio_hog_ = hog_.winSize.width / (double) hog_.winSize.height;
    if(hog_.winSigma == 0)
        hog_.winSigma = -1;

    if(in->value.channels() != 1 && in->value.channels() != 3) {
        throw std::runtime_error("Only 1 or 3 channel matrices supported!");
    }

    for(auto &entry : in_rois->value) {
        RoiMessage::ConstPtr roi  = std::dynamic_pointer_cast<RoiMessage const>(entry);
        cv::Mat data;

        getData(in->value, roi->value.rect(), data);

        if(data.empty())
            continue;

        assert(data.rows == hog_.winSize.height);
        assert(data.cols == hog_.winSize.width);

        FeaturesMessage::Ptr feature(new FeaturesMessage);
        feature->classification = roi->value.classification();
        hog_.computeSingle(data, feature->value);
        out->value.push_back(feature);
        if(mirror_) {
            feature.reset(new FeaturesMessage);
            feature->classification = roi->value.classification();

            cv::flip(data, data, 1);
            hog_.compute(data, feature->value);
            out->value.push_back(feature);
        }
    }
    msg::publish(out_, out);
}

void HOGExtractor::getData(const cv::Mat &src, const cv::Rect &roi, cv::Mat &dst)
{
    cv::Mat window;
    double ratio_roi = roi.width / (double) roi.height;
    cv::Rect roi_adapted = roi;

    switch(adaption_type_) {
    case SCALE:
        break;
    case TRY_GROW:
    case GROW_STRICT:
        if(ratio_roi < ratio_hog_) {
            /// scale the width
            double scale_width = ratio_roi / ratio_hog_;
            roi_adapted.width *= scale_width;
            roi_adapted.x -= (roi_adapted.width - roi.width) / 2;
            /// move to fit into image
            if(roi_adapted.x < 0) {
                roi_adapted.x = 0;
            } else {
                int overshoot = (src.cols - 1) - (roi_adapted.x + roi.width);
                if(overshoot < 0) {
                    roi_adapted.x += overshoot;
                }
            }
        } else if(ratio_roi > ratio_hog_) {
            /// scale the height
            double scale_height = ratio_hog_ / ratio_roi;
            roi_adapted.height *= scale_height;
            roi_adapted.y -= (roi_adapted.height - roi.height) / 2;
            /// move to fit into image
            if(roi_adapted.y < 0) {
                roi_adapted.y = 0;
            } else {
                int overshoot = (src.rows - 1) - (roi_adapted.y + roi.height);
                if(overshoot < 0) {
                    roi_adapted.y += overshoot;
                }
            }
        }
        if(roi.height > src.rows || roi.width > src.cols) {
            cv::Rect img_rect(0,0,src.cols, src.rows);
            roi_adapted = roi_adapted & img_rect;

            if(adaption_type_ == GROW_STRICT)
                return;
        }
        break;
    default:
        throw std::runtime_error("Unknown adaption type!");
    }

    window = cv::Mat(src, roi_adapted);
    cv::resize(window, dst, hog_.winSize);

}
<commit_msg>the missing parameter<commit_after>/// HEADER
#include "hog_extractor.h"

/// PROJECT
#include <csapex/msg/io.h>
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex_core_plugins/vector_message.h>
#include <csapex_vision/roi_message.h>
#include <csapex_vision/cv_mat_message.h>
#include <csapex_ml/features_message.h>

/// SYSTEM
#include <boost/assign.hpp>
#include <opencv2/objdetect/objdetect.hpp>

CSAPEX_REGISTER_CLASS(vision_plugins::HOGExtractor, csapex::Node)
/// TODO : L2HysThreshold - derivAperture

using namespace csapex;
using namespace csapex::connection_types;
using namespace vision_plugins;

HOGExtractor::HOGExtractor()
{
}

void HOGExtractor::setupParameters(Parameterizable& parameters)
{
    parameters.addParameter(param::ParameterFactory::declareRange("hog/sigma",
                                                                  param::ParameterDescription("Standard deviation for Gaussian blur."),
                                                                  0.0, 10.0, 0.0, 0.1),
                            hog_.winSigma);

    parameters.addParameter(param::ParameterFactory::declareBool("hog/gamma_correction",
                                                                 param::ParameterDescription("Enable the gamma correction."),
                                                                 true),
                            hog_.gammaCorrection);
    parameters.addParameter(param::ParameterFactory::declareBool("hog/signed_gradient",
                                                                 param::ParameterDescription("Un-/directed gradients."),
                                                                 hog_.signedGradient),
                            hog_.signedGradient);

    addParameter(param::ParameterFactory::declareRange("hog/gradient_bins",
                                                       param::ParameterDescription("Amount of gradient bins."),
                                                       2, 18, hog_.nbins, 1),
                 hog_.nbins);

    parameters.addParameter(param::ParameterFactory::declareRange("hog/cells_x",
                                                                  param::ParameterDescription("Cells in x direction."),
                                                                  2, 16, 8, 1),
                            cells_x_);

    parameters.addParameter(param::ParameterFactory::declareRange("hog/cells_y",
                                                                  param::ParameterDescription("Cells in x direction."),
                                                                  2, 16, 16, 1),
                            cells_y_);

    parameters.addParameter(param::ParameterFactory::declareRange("hog/cell_size",
                                                                  param::ParameterDescription("Size of the cells."),
                                                                  4, 16, 8, 1),
                            cell_size_);
    parameters.addParameter(param::ParameterFactory::declareRange("hog/block size",
                                                                  param::ParameterDescription("Cell count in both dimension of a block."),
                                                                  1, 4, 2, 1),
                            block_size_);
    parameters.addParameter(param::ParameterFactory::declareRange("hog/bock_stride",
                                                                  param::ParameterDescription("Overlap of each block in cells."),
                                                                  1, 3, 1, 1),
                            block_stride_);

    std::map<std::string, int> adpation_types =
            boost::assign::map_list_of("Scale", SCALE)("TryGrow", TRY_GROW)("GrowStrict", GROW_STRICT);
    parameters.addParameter(param::ParameterFactory::declareParameterSet("hog/adaption_mode",
                                                                         param::ParameterDescription("Adaption of rois to window size of hog."),
                                                                         adpation_types,
                                                                         (int) SCALE),
                            adaption_type_);
    parameters.addParameter(param::ParameterFactory::declareBool("mirror", true),
                            mirror_);

}

void HOGExtractor::setup(NodeModifier& node_modifier)
{
    in_img_     = node_modifier.addInput<CvMatMessage>("image");
    in_rois_    = node_modifier.addInput<VectorMessage, RoiMessage>("rois");
    out_        = node_modifier.addOutput<VectorMessage, FeaturesMessage>("features");
}

void HOGExtractor::process()
{
    CvMatMessage::ConstPtr  in = msg::getMessage<CvMatMessage>(in_img_);
    VectorMessage::ConstPtr in_rois = msg::getMessage<VectorMessage>(in_rois_);
    VectorMessage::Ptr      out(VectorMessage::make<FeaturesMessage>());

    /// update HOG parameters
    hog_.cellSize.width  = cell_size_;
    hog_.cellSize.height = cell_size_;
    hog_.winSize.height  = cell_size_ * cells_y_;
    hog_.winSize.width   = cell_size_ * cells_x_;
    hog_.blockSize       = hog_.cellSize * block_size_;
    hog_.blockStride     = hog_.cellSize * block_stride_;
    ratio_hog_ = hog_.winSize.width / (double) hog_.winSize.height;
    if(hog_.winSigma == 0)
        hog_.winSigma = -1;

    if(in->value.channels() != 1 && in->value.channels() != 3) {
        throw std::runtime_error("Only 1 or 3 channel matrices supported!");
    }

    for(auto &entry : in_rois->value) {
        RoiMessage::ConstPtr roi  = std::dynamic_pointer_cast<RoiMessage const>(entry);
        cv::Mat data;

        getData(in->value, roi->value.rect(), data);

        if(data.empty())
            continue;

        assert(data.rows == hog_.winSize.height);
        assert(data.cols == hog_.winSize.width);

        FeaturesMessage::Ptr feature(new FeaturesMessage);
        feature->classification = roi->value.classification();
        hog_.computeSingle(data, feature->value);
        out->value.push_back(feature);
        if(mirror_) {
            feature.reset(new FeaturesMessage);
            feature->classification = roi->value.classification();

            cv::flip(data, data, 1);
            hog_.compute(data, feature->value);
            out->value.push_back(feature);
        }
    }
    msg::publish(out_, out);
}

void HOGExtractor::getData(const cv::Mat &src, const cv::Rect &roi, cv::Mat &dst)
{
    cv::Mat window;
    double ratio_roi = roi.width / (double) roi.height;
    cv::Rect roi_adapted = roi;

    switch(adaption_type_) {
    case SCALE:
        break;
    case TRY_GROW:
    case GROW_STRICT:
        if(ratio_roi < ratio_hog_) {
            /// scale the width
            double scale_width = ratio_roi / ratio_hog_;
            roi_adapted.width *= scale_width;
            roi_adapted.x -= (roi_adapted.width - roi.width) / 2;
            /// move to fit into image
            if(roi_adapted.x < 0) {
                roi_adapted.x = 0;
            } else {
                int overshoot = (src.cols - 1) - (roi_adapted.x + roi.width);
                if(overshoot < 0) {
                    roi_adapted.x += overshoot;
                }
            }
        } else if(ratio_roi > ratio_hog_) {
            /// scale the height
            double scale_height = ratio_hog_ / ratio_roi;
            roi_adapted.height *= scale_height;
            roi_adapted.y -= (roi_adapted.height - roi.height) / 2;
            /// move to fit into image
            if(roi_adapted.y < 0) {
                roi_adapted.y = 0;
            } else {
                int overshoot = (src.rows - 1) - (roi_adapted.y + roi.height);
                if(overshoot < 0) {
                    roi_adapted.y += overshoot;
                }
            }
        }
        if(roi.height > src.rows || roi.width > src.cols) {
            cv::Rect img_rect(0,0,src.cols, src.rows);
            roi_adapted = roi_adapted & img_rect;

            if(adaption_type_ == GROW_STRICT)
                return;
        }
        break;
    default:
        throw std::runtime_error("Unknown adaption type!");
    }

    window = cv::Mat(src, roi_adapted);
    cv::resize(window, dst, hog_.winSize);

}
<|endoftext|>


<commit_before>#include "OI.h"
#include "Subsystems/CatapultFire.h"
#include "Subsystems/IntakeHorizontal.h"
#include "Commands/ControlCatapultFire.h"
#include "Commands/ReloadCatapult.h"

/// Default constructor of the class.
ControlCatapultFire::ControlCatapultFire(bool bypass)
	: m_nextCommand(new ReloadCatapult(BTN_PRESET_2))
	, timer(new Timer())
	, m_waiting(false)
	, m_bypass(bypass)
{
	Requires(CatapultFire::GetInstance());
	//Requires(IntakeHorizontal::GetInstance());
}

/// Called just before this Command runs the first time.
void ControlCatapultFire::Initialize()
{
	CatapultFire::GetInstance()->Actuate(false);
	if(IntakeHorizontal::GetInstance()->IsExtended() == false)
	{
		IntakeHorizontal::GetInstance()->Actuate(true);
		m_waiting = true;
	}
	else {
		m_waiting = false;
	}
	timer->Reset();
	timer->Start();
}

void ControlCatapultFire::Execute()
{
	if((!m_waiting or timer->Get() > .25) && ((m_bypass && Catapult::GetInstance()->IsBallPresent()) || !m_bypass))
	{
		CatapultFire::GetInstance()->Actuate(true);
		m_waiting = false;
	}

}

/// Make this return true when this Command no longer needs to run execute().
/// \return always false since this is the default command and should never finish.
bool ControlCatapultFire::IsFinished()
{
	if (m_bypass) return false;
	else return not OI::GetInstance()->gamepad->GetRawButton(BTN_SHOOT);
}

/// Called once after isFinished returns true
void ControlCatapultFire::End()
{
	CatapultFire::GetInstance()->Actuate(false);
	if(!m_waiting and timer->Get() < 3.0) m_nextCommand->Start();
}

/// Called when another command which requires one or more of the same
/// subsystems is scheduled to run
void ControlCatapultFire::Interrupted()
{
	// Do not call the normal End(); We don't want to start the next command if we're interrupted.
	CatapultFire::GetInstance()->Actuate(false);
}
<commit_msg>Added Missing Include<commit_after>#include "OI.h"
#include "Subsystems/CatapultFire.h"
#include "Subsystems/IntakeHorizontal.h"
#include "Subsystems/Catapult.h"
#include "Commands/ControlCatapultFire.h"
#include "Commands/ReloadCatapult.h"

/// Default constructor of the class.
ControlCatapultFire::ControlCatapultFire(bool bypass)
	: m_nextCommand(new ReloadCatapult(BTN_PRESET_2))
	, timer(new Timer())
	, m_waiting(false)
	, m_bypass(bypass)
{
	Requires(CatapultFire::GetInstance());
	//Requires(IntakeHorizontal::GetInstance());
}

/// Called just before this Command runs the first time.
void ControlCatapultFire::Initialize()
{
	CatapultFire::GetInstance()->Actuate(false);
	if(IntakeHorizontal::GetInstance()->IsExtended() == false)
	{
		IntakeHorizontal::GetInstance()->Actuate(true);
		m_waiting = true;
	}
	else {
		m_waiting = false;
	}
	timer->Reset();
	timer->Start();
}

void ControlCatapultFire::Execute()
{
	if((!m_waiting or timer->Get() > .25) && ((m_bypass && Catapult::GetInstance()->IsBallPresent()) || !m_bypass))
	{
		CatapultFire::GetInstance()->Actuate(true);
		m_waiting = false;
	}

}

/// Make this return true when this Command no longer needs to run execute().
/// \return always false since this is the default command and should never finish.
bool ControlCatapultFire::IsFinished()
{
	if (m_bypass) return false;
	else return not OI::GetInstance()->gamepad->GetRawButton(BTN_SHOOT);
}

/// Called once after isFinished returns true
void ControlCatapultFire::End()
{
	CatapultFire::GetInstance()->Actuate(false);
	if(!m_waiting and timer->Get() < 3.0) m_nextCommand->Start();
}

/// Called when another command which requires one or more of the same
/// subsystems is scheduled to run
void ControlCatapultFire::Interrupted()
{
	// Do not call the normal End(); We don't want to start the next command if we're interrupted.
	CatapultFire::GetInstance()->Actuate(false);
}
<|endoftext|>


<commit_before>
/*

a wrapped library for perl interprater.
please refer to this:
  http://perldoc.perl.org/perlembed.html
for more info.
--By Jidor Tang @ 20170307

------------

how to build and run (both Windows and Linux platform is OK)
   perl_interp_get_var_from_perl_to_c
   need to locate libperl.so or libperl.a  , something like this
   if on windows,
   first redirect the embed pm opts to a bat file, then put them in one line.
   and use straberryperl 's gcc : Strawberry\c\bin\gcc.exe
   to build , and may need use g++ -std=c++11   , or g++ is also ok.

   on Windows:  use :           g++ -std=c++11 -o interp interp.cpp  -s -L"C:\jd_p\sw\pro\STRAWB~1\perl\lib\CORE" -L ...
   and dep on at least these 4 DLLs:

   copy c:\jd_p\sw\pro\strawberry\c\bin\LIBWINPTHREAD-1.DLL .\
   copy c:\jd_p\sw\pro\strawberry\c\bin\LIBGCC_S_SJLJ-1.DLL .\
   copy "c:\jd_p\sw\pro\strawberry\c\bin\LIBSTDC++-6.DLL" .\
   copy c:\jd_p\sw\pro\strawberry\perl\bin\PERL522.DLL .\

### shell ###
export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH
g++ -o -DWINDIR interp interp.cpp -L`pwd` `perl -MExtUtils::Embed -e ccopts -e ldopts`
# g++ -o  interp interp.cpp -L`pwd` `perl -MExtUtils::Embed -e ccopts -e ldopts`
./interp
### end shell ###

*/

#include <iostream>
#include<stdlib.h>
using namespace std;

/* perl: static my_perl interp  */
#include "perl_lib.hpp"

/*** function readme ***
  INIT_PERL_INTERP;                             init perl and perl interp :my_perl
...
  P_eval("$_=111");                             run perl statement
  Int("a");                                     get $a from eval()
  Float("a");                                   dotto
  Str("a");                                     dotto
  P_arr_len("arr");                             get @arr length
  P_arr_Str_i("arr", 3);                        get @arr[3] as Str;
  P_arr_Int_i("arr", 3);                        get @arr[3] as Int;
  P_arr_Float_i("arr", 3);                      get @arr[3] as Float;
  P_arr_print("arr");                           print out @arr and its index,very slowly...
  int xx = m("abc", "m/b./");                   perl match
  char *ss = s("abc", "s/b/B/g");               perl substitute
...
  DESTROY_PERL_INTERP;                          Destroy my_perl
 ***********************/

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

        INIT_PERL_INTERP ;

        // -------- TODO ----------
        // ------------------------

        char *id_cmd = " $a=qq/ABC_/;$a=$a x 10; $a =~ s/.$//;@arr=split m/_/,$a;  ";
        P_eval( id_cmd );

        P_arr_print( "arr" );

        // ------------------------
        // ------------------------
        DESTROY_PERL_INTERP ;
        return 0;
}

<commit_msg>update using perl to format perl script to c char<commit_after>
/*

a wrapped library for perl interprater.
please refer to this:
  http://perldoc.perl.org/perlembed.html
for more info.
--By Jidor Tang @ 20170307

------------

how to build and run (both Windows and Linux platform is OK)
   perl_interp_get_var_from_perl_to_c
   need to locate libperl.so or libperl.a  , something like this
   if on windows,
   first redirect the embed pm opts to a bat file, then put them in one line.
   and use straberryperl 's gcc : Strawberry\c\bin\gcc.exe
   to build , and may need use g++ -std=c++11   , or g++ is also ok.

   on Windows:  use :           g++ -std=c++11 -o interp interp.cpp  -s -L"C:\jd_p\sw\pro\STRAWB~1\perl\lib\CORE" -L ...
   and dep on at least these 4 DLLs:

   copy c:\jd_p\sw\pro\strawberry\c\bin\LIBWINPTHREAD-1.DLL .\
   copy c:\jd_p\sw\pro\strawberry\c\bin\LIBGCC_S_SJLJ-1.DLL .\
   copy "c:\jd_p\sw\pro\strawberry\c\bin\LIBSTDC++-6.DLL" .\
   copy c:\jd_p\sw\pro\strawberry\perl\bin\PERL522.DLL .\

### shell ###
export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu:$LD_LIBRARY_PATH
g++ -o -DWINDIR interp interp.cpp -L`pwd` `perl -MExtUtils::Embed -e ccopts -e ldopts`
# g++ -o  interp interp.cpp -L`pwd` `perl -MExtUtils::Embed -e ccopts -e ldopts`

useful resource:

cat perlscript.pl   | perl -e '@arr=<>;map{s/\"(\w.*?)\"/qq\{\1\}/g; s/^(.*)/\"\1/g; s/(.)$/\1\"/; s|\\|\\\\|g;  ;print ; }@arr;print qq(;);'

- this will convert the script to c char* string.

like:
      my $sum=0;
      map{
              $sum+=$_;
      }(0..50);
      @arr=(qq{latest}, $sum);
===> c char*
"      my $sum=0;  "
"      map{  "
"              $sum+=$_;   "
"      }(0..50);  "
"      @arr=(qq{latest}, $sum); "
" "
;

./interp
### end shell ###

*/

#include <iostream>
#include<stdlib.h>
using namespace std;

/* perl: static my_perl interp  */
#include "perl_lib.hpp"

/*** function readme ***
  INIT_PERL_INTERP;                             init perl and perl interp :my_perl
...
  P_eval("$_=111");                             run perl statement
  Int("a");                                     get $a from eval()
  Float("a");                                   dotto
  Str("a");                                     dotto
  P_arr_len("arr");                             get @arr length
  P_arr_Str_i("arr", 3);                        get @arr[3] as Str;
  P_arr_Int_i("arr", 3);                        get @arr[3] as Int;
  P_arr_Float_i("arr", 3);                      get @arr[3] as Float;
  P_arr_print("arr");                           print out @arr and its index,very slowly...
  int xx = m("abc", "m/b./");                   perl match
  char *ss = s("abc", "s/b/B/g");               perl substitute
...
  DESTROY_PERL_INTERP;                          Destroy my_perl
 ***********************/

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

        INIT_PERL_INTERP ;

        // -------- TODO ----------
        // ------------------------

        char *id_cmd = " $a=qq/ABC_/;$a=$a x 10; $a =~ s/.$//;@arr=split m/_/,$a;  ";
        P_eval( id_cmd );

        P_arr_print( "arr" );

        // ------------------------
        // ------------------------
        DESTROY_PERL_INTERP ;
        return 0;
}

<|endoftext|>


<commit_before>#include "AppDelegate.h"
#include "HelloWorldScene.h"

USING_NS_CC;

static cocos2d::Size designResolutionSize = cocos2d::Size(1366, 700);
static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320);
static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768);
static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536);

AppDelegate::AppDelegate()
{
}

AppDelegate::~AppDelegate()
{
}

// if you want a different context, modify the value of glContextAttrs
// it will affect all platforms
void AppDelegate::initGLContextAttrs()
{
    // set OpenGL context attributes: red,green,blue,alpha,depth,stencil
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};

    GLView::setGLContextAttrs(glContextAttrs);
}

// if you want to use the package manager to install more packages,
// don't modify or remove this function
static int register_all_packages()
{
    return 0; //flag for packages manager
}

bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    auto director = Director::getInstance();
    auto glview = director->getOpenGLView();
    if(!glview) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
        glview = GLViewImpl::createWithRect("HelloCpp", cocos2d::Rect(0, 0, designResolutionSize.width, designResolutionSize.height));
#else
        glview = GLViewImpl::create("HelloCpp");
#endif
        director->setOpenGLView(glview);
    }

    // turn on display FPS
    director->setDisplayStats(true);

    // set FPS. the default value is 1.0/60 if you don't call this
    director->setAnimationInterval(1.0f / 60);

    // Set the design resolution
    glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER);
    auto frameSize = glview->getFrameSize();
    // if the frame's height is larger than the height of medium size.
    if (frameSize.height > mediumResolutionSize.height)
    {
        director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width));
    }
    // if the frame's height is larger than the height of small size.
    else if (frameSize.height > smallResolutionSize.height)
    {
        director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width));
    }
    // if the frame's height is smaller than the height of medium size.
    else
    {
        director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width));
    }

    register_all_packages();

    // create a scene. it's an autorelease object
    auto scene = HelloWorld::createScene();

    // run
    director->runWithScene(scene);

    return true;
}

// This function will be called when the app is inactive. Note, when receiving a phone call it is invoked.
void AppDelegate::applicationDidEnterBackground() {
    Director::getInstance()->stopAnimation();

    // if you use SimpleAudioEngine, it must be paused
    // SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}

// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
    Director::getInstance()->startAnimation();

    // if you use SimpleAudioEngine, it must resume here
    // SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
<commit_msg>just for test<commit_after>#include "AppDelegate.h"
#include "HelloWorldScene.h"

USING_NS_CC;

static cocos2d::Size designResolutionSize = cocos2d::Size(1366, 700);
static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320);
static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768);
static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536);

AppDelegate::AppDelegate()
{
	;
}

AppDelegate::~AppDelegate()
{
}

// if you want a different context, modify the value of glContextAttrs
// it will affect all platforms
void AppDelegate::initGLContextAttrs()
{
    // set OpenGL context attributes: red,green,blue,alpha,depth,stencil
    GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};

    GLView::setGLContextAttrs(glContextAttrs);
}

// if you want to use the package manager to install more packages,
// don't modify or remove this function
static int register_all_packages()
{
    return 0; //flag for packages manager
}

bool AppDelegate::applicationDidFinishLaunching() {
    // initialize director
    auto director = Director::getInstance();
    auto glview = director->getOpenGLView();
    if(!glview) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
        glview = GLViewImpl::createWithRect("HelloCpp", cocos2d::Rect(0, 0, designResolutionSize.width, designResolutionSize.height));
#else
        glview = GLViewImpl::create("HelloCpp");
#endif
        director->setOpenGLView(glview);
    }

    // turn on display FPS
    director->setDisplayStats(true);

    // set FPS. the default value is 1.0/60 if you don't call this
    director->setAnimationInterval(1.0f / 60);

    // Set the design resolution
    glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER);
    auto frameSize = glview->getFrameSize();
    // if the frame's height is larger than the height of medium size.
    if (frameSize.height > mediumResolutionSize.height)
    {
        director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width));
    }
    // if the frame's height is larger than the height of small size.
    else if (frameSize.height > smallResolutionSize.height)
    {
        director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width));
    }
    // if the frame's height is smaller than the height of medium size.
    else
    {
        director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width));
    }

    register_all_packages();

    // create a scene. it's an autorelease object
    auto scene = HelloWorld::createScene();

    // run
    director->runWithScene(scene);

    return true;
}

// This function will be called when the app is inactive. Note, when receiving a phone call it is invoked.
void AppDelegate::applicationDidEnterBackground() {
    Director::getInstance()->stopAnimation();

    // if you use SimpleAudioEngine, it must be paused
    // SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}

// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
    Director::getInstance()->startAnimation();

    // if you use SimpleAudioEngine, it must resume here
    // SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
<|endoftext|>