hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
bec27ea3ef18b955df25aad15de4b1b0f03d759e
11,458
cpp
C++
tiled_plugin/gfm/gfmplugin.cpp
SirGFM/big-15
dd41cd9483f7f2e8e27545e7e97340a1c1969bd6
[ "Zlib" ]
4
2015-04-14T14:34:57.000Z
2019-10-14T00:16:52.000Z
tiled_plugin/gfm/gfmplugin.cpp
SirGFM/big-15
dd41cd9483f7f2e8e27545e7e97340a1c1969bd6
[ "Zlib" ]
null
null
null
tiled_plugin/gfm/gfmplugin.cpp
SirGFM/big-15
dd41cd9483f7f2e8e27545e7e97340a1c1969bd6
[ "Zlib" ]
2
2016-04-21T16:22:31.000Z
2019-11-08T14:05:37.000Z
/** * GFM (proprietary) tiled plugin * * Based on the "CSV Tiled Plugin" * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #include "gfmplugin.h" #include "map.h" #include "mapobject.h" #include "objectgroup.h" #include "tile.h" #include "tilelayer.h" #include <QFile> #if QT_VERSION >= 0x050100 #define HAS_QSAVEFILE_SUPPORT #endif #ifdef HAS_QSAVEFILE_SUPPORT #include <QSaveFile> #endif using namespace Tiled; using namespace Gfm; typedef struct { int x; int y; int w; int h; } gfm_offset; static void getTilemapBounds(gfm_offset *pOff, const TileLayer *tileLayer); #ifdef HAS_QSAVEFILE_SUPPORT static void writeTilemap(QSaveFile &file, const TileLayer *tileLayer, gfm_offset *pOff); static void writeObject(QSaveFile &file, const MapObject *obj, gfm_offset *pOff); static void writeEvent(QSaveFile &file, const MapObject *ev, gfm_offset *pOff); static void writeMob(QSaveFile &file, const MapObject *obj, gfm_offset *pOff); #else static void writeTilemap(QFile &file, const TileLayer *tileLayer, gfm_offset *pOff); static void writeObject(QFile &file, const MapObject *obj, gfm_offset *pOff); static void writeEvent(QFile &file, const MapObject *ev, gfm_offset *pOff); static void writeMob(QFile &file, const MapObject *obj, gfm_offset *pOff); #endif GfmPlugin::GfmPlugin() { } bool GfmPlugin::write(const Map *map, const QString &fileName) { gfm_offset off; int foundTileLayer; #ifdef HAS_QSAVEFILE_SUPPORT QSaveFile file(fileName); #else QFile file(fileName); #endif if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { mError = tr("Could not open file for writing."); return false; } foundTileLayer = 0; // Write every layer foreach (const Layer *layer, map->layers()) { if (!layer->isVisible()) continue; // Write a tilemap if (layer->layerType() == Layer::TileLayerType) { const TileLayer *tileLayer; if (foundTileLayer == 1) { mError = tr("Found more than one tilemap!"); return false; } foundTileLayer = 1; tileLayer = static_cast<const TileLayer*>(layer); getTilemapBounds(&off, tileLayer); writeTilemap(file, tileLayer, &off); } else if (layer->layerType() == Layer::ObjectGroupType) { const ObjectGroup *objectGroup; if (foundTileLayer == 0) { mError = tr("First layer must be a tilemap!"); return false; } objectGroup = static_cast<const ObjectGroup*>(layer); foreach (const MapObject *obj, objectGroup->objects()) { if (!obj->isVisible()) continue; if (obj->type() == "obj") writeObject(file, obj, &off); else if (obj->type() == "event") writeEvent(file, obj, &off); else if (obj->type() == "mob") writeMob(file, obj, &off); else { mError = "Invalid object type!"; return false; } } } } if (file.error() != QFile::NoError) { mError = file.errorString(); return false; } #ifdef HAS_QSAVEFILE_SUPPORT if (!file.commit()) { mError = file.errorString(); return false; } #endif return true; } QString GfmPlugin::nameFilter() const { return tr("GFM files (*.gfm)"); } QString GfmPlugin::errorString() const { return mError; } #if QT_VERSION < 0x050000 Q_EXPORT_PLUGIN2(Gfm, GfmPlugin) #endif static void getTilemapBounds(gfm_offset *pOff, const TileLayer *tileLayer) { int j, x, y, w, h; x = -1; y = -1; w = -1; h = -1; j = 0; while (j < tileLayer->height()) { // Search for the first tile if (x == -1 && y == -1) { int i; i = 0; while (i < tileLayer->width()) { const Tile *tile; tile = tileLayer->cellAt(i, j).tile; if (tile && tile->id() != -1) { x = i; y = j; break; } i++; } } // Now, calculate the width if (x != -1 && y != -1 && w == -1) { int i; i = x; while (i < tileLayer->width()) { const Tile *tile; tile = tileLayer->cellAt(i, j).tile; if (!tile || tile->id() == -1) { w = i - x; break; } i++; } } // Finally, search for the height if (x != -1 && y != -1 && w != -1 && h == -1) { j = y; while (j < tileLayer->height()) { const Tile *tile; tile = tileLayer->cellAt(x, j).tile; if (!tile || tile->id() == -1) { h = j - y; break; } j++; } if (h == -1) h = j - y; break; } // Shouldn't happen, but just in case... if (x != -1 && y != -1 && w != -1 && h != -1) break; j++; } pOff->x = x; pOff->y = y; pOff->w = w; pOff->h = h; } #ifdef HAS_QSAVEFILE_SUPPORT static void writeTilemap(QSaveFile &file, const TileLayer *tileLayer, gfm_offset *pOff) { #else static void writeTilemap(QFile &file, const TileLayer *tileLayer, gfm_offset *pOff) { #endif // Write out the tilemap, by ID /* file.write("teste: {", 8); file.write(QByteArray::number(pOff->x)); file.write(", ", 2); file.write(QByteArray::number(pOff->y)); file.write(", ", 2); file.write(QByteArray::number(pOff->w)); file.write(", ", 2); file.write(QByteArray::number(pOff->h)); file.write(", ", 2); file.write("}\n", 2); */ file.write("tm:[\n", 5); // for (int y = 0; y < tileLayer->height(); ++y) { // for (int x = 0; x < tileLayer->width(); ++x) { for (int y = 0; y < pOff->h; y++) { for (int x = 0; x < pOff->w; x++) { const Cell &cell = tileLayer->cellAt(pOff->x + x, pOff->y + y); const Tile *tile = cell.tile; const int id = tile ? tile->id() : -1; file.write(QByteArray::number(id)); file.write(",", 1); } file.write("\n", 1); } file.write("]\n", 2); } #ifdef HAS_QSAVEFILE_SUPPORT static void writeObjectBounds(QSaveFile &file, const MapObject *obj, gfm_offset *pOff) { #else static void writeObjectBounds(QFile &file, const MapObject *obj, gfm_offset *pOff) { #endif int h, w, x, y; x = ((int)obj->x()) / 8 - pOff->x; y = ((int)obj->y()) / 8 - pOff->y; w = ((int)obj->width()) / 8; h = ((int)obj->height()) / 8; file.write(" x:", 3); file.write(QByteArray::number(x)); file.write(" y:", 3); file.write(QByteArray::number(y)); file.write(" w:", 3); file.write(QByteArray::number(w)); file.write(" h:", 3); file.write(QByteArray::number(h)); } #ifdef HAS_QSAVEFILE_SUPPORT static void writeString(QSaveFile &file, const QString &str) { #else static void writeString(QFile &file, const QString &str) { #endif int i; QStringList list = str.split("|"); i = 0; while (1) { file.write("\"", 1); file.write(list.at(i).toUtf8()); file.write("\"", 1); i++; if (i >= list.count()) break; file.write("|", 1); } } #define isVar(it)\ (it.key() == "var" || it.key() == "var0" || it.key() == "var1" \ || it.key() == "var2" || it.key() == "var3" ) #define isInt(it)\ (it.key() == "int" || it.key() == "int0" || it.key() == "int1" \ || it.key() == "int2" || it.key() == "int3" ) #ifdef HAS_QSAVEFILE_SUPPORT static void writeObject(QSaveFile &file, const MapObject *obj, gfm_offset *pOff) { #else static void writeObject(QFile &file, const MapObject *obj, gfm_offset *pOff) { #endif file.write("obj: {", 6); writeObjectBounds(file, obj, pOff); for (QMap<QString, QString>::const_iterator it = obj->properties().begin(); it != obj->properties().end(); it++) { file.write(" ", 1); if (isVar(it)) file.write("var", 3); else file.write(it.key().toUtf8()); file.write(":", 1); if (!isInt(it)) writeString(file, it.value()); else file.write(it.value().toUtf8()); } file.write(" }\n", 3); } #ifdef HAS_QSAVEFILE_SUPPORT static void writeEvent(QSaveFile &file, const MapObject *ev, gfm_offset *pOff) { #else static void writeEvent(QFile &file, const MapObject *ev, gfm_offset *pOff) { #endif file.write("ev: {", 5); writeObjectBounds(file, ev, pOff); for (QMap<QString, QString>::const_iterator it = ev->properties().begin(); it != ev->properties().end(); it++) { file.write(" ", 1); if (isVar(it)) { if (it.value() == "gv_max") continue; file.write("var", 3); } else if (isInt(it)) file.write("int", 3); else file.write(it.key().toUtf8()); file.write(":", 1); if (!isInt(it)) writeString(file, it.value()); else file.write(it.value().toUtf8()); } file.write(" }\n", 3); } #ifdef HAS_QSAVEFILE_SUPPORT static void writeMob(QSaveFile &file, const MapObject *obj, gfm_offset *pOff) { #else static void writeMob(QFile &file, const MapObject *obj, gfm_offset *pOff) { #endif file.write("mob: {", 6); // Write the mob to its exact position file.write(" x:", 3); file.write(QByteArray::number(((int)obj->x()) - pOff->x * 8)); file.write(" y:", 3); file.write(QByteArray::number(((int)obj->y()) - pOff->y * 8)); for (QMap<QString, QString>::const_iterator it = obj->properties().begin(); it != obj->properties().end(); it++) { file.write(" ", 1); if (isVar(it)) file.write("var", 3); else file.write(it.key().toUtf8()); file.write(":", 1); if (!isInt(it)) writeString(file, it.value()); else file.write(it.value().toUtf8()); } file.write(" }\n", 3); }
26.833724
79
0.51536
[ "object" ]
bec3649f2841c0d1af2408430403ce05b1aa624d
6,921
cpp
C++
libs/ofxLineaDeTiempo/src/View/ModalView.cpp
roymacdonald/ofxLineaDeTiempo
1a080c7d5533dc9b0e587bd1557506fe288f05e8
[ "MIT" ]
31
2020-04-29T06:11:54.000Z
2021-11-10T19:14:09.000Z
libs/ofxLineaDeTiempo/src/View/ModalView.cpp
roymacdonald/ofxLineaDeTiempo
1a080c7d5533dc9b0e587bd1557506fe288f05e8
[ "MIT" ]
11
2020-07-27T17:12:05.000Z
2021-12-01T16:33:18.000Z
libs/ofxLineaDeTiempo/src/View/ModalView.cpp
roymacdonald/ofxLineaDeTiempo
1a080c7d5533dc9b0e587bd1557506fe288f05e8
[ "MIT" ]
null
null
null
// // ModalView.cpp // example-basic // // Created by Roy Macdonald on 8/5/20. // #include "ofGraphics.h" #include "LineaDeTiempo/View/ModalView.h" #include "LineaDeTiempo/View/TimelineDocument.h" #include "LineaDeTiempo/Utils/ConstVars.h" #include "ofxTimecode.h" namespace ofx { namespace LineaDeTiempo { AbstractModalElement::AbstractModalElement(DOM::Element* owner): _owner(owner) { _creationTime = ofGetElapsedTimeMillis(); } AbstractModalElement::~AbstractModalElement() { } void AbstractModalElement::update(uint64_t currentTime) { if(!_needsToBeRemoved) { if(_expired || ( _timeout > 0 && currentTime - _creationTime > _timeout)) { _willBeRemoved(); } } } void AbstractModalElement::_willBeRemoved() { ofNotifyEvent(willBeRemovedEvent, this); _needsToBeRemoved = true; } bool AbstractModalElement::needsToBeRemoved() const { return _needsToBeRemoved; } void AbstractModalElement::expire() { _expired = true; } TooltipOwner::TooltipOwner(DOM::Element* _self, const std::string& tooltip) :_tooltipOwner(_self) ,_tooltip(tooltip) { _pointerListeners.push(_self->pointerOver.event(false).newListener(this, &TooltipOwner::onPointerEvent, std::numeric_limits<int>::lowest())); _pointerListeners.push(_self->pointerEnter.event(false).newListener(this, &TooltipOwner::onPointerEvent, std::numeric_limits<int>::lowest())); _pointerListeners.push(_self->pointerDown.event(false).newListener(this, &TooltipOwner::onPointerEvent, std::numeric_limits<int>::lowest())); _overStartTime = ofGetElapsedTimeMillis(); } TooltipOwner::~TooltipOwner() { } void TooltipOwner::onPointerEvent(DOM::PointerUIEventArgs& e) { if(e.type() == PointerEventArgs::POINTER_OVER || e.type() == PointerEventArgs::POINTER_ENTER) { _bCanShowTooltip = true; } else { expireTooltip(); _bCanShowTooltip = false; } } void TooltipOwner::expireTooltip() { if(_tooltipModal != nullptr) { _tooltipModal->expire(); } } void TooltipOwner::_updateShowTooltip( bool bMoving, bool bOver, const std::map<size_t, PointerEventArgs>& pointersOver, DOM::Document* docu) { if(!ConstVars::showTooltips) return; if(_tooltipOwner == nullptr) { std::cout << "TooltipOwner::_updateShowTooltip: tooltop Owner is null\n"; return; } if(_tooltip != "") { if(bOver) { if(bMoving){ _overStartTime = ofGetElapsedTimeMillis(); expireTooltip(); } else { if(_tooltipModal == nullptr && _bCanShowTooltip) { if(ofGetElapsedTimeMillis() - _overStartTime > ConstVars::tooltipDelay) { auto doc = dynamic_cast<TimelineDocument*>(docu); if(doc) { for(auto& p: pointersOver) { _tooltipModal = doc->getModal()->add<Tooltip>(_tooltipOwner, _tooltip, p.second.position()); _modalRemoveListener = _tooltipModal->willBeRemovedEvent.newListener(this, &::ofx::LineaDeTiempo::TooltipOwner::_removeModalCB); } } } } } } else { expireTooltip(); } } } void TooltipOwner::_removeModalCB() { _tooltipModal = nullptr; _modalRemoveListener.unsubscribe(); _bCanShowTooltip = false; } Tooltip::Tooltip(DOM::Element* owner, const std::string& label, const DOM::Position& screenPos) :AbstractModalElement(owner) ,_label(label) ,_screenPos(screenPos) , DOM::Element(label, screenPos.x, screenPos.y, 0,0) { _timeout = ConstVars::tooltipTimeout; } Tooltip::~Tooltip() { } void Tooltip::make() { auto s = document()->getDocumentStyles(); if(s){ auto f = s->getFont(MUI::EXTRA_SMALL); _screenPos.y -= _margin; _screenPos.x += _margin + 2; auto pos = screenToParent(_screenPos); auto bb = f.getStringBoundingBox(_label, pos.x, pos.y); bb.standardize(); bb.x -= _margin; bb.y -= _margin; bb.height += _margin*2; bb.width += _margin*2; setShape(bb); auto localPos = screenToLocal(_screenPos); if(bb.width + _screenPos.x > ofGetWidth()) { bb.x -= bb.width + _margin + 2; setShape(bb); } _textMesh = f.getStringMesh(_label, localPos.x, localPos.y); _bNeedsMake = false; } } void Tooltip::onUpdate() { if(_bNeedsMake) make(); } void Tooltip::onDraw() const { auto s = document()->getDocumentStyles(); if(s){ ofFill(); ofSetColor(ConstVars::TooltipBackgroundColor.get()); ofDrawRectangle(0,0,getWidth(), getHeight()); ofNoFill(); ofSetColor(ConstVars::TooltipBorderColor.get()); ofDrawRectangle(0,0,getWidth(), getHeight()); ofSetColor(ConstVars::TooltipTextColor.get()); auto f = s->getFont(MUI::EXTRA_SMALL); f.getFontTexture().bind(); _textMesh.draw(); f.getFontTexture().unbind(); } } ModalTimeModifier::ModalTimeModifier(DOM::Element* owner, size_t initialMillis) : Panel<TimeModifier>("TimeModifierPanel", ofRectangle(), initialMillis) , AbstractModalElement(owner) { _timeout = 0; followContainerSize(true); setHeaderLabel("Set Total Time"); setResizable(false); updateLayout(); } void ModalTimeModifier::expire() { AbstractModalElement::expire(); container->disableKeys(); } TimeModifier* ModalTimeModifier::getTimeModifier() { return container; } const TimeModifier* ModalTimeModifier::getTimeModifier() const { return container; } ModalView::ModalView(const std::string& id, const ofRectangle& shape, TimelineDocument* doc) : MUI::Widget(id, shape) ,_doc(doc) { } ModalView::~ModalView() { } bool ModalView::shouldBeDestroyed() { return _needsToBeDestroyed; } void ModalView::onDraw() const { if(_useBackgroundOverlay) { ofPushStyle(); ofFill(); ofSetColor(_backgroundOverlay); ofDrawRectangle(0,0,getWidth(), getHeight()); ofPopStyle(); } } void ModalView::useBackgroundOverlay(const ofColor& bg) { _useBackgroundOverlay = true; _backgroundOverlay = bg; } void ModalView::_onPointerCaptureEvent(DOM::PointerCaptureUIEventArgs& e) { Widget::_onPointerCaptureEvent(e); if (e.target() == this && e.type() == PointerEventArgs::GOT_POINTER_CAPTURE) { // if this gets triggered it means that the pointer was clicked outside any of the modal view's children, thus it need to be destroyed. // _needsToBeDestroyed = true; for(auto m : _modalElements) { if(m) { m->expire(); } } } } void ModalView::onUpdate() { if(_modalElements.size()) { auto t = ofGetElapsedTimeMillis(); for(auto& e: _modalElements) { e->update(t); } ofRemove(_modalElements, [this](AbstractModalElement* e){ return this->remove(e); }); } else { _needsToBeDestroyed = true; } } bool ModalView::remove(AbstractModalElement* e) { if(e->needsToBeRemoved()) { auto c = dynamic_cast<DOM::Element*>(e); if(c) { removeChild(c); } return true; } return false; } void ModalView::_documentShapeChange(DOM::ShapeChangeEventArgs& s) { setShape({0,0, s.shape.getWidth(), s.shape.getHeight()}); } } } // ofx::LineaDeTiempo
17.746154
143
0.691519
[ "shape" ]
bec96148cab3ab2553214927fbc2631b59ae8f79
1,924
hpp
C++
lib/libstereo/src/dsbase.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
4
2020-12-28T15:29:15.000Z
2021-06-27T12:37:15.000Z
lib/libstereo/src/dsbase.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
null
null
null
lib/libstereo/src/dsbase.hpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
2
2021-01-13T05:28:39.000Z
2021-05-04T03:37:11.000Z
#ifndef _FTL_LIBSTEREO_DSBASE_HPP_ #define _FTL_LIBSTEREO_DSBASE_HPP_ #include <cstdint> #include <cuda_runtime.h> #include <type_traits> namespace impl { template <typename T> struct DSImplBase { typedef T Type; static_assert(std::is_arithmetic<T>::value, "Cost type is not numeric"); //DSImplBase(int w, int h, int dmin, int dmax) : width(w), height(h), disp_min(dmin), disp_max(dmax) {} uint16_t width; uint16_t height; uint16_t disp_min; uint16_t disp_max; //static constexpr T COST_MAX = std::numeric_limits<T>::max(); __host__ __device__ inline uint16_t disparityRange() const { return disp_max-disp_min+1; } __host__ __device__ inline uint32_t size() const { return width * disparityRange() * height; } __host__ __device__ inline uint32_t bytes() const { return size() * sizeof(Type); } }; } /** * Base class representing a 3D disparity space structure. This may * implement the 3D data structure as a stored memory object or through * dynamic calculation using other data. */ template<typename T> class DSBase { public: typedef T DataType; typedef typename T::Type Type; #if __cplusplus >= 201703L static_assert(std::is_invocable_r<Type,T,int,int,int>::value, "Incorrect disparity space operator"); #endif static_assert(std::is_convertible<T, impl::DSImplBase<Type>>::value, "Data type is not derived from DSImplBase"); DSBase(int w, int h, int dmin, int dmax) : data_(w,h,dmin,dmax) {} ~DSBase() {}; DataType &data() { return data_; }; const DataType &data() const { return data_; }; int width() const { return data_.width; } int height() const { return data_.height; } int numDisparities() const { return data_.disparityRange(); } int maxDisparity() const { return data_.disp_max; } int minDisparity() const { return data_.disp_min; } Type maxCost() const { return DataType::COST_MAX; } protected: DataType data_; }; //#include "dsbase_impl.hpp" #endif
29.151515
114
0.725572
[ "object", "3d" ]
beda3643c994052be409723c3d47fd682895fe4a
20,330
cpp
C++
source/houaud/test/hou/aud/test_wav_file_in.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
2
2018-04-12T20:59:20.000Z
2018-07-26T16:04:07.000Z
source/houaud/test/hou/aud/test_wav_file_in.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
source/houaud/test/hou/aud/test_wav_file_in.cpp
DavideCorradiDev/houzi-game-engine
d704aa9c5b024300578aafe410b7299c4af4fcec
[ "MIT" ]
null
null
null
// Houzi Game Engine // Copyright (c) 2018 Davide Corradi // Licensed under the MIT license. #include "hou/test.hpp" #include "hou/aud/test_data.hpp" #include "hou/aud/aud_exceptions.hpp" #include "hou/aud/wav_file_in.hpp" #include "hou/sys/sys_exceptions.hpp" using namespace hou; using namespace testing; namespace { class test_wav_file_in : public Test { public: static const std::string mono16_unicode_filename; static const std::string mono8_filename; static const std::string mono16_filename; static const std::string stereo8_filename; static const std::string stereo16_filename; static const std::string low_sample_rate_filename; static const std::string ogg_filename; }; class test_wav_file_in_death_test : public test_wav_file_in {}; const std::string test_wav_file_in::mono16_unicode_filename = get_data_dir() + u8"TestWav\U00004f60\U0000597d.wav"; const std::string test_wav_file_in::mono8_filename = get_data_dir() + u8"TestWav-mono-8-44100.wav"; const std::string test_wav_file_in::mono16_filename = get_data_dir() + u8"TestWav-mono-16-44100.wav"; const std::string test_wav_file_in::stereo8_filename = get_data_dir() + u8"TestWav-stereo-8-44100.wav"; const std::string test_wav_file_in::stereo16_filename = get_data_dir() + u8"TestWav-stereo-16-44100.wav"; const std::string test_wav_file_in::low_sample_rate_filename = get_data_dir() + u8"TestWav-mono-16-22050.wav"; const std::string test_wav_file_in::ogg_filename = get_data_dir() + u8"TestOgg\U00004f60\U0000597d.ogg"; } // namespace TEST_F(test_wav_file_in, check_success) { EXPECT_TRUE(wav_file_in::check(mono16_unicode_filename)); } TEST_F(test_wav_file_in, check_failure_invalid_format) { EXPECT_FALSE(wav_file_in::check(ogg_filename)); } TEST_F(test_wav_file_in_death_test, check_failure_invalid_file) { std::string invalid_filename = u8"Invalidfile"; EXPECT_ERROR_N( wav_file_in::check(invalid_filename), file_open_error, invalid_filename); } TEST_F(test_wav_file_in, path_constructor) { wav_file_in fi(mono16_unicode_filename); EXPECT_FALSE(fi.eof()); EXPECT_FALSE(fi.error()); EXPECT_EQ(42206u, fi.get_byte_count()); EXPECT_EQ(0u, fi.get_read_byte_count()); EXPECT_EQ(0u, fi.get_read_element_count()); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(audio_buffer_format::mono16, fi.get_format()); EXPECT_EQ(1u, fi.get_channel_count()); EXPECT_EQ(2u, fi.get_bytes_per_sample()); EXPECT_EQ(44100u, fi.get_sample_rate()); EXPECT_EQ(21103u, fi.get_sample_count()); EXPECT_EQ(0, fi.get_sample_pos()); } TEST_F(test_wav_file_in_death_test, path_constructor_failure_file_not_existing) { std::string invalid_filename = u8"InvalidFileName"; EXPECT_ERROR_N( wav_file_in fi(invalid_filename), file_open_error, invalid_filename); } TEST_F(test_wav_file_in_death_test, path_constructor_failure_invalid_wav_file) { static constexpr size_t string_size = 4u; struct wav_metadata { char id[string_size]; uint32_t chunk_size; char form[string_size]; char sc1Id[string_size]; uint32_t sc1Size; uint16_t format; uint16_t channels; uint32_t sample_rate; uint32_t byteRate; uint16_t blockAlign; uint16_t bitsPerSample; char sc2Id[string_size]; uint32_t sc2Size; }; std::string dummy_wav_filename = get_output_dir() + u8"dummy_wav_file.wav"; { file dummy_wav_file( dummy_wav_filename, file_open_mode::write, file_type::binary); wav_metadata data; data.id[0] = 'F'; data.id[1] = 'a'; data.id[2] = 'K'; data.id[3] = 'E'; dummy_wav_file.write(&data, 1u); } EXPECT_ERROR_0(wav_file_in fi(dummy_wav_filename), invalid_audio_data); remove_dir(dummy_wav_filename); } TEST_F(test_wav_file_in_death_test, path_constructor_failure_no_wav_header) { std::string dummy_wav_filename = get_output_dir() + u8"dummy_wav_file.wav"; { file dummy_wav_file( dummy_wav_filename, file_open_mode::write, file_type::binary); } EXPECT_ERROR_0(wav_file_in fi(dummy_wav_filename), invalid_audio_data); remove_dir(dummy_wav_filename); } TEST_F(test_wav_file_in, move_constructor) { wav_file_in fi_dummy(mono16_unicode_filename); wav_file_in fi(std::move(fi_dummy)); EXPECT_FALSE(fi.eof()); EXPECT_FALSE(fi.error()); EXPECT_EQ(42206u, fi.get_byte_count()); EXPECT_EQ(0u, fi.get_read_byte_count()); EXPECT_EQ(0u, fi.get_read_element_count()); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(audio_buffer_format::mono16, fi.get_format()); EXPECT_EQ(1u, fi.get_channel_count()); EXPECT_EQ(2u, fi.get_bytes_per_sample()); EXPECT_EQ(44100u, fi.get_sample_rate()); EXPECT_EQ(21103u, fi.get_sample_count()); EXPECT_EQ(0, fi.get_sample_pos()); } TEST_F(test_wav_file_in, audio_buffer_format_attributes) { wav_file_in fi_mono8(mono8_filename); wav_file_in fi_mono16(mono16_filename); wav_file_in fi_stereo8(stereo8_filename); wav_file_in fi_stereo16(stereo16_filename); EXPECT_EQ(audio_buffer_format::mono8, fi_mono8.get_format()); EXPECT_EQ(1u, fi_mono8.get_channel_count()); EXPECT_EQ(1u, fi_mono8.get_bytes_per_sample()); EXPECT_EQ(audio_buffer_format::mono16, fi_mono16.get_format()); EXPECT_EQ(1u, fi_mono16.get_channel_count()); EXPECT_EQ(2u, fi_mono16.get_bytes_per_sample()); EXPECT_EQ(audio_buffer_format::stereo8, fi_stereo8.get_format()); EXPECT_EQ(2u, fi_stereo8.get_channel_count()); EXPECT_EQ(1u, fi_stereo8.get_bytes_per_sample()); EXPECT_EQ(audio_buffer_format::stereo16, fi_stereo16.get_format()); EXPECT_EQ(2u, fi_stereo16.get_channel_count()); EXPECT_EQ(2u, fi_stereo16.get_bytes_per_sample()); } TEST_F(test_wav_file_in, sample_rate_attributes) { wav_file_in fi_normal_rate(mono16_filename); wav_file_in fi_low_rate(low_sample_rate_filename); EXPECT_EQ(44100u, fi_normal_rate.get_sample_rate()); EXPECT_EQ(22050u, fi_low_rate.get_sample_rate()); } TEST_F(test_wav_file_in, get_sample_count) { wav_file_in fi_mono8(mono8_filename); wav_file_in fi_mono16(mono16_filename); wav_file_in fi_stereo8(stereo8_filename); wav_file_in fi_stereo16(stereo16_filename); EXPECT_EQ(21231u, fi_mono8.get_sample_count()); EXPECT_EQ(21231u, fi_mono16.get_sample_count()); EXPECT_EQ(21231u, fi_stereo8.get_sample_count()); EXPECT_EQ(21231u, fi_stereo16.get_sample_count()); EXPECT_EQ(21231u, fi_mono8.get_byte_count()); EXPECT_EQ(42462u, fi_mono16.get_byte_count()); EXPECT_EQ(42462u, fi_stereo8.get_byte_count()); EXPECT_EQ(84924u, fi_stereo16.get_byte_count()); } TEST_F(test_wav_file_in, set_byte_pos) { wav_file_in fi(mono16_filename); EXPECT_EQ(0, fi.get_byte_pos()); fi.set_byte_pos(6); EXPECT_EQ(6, fi.get_byte_pos()); fi.set_byte_pos(0); EXPECT_EQ(0, fi.get_byte_pos()); fi.set_byte_pos(static_cast<wav_file_in::byte_position>(fi.get_byte_count())); EXPECT_EQ(static_cast<wav_file_in::byte_position>(fi.get_byte_count()), fi.get_byte_pos()); } TEST_F(test_wav_file_in_death_test, set_byte_pos_error_position_in_sample) { wav_file_in fi(mono16_filename); EXPECT_PRECOND_ERROR(fi.set_byte_pos(3)); EXPECT_PRECOND_ERROR(fi.set_byte_pos( static_cast<wav_file_in::byte_position>(fi.get_byte_count() + 3))); } TEST_F(test_wav_file_in_death_test, set_byte_pos_error_invalid_position) { wav_file_in fi(mono16_filename); EXPECT_ERROR_0(fi.set_byte_pos(-2), cursor_error); EXPECT_ERROR_0(fi.set_byte_pos(static_cast<wav_file_in::byte_position>( fi.get_byte_count() + 2)), cursor_error); } TEST_F(test_wav_file_in, move_byte_pos) { wav_file_in fi(mono16_filename); EXPECT_EQ(0, fi.get_byte_pos()); fi.move_byte_pos(6); EXPECT_EQ(6, fi.get_byte_pos()); fi.move_byte_pos(-2); EXPECT_EQ(4, fi.get_byte_pos()); fi.move_byte_pos(-4); EXPECT_EQ(0, fi.get_byte_pos()); fi.move_byte_pos( static_cast<wav_file_in::byte_position>(fi.get_byte_count())); EXPECT_EQ(static_cast<wav_file_in::byte_position>(fi.get_byte_count()), fi.get_byte_pos()); } TEST_F(test_wav_file_in_death_test, move_byte_pos_error_position_in_sample) { wav_file_in fi(mono16_filename); fi.move_byte_pos(4); EXPECT_PRECOND_ERROR(fi.move_byte_pos(3)); EXPECT_PRECOND_ERROR(fi.move_byte_pos( static_cast<wav_file_in::byte_position>(fi.get_byte_count() + 3))); } TEST_F(test_wav_file_in_death_test, move_byte_pos_error_invalid_position) { wav_file_in fi(mono16_filename); fi.move_byte_pos(4); EXPECT_ERROR_0(fi.move_byte_pos(-6), cursor_error); EXPECT_ERROR_0(fi.move_byte_pos(static_cast<wav_file_in::byte_position>( fi.get_byte_count() - 2)), cursor_error); } TEST_F(test_wav_file_in, set_sample_pos_mono8) { wav_file_in fi(mono8_filename); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.set_sample_pos(3); EXPECT_EQ(3, fi.get_byte_pos()); EXPECT_EQ(3, fi.get_sample_pos()); fi.set_sample_pos( static_cast<wav_file_in::byte_position>(fi.get_sample_count())); EXPECT_EQ(static_cast<wav_file_in::byte_position>(fi.get_byte_count()), fi.get_byte_pos()); EXPECT_EQ(static_cast<wav_file_in::sample_position>(fi.get_sample_count()), fi.get_sample_pos()); } TEST_F(test_wav_file_in, set_sample_pos_mono16) { wav_file_in fi(mono16_filename); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.set_sample_pos(3); EXPECT_EQ(6, fi.get_byte_pos()); EXPECT_EQ(3, fi.get_sample_pos()); fi.set_sample_pos( static_cast<wav_file_in::byte_position>(fi.get_sample_count())); EXPECT_EQ(static_cast<wav_file_in::byte_position>(fi.get_byte_count()), fi.get_byte_pos()); EXPECT_EQ(static_cast<wav_file_in::sample_position>(fi.get_sample_count()), fi.get_sample_pos()); } TEST_F(test_wav_file_in, set_sample_pos_stereo8) { wav_file_in fi(stereo8_filename); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.set_sample_pos(3); EXPECT_EQ(6, fi.get_byte_pos()); EXPECT_EQ(3, fi.get_sample_pos()); fi.set_sample_pos( static_cast<wav_file_in::byte_position>(fi.get_sample_count())); EXPECT_EQ(static_cast<wav_file_in::byte_position>(fi.get_byte_count()), fi.get_byte_pos()); EXPECT_EQ(static_cast<wav_file_in::sample_position>(fi.get_sample_count()), fi.get_sample_pos()); } TEST_F(test_wav_file_in, set_sample_pos_stereo16) { wav_file_in fi(stereo16_filename); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.set_sample_pos(3); EXPECT_EQ(12, fi.get_byte_pos()); EXPECT_EQ(3, fi.get_sample_pos()); fi.set_sample_pos( static_cast<wav_file_in::byte_position>(fi.get_sample_count())); EXPECT_EQ(static_cast<wav_file_in::byte_position>(fi.get_byte_count()), fi.get_byte_pos()); EXPECT_EQ(static_cast<wav_file_in::sample_position>(fi.get_sample_count()), fi.get_sample_pos()); } TEST_F(test_wav_file_in_death_test, set_sample_pos_error_invalid_position) { wav_file_in fi(mono16_filename); EXPECT_ERROR_0(fi.set_sample_pos(-1), cursor_error); EXPECT_ERROR_0(fi.set_sample_pos(static_cast<wav_file_in::byte_position>( fi.get_sample_count() + 1)), cursor_error); } TEST_F(test_wav_file_in, move_sample_pos_mono8) { wav_file_in fi(mono8_filename); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.move_sample_pos(3); EXPECT_EQ(3, fi.get_byte_pos()); EXPECT_EQ(3, fi.get_sample_pos()); fi.move_sample_pos(-1); EXPECT_EQ(2, fi.get_byte_pos()); EXPECT_EQ(2, fi.get_sample_pos()); fi.move_sample_pos(-2); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.move_sample_pos( static_cast<wav_file_in::byte_position>(fi.get_sample_count())); EXPECT_EQ(static_cast<wav_file_in::byte_position>(fi.get_byte_count()), fi.get_byte_pos()); EXPECT_EQ(static_cast<wav_file_in::sample_position>(fi.get_sample_count()), fi.get_sample_pos()); } TEST_F(test_wav_file_in, move_sample_pos_mono16) { wav_file_in fi(mono16_filename); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.move_sample_pos(3); EXPECT_EQ(6, fi.get_byte_pos()); EXPECT_EQ(3, fi.get_sample_pos()); fi.move_sample_pos(-1); EXPECT_EQ(4, fi.get_byte_pos()); EXPECT_EQ(2, fi.get_sample_pos()); fi.move_sample_pos(-2); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.move_sample_pos( static_cast<wav_file_in::byte_position>(fi.get_sample_count())); EXPECT_EQ(static_cast<wav_file_in::byte_position>(fi.get_byte_count()), fi.get_byte_pos()); EXPECT_EQ(static_cast<wav_file_in::sample_position>(fi.get_sample_count()), fi.get_sample_pos()); } TEST_F(test_wav_file_in, move_sample_pos_stereo8) { wav_file_in fi(stereo8_filename); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.move_sample_pos(3); EXPECT_EQ(6, fi.get_byte_pos()); EXPECT_EQ(3, fi.get_sample_pos()); fi.move_sample_pos(-1); EXPECT_EQ(4, fi.get_byte_pos()); EXPECT_EQ(2, fi.get_sample_pos()); fi.move_sample_pos(-2); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.move_sample_pos( static_cast<wav_file_in::byte_position>(fi.get_sample_count())); EXPECT_EQ(static_cast<wav_file_in::byte_position>(fi.get_byte_count()), fi.get_byte_pos()); EXPECT_EQ(static_cast<wav_file_in::sample_position>(fi.get_sample_count()), fi.get_sample_pos()); } TEST_F(test_wav_file_in, move_sample_pos_stereo16) { wav_file_in fi(stereo16_filename); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.move_sample_pos(3); EXPECT_EQ(12, fi.get_byte_pos()); EXPECT_EQ(3, fi.get_sample_pos()); fi.move_sample_pos(-1); EXPECT_EQ(8, fi.get_byte_pos()); EXPECT_EQ(2, fi.get_sample_pos()); fi.move_sample_pos(-2); EXPECT_EQ(0, fi.get_byte_pos()); EXPECT_EQ(0, fi.get_sample_pos()); fi.move_sample_pos( static_cast<wav_file_in::byte_position>(fi.get_sample_count())); EXPECT_EQ(static_cast<wav_file_in::byte_position>(fi.get_byte_count()), fi.get_byte_pos()); EXPECT_EQ(static_cast<wav_file_in::sample_position>(fi.get_sample_count()), fi.get_sample_pos()); } TEST_F(test_wav_file_in_death_test, move_sample_pos_error_invalid_position) { wav_file_in fi(mono16_filename); fi.move_sample_pos(2); EXPECT_ERROR_0(fi.move_sample_pos(-3), cursor_error); EXPECT_ERROR_0(fi.move_sample_pos(static_cast<wav_file_in::byte_position>( fi.get_sample_count() - 1)), cursor_error); } TEST_F(test_wav_file_in, read_to_variable) { using buffer_type = uint16_t; static constexpr size_t buffer_size = 1u; static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size; wav_file_in fi(mono16_unicode_filename); buffer_type buffer; fi.read(buffer); EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count()); EXPECT_EQ(buffer_size, fi.get_read_element_count()); EXPECT_EQ(buffer_size, fi.get_read_sample_count()); EXPECT_EQ(12480u, buffer); fi.read(buffer); EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count()); EXPECT_EQ(buffer_size, fi.get_read_element_count()); EXPECT_EQ(buffer_size, fi.get_read_sample_count()); EXPECT_EQ(12460, buffer); } TEST_F(test_wav_file_in, read_to_basic_array) { using buffer_type = uint16_t; static constexpr size_t buffer_size = 3u; static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size; wav_file_in fi(mono16_unicode_filename); buffer_type buffer[buffer_size]; fi.read(buffer, buffer_size); buffer_type buffer_ref1[buffer_size] = {12480u, 12460u, 12440u}; EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count()); EXPECT_EQ(buffer_size, fi.get_read_element_count()); EXPECT_EQ(buffer_size, fi.get_read_sample_count()); EXPECT_ARRAY_EQ(buffer_ref1, buffer, buffer_size); fi.read(buffer, buffer_size); buffer_type buffer_ref2[buffer_size] = {12420u, 12400u, 12380u}; EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count()); EXPECT_EQ(buffer_size, fi.get_read_element_count()); EXPECT_EQ(buffer_size, fi.get_read_sample_count()); EXPECT_ARRAY_EQ(buffer_ref2, buffer, buffer_size); } TEST_F(test_wav_file_in, read_to_array) { using buffer_type = uint16_t; static constexpr size_t buffer_size = 3u; static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size; wav_file_in fi(mono16_unicode_filename); std::array<buffer_type, buffer_size> buffer = {0, 0, 0}; fi.read(buffer); std::array<buffer_type, buffer_size> buffer_ref1 = {12480u, 12460u, 12440u}; EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count()); EXPECT_EQ(buffer_size, fi.get_read_element_count()); EXPECT_EQ(buffer_size, fi.get_read_sample_count()); EXPECT_EQ(buffer_ref1, buffer); fi.read(buffer); std::array<buffer_type, buffer_size> buffer_ref2 = {12420u, 12400u, 12380u}; EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count()); EXPECT_EQ(buffer_size, fi.get_read_element_count()); EXPECT_EQ(buffer_size, fi.get_read_sample_count()); EXPECT_EQ(buffer_ref2, buffer); } TEST_F(test_wav_file_in, read_to_vector) { using buffer_type = uint16_t; static constexpr size_t buffer_size = 3u; static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size; wav_file_in fi(mono16_unicode_filename); std::vector<buffer_type> buffer(buffer_size, 0u); fi.read(buffer); std::vector<buffer_type> buffer_ref1 = {12480u, 12460u, 12440u}; EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count()); EXPECT_EQ(buffer_size, fi.get_read_element_count()); EXPECT_EQ(buffer_size, fi.get_read_sample_count()); EXPECT_EQ(buffer_ref1, buffer); fi.read(buffer); std::vector<buffer_type> buffer_ref2 = {12420u, 12400u, 12380u}; EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count()); EXPECT_EQ(buffer_size, fi.get_read_element_count()); EXPECT_EQ(buffer_size, fi.get_read_sample_count()); EXPECT_EQ(buffer_ref2, buffer); } TEST_F(test_wav_file_in, read_to_string) { using buffer_type = std::string::value_type; static constexpr size_t buffer_size = 4u; static constexpr size_t buffer_byte_size = sizeof(buffer_type) * buffer_size; wav_file_in fi(mono16_unicode_filename); std::string buffer(buffer_size, 0); fi.read(buffer); std::string buffer_ref1 = {-64, 48, -84, 48}; EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count()); EXPECT_EQ(buffer_size, fi.get_read_element_count()); EXPECT_EQ(buffer_size / 2, fi.get_read_sample_count()); EXPECT_EQ(buffer_ref1, buffer); fi.read(buffer); std::string buffer_ref2 = {-104, 48, -124, 48}; EXPECT_EQ(buffer_byte_size, fi.get_read_byte_count()); EXPECT_EQ(buffer_size, fi.get_read_element_count()); EXPECT_EQ(buffer_size / 2, fi.get_read_sample_count()); EXPECT_EQ(buffer_ref2, buffer); } TEST_F(test_wav_file_in_death_test, read_to_invalid_size_buffer) { using buffer_type = uint8_t; static constexpr size_t buffer_size = 3u; std::vector<buffer_type> buffer(buffer_size, 0u); wav_file_in fi(mono16_filename); EXPECT_EQ(audio_buffer_format::mono16, fi.get_format()); EXPECT_PRECOND_ERROR(fi.read(buffer)); } TEST_F(test_wav_file_in, read_all_to_vector) { wav_file_in fi(mono8_filename); std::vector<uint8_t> file_content(fi.get_byte_count()); fi.read(file_content); fi.set_byte_pos(0u); auto fi_content = fi.read_all<std::vector<uint8_t>>(); EXPECT_EQ(file_content, fi_content); EXPECT_EQ(file_content.size(), fi.get_read_byte_count()); EXPECT_EQ(file_content.size(), static_cast<size_t>(fi.get_byte_pos())); } TEST_F(test_wav_file_in, read_all_to_vector_not_from_start) { wav_file_in fi(mono8_filename); std::vector<uint8_t> file_content(fi.get_byte_count()); fi.read(file_content); fi.set_byte_pos(2u); auto fi_content = fi.read_all<std::vector<uint8_t>>(); EXPECT_EQ(file_content, fi_content); EXPECT_EQ(file_content.size(), fi.get_read_byte_count()); EXPECT_EQ(file_content.size(), static_cast<size_t>(fi.get_byte_pos())); } TEST_F(test_wav_file_in, eof) { wav_file_in fi(mono16_filename); std::vector<uint8_t> buffer(fi.get_byte_count() + 2u, 0u); fi.read(buffer); EXPECT_TRUE(fi.eof()); EXPECT_EQ(fi.get_byte_count(), fi.get_read_byte_count()); EXPECT_TRUE(fi.eof()); fi.get_byte_pos(); EXPECT_TRUE(fi.eof()); fi.set_byte_pos(0u); EXPECT_FALSE(fi.eof()); EXPECT_FALSE(fi.error()); }
28.796034
80
0.757501
[ "vector" ]
bee2ee4ec5b854dda7324e4abdef34e9565f3d59
1,124
hpp
C++
tcpp/minion2/minion/system/minlib/map.hpp
Behrouz-Babaki/TCPP-chuffed
d832b44690914ef4b73d71bc7e565efb98e42937
[ "MIT" ]
1
2021-09-09T13:03:02.000Z
2021-09-09T13:03:02.000Z
tcpp/minion2/minion/system/minlib/map.hpp
Behrouz-Babaki/TCPP-chuffed
d832b44690914ef4b73d71bc7e565efb98e42937
[ "MIT" ]
null
null
null
tcpp/minion2/minion/system/minlib/map.hpp
Behrouz-Babaki/TCPP-chuffed
d832b44690914ef4b73d71bc7e565efb98e42937
[ "MIT" ]
null
null
null
#ifndef MAPPER_HPP_CD #define MAPPER_HPP_CD #include "variadic.hpp" #include <vector> #include <set> #include "multdim_container.hpp" template <typename Map, typename V> std::vector<typename ObjectResult<Map, V>::type> doMap(Map m, const std::vector<V>& v) { std::vector<typename ObjectResult<Map, V>::type> vec; vec.reserve(v.size()); for(auto it = v.begin(); it != v.end(); ++it) vec.push_back(m(*it)); return vec; } template <typename Map, typename V> std::set<typename ObjectResult<Map, V>::type> doMap(Map m, const std::set<V>& v) { std::set<typename ObjectResult<Map, V>::type> vec; for(auto it = v.begin(); it != v.end(); ++it) vec.insert(m(*it)); return vec; } template <typename Map, typename Index, typename Result> MultiDimCon<Index, typename ObjectResult<Map, Result>::type> doMap(Map m, const MultiDimCon<Index, Result>& mdc) { MultiDimCon<Index, typename ObjectResult<Map, Result>::type> res_mdc(mdc.getBounds()); for(auto it = mdc.indices.begin(); it != mdc.indices.end(); ++it) { res_mdc.indices.insert(make_pair(it->first, m(it->second))); } return res_mdc; } #endif
29.578947
88
0.684164
[ "vector" ]
bee42364d89aa5190e2ee31fd9f2bad61841cfb2
718
cpp
C++
Discrete-simulation/QRandom-distribution-generator/ParallelSimulator.cpp
JoseZancanaro/CienciaDaComputacao
0e08d9a3fd17cba38ef9d09f38026e9417b5536a
[ "MIT" ]
null
null
null
Discrete-simulation/QRandom-distribution-generator/ParallelSimulator.cpp
JoseZancanaro/CienciaDaComputacao
0e08d9a3fd17cba38ef9d09f38026e9417b5536a
[ "MIT" ]
1
2022-02-13T22:22:59.000Z
2022-02-13T22:22:59.000Z
Discrete-simulation/QRandom-distribution-generator/ParallelSimulator.cpp
JoseZancanaro/CienciaDaComputacao
0e08d9a3fd17cba38ef9d09f38026e9417b5536a
[ "MIT" ]
null
null
null
#include "ParallelSimulator.hpp" ParallelSimulator::ParallelSimulator(simulation::Model model, simulation::NaturalNumber sleepTime) : model(model), sleepTime(sleepTime) {} auto ParallelSimulator::simulate() -> void { while (!model.state.over) { model.state = simulation::simulate(model.state, model.controller); emit newState(model); if (sleepTime > 0) { this->msleep(static_cast<unsigned long>(sleepTime)); } } emit finished(model); } auto ParallelSimulator::updateSleepTime(int sleepTime) -> void { this->sleepTime = sleepTime; } auto ParallelSimulator::run() -> void { this->simulate(); } ParallelSimulator::~ParallelSimulator() = default;
24.758621
98
0.681058
[ "model" ]
bee9d00502481a2c2286e367d2846bb5354517e7
3,096
cpp
C++
C++/constructBSTFromInOrderAndPreOrder.cpp
MariaMich/Hacktoberfest2019-2
a1a1756fa4594ab9965405e0361a5125b1d4dd48
[ "MIT" ]
null
null
null
C++/constructBSTFromInOrderAndPreOrder.cpp
MariaMich/Hacktoberfest2019-2
a1a1756fa4594ab9965405e0361a5125b1d4dd48
[ "MIT" ]
null
null
null
C++/constructBSTFromInOrderAndPreOrder.cpp
MariaMich/Hacktoberfest2019-2
a1a1756fa4594ab9965405e0361a5125b1d4dd48
[ "MIT" ]
null
null
null
//A program to construct a binary tree, given the inorder and preorder traversals of the tree. # include <iostream> # include <vector> # include <map> using namespace std; //Structure for binary tree struct Node { int Data; Node *Left, *Right; Node(int x) { Data = x; Left = Right = NULL; } }; void inOrderTraversal(Node *Root) { if(Root == NULL) return ; inOrderTraversal(Root -> Left); cout << Root -> Data << " "; inOrderTraversal(Root -> Right); } void preOrderTraversal(Node *Root) { if(Root == NULL) return ; cout << Root -> Data << " "; preOrderTraversal(Root -> Left); preOrderTraversal(Root -> Right); } /* The logic here is: Say we have 2 arrays, PRE and IN. Preorder traversing implies that PRE[0] is the root node. Then we can find this PRE[0] in IN, say it's IN[5]. Now we know that IN[5] is root, so we know that IN[0] - IN[4] is on the left side, IN[6] to the end is on the right side. Recursively doing this on subarrays, we can build a tree out of it. */ //Function to construct tree from the preOrder and inOrder traversals //Note To Self : The preEnd parameter is not necessary here, but I am including it for uniformity. Node *constructTree(int preStart, int preEnd, int inStart, int inEnd, vector <int> preOrder, vector <int> inOrder, map <int, int> inMap) { if(preStart > preEnd || inStart > inEnd) { return NULL; } Node *Root = new Node(preOrder[preStart]); //The first node of the preOrder traversal will be the root node. int inRoot = inMap[preOrder[preStart]]; //Find where the root node exists in the inOrder traversal list. int numsLeft = inRoot - inStart; //The number of nodes on the left side of the root on the inorder traversal are the number of nodes in the left subtree. //The left subtree of the root will be all the nodes which are present before the root node in the inorder traversal. Root -> Left = constructTree(preStart + 1, preEnd, inStart, inRoot - 1, preOrder, inOrder, inMap); //The right subtree of the root will be all the nodes which are present after the root node in the inorder traversal. Root -> Right = constructTree(preStart + numsLeft + 1, preEnd, inRoot + 1, inEnd, preOrder, inOrder, inMap); return Root; } int main(void) { vector <int> inOrder = {4, 2, 5, 1, 3, 6}; vector <int> preOrder = {1, 2, 4, 5, 3, 6}; if(inOrder.size() != preOrder.size()) { cout << "\nCannot construct tree since both the tree since the number of elements in the both the lists is different."; return 1; } map <int, int> inMap; //Create a map to store the data as the key and the index as the value. for(int i = 0 ; i < inOrder.size() ; i++) inMap[inOrder[i]] = i; Node *Root = constructTree(0, preOrder.size() - 1, 0, inOrder.size() - 1, preOrder, inOrder, inMap); cout << "\nInorder and preorder traversals after constructing the tree : \n"; inOrderTraversal(Root); cout << "\n"; preOrderTraversal(Root); return 0; } //End of program
32.93617
157
0.66053
[ "vector" ]
beec8cce4af5d76875edee02f274126279ba048b
3,480
cpp
C++
subcommands/unique.cpp
opa-oz/atomic-processors
a2aa72671fc1a206bbbb064ea4c1a99455bbee36
[ "MIT" ]
null
null
null
subcommands/unique.cpp
opa-oz/atomic-processors
a2aa72671fc1a206bbbb064ea4c1a99455bbee36
[ "MIT" ]
null
null
null
subcommands/unique.cpp
opa-oz/atomic-processors
a2aa72671fc1a206bbbb064ea4c1a99455bbee36
[ "MIT" ]
null
null
null
#include <iostream> #include <list> #include <vector> #include <unordered_set> #include "../utils/string.h" #include "../utils/read.h" #include "../utils/write.h" #include "../utils/json.h" #include "unique.h" namespace AtomicProcessors::Unique { void process(const string &input_path, const Filetype &filetype, const Datatype &datatype, const string &_keys, const string &output_path) { vector<string> keys({}); if (_keys.length() > 0) { keys = Utils::String::split(_keys); } using CLI::enums::operator<<; cout << "Processing params: " << endl; cout << "- filetype=" << filetype << endl; cout << "- datatype=" << datatype << endl; cout << "- keys=" << Utils::String::join(keys, ", ") << endl; if (filetype != Filetype::JSON) { throw runtime_error("We can only process JSON"); } cout << "Lets parse input file" << endl; auto input = Utils::Read::file2json(input_path); if (!input.is_array()) { throw runtime_error("Expected json array"); } if (datatype == Datatype::Simple) { std::unordered_set<size_t> hashes = {}; json output = json::array(); for (json::iterator it = input.begin(); it != input.end(); ++it) { auto value = it.value(); if (value.is_array() || value.is_object()) { throw runtime_error("Expected FLAT array"); } const size_t h = Utils::JSON::get_hash(value); if (hashes.find(h) == hashes.end()) { hashes.insert(h); output.push_back(value); } } Utils::Write::json2file(output_path, output); return; } if (datatype == Datatype::Complex && keys.empty()) { throw runtime_error("Keys are required when datatype=Complex"); } std::unordered_set<size_t> hashes = {}; json output = json::array(); for (json::iterator it = input.begin(); it != input.end(); ++it) { auto value = it.value(); if (value.is_array()) { throw runtime_error("Expected array of OBJECTS"); } const size_t h = Utils::JSON::get_hash_by_keys(value, keys); if (hashes.find(h) == hashes.end()) { hashes.insert(h); output.push_back(value); } } Utils::Write::json2file(output_path, output); } void init(CLI::App &app) { auto unique = app.add_subcommand("unique", "Uniq any array"); unique->add_option("--input1", _input_path, "Input file")->required()->check(CLI::ExistingFile); unique->add_option("--param1", _filetype, "Type of input file (CSV/JSON). Default: JSON") ->transform(CLI::CheckedTransformer(filetype_map, CLI::ignore_case)); unique->add_option("--param2", _datatype, "Data type (Simple/Complex). Default: Simple") ->transform(CLI::CheckedTransformer(datatype_map, CLI::ignore_case)); unique->add_option("--param3", _keys, "Keys to match 'Complex' (string, comma separated). Default: <all>"); unique->add_option("--output1", _output_path, "Output file")->required(); unique->callback([&]() { Unique::process(_input_path, _filetype, _datatype, _keys, _output_path); }); } }
35.876289
115
0.55
[ "vector", "transform" ]
beeefb540f89084b200fb91c3d32889ee61718d7
2,589
cpp
C++
621.task_scheduler.cpp
liangwt/leetcode
8f279343e975666a63ee531228c6836f20f199ca
[ "Apache-2.0" ]
5
2019-09-12T05:23:44.000Z
2021-11-15T11:19:39.000Z
621.task_scheduler.cpp
liangwt/leetcode
8f279343e975666a63ee531228c6836f20f199ca
[ "Apache-2.0" ]
18
2019-09-23T13:11:06.000Z
2019-11-09T11:20:17.000Z
621.task_scheduler.cpp
liangwt/leetcode
8f279343e975666a63ee531228c6836f20f199ca
[ "Apache-2.0" ]
null
null
null
/* * Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks. Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle. * * However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle. * * You need to return the least number of intervals the CPU will take to finish all the given tasks. * * * * Example: * * Input: tasks = ["A","A","A","B","B","B"], n = 2 * Output: 8 * Explanation: A -> B -> idle -> A -> B -> idle -> A -> B. * * * Note: * * The number of tasks is in the range [1, 10000]. * The integer n is in the range [0, 100]. * */ /** * 首先理解题意: * 其中n是指相同任务的间隔 * 例如n=2 那A和A直接必须得隔两个空位 AXXA, 这个X可以是其他任务,也可以是idle。 * 如果是ABCABC依旧是符合要求的,因为A与A间隔超过了2,B与B间隔也超过了2 * * 解题思路: * * 我们找到数量最多的任务,然后再根据n值在任务中插入空,之后用剩余的任务填充这些空值,最后得到的长度就是需要的周期,空值就是idle * * 再思考如何获取最终结果的长度,对于数量最多的任务个数mx。因为是现在任务之间插入空值,所以长度的一部分为 (mx-1)*(n+1) * 这部分没有包含最后的结尾,最后结尾的长度应该是具有相同最多数量的任务的个数num * * 例如 ['A', 'A', 'A', 'B', 'B'] , 2 * * 任务A的数量最多,在A之间直接插入数量为n的空,可得 * * A--A--A * * 然后用剩余的B来填充,得 * * AB-AB-A * * 而所需时间就是 A的个数3-1,乘上n+1得 6 这是 `AB-AB-` 的长度,再加上末尾的A就是总长度7 * * * 例如 {'A', 'A', 'A', 'B', 'B', 'B', 'C'}, 2 * * 任务 A、B数量最多,数量都是num = 2,在AB之间插入n-1个空值 * * AB-AB-AB * * 剩余用C来填充 * * ABCAB-AB * * 所需时间为:A的个数3-1,乘上n+1 得 6,这是 `ABCAB-`的长度,再加上末尾AB,注意是AB的长度2 * */ #include <vector> using namespace std; class Solution { public: int leastInterval(vector<char> &tasks, int n) { vector<int> table(25, 0); for (auto task : tasks) { table[task - 'A']++; } int mx = 0, nu = 0; for (auto i: table) { if (i == mx) { nu++; } if (i > mx) { mx = i; nu = 1; } } return max((int) tasks.size(), (mx - 1) * (n + 1) + nu); } }; int main() { Solution s; vector<char> t1 = {'A', 'A', 'A', 'B', 'B', 'B'}; assert(s.leastInterval(t1, 2) == 8); vector<char> t2 = {'A', 'B', 'C', 'D', 'E', 'A', 'B', 'C', 'D', 'E'}; assert(s.leastInterval(t2, 4) == 10); vector<char> t3 = {'A', 'A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'}; assert(s.leastInterval(t3, 2) == 10); vector<char> t4 = {'A', 'A', 'A', 'B', 'B', 'B'}; assert(s.leastInterval(t4, 0) == 6); return 0; }
23.752294
289
0.545384
[ "vector" ]
bef7321e46a67a5255ed3fb48d321449b6e55c7b
2,459
hxx
C++
opencascade/ShapeExtend_BasicMsgRegistrator.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/ShapeExtend_BasicMsgRegistrator.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/ShapeExtend_BasicMsgRegistrator.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 2000-01-28 // Created by: data exchange team // Copyright (c) 2000-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ShapeExtend_BasicMsgRegistrator_HeaderFile #define _ShapeExtend_BasicMsgRegistrator_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Transient.hxx> #include <Message_Gravity.hxx> class Standard_Transient; class Message_Msg; class TopoDS_Shape; class ShapeExtend_BasicMsgRegistrator; DEFINE_STANDARD_HANDLE(ShapeExtend_BasicMsgRegistrator, Standard_Transient) //! Abstract class that can be used for attaching messages //! to the objects (e.g. shapes). //! It is used by ShapeHealing algorithms to attach a message //! describing encountered case (e.g. removing small edge from //! a wire). //! //! The methods of this class are empty and redefined, for instance, //! in the classes for Data Exchange processors for attaching //! messages to interface file entities or CAS.CADE shapes. class ShapeExtend_BasicMsgRegistrator : public Standard_Transient { public: //! Empty constructor. Standard_EXPORT ShapeExtend_BasicMsgRegistrator(); //! Sends a message to be attached to the object. //! Object can be of any type interpreted by redefined MsgRegistrator. Standard_EXPORT virtual void Send (const Handle(Standard_Transient)& object, const Message_Msg& message, const Message_Gravity gravity); //! Sends a message to be attached to the shape. Standard_EXPORT virtual void Send (const TopoDS_Shape& shape, const Message_Msg& message, const Message_Gravity gravity); //! Calls Send method with Null Transient. Standard_EXPORT virtual void Send (const Message_Msg& message, const Message_Gravity gravity); DEFINE_STANDARD_RTTIEXT(ShapeExtend_BasicMsgRegistrator,Standard_Transient) protected: private: }; #endif // _ShapeExtend_BasicMsgRegistrator_HeaderFile
29.27381
138
0.785279
[ "object", "shape" ]
8305bf27110b938965b3eab5b0056e0d155836d0
17,991
cpp
C++
src/BaseSpline.cpp
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
71
2015-03-30T17:22:52.000Z
2022-01-01T14:19:23.000Z
src/BaseSpline.cpp
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
190
2015-01-27T16:18:58.000Z
2022-03-31T16:49:58.000Z
src/BaseSpline.cpp
BR903/percolator
2d9315699cf3309421b83c4c21ce8275ede87089
[ "Apache-2.0" ]
45
2015-04-13T13:42:35.000Z
2021-12-17T08:26:21.000Z
/******************************************************************************* Copyright 2006-2012 Lukas Käll <lukas.kall@scilifelab.se> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ #include<iterator> #include<vector> #include<algorithm> #include<numeric> #include<functional> #include<cmath> #include "BaseSpline.h" #include "Globals.h" using namespace std; class SplinePredictor { BaseSpline* bs; public: SplinePredictor(BaseSpline* b) { bs = b; } double operator()(double x) { return bs->predict(x); } }; double BaseSpline::convergeEpsilon = 1e-4; double BaseSpline::stepEpsilon = 1e-8; double BaseSpline::weightSlope = 1e1; double BaseSpline::scaleAlpha = 1; double BaseSpline::splineEval(double xx) { xx = transf(xx); std::size_t n = x.size(); vector<double>::iterator left, right = lower_bound(x.begin(), x.end(), xx); if (right == x.end()) { double derl = (g[n - 1] - g[n - 2]) / (x[n - 1] - x[n - 2]) + (x[n - 1] - x[n - 2]) / 6 * gamma[n - 3]; double gx = g[n - 1] + (xx - x[n - 1]) * derl; return gx; } int rix = static_cast<int>(right - x.begin()); if (*right == xx) { return g[rix]; } if (rix > 0) { left = right; left--; double dr = *right - xx; double dl = xx - *left; double gamr = (rix < static_cast<int>(n - 1) ? gamma[rix - 1] : 0.0); double gaml = (rix > 1 ? gamma[rix - 1 - 1] : 0.0); double h = *right - *left; double gx = (dl * g[rix] + dr * g[rix - 1]) / h - dl * dr / 6 * ((1.0 + dl / h) * gamr + (1.0 + dr / h) * gaml); return gx; } // if (rix==0) double derr = (g[1] - g[0]) / (x[1] - x[0]) - (x[1] - x[0]) / 6 * gamma[0]; double gx = g[0] - (x[0] - xx) * derr; return gx; } static double tao = 2 / (1 + sqrt(5.0)); // inverse of golden section void BaseSpline::roughnessPenaltyIRLS_Old() { unsigned int alphaIter = 0; initiateQR(); double alpha = .05, cv = 1e100; initg(); do { iterativeReweightedLeastSquares(alpha); double p1 = 1 - tao; double p2 = tao; pair<double, double> res = alphaLinearSearch(0.0, 1.0, p1, p2, crossValidation(-log(p1)), crossValidation(-log(p2))); if (VERB > 2) { cerr << "Alpha=" << res.first << ", cv=" << res.second << endl; } assert(isfinite(res.second)); if ((cv - res.second) / cv < convergeEpsilon || alphaIter++ > 100) { // Reject our last attempt to set alpha, // Return with the alpha used when setting g break; } cv = res.second; alpha = res.first; } while (true); if (VERB > 2) { cerr << "Alpha selected to be " << alpha << endl; } g = gnew; } void BaseSpline::roughnessPenaltyIRLS() { initiateQR(); initg(); double p1 = 1 - tao; double p2 = tao; double alpha = alphaLinearSearchBA(0.0, 1.0, p1, p2, evaluateSlope(-scaleAlpha*log(p1)), evaluateSlope(-scaleAlpha*log(p2))); if (VERB > 2) { cerr << "Alpha selected to be " << alpha << endl; } iterativeReweightedLeastSquares(alpha); } void BaseSpline::iterativeReweightedLeastSquares(double alpha) { double step = 0.0; int iter = 0; unsigned int n = static_cast<unsigned int>(x.size()); do { g = gnew; calcPZW(); PackedMatrix diag = PackedMatrix::packedDiagonalMatrix(PackedVector(static_cast<int>(n), 1) / w).packedMultiply(alpha); PackedMatrix aWiQ = (diag).packedMultiply(Q); PackedMatrix M = R.packedAdd(Qt.packedMultiply(aWiQ)); gamma = Qt.packedMultiply(z); solveInPlace(M,gamma); gnew = z.packedSubtract(aWiQ.packedMultiply(gamma)); limitg(); PackedVector difference = g.packedSubtract(gnew); step = packedNorm(difference) / n; if (VERB > 3) { cerr << "step size:" << step << endl; } } while ((step > stepEpsilon || step < 0.0) && (++iter < 20)); g = gnew; } pair<double, double> BaseSpline::alphaLinearSearch(double min_p, double max_p, double p1, double p2, double cv1, double cv2) { double oldCV; if (cv1 > cv2) { min_p = p1; p1 = p2; oldCV = cv1; cv1 = cv2; p2 = min_p + tao * (max_p - min_p); cv2 = crossValidation(-log(p2)); if (VERB > 3) { cerr << "New point with alpha=" << -log(p2) << ", giving cv=" << cv2 << " taken in consideration" << endl; } } else { max_p = p2; p2 = p1; oldCV = cv2; cv2 = cv1; p1 = min_p + (1 - tao) * (max_p - min_p); cv1 = crossValidation(-log(p1)); if (VERB > 3) { cerr << "New point with alpha=" << -log(p1) << ", giving cv=" << cv1 << " taken in consideration" << endl; } } if ((oldCV - min(cv1, cv2)) / oldCV < 1e-3 || (abs(p2 - p1) < 1e-10)) { return (cv1 > cv2 ? make_pair(-log(p2), cv2) : make_pair(-log(p1), cv1)); } return alphaLinearSearch(min_p, max_p, p1, p2, cv1, cv2); } double BaseSpline::alphaLinearSearchBA(double min_p, double max_p, double p1, double p2, double cv1, double cv2) { // Minimize Slope score // Use neg log of 0<p<1 so that we allow for searches 0<alpha<inf double oldCV = 0.0; if (cv2 < cv1) { // keep point 2 min_p = p1; p1 = p2; p2 = min_p + tao * (max_p - min_p); oldCV = cv1; cv1 = cv2; cv2 = evaluateSlope(-scaleAlpha*log(p2)); if (VERB > 3) { cerr << "New point with alpha=" << -scaleAlpha*log(p2) << ", giving slopeScore=" << cv2 << endl; } } else { // keep point 1 max_p = p2; p2 = p1; p1 = min_p + (1 - tao) * (max_p - min_p); oldCV = cv2; cv2 = cv1; cv1 = evaluateSlope(-scaleAlpha*log(p1)); if (VERB > 3) { cerr << "New point with alpha=" << -scaleAlpha*log(p1) << ", giving slopeScore=" << cv1 << endl; } } if ((oldCV - min(cv1, cv2)) / oldCV < 1e-5 || (abs(p2 - p1) < 1e-10)) { return (cv1 < cv2 ? -scaleAlpha*log(p1) : -scaleAlpha*log(p2)); } return alphaLinearSearchBA(min_p, max_p, p1, p2, cv1, cv2); } void BaseSpline::initiateQR() { int n = static_cast<int>(x.size()); dx.resize(n-1); for (std::size_t ix = 0; static_cast<int>(ix) < n - 1; ix++) { dx.addElement(static_cast<int>(ix), x[ix + 1] - x[ix]); assert(dx[ix] > 0); } Q = PackedMatrix(n,n-2); R = PackedMatrix(n-2, n-2); //Fill Q Q[0].packedAddElement(0, 1 / dx[0]); Q[1].packedAddElement(0, -1 / dx[0] - 1 / dx[1]); Q[1].packedAddElement(1, 1 / dx[1]); for (int j = 2; j < n - 2; j++) { Q[j].packedAddElement(j-2, 1 / dx[j - 1]); Q[j].packedAddElement(j-1, -1 / dx[j - 1] - 1 / dx[j]); Q[j].packedAddElement(j, 1 / dx[j]); } Q[n - 2].packedAddElement(n-4, 1 / dx[n - 3]); Q[n - 2].packedAddElement(n - 3, -1 / dx[n - 3] - 1 / dx[n - 2]); Q[n - 1].packedAddElement(n - 3, 1 / dx[n - 2]); //Fill R for (int i = 0; i < n - 3; i++) { R[i].packedAddElement(i, (dx[i] + dx[i + 1]) / 3); R[i].packedAddElement(i + 1, dx[i + 1] / 6); R[i + 1].packedAddElement(i, dx[i + 1] / 6); } R[n - 3].packedAddElement(n - 3, (dx[n - 3] + dx[n - 2]) / 3); Qt = PackedMatrix(n-2,n); Qt = Qt.packedTranspose(Q); } double BaseSpline::evaluateSlope(double alpha) { // Calculate a spline for current alpha iterativeReweightedLeastSquares(alpha); // Find highest point (we only want to evaluate things to the right of that point) int n = g.numberEntries(); int mixg=1; // Ignore 0 and n-1 double maxg = g[mixg]; for (int ix=mixg;ix<n-1;++ix) { assert(ix=g.index(ix)); //This should be a filled vector if (g[ix]>=maxg) { maxg = g[ix]; mixg = ix; } } double maxSlope = -10e6; int slopeix=-1; for (int ix=mixg+1;ix<n-2; ++ix) { double slope=g[ix-1]-g[ix]; if (slope>maxSlope) { maxSlope = slope; slopeix = ix; } } // Now score the fit based on a linear combination between // The bump area and alpha if (VERB > 3) { cerr << "mixg=" << mixg << ", maxg=" << maxg << ", maxBA=" << maxSlope << " at ix=" << slopeix << ", alpha=" << alpha << endl; } return maxSlope*weightSlope + alpha; } double BaseSpline::crossValidation(double alpha) { std::size_t n = static_cast<std::size_t>(R.numRows()); // Vec k0(n),k1(n),k2(n); vector<double> k0(n), k1(n), k2(n); PackedMatrix B = R.packedAdd( ((Qt.packedMultiply(alpha)).packedMultiply( PackedMatrix::packedDiagonalMatrix(Vector(static_cast<int>(n)+2, 1.0) / w)).packedMultiply(Q))); // Get the diagonals from K // ka[i]=B[i,i+a]=B[i+a,i] for (std::size_t row = 0; row < n; ++row) { for (int rowPos = B[row].numberEntries(); rowPos--;) { std::size_t col = static_cast<std::size_t>(B[row].index(rowPos)); if (col == row) { k0[row] = B[row][rowPos]; } else if (col + 1 == row) { k1[row] = B[row][rowPos]; } else if (col + 2 == row) { k2[row] = B[row][rowPos]; } } } // LDL decompose Page 26 Green Silverman // d[i]=D[i,i] // la[i]=L[i+a,i] // Vec d(n),l1(n),l2(n); vector<double> d(n), l1(n), l2(n); d[0] = k0[0]; l1[0] = k1[0] / d[0]; d[1] = k0[1] - l1[0] * l1[0] * d[0]; for (std::size_t row = 2; row < n; ++row) { l2[row - 2] = k2[row - 2] / d[row - 2]; l1[row - 1] = (k1[row - 1] - l1[row - 2] * l2[row - 2] * d[row - 2]) / d[row - 1]; d[row] = k0[row] - l1[row - 1] * l1[row - 1] * d[row - 1] - l2[row - 2] * l2[row - 2] * d[row - 2]; } // Find diagonals of inverse Page 34 Green Silverman // ba[i]=B^{-1}[i+a,i]=B^{-1}[i,i+a] // Vec b0(n),b1(n),b2(n); vector<double> b0(n), b1(n), b2(n); for (std::size_t row = n; --row;) { if (row == n - 1) { b0[n - 1] = 1 / d[n - 1]; } else if (row == n - 2) { b0[n - 2] = 1 / d[n - 2] - l1[n - 2] * b1[n - 2]; } else { b0[row] = 1 / d[row] - l1[row] * b1[row] - l2[row] * b2[row]; } if (row == n - 1) { b1[n - 2] = -l1[n - 2] * b0[n - 1]; } else if (row >= 1) { b1[row - 1] = -l1[row - 1] * b0[row] - l1[row] * b1[row]; } if (row >= 2) { b2[row - 2] = -l1[row - 2] * b0[row]; } } // Calculate diagonal elements a[i]=Aii p35 Green Silverman // (expanding q according to p12) // Vec a(n+2),c(n+1); vector<double> a(n), c(n - 1); for (std::size_t ix = 0; ix < n - 1; ix++) { c[ix] = 1 / dx[ix]; } for (std::size_t ix = 0; ix < n; ix++) { if (ix > 0) { a[ix] += b0[ix - 1] * c[ix - 1] * c[ix - 1]; if (ix < n - 1) { a[ix] += b0[ix] * (-c[ix - 1] - c[ix]) * (-c[ix - 1] - c[ix]); a[ix] += 2 * b1[ix] * c[ix] * (-c[ix - 1] - c[ix]); a[ix] += 2 * b1[ix - 1] * c[ix - 1] * (-c[ix - 1] - c[ix]); a[ix] += 2 * b2[ix - 1] * c[ix - 1] * c[ix]; } } if (ix < n - 1) { a[ix] += b0[ix + 1] * c[ix] * c[ix]; } } // Calculating weighted cross validation as described in p double cv = 0.0; for (std::size_t ix = 0; ix < n; ix++) { double f = (z[ix] - gnew[ix]) * w[ix] / (alpha * a[ix]); // double f =(z[ix]-gnew[ix])/(alpha*alpha*a[ix]*a[ix]); cv += f * f * w[ix]; } return cv; } void BaseSpline::predict(const vector<double>& xx, vector<double>& predict) { predict.clear(); transform(xx.begin(), xx.end(), back_inserter(predict), SplinePredictor(this)); } void BaseSpline::setData(const vector<double>& xx) { x.clear(); double minV = *min_element(xx.begin(), xx.end()); double maxV = *max_element(xx.begin(), xx.end()); if (minV >= 0.0 && maxV <= 1.0) { if (VERB > 1) { cerr << "Logit transforming all scores prior to PEP calculation" << endl; } transf = Transform(minV > 0.0 ? 0.0 : 1e-20, maxV < 1.0 ? 0.0 : 1e-10, true); } else if (minV >= 0.0) { if (VERB > 1) { cerr << "Log transforming all scores prior to PEP calculation" << endl; } transf = Transform(minV > 0.0 ? 0.0 : 1e-20, 0.0, false, true); } transform(xx.begin(), xx.end(), back_inserter(x), transf); } void BaseSpline::solveInPlace(PackedMatrix& mat, PackedVector& res) { res = res.makeSparse(); // Current implementation requires a quadratic mat int nCol = mat.numCols(); PackedVector nonEmpty; int col, row, rowPos; for (col = 0; col < nCol; col++) { //int stop = 1; //if(col==stop-1){ // cout << "*********************"<<endl; // cout << col << endl; // cout << "*********************"<<endl; // mat.displayMatrix(); // cout << "RES: " <<res.values<<endl; //} // find the non-null elements in this column (below row "col") nonEmpty = PackedVector(); int pivotPos(-1); for (row = col; row < mat.numRows(); row++) { int rowEntries = mat[row].numberEntries(); for (rowPos = rowEntries; rowPos--;) { int entryIndex = mat[row].index(rowPos); if (entryIndex == col) { nonEmpty.packedAddElement(row, mat[row][rowPos]); if (row == col) { pivotPos = nonEmpty.numberEntries()-1; } } } } // if(col==stop-1){ // cout<<"nonEmpty " << nonEmpty.values<< endl; // cout<<"pivot " << pivotPos<< endl<<endl; // } //find most significant row double maxVal(0.0); int maxRow(-1), maxRowPos(-1); for (rowPos = nonEmpty.numberEntries(); rowPos--;) { double val = nonEmpty[rowPos]; assert(isfinite(val)); if (fabs(val) > fabs(maxVal)) { maxVal = val; maxRow = nonEmpty.index(rowPos); maxRowPos = rowPos; } } //int imaxRow = maxRow; //int imaxRowPos = maxRowPos; // if(col==stop-1){ // cout << "imaxRow " << imaxRow << endl; // cout << "imaxRowPos " << imaxRowPos << endl<<endl; // } // Put the most significant row at row "col" if (maxVal != 0.0) { if (maxRow != col) { swap(mat[col], mat[maxRow]); res.swapElements(col, maxRow); if (pivotPos >= 0) { nonEmpty.swapElements(maxRowPos, pivotPos); } } // if(col==stop-1){ // cout << "SWAP\n"; // mat.displayMatrix(); // } // Divide the row with maxVal mat[col].packedDiv(maxVal); double value = res[col] / maxVal; res.packedReplace(col,value); // if(col==stop-1){ // cout << "\nDIVIDE ROW\n"; // mat.displayMatrix(); // cout << "res " << res.values<<endl; // cout << "nonEmpty " << nonEmpty.values<<endl; // cout << "\n\n"; // } } // subtract the row from other rows for (rowPos = nonEmpty.numberEntries(); rowPos--;) { row = nonEmpty.index(rowPos); if (row == col) { continue; } // If the pivotRow was empty (prior to swap) at col=row do not process this row if (pivotPos < 0 && row == maxRow) { continue; } double val = nonEmpty[rowPos]; PackedVector prodVector = mat[col]; mat[row] = mat[row].packedSubtract(prodVector.packedProd(val)); double value = res[row] - (val * res[col]); res.packedReplace(row, value); // if(col==stop-1){ // cout << "SUBTRACT ROW\n"; // mat.displayMatrix(); // cout << "res " << res.values<<endl; // cout << "nonEmpty " << nonEmpty.values<<endl; // cout << "\n\n"; // } } } // Go bottom up and clear upper halfmatrix // mat.displayMatrix(); // res.displayVector(); // nonEmpty.displayVector(); // cout << "\n\n\n\n"; for (col = mat.numCols(); col--;) { nonEmpty = PackedVector(); for (row = 0; row < col; row++) { for (rowPos = mat[row].numberEntries(); rowPos--;) { if (mat[row].index(rowPos) == col) { nonEmpty.packedAddElement(row, mat[row][rowPos]); } } } // cout << nonEmpty.values<<endl; // subtract the row from other rows for (rowPos = nonEmpty.numberEntries(); rowPos--;) { row = nonEmpty.index(rowPos); double val = nonEmpty[rowPos]; mat[row] = mat[row].packedSubtract(mat[col].packedProd(val)); double value = res[row] - (val * res[col]); res.packedReplace(row, value); } // cout << res.values<<endl; } return; } void BaseSpline::testPerformance(){ cout << "\nTesting performance for fido:\n"; PackedVector v; PackedMatrix M1; PackedMatrix M2; for (int n= 500; n <= 1000; n+=100){ cout << "********** " << "\n"; cout << "MATRIX DIM: " << n << "\n"; cout << "********** "<< "\n"; double s = 2.0; v = PackedVector(n,3.0); M1 = PackedMatrix(n,n); M2 = PackedMatrix(n,n); for (signed i = 0; i < signed (n); ++ i){ for (signed j = max (i-1, 0); j < min (i+2, signed (n)); ++ j){ M1[i].packedAddElement(j, 3 * i + j); M2[i].packedAddElement(j, 2 * i + j); } } M1.packedMultiply(s); M1.packedMultiply(v); M1.packedAdd(M2); M1.packedMultiply(M2); cout << endl; } }
31.563158
130
0.518092
[ "vector", "transform" ]
830943e98e2be25a17854b7fa92ab8dbefccba92
2,130
hpp
C++
src/ccoold/protocol.hpp
metthal/ccool
5b26208fbd61c0f115e37fbbce57716ceaed398b
[ "MIT" ]
null
null
null
src/ccoold/protocol.hpp
metthal/ccool
5b26208fbd61c0f115e37fbbce57716ceaed398b
[ "MIT" ]
null
null
null
src/ccoold/protocol.hpp
metthal/ccool
5b26208fbd61c0f115e37fbbce57716ceaed398b
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <tuple> #include "buffer.hpp" #include "interfaces/device_interface.hpp" #include "types.hpp" namespace ccool { template <Endian DataEndian, typename OpcodeTypeT> class Protocol { public: static constexpr Endian endian = DataEndian; using OpcodeType = OpcodeTypeT; Protocol(DeviceInterface* device_interface, const std::string& name) : _device_interface(device_interface), _name(name) {} virtual ~Protocol() = default; const std::string& get_name() const { return _name; } Buffer send(std::uint8_t endpoint, const Buffer& data) { pre_request(); _device_interface->send(endpoint, data); auto response = _device_interface->recv(endpoint); post_response(); return response; } virtual void pre_request() {} virtual void post_response() {} virtual std::uint16_t read_pump_rpm(std::uint8_t endpoint) = 0; virtual std::tuple<std::uint32_t, std::uint16_t> read_fan_rpm(std::uint8_t endpoint, std::uint8_t fan_index) = 0; virtual FixedPoint<16> read_temperature(std::uint8_t endpoint) = 0; virtual std::tuple<std::uint8_t, std::uint8_t, std::uint8_t> read_firmware_version(std::uint8_t endpoint) = 0; virtual void write_pump_mode(std::uint8_t endpoint, std::uint8_t mode) = 0; virtual void write_fan_curve(std::uint8_t endpoint, std::uint8_t fan_index, const std::vector<std::uint8_t>& temperatures, const std::vector<std::uint8_t>& pwm) = 0; virtual void write_fan_pwm(std::uint8_t endpoint, std::uint8_t fan_index, std::uint8_t pwm) = 0; virtual void write_fan_rpm(std::uint8_t endpoint, std::uint8_t fan_index, std::uint16_t rpm) = 0; virtual void write_custom_led_color_enabled(std::uint8_t endpoint, std::uint8_t enabled) = 0; virtual void write_custom_led_color(std::uint8_t endpoint, std::uint8_t red, std::uint8_t green, std::uint8_t blue) = 0; virtual void write_enabled_external_temperature(std::uint8_t endpoint, std::uint8_t enabled) = 0; virtual void write_external_temperature(std::uint8_t endpoint, const FixedPoint<16>& temperature) = 0; protected: DeviceInterface* _device_interface; private: std::string _name; }; } // namespace ccool
37.368421
166
0.76338
[ "vector" ]
830c0c33726b875229555f16dc1ef6d285f0e155
1,826
hpp
C++
src/lola/iface/include/iface_wpatt_lola.hpp
am-lola/lepp3
7f92ce61bccad984e18ce86da0d8a1b9c48feb65
[ "MIT" ]
6
2017-01-16T10:41:56.000Z
2020-10-09T09:13:30.000Z
src/lola/iface/include/iface_wpatt_lola.hpp
am-lola/lepp3
7f92ce61bccad984e18ce86da0d8a1b9c48feb65
[ "MIT" ]
null
null
null
src/lola/iface/include/iface_wpatt_lola.hpp
am-lola/lepp3
7f92ce61bccad984e18ce86da0d8a1b9c48feb65
[ "MIT" ]
4
2015-08-07T13:07:32.000Z
2021-08-03T03:18:33.000Z
/*! @file wpatt_data_johnnie.hpp time sequence data output from walking pattern generator Copyright (C) Institute of Applied Mechanics, TU-Muenchen All rights reserved. */ #ifndef __IFACE_WPATT_LOLA_HPP__ #define __IFACE_WPATT_LOLA_HPP__ #include <stdint.h> #include <begin_pack.h> namespace am2b_iface { namespace lola { struct WPattGenDataLola { enum{NX=29}; //incremented every update uint64_t stamp_gen; uint64_t stamp_plan; //current time double time_gen; double time_plan; //load factor double stance_load; //stance leg index int stance; //reference trajectory point double x_ideal[NX]; //d(x_ideal)/dt double dot_x_ideal[NX]; //d^2(x_ideal)/dt^2 double ddot_x_ideal[NX]; //T_cog of 3-mass model double T_cog_3m[2]; //robert: step-modification variables: double initial_state_x[2]; double initial_state_y[2]; double phi_imu[4]; //number of stabilisation directions enum{NSTAB=2}; //!swing-leg double dr_swing_stab[NSTAB+1]; double dcsin_swing_stab[NSTAB]; //!stance-leg double dr_stance_stab[NSTAB+1]; double dcsin_stance_stab[NSTAB]; double dx_step_new; double dy_step_new; double dz_step_new; double dphi_x_step_new; double dphi_y_step_new; double l_init[2]; double l_coll[2]; double dx_cog, dot_dx_cog, ddot_dx_cog; double dy_cog, dot_dy_cog, ddot_dy_cog; //Arne - compare struct_data_stepseq // 3 - 3 steps float L0[3]; float L1[3]; float B[3]; float phiO[3]; float dz_clear[3]; float dy[3]; }; } //lola }//am2b_iface #include <end_pack.h> #endif//__IFACE_WPATT_LOLA_HPP__
22.54321
60
0.635268
[ "model" ]
23fc54e794ff141f662b45a48fe1321a7c001f9a
3,090
cpp
C++
filtering/OrientationPredictor.cpp
AlesMaver/ExpansionHunter
274903d26a33cfbc546aac98c85bbfe51701fd3b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
filtering/OrientationPredictor.cpp
AlesMaver/ExpansionHunter
274903d26a33cfbc546aac98c85bbfe51701fd3b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
filtering/OrientationPredictor.cpp
AlesMaver/ExpansionHunter
274903d26a33cfbc546aac98c85bbfe51701fd3b
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
// // Expansion Hunter // Copyright 2016-2019 Illumina, Inc. // All rights reserved. // // Author: Egor Dolzhenko <edolzhenko@illumina.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // #include "filtering/OrientationPredictor.hh" #include <algorithm> #include <iostream> #include <list> #include <stdexcept> #include <string> #include <vector> #include <stdexcept> #include "graphcore/Path.hh" using graphtools::Graph; using graphtools::GraphAlignment; using graphtools::Path; using graphtools::reverseGraph; using std::list; using std::string; using std::vector; namespace ehunter { static int countNonoverlappingKmerMatches(const string& query, int kmerLength, const BloomFilter& bloomFilter) { int matchCount = 0; size_t position = 0; while (position + kmerLength <= query.length()) { string kmer = query.substr(position, kmerLength); std::transform(kmer.begin(), kmer.end(), kmer.begin(), ::toupper); if (bloomFilter.maybeContains(kmer)) { ++matchCount; position += kmerLength; } else { ++position; } } return matchCount; } OrientationPredictor::OrientationPredictor(const Graph* graph) : kmerLength_(10) , minKmerMatchesToPass_(3) , bloomFilter_(build(*graph, kmerLength_)) , oppositeBloomFilter_(build(reverseGraph(*graph, true), kmerLength_)) { } OrientationPrediction OrientationPredictor::predict(const string& query) const { const int numMatches = countNonoverlappingKmerMatches(query, kmerLength_, bloomFilter_); const int numOppositeMatches = countNonoverlappingKmerMatches(query, kmerLength_, oppositeBloomFilter_); const int maxMatches = std::max(numMatches, numOppositeMatches); if (maxMatches < minKmerMatchesToPass_) { return OrientationPrediction::kDoesNotAlign; } if (numMatches >= numOppositeMatches) { return OrientationPrediction::kAlignsInOriginalOrientation; } else { return OrientationPrediction::kAlignsInOppositeOrientation; } } std::ostream& operator<<(std::ostream& out, OrientationPrediction orientationPrediction) { switch (orientationPrediction) { case OrientationPrediction::kAlignsInOriginalOrientation: out << "kAlignsInOriginalOrientation"; break; case OrientationPrediction::kAlignsInOppositeOrientation: out << "kAlignsInOppositeOrientation"; break; case OrientationPrediction::kDoesNotAlign: out << "kDoesNotAlign"; } return out; } }
26.410256
110
0.705825
[ "vector", "transform" ]
23fe968e1e61e80c44762f8f1f46b4fd64825cc3
18,573
cpp
C++
src/RigidBody.cpp
AndresTraks/BulletSharp
c277666667f91c58191f4cfa97f117053de679ef
[ "MIT" ]
245
2015-01-02T14:11:26.000Z
2022-03-18T08:56:36.000Z
src/RigidBody.cpp
AndresTraks/BulletSharp
c277666667f91c58191f4cfa97f117053de679ef
[ "MIT" ]
50
2015-01-04T22:32:21.000Z
2021-06-08T20:26:24.000Z
src/RigidBody.cpp
AndresTraks/BulletSharp
c277666667f91c58191f4cfa97f117053de679ef
[ "MIT" ]
69
2015-04-03T15:38:44.000Z
2022-01-20T14:27:30.000Z
#include "StdAfx.h" #include "BroadphaseProxy.h" #include "CollisionShape.h" #include "DefaultMotionState.h" #include "MotionState.h" #include "RigidBody.h" #ifndef DISABLE_CONSTRAINTS #include "TypedConstraint.h" #endif RigidBodyConstructionInfo::~RigidBodyConstructionInfo() { this->!RigidBodyConstructionInfo(); } RigidBodyConstructionInfo::!RigidBodyConstructionInfo() { ALIGNED_FREE(_native); _native = NULL; } #ifndef BTSHARP_USE_SSE_ALIGNMENT #pragma managed(push, off) btRigidBody::btRigidBodyConstructionInfo* RigidBody_GetUnmanagedConstructionInfo( btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape) { return ALIGNED_NEW(btRigidBody::btRigidBodyConstructionInfo) (mass, motionState, collisionShape); } #pragma managed(pop) #endif btRigidBody::btRigidBodyConstructionInfo* RigidBody_GetUnmanagedConstructionInfoLocalInertia( btScalar mass, btMotionState* motionState, btCollisionShape* collisionShape, btVector3* localInertia) { return ALIGNED_NEW(btRigidBody::btRigidBodyConstructionInfo) (mass, motionState, collisionShape, *localInertia); } RigidBodyConstructionInfo::RigidBodyConstructionInfo(btScalar mass, BulletSharp::MotionState^ motionState, BulletSharp::CollisionShape^ collisionShape) { #ifdef BTSHARP_USE_SSE_ALIGNMENT btVector3* localInertia = ALIGNED_NEW(btVector3) (0,0,0); // default localInertia parameter is not aligned _native = RigidBody_GetUnmanagedConstructionInfoLocalInertia(mass, GetUnmanagedNullable(motionState), GetUnmanagedNullable(collisionShape), localInertia); ALIGNED_FREE(localInertia); #else _native = RigidBody_GetUnmanagedConstructionInfo(mass, GetUnmanagedNullable(motionState), GetUnmanagedNullable(collisionShape)); #endif _collisionShape = collisionShape; _motionState = motionState; } RigidBodyConstructionInfo::RigidBodyConstructionInfo(btScalar mass, BulletSharp::MotionState^ motionState, BulletSharp::CollisionShape^ collisionShape, Vector3 localInertia) { VECTOR3_CONV(localInertia); _native = RigidBody_GetUnmanagedConstructionInfoLocalInertia(mass, GetUnmanagedNullable(motionState), GetUnmanagedNullable(collisionShape), VECTOR3_PTR(localInertia)); VECTOR3_DEL(localInertia); _collisionShape = collisionShape; _motionState = motionState; } btScalar RigidBodyConstructionInfo::AdditionalAngularDampingFactor::get() { return _native->m_additionalAngularDampingFactor; } void RigidBodyConstructionInfo::AdditionalAngularDampingFactor::set(btScalar value) { _native->m_additionalAngularDampingFactor = value; } btScalar RigidBodyConstructionInfo::AdditionalAngularDampingThresholdSqr::get() { return _native->m_additionalAngularDampingThresholdSqr; } void RigidBodyConstructionInfo::AdditionalAngularDampingThresholdSqr::set(btScalar value) { _native->m_additionalAngularDampingThresholdSqr = value; } bool RigidBodyConstructionInfo::AdditionalDamping::get() { return _native->m_additionalDamping; } void RigidBodyConstructionInfo::AdditionalDamping::set(bool value) { _native->m_additionalDamping = value; } btScalar RigidBodyConstructionInfo::AdditionalDampingFactor::get() { return _native->m_additionalDampingFactor; } void RigidBodyConstructionInfo::AdditionalDampingFactor::set(btScalar value) { _native->m_additionalDampingFactor = value; } btScalar RigidBodyConstructionInfo::AdditionalLinearDampingThresholdSqr::get() { return _native->m_additionalLinearDampingThresholdSqr; } void RigidBodyConstructionInfo::AdditionalLinearDampingThresholdSqr::set(btScalar value) { _native->m_additionalLinearDampingThresholdSqr = value; } btScalar RigidBodyConstructionInfo::AngularDamping::get() { return _native->m_angularDamping; } void RigidBodyConstructionInfo::AngularDamping::set(btScalar value) { _native->m_angularDamping = value; } btScalar RigidBodyConstructionInfo::AngularSleepingThreshold::get() { return _native->m_angularSleepingThreshold; } void RigidBodyConstructionInfo::AngularSleepingThreshold::set(btScalar value) { _native->m_angularSleepingThreshold = value; } CollisionShape^ RigidBodyConstructionInfo::CollisionShape::get() { return _collisionShape; } void RigidBodyConstructionInfo::CollisionShape::set(BulletSharp::CollisionShape^ value) { _collisionShape = value; _native->m_collisionShape = GetUnmanagedNullable(value); } btScalar RigidBodyConstructionInfo::Friction::get() { return _native->m_friction; } void RigidBodyConstructionInfo::Friction::set(btScalar value) { _native->m_friction = value; } btScalar RigidBodyConstructionInfo::LinearDamping::get() { return _native->m_linearDamping; } void RigidBodyConstructionInfo::LinearDamping::set(btScalar value) { _native->m_linearDamping = value; } btScalar RigidBodyConstructionInfo::LinearSleepingThreshold::get() { return _native->m_linearSleepingThreshold; } void RigidBodyConstructionInfo::LinearSleepingThreshold::set(btScalar value) { _native->m_linearSleepingThreshold = value; } Vector3 RigidBodyConstructionInfo::LocalInertia::get() { return Math::BtVector3ToVector3(&_native->m_localInertia); } void RigidBodyConstructionInfo::LocalInertia::set(Vector3 value) { Math::Vector3ToBtVector3(value, &_native->m_localInertia); } btScalar RigidBodyConstructionInfo::Mass::get() { return _native->m_mass; } void RigidBodyConstructionInfo::Mass::set(btScalar value) { _native->m_mass = value; } BulletSharp::MotionState^ RigidBodyConstructionInfo::MotionState::get() { return _motionState; } void RigidBodyConstructionInfo::MotionState::set(BulletSharp::MotionState^ value) { _native->m_motionState = GetUnmanagedNullable(value); _motionState = value; } btScalar RigidBodyConstructionInfo::Restitution::get() { return _native->m_restitution; } void RigidBodyConstructionInfo::Restitution::set(btScalar value) { _native->m_restitution = value; } btScalar RigidBodyConstructionInfo::RollingFriction::get() { return _native->m_rollingFriction; } void RigidBodyConstructionInfo::RollingFriction::set(btScalar value) { _native->m_rollingFriction = value; } Matrix RigidBodyConstructionInfo::StartWorldTransform::get() { return Math::BtTransformToMatrix(&_native->m_startWorldTransform); } void RigidBodyConstructionInfo::StartWorldTransform::set(Matrix value) { Math::MatrixToBtTransform(value, &_native->m_startWorldTransform); } #define Native static_cast<btRigidBody*>(_native) RigidBody::RigidBody(RigidBodyConstructionInfo^ constructionInfo) : CollisionObject(ALIGNED_NEW(btRigidBody) (*constructionInfo->_native)) { _collisionShape = constructionInfo->CollisionShape; _motionState = constructionInfo->_motionState; } #ifndef DISABLE_CONSTRAINTS void RigidBody::AddConstraintRef(TypedConstraint^ c) { Native->addConstraintRef(c->_native); } #endif void RigidBody::ApplyCentralForce(Vector3 force) { VECTOR3_CONV(force); Native->applyCentralForce(VECTOR3_USE(force)); VECTOR3_DEL(force); } void RigidBody::ApplyCentralImpulse(Vector3 impulse) { VECTOR3_CONV(impulse); Native->applyCentralImpulse(VECTOR3_USE(impulse)); VECTOR3_DEL(impulse); } void RigidBody::ApplyDamping(btScalar timeStep) { Native->applyDamping(timeStep); } void RigidBody::ApplyForce(Vector3 force, Vector3 relativePosition) { VECTOR3_CONV(force); VECTOR3_CONV(relativePosition); Native->applyForce(VECTOR3_USE(force), VECTOR3_USE(relativePosition)); VECTOR3_DEL(force); VECTOR3_DEL(relativePosition); } void RigidBody::ApplyGravity() { Native->applyGravity(); } void RigidBody::ApplyImpulse(Vector3 impulse, Vector3 relativePosition) { VECTOR3_CONV(impulse); VECTOR3_CONV(relativePosition); Native->applyImpulse(VECTOR3_USE(impulse), VECTOR3_USE(relativePosition)); VECTOR3_DEL(impulse); VECTOR3_DEL(relativePosition); } void RigidBody::ApplyTorque(Vector3 torque) { VECTOR3_CONV(torque); Native->applyTorque(VECTOR3_USE(torque)); VECTOR3_DEL(torque); } void RigidBody::ApplyTorqueImpulse(Vector3 torque) { VECTOR3_CONV(torque); Native->applyTorqueImpulse(VECTOR3_USE(torque)); VECTOR3_DEL(torque); } void RigidBody::ClearForces() { Native->clearForces(); } btScalar RigidBody::ComputeAngularImpulseDenominator(Vector3 axis) { VECTOR3_CONV(axis); btScalar ret = Native->computeAngularImpulseDenominator(VECTOR3_USE(axis)); VECTOR3_DEL(axis); return ret; } #pragma managed(push, off) void RigidBody_ComputeGyroscopicForceExplicit(btRigidBody* body, btVector3* ret, btScalar maxGyroscopicForce) { *ret = body->computeGyroscopicForceExplicit(maxGyroscopicForce); } #pragma managed(pop) Vector3 RigidBody::ComputeGyroscopicForceExplicit(btScalar maxGyroscopicForce) { btVector3* retTemp = ALIGNED_NEW(btVector3); RigidBody_ComputeGyroscopicForceExplicit(Native, retTemp, maxGyroscopicForce); Vector3 ret = Math::BtVector3ToVector3(retTemp); ALIGNED_FREE(retTemp); return ret; } #pragma managed(push, off) void RigidBody_ComputeGyroscopicImpulseImplicit_Body(btRigidBody* body, btVector3* ret, btScalar step) { *ret = body->computeGyroscopicImpulseImplicit_Body(step); } #pragma managed(pop) Vector3 RigidBody::ComputeGyroscopicImpulseImplicitBody(btScalar step) { btVector3* retTemp = ALIGNED_NEW(btVector3); RigidBody_ComputeGyroscopicImpulseImplicit_Body(Native, retTemp, step); Vector3 ret = Math::BtVector3ToVector3(retTemp); ALIGNED_FREE(retTemp); return ret; } #pragma managed(push, off) void RigidBody_ComputeGyroscopicImpulseImplicit_World(btRigidBody* body, btVector3* ret, btScalar dt) { *ret = body->computeGyroscopicImpulseImplicit_World(dt); } #pragma managed(pop) Vector3 RigidBody::ComputeGyroscopicImpulseImplicitWorld(btScalar deltaTime) { btVector3* retTemp = ALIGNED_NEW(btVector3); RigidBody_ComputeGyroscopicImpulseImplicit_World(Native, retTemp, deltaTime); Vector3 ret = Math::BtVector3ToVector3(retTemp); ALIGNED_FREE(retTemp); return ret; } btScalar RigidBody::ComputeImpulseDenominator(Vector3 pos, Vector3 normal) { VECTOR3_CONV(pos); VECTOR3_CONV(normal); btScalar ret = Native->computeImpulseDenominator(VECTOR3_USE(pos), VECTOR3_USE(normal)); VECTOR3_DEL(pos); VECTOR3_DEL(normal); return ret; } void RigidBody::GetAabb([Out] Vector3% aabbMin, [Out] Vector3% aabbMax) { btVector3* aabbMinTemp = ALIGNED_NEW(btVector3); btVector3* aabbMaxTemp = ALIGNED_NEW(btVector3); Native->getAabb(*aabbMinTemp, *aabbMaxTemp); Math::BtVector3ToVector3(aabbMinTemp, aabbMin); Math::BtVector3ToVector3(aabbMaxTemp, aabbMax); ALIGNED_FREE(aabbMinTemp); ALIGNED_FREE(aabbMaxTemp); } #ifndef DISABLE_CONSTRAINTS TypedConstraint^ RigidBody::GetConstraintRef(int index) { return TypedConstraint::GetManaged(Native->getConstraintRef(index)); } #endif #pragma managed(push, off) void RigidBody_GetVelocityInLocalPoint(btRigidBody* body, btVector3* velocity, btVector3* rel_pos) { *velocity = body->getVelocityInLocalPoint(*rel_pos); } #pragma managed(pop) Vector3 RigidBody::GetVelocityInLocalPoint(Vector3 relativePosition) { VECTOR3_CONV(relativePosition); btVector3* velocityTemp = ALIGNED_NEW(btVector3); RigidBody_GetVelocityInLocalPoint(Native, velocityTemp, VECTOR3_PTR(relativePosition)); Vector3 velocity = Math::BtVector3ToVector3(velocityTemp); VECTOR3_DEL(relativePosition); ALIGNED_FREE(velocityTemp); return velocity; } void RigidBody::IntegrateVelocities(btScalar step) { Native->integrateVelocities(step); } void RigidBody::PredictIntegratedTransform(btScalar step, [Out] Matrix% predictedTransform) { btTransform* predictedTransformTemp = ALIGNED_NEW(btTransform); Native->predictIntegratedTransform(step, *predictedTransformTemp); Math::BtTransformToMatrix(predictedTransformTemp, predictedTransform); ALIGNED_FREE(predictedTransformTemp); } void RigidBody::ProceedToTransform(Matrix newTrans) { TRANSFORM_CONV(newTrans); Native->proceedToTransform(TRANSFORM_USE(newTrans)); TRANSFORM_DEL(newTrans); } #ifndef DISABLE_CONSTRAINTS void RigidBody::RemoveConstraintRef(TypedConstraint^ c) { Native->removeConstraintRef(c->_native); } #endif void RigidBody::SaveKinematicState(btScalar step) { Native->saveKinematicState(step); } void RigidBody::SetDamping(btScalar linearDamping, btScalar angularDamping) { Native->setDamping(linearDamping, angularDamping); } void RigidBody::SetMassProps(btScalar mass, Vector3 inertia) { VECTOR3_CONV(inertia); Native->setMassProps(mass, VECTOR3_USE(inertia)); VECTOR3_DEL(inertia); } void RigidBody::SetSleepingThresholds(btScalar linear, btScalar angular) { Native->setSleepingThresholds(linear, angular); } void RigidBody::Translate(Vector3 vector) { VECTOR3_CONV(vector); Native->translate(VECTOR3_USE(vector)); VECTOR3_DEL(vector); } RigidBody^ RigidBody::Upcast(CollisionObject^ colObj) { btRigidBody* body = btRigidBody::upcast(colObj->_native); return (RigidBody^)CollisionObject::GetManaged(body); } void RigidBody::UpdateDeactivation(btScalar timeStep) { Native->updateDeactivation(timeStep); } void RigidBody::UpdateInertiaTensor() { Native->updateInertiaTensor(); } btScalar RigidBody::AngularDamping::get() { return Native->getAngularDamping(); } Vector3 RigidBody::AngularFactor::get() { return Math::BtVector3ToVector3(&Native->getAngularFactor()); } void RigidBody::AngularFactor::set(Vector3 value) { VECTOR3_CONV(value); Native->setAngularFactor(VECTOR3_USE(value)); VECTOR3_DEL(value); } btScalar RigidBody::AngularSleepingThreshold::get() { return Native->getAngularSleepingThreshold(); } Vector3 RigidBody::AngularVelocity::get() { return Math::BtVector3ToVector3(&Native->getAngularVelocity()); } void RigidBody::AngularVelocity::set(Vector3 angVel) { VECTOR3_CONV(angVel); Native->setAngularVelocity(VECTOR3_USE(angVel)); VECTOR3_DEL(angVel); } BroadphaseProxy^ RigidBody::BroadphaseProxy::get() { return BulletSharp::BroadphaseProxy::GetManaged(Native->getBroadphaseProxy()); } void RigidBody::BroadphaseProxy::set(BulletSharp::BroadphaseProxy^ value) { Native->setNewBroadphaseProxy(value->_native); } Vector3 RigidBody::CenterOfMassPosition::get() { return Math::BtVector3ToVector3(&Native->getCenterOfMassPosition()); } Matrix RigidBody::CenterOfMassTransform::get() { return Math::BtTransformToMatrix(&Native->getCenterOfMassTransform()); } void RigidBody::CenterOfMassTransform::set(Matrix xform) { TRANSFORM_CONV(xform); Native->setCenterOfMassTransform(TRANSFORM_USE(xform)); TRANSFORM_DEL(xform); } int RigidBody::ContactSolverType::get() { return Native->m_contactSolverType; } void RigidBody::ContactSolverType::set(int value) { Native->m_contactSolverType = value; } RigidBodyFlags RigidBody::Flags::get() { return (RigidBodyFlags)Native->getFlags(); } void RigidBody::Flags::set(RigidBodyFlags flags) { Native->setFlags((btRigidBodyFlags) flags); } int RigidBody::FrictionSolverType::get() { return Native->m_frictionSolverType; } void RigidBody::FrictionSolverType::set(int value) { Native->m_frictionSolverType = value; } Vector3 RigidBody::Gravity::get() { return Math::BtVector3ToVector3(&Native->getGravity()); } void RigidBody::Gravity::set(Vector3 acceleration) { VECTOR3_CONV(acceleration); Native->setGravity(VECTOR3_USE(acceleration)); VECTOR3_DEL(acceleration); } Vector3 RigidBody::InvInertiaDiagLocal::get() { return Math::BtVector3ToVector3(&Native->getInvInertiaDiagLocal()); } void RigidBody::InvInertiaDiagLocal::set(Vector3 diagInvInertia) { VECTOR3_CONV(diagInvInertia); Native->setInvInertiaDiagLocal(VECTOR3_USE(diagInvInertia)); VECTOR3_DEL(diagInvInertia); } Matrix RigidBody::InvInertiaTensorWorld::get() { return Math::BtMatrix3x3ToMatrix(&Native->getInvInertiaTensorWorld()); } btScalar RigidBody::InvMass::get() { return Native->getInvMass(); } bool RigidBody::IsInWorld::get() { return Native->isInWorld(); } btScalar RigidBody::LinearDamping::get() { return Native->getLinearDamping(); } Vector3 RigidBody::LinearFactor::get() { return Math::BtVector3ToVector3(&Native->getLinearFactor()); } void RigidBody::LinearFactor::set(Vector3 linearFactor) { VECTOR3_CONV(linearFactor); Native->setLinearFactor(VECTOR3_USE(linearFactor)); VECTOR3_DEL(linearFactor); } btScalar RigidBody::LinearSleepingThreshold::get() { return Native->getLinearSleepingThreshold(); } Vector3 RigidBody::LinearVelocity::get() { return Math::BtVector3ToVector3(&Native->getLinearVelocity()); } void RigidBody::LinearVelocity::set(Vector3 linVel) { VECTOR3_CONV(linVel); Native->setLinearVelocity(VECTOR3_USE(linVel)); VECTOR3_DEL(linVel); } #pragma managed(push, off) void RigidBody_GetLocalInertia(btRigidBody* body, btVector3* ret) { *ret = body->getLocalInertia(); } #pragma managed(pop) Vector3 RigidBody::LocalInertia::get() { btVector3* retTemp = ALIGNED_NEW(btVector3); RigidBody_GetLocalInertia(Native, retTemp); Vector3 ret = Math::BtVector3ToVector3(retTemp); ALIGNED_FREE(retTemp); return ret; } BulletSharp::MotionState^ RigidBody::MotionState::get() { return _motionState; } void RigidBody::MotionState::set(BulletSharp::MotionState^ motionState) { Native->setMotionState(GetUnmanagedNullable(motionState)); _motionState = motionState; } #ifndef DISABLE_CONSTRAINTS int RigidBody::NumConstraintRefs::get() { return Native->getNumConstraintRefs(); } #endif #pragma managed(push, off) void RigidBody_GetOrientation(btRigidBody* body, btQuaternion* orientation) { //FIXME: *orientation = body->getOrientation(); body->getWorldTransform().getBasis().getRotation(*orientation); } #pragma managed(pop) Quaternion RigidBody::Orientation::get() { btQuaternion* orientationTemp = ALIGNED_NEW(btQuaternion); RigidBody_GetOrientation(Native, orientationTemp); Quaternion orientation = Math::BtQuatToQuaternion(orientationTemp); ALIGNED_FREE(orientationTemp); return orientation; } Vector3 RigidBody::TotalForce::get() { return Math::BtVector3ToVector3(&Native->getTotalForce()); } Vector3 RigidBody::TotalTorque::get() { return Math::BtVector3ToVector3(&Native->getTotalTorque()); } bool RigidBody::WantsSleeping::get() { return Native->wantsSleeping(); }
27.034934
174
0.77575
[ "vector" ]
9b04b1ff3f668b624163f7e3a6f57bf397446571
1,034
cpp
C++
Clase_17_DynamicProgramming/minimum_path_sum.cpp
EdgarEspinozaPE/ProgramacionCompetitivaA
53c3eb3e2bc9f1dd1033e0c24b0cb24f96def1e9
[ "BSD-3-Clause" ]
null
null
null
Clase_17_DynamicProgramming/minimum_path_sum.cpp
EdgarEspinozaPE/ProgramacionCompetitivaA
53c3eb3e2bc9f1dd1033e0c24b0cb24f96def1e9
[ "BSD-3-Clause" ]
null
null
null
Clase_17_DynamicProgramming/minimum_path_sum.cpp
EdgarEspinozaPE/ProgramacionCompetitivaA
53c3eb3e2bc9f1dd1033e0c24b0cb24f96def1e9
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; typedef vector<int> vi; typedef vector<vector<int>> vvi; int minPathSum(vector<vector<int>>& grid) { int rows = grid.size(); int cols = grid[0].size(); vector<vector<int>> memo(rows, vector<int>(cols, 0)); int i, j; memo[0][0] = grid[0][0]; for (i = 1; i < rows; i++) { memo[i][0] = memo[i - 1][0] + grid[i][0]; } for (j = 1; j < cols; j++) { memo[0][j] = memo[0][j - 1] + grid[0][j]; } for (i = 1; i < rows; i++) for (j = 1; j < cols; j++) { memo[i][j] = min(memo[i - 1][j], memo[i][j - 1]) + grid[i][j]; } return memo[rows - 1][cols - 1]; } int main(int argc, char const* argv[]) { ios_base::sync_with_stdio(false); cin.tie(NULL); vector<vector<int>> grid = { {1,3,1}, {1,5,1}, {4,2,1} }; cout << minPathSum(grid) << endl; return 0; }
24.619048
75
0.455513
[ "vector" ]
9b08b6eda31beee2ef865979ffff559d237a6610
24,012
cpp
C++
production_apps/BEM4I/Tests/testIntegratorLaplace.cpp
readex-eu/readex-apps
38493b11806c306f4e8f1b7b2d97764b45fac8e2
[ "BSD-3-Clause" ]
2
2020-11-25T13:10:11.000Z
2021-03-15T20:26:35.000Z
production_apps/BEM4I/Tests/testIntegratorLaplace.cpp
readex-eu/readex-apps
38493b11806c306f4e8f1b7b2d97764b45fac8e2
[ "BSD-3-Clause" ]
null
null
null
production_apps/BEM4I/Tests/testIntegratorLaplace.cpp
readex-eu/readex-apps
38493b11806c306f4e8f1b7b2d97764b45fac8e2
[ "BSD-3-Clause" ]
1
2018-09-30T19:04:38.000Z
2018-09-30T19:04:38.000Z
#include "catch.hpp" #include "../Settings.h" #include "../FullMatrix.h" #include "../SurfaceMesh3D.h" #include "../BESpace.h" #include "../BEBilinearFormLaplace1Layer.h" #include "../BEBilinearFormLaplace2Layer.h" #include "../BEBilinearFormLaplaceHypersingular.h" using namespace bem4i; TEST_CASE( "Element system matrices are computed", "[element]" ) { typedef double SC; typedef double SCVT; typedef int LO; SurfaceMesh3D< LO, SC > mesh; string filename = "../input/lshape_28.txt"; mesh.load( filename ); int order = 4; int quadOrder[4] = { order, order, order, order }; std::cout.precision(15); std::cout << std::scientific; SECTION( "Testing p0p0 integration" ) { SC result; FullMatrix< LO, SC > elemMatrix( 1, 1 ); BESpace< LO, SC > bespaceV( &mesh, p0, p0 ); SECTION( "Using semi-analytic quadrature" ) { quadratureType quadType = Steinbach; BEIntegratorLaplace< LO, SC > integrator( &bespaceV, quadOrder, quadType); SECTION( "Identical triangular panels" ) { integrator.computeElemMatrix1Layer( 0, 0, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 8.050529697022868e-02 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common edge" ) { integrator.computeElemMatrix1Layer( 0, 1, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 3.830554878450952e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix1Layer( 0, 4, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 3.711608453472868e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix1Layer( 19, 25, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 3.711608453472869e-02 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common vertex" ) { integrator.computeElemMatrix1Layer( 0, 2, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 2.103342514152386e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix1Layer( 0, 5, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 2.573278126528793e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix1Layer( 6, 17, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 2.573278126528794e-02 ).epsilon( 1e-14 ) ); } } SECTION( "Using fully numerical quadrature" ) { quadratureType quadType = SauterSchwab; BEIntegratorLaplace< LO, SC > integrator( &bespaceV, quadOrder, quadType); SECTION( "Identical triangular panels" ) { integrator.computeElemMatrix1Layer( 0, 0, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 7.980853550151068e-02 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common edge" ) { integrator.computeElemMatrix1Layer( 0, 1, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 3.847765191055143e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix1Layer( 0, 4, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 3.713972124199284e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix1Layer( 19, 25, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 3.714425417395063e-02 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common vertex" ) { integrator.computeElemMatrix1Layer( 0, 2, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 2.103408305546696e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix1Layer( 0, 5, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 2.572450109141559e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix1Layer( 6, 17, elemMatrix ); result = elemMatrix.get( 0, 0 ); REQUIRE( result == Approx( 2.572450109141558e-02 ).epsilon( 1e-14 ) ); } } } SECTION( "Testing p1p0 integration" ) { FullMatrix< LO, SC > elemMatrix( 1, 3 ); BESpace< LO, SC > bespaceK( &mesh, p1, p0 ); SECTION( "Using semi-analytic quadrature" ) { quadratureType quadType = Steinbach; BEIntegratorLaplace< LO, SC > integrator( &bespaceK, quadOrder, quadType); SECTION( "Identical triangular panels" ) { integrator.computeElemMatrix2Layer( 0, 0, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common edge" ) { integrator.computeElemMatrix2Layer( 0, 1, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix2Layer( 0, 4, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( -2.672476730025871e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -2.096898356255206e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -7.648993494407460e-03 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix2Layer( 19, 25, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( -2.096898356255205e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -2.672476730025870e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -7.648993494407457e-03 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common vertex" ) { integrator.computeElemMatrix2Layer( 0, 2, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix2Layer( 0, 5, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( -8.852093280961244e-03 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -3.480533852125474e-03 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -3.479614027251039e-03 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix2Layer( 6, 17, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( -8.852093280961249e-03 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -3.480533852125474e-03 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -3.479614027251036e-03 ).epsilon( 1e-14 ) ); } } SECTION( "Using fully numerical quadrature" ) { quadratureType quadType = SauterSchwab; BEIntegratorLaplace< LO, SC > integrator( &bespaceK, quadOrder, quadType); SECTION( "Identical triangular panels" ) { integrator.computeElemMatrix2Layer( 0, 0, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common edge" ) { integrator.computeElemMatrix2Layer( 0, 1, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix2Layer( 0, 4, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( -2.692964852243636e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -2.128733992703048e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -7.382469235257322e-03 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix2Layer( 19, 25, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( -2.132490009262535e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -2.700037909588355e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -7.387198324567223e-03 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common vertex" ) { integrator.computeElemMatrix2Layer( 0, 2, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix2Layer( 0, 5, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( -8.570194662118657e-03 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -3.489170270776185e-03 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -3.485406471287686e-03 ).epsilon( 1e-14 ) ); integrator.computeElemMatrix2Layer( 6, 17, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( -8.570194662118658e-03 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -3.489170270776185e-03 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -3.485406471287686e-03 ).epsilon( 1e-14 ) ); } } } SECTION( "Testing p1p1 integration" ) { FullMatrix< LO, SC > elemMatrix( 3, 3 ); BESpace< LO, SC > bespaceD( &mesh, p1, p1 ); SECTION( "Using semi-analytic quadrature" ) { quadratureType quadType = Steinbach; BEIntegratorLaplace< LO, SC > integrator( &bespaceD, quadOrder, quadType); SECTION( "Identical triangular panels" ) { integrator.computeElemMatrixHypersingular( 0, 0, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 1.610105939404574e-01 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -8.050529697022868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -8.050529697022868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( -8.050529697022868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 8.050529697022868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( -8.050529697022868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 8.050529697022868e-02 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common edge" ) { integrator.computeElemMatrixHypersingular( 0, 1, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 3.830554878450952e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 3.830554878450952e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -7.661109756901904e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( -3.830554878450952e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( 3.830554878450952e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( -3.830554878450952e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 3.830554878450952e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrixHypersingular( 0, 4, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -3.711608453472868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 3.711608453472868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 3.711608453472868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( -3.711608453472868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); integrator.computeElemMatrixHypersingular( 19, 25, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( 3.711608453472868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( -3.711608453472868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( -3.711608453472868e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 3.711608453472868e-02 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common vertex" ) { integrator.computeElemMatrixHypersingular( 0, 2, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 4.206685028304773e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -2.103342514152387e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -2.103342514152387e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( -2.103342514152387e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 2.103342514152387e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( -2.103342514152387e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 2.103342514152387e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrixHypersingular( 0, 5, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( -2.573278126528793e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 2.573278126528793e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( 2.573278126528793e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( -2.573278126528793e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); integrator.computeElemMatrixHypersingular( 6, 17, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 2.573278126528794e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -2.573278126528794e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( -2.573278126528794e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( -0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 2.573278126528794e-02 ).epsilon( 1e-14 ) ); } } SECTION( "Using fully numerical quadrature" ) { quadratureType quadType = SauterSchwab; BEIntegratorLaplace< LO, SC > integrator( &bespaceD, quadOrder, quadType); SECTION( "Identical triangular panels" ) { integrator.computeElemMatrixHypersingular( 0, 0, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 1.596170710030214e-01 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -7.980853550151068e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -7.980853550151068e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( -7.980853550151068e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 7.980853550151068e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( -7.980853550151068e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 7.980853550151068e-02 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common edge" ) { integrator.computeElemMatrixHypersingular( 0, 1, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 3.847765191055143e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 3.847765191055143e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -7.695530382110287e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( -3.847765191055143e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( 3.847765191055143e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( -3.847765191055143e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 3.847765191055143e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrixHypersingular( 0, 4, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -3.713972124199284e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 3.713972124199284e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 3.713972124199284e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( -3.713972124199284e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); integrator.computeElemMatrixHypersingular( 19, 25, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( 3.714425417395063e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( -3.714425417395063e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( -3.714425417395063e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 3.714425417395063e-02 ).epsilon( 1e-14 ) ); } SECTION( "Triangular panels with common vertex" ) { integrator.computeElemMatrixHypersingular( 0, 2, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 4.206816611093393e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -2.103408305546696e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -2.103408305546696e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( -2.103408305546696e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 2.103408305546696e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( -2.103408305546696e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 2.103408305546696e-02 ).epsilon( 1e-14 ) ); integrator.computeElemMatrixHypersingular( 0, 5, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( -2.572450109141559e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( -0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( 2.572450109141559e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( 2.572450109141559e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( -2.572450109141559e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); integrator.computeElemMatrixHypersingular( 6, 17, elemMatrix ); REQUIRE( elemMatrix.get( 0, 0 ) == Approx( 2.572450109141558e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 0, 2 ) == Approx( -2.572450109141558e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 0 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 1 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 1, 2 ) == Approx( 0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 0 ) == Approx( -2.572450109141558e-02 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 1 ) == Approx( -0.000000000000000e+00 ).epsilon( 1e-14 ) ); REQUIRE( elemMatrix.get( 2, 2 ) == Approx( 2.572450109141558e-02 ).epsilon( 1e-14 ) ); } } } }
37.636364
75
0.618066
[ "mesh" ]
9b1e6622c9f7a8bc289468c7609227d827dcde5a
7,199
cxx
C++
src/main.cxx
Alabuta/RaytracingInOneWeekend
38efac0d003358003294994bcffbef35d68f7253
[ "MIT" ]
null
null
null
src/main.cxx
Alabuta/RaytracingInOneWeekend
38efac0d003358003294994bcffbef35d68f7253
[ "MIT" ]
null
null
null
src/main.cxx
Alabuta/RaytracingInOneWeekend
38efac0d003358003294994bcffbef35d68f7253
[ "MIT" ]
null
null
null
#include <optional> #include <execution> #include <variant> #include <string_view> using namespace std::string_view_literals; #include <fstream> #include <filesystem> namespace fs = std::filesystem; #include "main.hxx" #include "math.hxx" #include "raytracer.hxx" #include "camera.hxx" extern void cuda_impl(std::uint32_t width, std::uint32_t height, std::vector<math::u8vec3> &image_texels); namespace app { struct data final { static auto constexpr sampling_number{16u}; #ifdef _DEBUG std::uint32_t width{512u}; std::uint32_t height{256u}; #else std::uint32_t width{1920u}; std::uint32_t height{1080u}; #endif std::random_device random_device; std::mt19937 generator; data() : generator{random_device()} { } }; template<class T> math::vec3 gamma_correction(T &&color) { auto constexpr gamma = math::vec3{1.f / 2.2f}; return math::pow(std::forward<T>(color), gamma); } math::vec3 background_color(float t) { return math::mix(math::vec3{1}, math::vec3{.5, .7, 1}, t); } template<class T> math::vec3 color(raytracer::data &raytracer_data, T &&ray) { math::vec3 attenuation{1}; auto scattered_ray = std::forward<T>(ray); math::vec3 energy_absorption{0}; for (auto bounce = 0u; bounce < raytracer_data.bounces_number; ++bounce) { if (auto hit = raytracer::hit_world(raytracer_data.spheres, scattered_ray); hit) { if (auto scattered = raytracer::apply_material(raytracer_data, scattered_ray, hit.value()); scattered) { std::tie(scattered_ray, energy_absorption) = *scattered; attenuation *= energy_absorption; } else return math::vec3{0}; } else return app::background_color(.5f * scattered_ray.unit_direction().y + 1.f) * attenuation; } return math::vec3{0}; } template<class T> math::u8vec3 normalize_rgb_to_8bit(T &&color) { return { static_cast<std::uint8_t>(255.f * color.x), static_cast<std::uint8_t>(255.f * color.y), static_cast<std::uint8_t>(255.f * color.z) }; } void save_to_file(std::string_view name, app::data const &app_data, std::vector<math::u8vec3> const &texels_data) { fs::path path{name}; std::ofstream file{path, std::ios::out | std::ios::trunc | std::ios::binary}; if (file.bad() || file.fail()) throw std::runtime_error("bad file"s); file << "P6\n"s << app_data.width << " "s << app_data.height << "\n255\n"s; using texel_type = std::decay_t<decltype(texels_data)>::value_type; file.write(reinterpret_cast<char const *>(std::data(texels_data)), std::size(texels_data) * sizeof(texel_type)); } } int main() { std::cout << "started... \n"s; app::data app_data; raytracer::data raytracer_data; std::vector<math::u8vec3> output(static_cast<std::size_t>(app_data.width) * app_data.height); cuda_impl(app_data.width, app_data.height, output); app::save_to_file("image_cuda.ppm"sv, app_data, output); return 0; raytracer_data.materials.push_back(material::lambert{math::vec3{.1, .2, .5}}); raytracer_data.materials.push_back(material::metal{math::vec3{.8, .6, .2}, 0}); raytracer_data.materials.push_back(material::dielectric{math::vec3{1}, 1.5f}); raytracer_data.materials.push_back(material::lambert{math::vec3{.64, .8, .0}}); raytracer_data.spheres.emplace_back(math::vec3{0, 1, 0}, 1.f, 0); raytracer_data.spheres.emplace_back(math::vec3{0, -1000.125f, 0}, 1000.f, 3); raytracer_data.spheres.emplace_back(math::vec3{+2, 1, 0}, 1.f, 1); raytracer_data.spheres.emplace_back(math::vec3{-2, 1, 0}, 1.f, 2); raytracer_data.spheres.emplace_back(math::vec3{-2, 1, 0}, -.99f, 2); #if 0 { std::random_device random_device; std::mt19937 generator{random_device()}; auto rd_int = std::uniform_int_distribution{0, 3}; auto rd_real = std::uniform_real_distribution{0.f, 1.f}; for (auto a = -11; a < 11; ++a) { for (auto b = -11; b < 11; ++b) { auto material_type_index = rd_int(generator); math::vec3 center{.9f * rd_real(generator) + a, .2f, .9f * rd_real(generator) + b}; if (math::distance(center, math::vec3{0, 1, 0}) < 1.f) continue; raytracer_data.spheres.emplace_back( center, .2f, std::size(raytracer_data.materials) ); switch (material_type_index) { case 0: raytracer_data.materials.emplace_back( raytracer::lambert{math::vec3{rd_real(generator), rd_real(generator), rd_real(generator)}} ); break; case 1: raytracer_data.materials.emplace_back( raytracer::metal{math::vec3{rd_real(generator), rd_real(generator), rd_real(generator)}, .5f * rd_real(generator)} ); break; case 2: raytracer_data.materials.emplace_back( raytracer::dielectric{math::vec3{rd_real(generator), rd_real(generator), rd_real(generator)}, 1.5f} ); break; default: break; } } } } #endif raytracer::camera camera{ math::vec3{-4, 3.2, 5}, math::vec3{0, 1, 0}, math::vec3{0, 1, 0}, static_cast<float>(app_data.width) / static_cast<float>(app_data.height), 42.f, 0.0625f, math::distance(math::vec3{-4, 3.2, 5}, math::vec3{0, 1, 0}) }; std::vector<math::vec3> multisampling_texels(app_data.sampling_number, math::vec3{0}); std::vector<math::u8vec3> texels_data(static_cast<std::size_t>(app_data.width) * app_data.height); auto random_distribution = std::uniform_real_distribution{0.f, 1.f}; for (auto y = 0u; y < app_data.height; ++y) { auto v = static_cast<float>(y) / static_cast<float>(app_data.height); for (auto x = 0u; x < app_data.width; ++x) { auto u = static_cast<float>(x) / static_cast<float>(app_data.width); std::generate(std::execution::par, std::begin(multisampling_texels), std::end(multisampling_texels), [&] () { auto _u = u + random_distribution(raytracer_data.generator) / static_cast<float>(app_data.width); auto _v = v + random_distribution(raytracer_data.generator) / static_cast<float>(app_data.height); return app::color(raytracer_data, camera.ray(_u, _v)); }); auto color = std::reduce(std::execution::seq, std::begin(multisampling_texels), std::end(multisampling_texels), math::vec3{0}); color /= static_cast<float>(app_data.sampling_number); color = app::gamma_correction(color); auto &&rgb = texels_data[x + static_cast<std::size_t>(app_data.width) * y]; rgb = app::normalize_rgb_to_8bit(std::move(color)); } } app::save_to_file("image.ppm"sv, app_data, texels_data); }
32.722727
142
0.606195
[ "vector" ]
9b29756ec93672ad1548b443250d14b7dc751d4a
2,738
cc
C++
src/perception/src/deproject_pixel_to_point.cc
camkisailus/Aerotech_Robot_Arm
4bf0ddd9b8a7b0d452d75eacd797e630bfe6f670
[ "MIT" ]
2
2020-12-01T03:33:20.000Z
2020-12-07T16:35:34.000Z
src/perception/src/deproject_pixel_to_point.cc
camkisailus/Aerotech_Robot_Arm
4bf0ddd9b8a7b0d452d75eacd797e630bfe6f670
[ "MIT" ]
null
null
null
src/perception/src/deproject_pixel_to_point.cc
camkisailus/Aerotech_Robot_Arm
4bf0ddd9b8a7b0d452d75eacd797e630bfe6f670
[ "MIT" ]
null
null
null
/* This code deprojects pixels into points in 3D space using basic stereo vision techniques. This is integral in the autonomy stack as it takes pixel detections as an input and outputs points in the camera's coordinate frame. */ #include <ros/ros.h> #include <tf/transform_listener.h> #include <sensor_msgs/CameraInfo.h> #include <geometry_msgs/PointStamped.h> #include <unordered_map> using namespace sensor_msgs; using namespace geometry_msgs; class DeprojectPixelToPoint { public: DeprojectPixelToPoint(){ point_pub_ = nh_.advertise<PointStamped>( "/detections/real_center", 0 ); camera_info_sub_ = nh_.subscribe("/camera/aligned_depth_to_color/camera_info", 1000, &DeprojectPixelToPoint::camera_info_callback, this); pixel_sub_ = nh_.subscribe("/detector/bb_center",1000, &DeprojectPixelToPoint::deproject_callback, this); nh_.getParam("/PixelToPointNode/camera_height", camera_height); } void camera_info_callback(const CameraInfoConstPtr& camera_info){ // Projection/camera matrix // [fx' 0 cx' Tx] // P = [ 0 fy' cy' Ty] // [ 0 0 1 0] // By convention, this matrix specifies the intrinsic (camera) matrix // of the processed (rectified) image. That is, the left 3x3 portion // is the normal camera intrinsic matrix for the rectified image. // It projects 3D points in the camera coordinate frame to 2D pixel // coordinates using the focal lengths (fx', fy') and principal point // (cx', cy') - these may differ from the values in K. // Given a 3D point [X Y Z]', the projection (x, y) of the point onto // the rectified image is given by: // [u v w]' = P * [X Y Z 1]' // x = u / w // y = v / w cam_info["cx"] = camera_info->P[2]; cam_info["cy"] = camera_info->P[6]; cam_info["fx"] = camera_info->P[0]; cam_info["fy"] = camera_info->P[5]; } void deproject_callback(const PointStampedConstPtr& pixel_stamped){ PointStamped pt_msg; pt_msg.point.x = (pixel_stamped->point.x*camera_height - cam_info["cx"]*camera_height) / cam_info["fx"]; pt_msg.point.y = (pixel_stamped->point.y*camera_height - cam_info["cy"]*camera_height) / cam_info["fy"]; pt_msg.point.z = camera_height; pt_msg.header.stamp = ros::Time::now(); pt_msg.header.frame_id = "camera_color_optical_frame"; point_pub_.publish(pt_msg); } private: ros::NodeHandle nh_; ros::Publisher point_pub_; ros::Subscriber pixel_sub_; ros::Subscriber camera_info_sub_; std::unordered_map<std::string, double> cam_info; double camera_height; }; int main(int argc, char **argv) { ros::init(argc, argv, "pixel_to_point"); DeprojectPixelToPoint foo; ros::spin(); return 0; }
35.558442
222
0.691381
[ "3d" ]
9b2adf294a82912994c72faa9f5ef75276215f96
4,088
cpp
C++
components/renderers/cpp/src/assimp_scene.cpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
4
2020-12-28T15:29:15.000Z
2021-06-27T12:37:15.000Z
components/renderers/cpp/src/assimp_scene.cpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
null
null
null
components/renderers/cpp/src/assimp_scene.cpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
2
2021-01-13T05:28:39.000Z
2021-05-04T03:37:11.000Z
#include <ftl/render/assimp_scene.hpp> #include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include <assimp/scene.h> #include <opencv2/imgproc.hpp> #include <opencv2/imgcodecs.hpp> using ftl::render::AssimpScene; using std::string; static std::string getBasePath(const std::string& path) { size_t pos = path.find_last_of("\\/"); return (std::string::npos == pos) ? "" : path.substr(0, pos + 1); } AssimpScene::AssimpScene(nlohmann::json &config) : ftl::Configurable(config) { } AssimpScene::~AssimpScene() { _freeTextureIds(); } void AssimpScene::load() { if (scene) return; Assimp::Importer importer; scene = importer.ReadFile(value("model", std::string("")), aiProcessPreset_TargetRealtime_Quality); if (!scene) { throw FTL_Error("Could not load model: " << value("model", string(""))); } _loadGLTextures(); for (size_t n=0; n<scene->mNumMeshes; ++n) { const aiMesh* mesh = scene->mMeshes[n]; vbo.reserve(vbo.size()+mesh->mNumVertices); for (size_t i=0; i<mesh->mNumVertices; ++i) { //vertices.push_back(mesh->mVertices) } } } void AssimpScene::_freeTextureIds() { textureIdMap.clear(); } bool AssimpScene::_loadGLTextures() { _freeTextureIds(); if (scene->HasTextures()) return true; /* getTexture Filenames and Numb of Textures */ for (unsigned int m=0; m<scene->mNumMaterials; m++) { int texIndex = 0; aiReturn texFound = AI_SUCCESS; aiString path; // filename while (texFound == AI_SUCCESS) { texFound = scene->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path); textureIdMap[path.data] = NULL; //fill map with textures, pointers still NULL yet texIndex++; } } const size_t numTextures = textureIdMap.size(); /* create and fill array with GL texture ids */ //textureIds = new GLuint[numTextures]; textureIds.resize(numTextures); glGenTextures(static_cast<GLsizei>(numTextures), textureIds.data()); /* Texture name generation */ /* get iterator */ std::map<std::string, GLuint*>::iterator itr = textureIdMap.begin(); std::string basepath = getBasePath(value("model", std::string(""))); for (size_t i=0; i<numTextures; i++) { //save IL image ID std::string filename = (*itr).first; // get filename (*itr).second = &textureIds[i]; // save texture id for filename in map ++itr; // next texture //ilBindImage(imageIds[i]); /* Binding of DevIL image name */ std::string fileloc = basepath + filename; /* Loading of image */ //success = ilLoadImage(fileloc.c_str()); int x, y, n; cv::Mat img = cv::imread(fileloc); unsigned char *data = img.data; if (!img.empty()) { // Convert every colour component into unsigned byte.If your image contains // alpha channel you can replace IL_RGB with IL_RGBA //success = ilConvertImage(IL_RGB, IL_UNSIGNED_BYTE); /*if (!success) { abortGLInit("Couldn't convert image"); return -1; }*/ // Binding of texture name glBindTexture(GL_TEXTURE_2D, textureIds[i]); // redefine standard texture values // We will use linear interpolation for magnification filter glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); // We will use linear interpolation for minifying filter glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); // Texture specification glTexImage2D(GL_TEXTURE_2D, 0, n, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);// Texture specification. // we also want to be able to deal with odd texture dimensions glPixelStorei( GL_UNPACK_ALIGNMENT, 1 ); glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 ); glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0 ); glPixelStorei( GL_UNPACK_SKIP_ROWS, 0 ); } else { /* Error occurred */ //MessageBox(NULL, UTFConverter("Couldn't load Image: " + fileloc).c_wstr(), TEXT("ERROR"), MB_OK | MB_ICONEXCLAMATION); throw FTL_Error("Could no load texture image: " << fileloc); } } return true; }
30.736842
123
0.66316
[ "mesh", "render", "model" ]
9b2e475a8632078f5cec278f430577cefeb79299
1,906
cpp
C++
window/modeSelfTest.cpp
ndrarmstrong/led-window
c9aa8197f79ac1f0cb21ed5a169d4a35e288d7c7
[ "MIT" ]
null
null
null
window/modeSelfTest.cpp
ndrarmstrong/led-window
c9aa8197f79ac1f0cb21ed5a169d4a35e288d7c7
[ "MIT" ]
null
null
null
window/modeSelfTest.cpp
ndrarmstrong/led-window
c9aa8197f79ac1f0cb21ed5a169d4a35e288d7c7
[ "MIT" ]
null
null
null
#include "modeSelfTest.h" void ModeSelfTest::onStart() { phase = 0; ticker.attach_ms_scheduled(750, std::bind(&ModeSelfTest::render, this)); } void ModeSelfTest::onStop() { ticker.detach(); } void ModeSelfTest::render() { switch (phase) { case 0: Leds::get().showTop(255, 0, 0); break; case 1: Leds::get().showTop(0, 255, 0); break; case 2: Leds::get().showTop(0, 0, 255); break; case 3: Leds::get().showBottom(255, 0, 0); break; case 4: Leds::get().showBottom(0, 255, 0); break; case 5: Leds::get().showBottom(0, 0, 255); break; case 6: Leds::get().showWhite(3); break; case 7: Leds::get().showWhite(10); break; case 8: Leds::get().showWhite(40); break; case 9: Leds::get().showColor(150, 0, 0, 0); break; case 10: Leds::get().showColor(0, 150, 0, 0); break; case 11: Leds::get().showColor(0, 0, 150, 0); break; case 12: Leds::get().showLeds(0, 0, 255, Leds::get().topLeds, 30, 39); break; case 13: Leds::get().showLeds(0, 0, 255, Leds::get().topLeds, 20, 29); break; case 14: Leds::get().showLeds(0, 0, 255, Leds::get().topLeds, 10, 19); break; case 15: Leds::get().showLeds(0, 0, 255, Leds::get().topLeds, 0, 9); break; case 16: Leds::get().showLeds(0, 0, 255, Leds::get().bottomLeds, 0, 9); break; case 17: Leds::get().showLeds(0, 0, 255, Leds::get().bottomLeds, 10, 19); break; case 18: Leds::get().showLeds(0, 0, 255, Leds::get().bottomLeds, 20, 29); break; case 19: Leds::get().showLeds(0, 0, 255, Leds::get().bottomLeds, 30, 39); break; } phase = (phase + 1) % 20; }
23.530864
76
0.498426
[ "render" ]
9b3c2a62993afe92f5120668e2ee43a8f99b70a9
2,110
hpp
C++
client/lib/controller_impl.hpp
sssssssuzuki/autd3-library-software
9f8382d099a38c0feb48176896db2f4db251ce40
[ "MIT" ]
null
null
null
client/lib/controller_impl.hpp
sssssssuzuki/autd3-library-software
9f8382d099a38c0feb48176896db2f4db251ce40
[ "MIT" ]
null
null
null
client/lib/controller_impl.hpp
sssssssuzuki/autd3-library-software
9f8382d099a38c0feb48176896db2f4db251ce40
[ "MIT" ]
null
null
null
// File: controller_impl.hpp // Project: lib // Created Date: 11/10/2020 // Author: Shun Suzuki // ----- // Last Modified: 26/12/2020 // Modified By: Shun Suzuki (suzuki@hapis.k.u-tokyo.ac.jp) // ----- // Copyright (c) 2020 Hapis Lab. All rights reserved. // #pragma once #include <memory> #include <vector> #include "autd_logic.hpp" #include "configuration.hpp" #include "controller.hpp" namespace autd::internal { class AUTDControllerSync; class AUTDControllerAsync; class AUTDControllerStm; class AUTDController final : public Controller { public: AUTDController(); ~AUTDController() override; AUTDController(const AUTDController& v) noexcept = delete; AUTDController& operator=(const AUTDController& obj) = delete; AUTDController(AUTDController&& obj) = delete; AUTDController& operator=(AUTDController&& obj) = delete; bool is_open() override; GeometryPtr geometry() noexcept override; bool silent_mode() noexcept override; size_t remaining_in_buffer() override; void SetSilentMode(bool silent) noexcept override; void OpenWith(LinkPtr link) override; bool Calibrate(Configuration config) override; bool Clear() override; void Close() override; void SetDelay(const std::vector<AUTDDataArray>& delay) override; void Flush() override; void Stop() override; void AppendGain(GainPtr gain) override; void AppendGainSync(GainPtr gain, bool wait_for_send = false) override; void AppendModulation(ModulationPtr mod) override; void AppendModulationSync(ModulationPtr mod) override; void AppendSTMGain(GainPtr gain) override; void AppendSTMGain(const std::vector<GainPtr>& gain_list) override; void StartSTModulation(Float freq) override; void StopSTModulation() override; void FinishSTModulation() override; void AppendSequence(SequencePtr seq) override; std::vector<FirmwareInfo> firmware_info_list() override; private: std::unique_ptr<AUTDControllerSync> _sync_cnt; std::unique_ptr<AUTDControllerAsync> _async_cnt; std::unique_ptr<AUTDControllerStm> _stm_cnt; std::shared_ptr<AUTDLogic> _autd_logic; }; } // namespace autd::internal
30.57971
73
0.762559
[ "geometry", "vector" ]
9b49635a8d78d1d6a13f7734c2928b310a5e0589
351
cpp
C++
CSC8503/GameTech/Trigger.cpp
KragusGit/Advanced-Game-Tech
db64f50f933468738322e2b97c2723a8f38bba67
[ "Apache-2.0" ]
null
null
null
CSC8503/GameTech/Trigger.cpp
KragusGit/Advanced-Game-Tech
db64f50f933468738322e2b97c2723a8f38bba67
[ "Apache-2.0" ]
null
null
null
CSC8503/GameTech/Trigger.cpp
KragusGit/Advanced-Game-Tech
db64f50f933468738322e2b97c2723a8f38bba67
[ "Apache-2.0" ]
null
null
null
#include "Trigger.h" void NCL::CSC8503::Trigger::ExecuteOnEnter(GameObject* object) { for (int i = 0; i < OnEnter.size(); i++) { if (OnEnter[i] != nullptr) OnEnter[i](object); } } void NCL::CSC8503::Trigger::ExecuteOnExit(GameObject* object) { for (int i = 0; i < OnExit.size(); i++) { if (OnExit[i] != nullptr) OnExit[i](object); } }
21.9375
64
0.618234
[ "object" ]
9b4aa44f63fcfb5abe4da190d582b3d8d26e82b2
10,115
cpp
C++
MInteraction/SimulTimer.cpp
vanch3d/DEMIST
f49e3409cf5eca8df6b03f1a1bbc0f9f4ca44521
[ "MIT" ]
null
null
null
MInteraction/SimulTimer.cpp
vanch3d/DEMIST
f49e3409cf5eca8df6b03f1a1bbc0f9f4ca44521
[ "MIT" ]
null
null
null
MInteraction/SimulTimer.cpp
vanch3d/DEMIST
f49e3409cf5eca8df6b03f1a1bbc0f9f4ca44521
[ "MIT" ]
1
2021-01-11T09:52:21.000Z
2021-01-11T09:52:21.000Z
// SimulTimer.cpp : implementation file // #include "stdafx.h" #include "Simul.h" #include "LearnerTrace.h" #include <MInstruction\LearningUnit.h> #include "simulDoc.h" #include "SimulTimer.h" #include <Prefs\Pref.h> #include "Format.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define TIMER_RUN 120 #define TIMER_REVIEW 130 //SYSTEMTIME lpTime1,lpTime2; ///////////////////////////////////////////////////////////////////////////// // CViewTimer IMPLEMENT_DYNCREATE(CViewTimer, CFormView) CViewTimer::CViewTimer() : CFormView(CViewTimer::IDD) { //{{AFX_DATA_INIT(CViewTimer) //}}AFX_DATA_INIT // m_hIRun = NULL; /// m_hIEnd = NULL; // m_hIBeg = NULL; m_pER = NULL; m_bIsRunning=FALSE; m_nBackReview = 0; // m_nCurrTTask=0; } CViewTimer::~CViewTimer() { CTrace::T_CLOSE(GetParentFrame()); } void CViewTimer::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); //{{AFX_DATA_MAP(CViewTimer) DDX_Control(pDX, IDC_TIMESLIDER, m_Slider); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CViewTimer, CFormView) //{{AFX_MSG_MAP(CViewTimer) ON_NOTIFY(NM_RELEASEDCAPTURE, IDC_TIMESLIDER, OnReleasedSlider) ON_NOTIFY(TB_THUMBTRACK, IDC_TIMESLIDER, OnTrackTimer) ON_WM_HSCROLL() ON_WM_GETMINMAXINFO() ON_WM_VSCROLL() ON_WM_MOVE() ON_WM_CREATE() ON_WM_KEYDOWN() ON_WM_DESTROY() //}}AFX_MSG_MAP ON_MESSAGE(TRACE_VIEW_ACTIVATE, OnActivateER) ON_MESSAGE(DOC_UPDATE_VIEWCONTENT, OnUpdateInitContent) //ON_COMMAND_RANGE(ID_TRANS_INDEPENDENT,ID_TRANS_DYNALINKED,OnTranslationTasks) ON_UPDATE_COMMAND_UI_RANGE(ID_TRANS_INDEPENDENT,ID_TRANS_DYNALINKED,OnUpdateTransTasks) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CViewTimer diagnostics #ifdef _DEBUG void CViewTimer::AssertValid() const { CFormView::AssertValid(); } void CViewTimer::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } CSimulDoc* CViewTimer::GetDocument() // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSimulDoc))); return (CSimulDoc*)m_pDocument; } #endif //_DEBUG int CViewTimer::GetTranslation() { int nTrans = 0; CFormatTranslation* pDlg = NULL; if (!m_pER) return nTrans; int nbF = m_pER->m_cFormatSet.GetSize(); if (nbF>=2) { CFormat *pPage = m_pER->m_cFormatSet.GetAt(1); pDlg = DYNAMIC_DOWNCAST(CFormatTranslation,pPage); } if (pDlg) nTrans = pDlg->m_nTranslation; return nTrans; } ///////////////////////////////////////////////////////////////////////////// // CViewTimer message handlers ///////////////////////////////////////////////////////////////////////////// /// The framework calls this function after receiving a DOC_UPDATE_VIEWCONTENT notification. /// /// Called just before the view is displayed for the first time, this function just /// assignes to the data member m_pER a pointer to the Learning Unit (see CLearningUnit) /// associated with that view. ///////////////////////////////////////////////////////////////////////////// LRESULT CViewTimer::OnUpdateInitContent(WPARAM wp, LPARAM lp) { m_pER = (CExternRepUnit*)lp; return 0; } void CViewTimer::OnTrackTimer(NMHDR* pNMHDR, LRESULT* pResult) { // TODO: Add your control notification handler code here *pResult = 0; } void CViewTimer::OnReleasedSlider(NMHDR* pNMHDR, LRESULT* pResult) { // TODO: Add your control notification handler code here *pResult = 0; } LRESULT CViewTimer::OnActivateER(WPARAM wp, LPARAM lp) { static BOOL bFirst = TRUE; if (!bFirst) CTrace::T_SWITCH(this, (CWnd*)wp); bFirst = FALSE; return 0; } void CViewTimer::OnInitialUpdate() { CFormView::OnInitialUpdate(); if (m_pER) GetParentFrame()->SetWindowText(m_pER->GetName()); CTrace::T_OPEN(GetParentFrame()); m_Slider.SetRange(0, GetDocument()->GetMaxTime(), true); m_Slider.SetPos(0); m_Slider.SetPastColour(CPref::g_crPast); m_Slider.SetFutureColour(CPref::g_crFuture); CLearningUnit *pLU = GetDocument()->GetCurrentLU(); if (pLU) { int nbBP = pLU->m_cTBreakSet.GetSize(); if (nbBP) { m_Slider.SetCurrentBreakPoint(-1); for (int i=0;i<nbBP;i++) { CTimerBreakPoint *pBP = pLU->m_cTBreakSet.GetAt(i); if (pBP) m_Slider.AddBreakPoint(pBP->m_tBreakPt); } } } int range = GetDocument()->GetMaxTime(); int interval = 1; if(range%50 == 0 && range != 50) interval = 50; if(range%10 == 0 && range != 10) interval = 10; else if(range%7 == 0 && range != 7) interval = 7; else if(range%5 == 0 && range != 5) interval = 5; else if(range%4 == 0 && range != 4) interval = 4; else if(range%3 == 0 && range != 3) interval = 3; else if(range%2 == 0 && range != 2) interval = 2; m_Slider.SetTicFreq(interval); //m_Slider.SetTicFreq(50); CRect rect,rect2; CWnd *par = GetParent( ); if (!par) return; par->GetWindowRect(&rect); par->GetParent()->GetWindowRect(&rect2); par->MoveWindow(rect.left-rect2.left-2,rect.top-rect2.top-2, 350,102); int nbTr = GetTranslation(); m_Slider.SetSelection(0,GetDocument()->m_runTimer); m_Slider.SetPos(GetDocument()->m_currTimer); m_Slider.EnableWindow(FALSE);//nbTr); m_nMaxTime = 0; // m_nBreakPoint = 0; /* SetWindowPos(&wndTopMost,0,0,0,0,SWP_NOMOVE |SWP_NOSIZE );*/ // OnTimerStop(); } ///////////////////////////////////////////////////////////////////////////// /// The framework calls this function after receiving a notification message. /// /// \param pSender Points to the view that modified the document, or NULL if all views are to be updated. /// \param lHint Contains information about the modifications. /// \param pHint Points to an object storing information about the modifications. /// /// This member function proceeds and/or dispatches all the messages sent by the framework /// to the relevant function. ///////////////////////////////////////////////////////////////////////////// void CViewTimer::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { // TODO: Add your specialized code here and/or call the base class if (lHint == DOC_UPDATE_TIMERDATA) { int nb = GetDocument()->m_currTimer; m_Slider.SetPos(nb); m_Slider.Invalidate(); m_Slider.SetSelection(0,GetDocument()->m_runTimer); } else if (lHint == DOC_UPDATE_RESTARTSIMUL) { int nb = GetDocument()->m_currTimer; int nbR = GetDocument()->GetCurrTime(); m_nMaxTime = 0; m_Slider.SetPos(nb); m_Slider.SetSelection(0,nbR); m_Slider.Invalidate(); } else if (/*(lHint == TRANSLATION_MAPFACT) || */ (lHint == TRANSLATION_MAPRELATION)) { if (!pHint) return; int nTranLevel = GetTranslation(); CTranslationInfo *mTInfo = (CTranslationInfo *)pHint; int nTLevel = -1; int nTime = -1; int nExpSet = -1;//mTInfo->m_nExpSet; int nData = -1;//mTInfo->m_nData; if (mTInfo) { nTLevel = mTInfo->m_nTransLvl; nTime = mTInfo->m_nTime; int nbD = mTInfo->m_nDatas.GetSize(); for (int jj=0;jj<nbD;jj++) { CTranslationInfo::CTInfo tt1 = mTInfo->m_nDatas.GetAt(jj); nTime = tt1.nTime; //nExpSet = tt1.nExpSet; //nData = tt1.nData; } } if (nTime!=-1) { m_Slider.SetPos(nTime); //m_Slider.SetSelection(0,nbR); m_Slider.Invalidate(); } } } void CViewTimer::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI) { // TODO: Add your message handler code here and/or call default CFormView::OnGetMinMaxInfo(lpMMI); CRect cr; GetClientRect(cr); lpMMI->ptMinTrackSize.x = 350; lpMMI->ptMinTrackSize.y = 190; GetWindowRect(cr); m_Slider.GetClientRect(cr); CRect rect,rect2; CWnd *par = GetParent( ); if (!par) return; par->GetWindowRect(&rect); par->GetParent()->GetWindowRect(&rect2); par->MoveWindow(rect.left-rect2.left-2,rect.top-rect2.top-2, 350,102); //m_Current.MoveWindow(320,5,20,30); } void CViewTimer::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { // TODO: Add your message handler code here and/or call default CFormView::OnVScroll(nSBCode, nPos, pScrollBar); } void CViewTimer::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { // TODO: Add your message handler code here and/or call default int nb = m_Slider.GetPos(); CFormView::OnHScroll(nSBCode, nPos, pScrollBar); nb = m_Slider.GetPos(); m_Slider.VerifyPos(); nb = m_Slider.GetPos(); GetDocument()->m_currTimer = nb; GetDocument()->UpdateTimerDoc(this); } void CViewTimer::OnMove(int x, int y) { CFormView::OnMove(x, y); // TODO: Add your message handler code here } int CViewTimer::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFormView::OnCreate(lpCreateStruct) == -1) return -1; // if (!m_cToolBar.CreateEx(GetParent(), TBSTYLE_FLAT | TBSTYLE_TOOLTIPS, // WS_CHILD | WS_VISIBLE | CBRS_TOP | // /* CBRS_GRIPPER | */CBRS_TOOLTIPS | CBRS_FLYBY | CCS_ADJUSTABLE, // CRect(0, 0, 0, 0), 120) || // !m_cToolBar.LoadToolBar(IDR_SIMULTIMER)) // { // TRACE0("Failed to create toolbar1\n"); // return -1; // fail to create // } return 0; } void CViewTimer::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { // TODO: Add your message handler code here and/or call default int r=0; switch (nChar) { case VK_RETURN: r++; break; } CFormView::OnKeyDown(nChar, nRepCnt, nFlags); } void CViewTimer::OnDestroy() { CTrace::T_CLOSE(GetParentFrame()); CFormView::OnDestroy(); // TODO: Add your message handler code here } void CViewTimer::OnTranslationTasks(UINT nID) { // TODO: Add your command handler code here switch (nID) { case ID_TASK_MAPFACT: case ID_TASK_MAPRELATION: case ID_TASK_SUPPORTACTION: // m_nCurrTTask = nID - ID_TASK_MAPFACT+1; break; case ID_TASK_CANCELTASK: default: // m_nCurrTTask = 0; break; } } void CViewTimer::OnUpdateTransTasks(CCmdUI* pCmdUI) { // TODO: Add your command update UI handler code here BOOL bEnab = FALSE; BOOL bCheck = FALSE; UINT nT = GetTranslation(); // //UINT nCT = m_nCurrTTask; switch (pCmdUI->m_nID) { case ID_TRANS_INDEPENDENT: case ID_TRANS_MAPRELATION: case ID_TRANS_DYNALINKED: bCheck = (nT == (pCmdUI->m_nID - ID_TRANS_INDEPENDENT)); bEnab = bCheck; break; default: break; } pCmdUI->Enable(bEnab); pCmdUI->SetCheck(bCheck); }
23.633178
105
0.671181
[ "object" ]
9b5404f9f269e3640fc5b2cc199337ada8741743
9,450
hpp
C++
include/common/simd_data_types.hpp
flwende/simd_benchmarks
29a00d4b8e7a9a6824b7b8f17424d3a6aa448857
[ "BSD-2-Clause" ]
3
2016-10-17T23:35:05.000Z
2021-05-27T11:35:55.000Z
include/common/simd_data_types.hpp
flwende/simd_benchmarks
29a00d4b8e7a9a6824b7b8f17424d3a6aa448857
[ "BSD-2-Clause" ]
null
null
null
include/common/simd_data_types.hpp
flwende/simd_benchmarks
29a00d4b8e7a9a6824b7b8f17424d3a6aa448857
[ "BSD-2-Clause" ]
2
2018-06-16T20:11:55.000Z
2020-01-31T10:11:42.000Z
// Copyright (c) 2016 Florian Wende (flwende@gmail.com) // // Distributed under the BSD 2-clause Software License // (See accompanying file LICENSE) #if !defined(SIMD_DATA_TYPES_HPP) #define SIMD_DATA_TYPES_HPP #include <cmath> #include <cstdint> #include <immintrin.h> #if defined(__MIC__) || defined(__AVX512F__) #define SIMD_512 #define ALIGNMENT (64) // the simdwidth given by the native size of the simd registers: for 64-bit words. #define SIMD_WIDTH_NATIVE_REAL64 (8) // OpenMP 4.x allows to operate on logical vectors of larger size. // values here can be larger than SIMD_WIDTH_NATIVE_REAL64. #if defined(MANUAL_VECTORIZATION) #undef SIMD_WIDTH_LOGICAL_REAL64 #define SIMD_WIDTH_LOGICAL_REAL64 (8) #else #if !defined(SIMD_WIDTH_LOGICAL_REAL64) #define SIMD_WIDTH_LOGICAL_REAL64 (8) #endif #endif #elif defined(__AVX__) || defined(__AVX2__) #define SIMD_256 #define ALIGNMENT (32) // the simdwidth given by the native size of the simd registers: for 64-bit words. #define SIMD_WIDTH_NATIVE_REAL64 (4) // OpenMP 4.x allows to operate on logical vectors of larger size. // values here can be larger than SIMD_WIDTH_NATIVE_REAL64. #if defined(MANUAL_VECTORIZATION) #undef SIMD_WIDTH_LOGICAL_REAL64 #define SIMD_WIDTH_LOGICAL_REAL64 (4) #else #if !defined(SIMD_WIDTH_LOGICAL_REAL64) #define SIMD_WIDTH_LOGICAL_REAL64 (4) #endif #endif #else static_assert(false, "AVX or higher required."); #endif // definitions of TRUE and FALSE. #if defined(__INTEL_COMPILER) && defined(SIMD_512) #define BOOL bool #define TRUE true #define FALSE false #else // the GNU compiler seems to want TRUE and FALSE be of the same data type // as the numerical values processed in that context (in our case: double). // with the Intel compiler this seems to be the better choice too when using AVX(2). #define BOOL double #define TRUE 1.0 #define FALSE 0.0 #endif // simdlen clause for OpenMP 4.x loop vectorization. #if defined(__INTEL_COMPILER) #define SIMDLEN(X) simdlen(X) #else #define SIMDLEN(X) #endif #if defined(ENHANCED_EXPLICIT_VECTORIZATION) || defined(MANUAL_VECTORIZATION) // enhanced explicit vectorization: user defined vector data types. // we use the logical simdwidth here to allow for vector loop unrolling with OpenMP 4.x. typedef struct { double x[SIMD_WIDTH_LOGICAL_REAL64]; } vec_real64_t __attribute__((aligned(ALIGNMENT))); typedef struct { BOOL x[SIMD_WIDTH_LOGICAL_REAL64]; } mask_real64_t __attribute__((aligned(ALIGNMENT))); #if defined(SIMD_512) #define ALL_LANES_ACTIVE {TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE} #elif defined(SIMD_256) #define ALL_LANES_ACTIVE {TRUE, TRUE, TRUE, TRUE} #endif // manual vectorization with simd intrinsics: some macro definitions. #if defined(SIMD_512) #define VEC_REAL64 __m512d #define MASK_REAL64 __mmask8 #define SIMD_TRUE (0x1) #define SIMD_FALSE (0x0) #define SIMD_SETZERO_REAL64() _mm512_setzero_pd() #define SIMD_SET1_REAL64(X1) _mm512_set1_pd(X1) #define SIMD_SET1_INT64(X1) _mm512_set1_epi64(X1) #define SIMD_SET_MASK_REAL64(M1) _mm512_int2mask(M1) #define SIMD_CAST_REAL64_INT64(X1) _mm512_castsi512_pd(X1) #define SIMD_CAST_INT64_REAL64(X1) _mm512_castpd_si512(X1) #define SIMD_ALL_LANES_ACTIVE_MASK_REAL64 _mm512_int2mask(0xFF) #define SIMD_ALL_LANES_ACTIVE_INT (0xFF) #define SIMD_ALL_LANES_INACTIVE_INT (0x0) #define SIMD_MASK_MOV_REAL64(X0, M1, X1) _mm512_mask_mov_pd(X0, M1, X1) #define SIMD_MASK_STORE_REAL64(ADDR, M1, X1) _mm512_mask_extstore_pd(reinterpret_cast<void*>(ADDR), M1, X1, _MM_DOWNCONV_PD_NONE, _MM_HINT_NONE) #define SIMD_CMPGT_REAL64(X1, X2) _mm512_cmp_pd_mask(X1, X2, _CMP_GT_OS) #define SIMD_CMPGE_REAL64(X1, X2) _mm512_cmp_pd_mask(X1, X2, _CMP_GE_OS) #define SIMD_CMPLT_REAL64(X1, X2) _mm512_cmp_pd_mask(X1, X2, _CMP_LT_OS) #define SIMD_CHANGE_SIGN_REAL64(X1) _mm512_mul_pd(SIMD_SET1_REAL64(-1.0), X1) #define SIMD_MASK_CHANGE_SIGN_REAL64(X0, M1, X1) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_CHANGE_SIGN_REAL64(X1)) #define SIMD_MUL_REAL64(X1, X2) _mm512_mul_pd(X1, X2) #define SIMD_ADD_REAL64(X1, X2) _mm512_add_pd(X1, X2) #define SIMD_FMADD_REAL64(X1, X2, X3) _mm512_fmadd_pd(X1, X2, X3) #define SIMD_MASK_FMADD_REAL64(X0, M1, X1, X2, X3) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_FMADD_REAL64(X1, X2, X3)) #define SIMD_SUB_REAL64(X1, X2) _mm512_sub_pd(X1, X2) #define SIMD_MASK_MUL_REAL64(X0, M1, X1, X2) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_MUL_REAL64(X1, X2)) #define SIMD_MASK_ADD_REAL64(X0, M1, X1, X2) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_ADD_REAL64(X1, X2)) #define SIMD_MASK_SUB_REAL64(X0, M1, X1, X2) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_SUB_REAL64(X1, X2)) #define SIMD_AND_MASK_REAL64(M1, M2) _mm512_kand(M1, M2) #define SIMD_ANDNOT_MASK_REAL64(M1, M2) _mm512_kandn(M1, M2) #define SIMD_OR_MASK_REAL64(M1, M2) _mm512_kor(M1, M2) #define SIMD_NOT_MASK_REAL64(M1) _mm512_knot(M1) #define SIMD_BITMASK_MASK_REAL64(M1) _mm512_mask2int(M1) #define SIMD_TEST_ANY_MASK_REAL64(M1) SIMD_BITMASK_MASK_REAL64(M1) #define SIMD_AND_INT64(X1, X2) _mm512_and_si512(X1, X2) #define SIMD_ABS_REAL64(X1) SIMD_CAST_REAL64_INT64(SIMD_AND_INT64(SIMD_CAST_INT64_REAL64(X1), SIMD_SET1_INT64(0x7FFFFFFFFFFFFFFF))) #define SIMD_SQRT_REAL64(X1) _mm512_sqrt_pd(X1) #define SIMD_MASK_SQRT_REAL64(X0, M1, X1) _mm512_mask_sqrt_pd(X0, M1, X1) #define SIMD_LOG_REAL64(X1) _mm512_log_pd(X1) #define SIMD_MASK_LOG_REAL64(X0, M1, X1) _mm512_mask_log_pd(X0, M1, X1) #define SIMD_EXP_REAL64(X1) _mm512_exp_pd(X1) #define SIMD_MASK_EXP_REAL64(X0, M1, X1) _mm512_mask_exp_pd(X0, M1, X1) #elif defined(SIMD_256) #define VEC_REAL64 __m256d #define MASK_REAL64 __m256d #define SIMD_TRUE (0xFFFFFFFFFFFFFFFF) #define SIMD_FALSE (0x0) #define SIMD_SETZERO_REAL64() _mm256_setzero_pd() #define SIMD_SET1_REAL64(X1) _mm256_set1_pd(X1) #define SIMD_SET1_INT64(X1) _mm256_set1_epi64x(X1) #define SIMD_CAST_REAL64_INT64(X1) _mm256_castsi256_pd(X1) #define SIMD_CAST_INT64_REAL64(X1) _mm256_castpd_si256(X1) #define SIMD_SET1_MASK_REAL64(X1) SIMD_CAST_REAL64_INT64(SIMD_SET1_INT64(X1)) #define SIMD_ALL_LANES_ACTIVE_MASK_REAL64 SIMD_SET1_MASK_REAL64(SIMD_TRUE) #define SIMD_ALL_LANES_ACTIVE_INT (0xF) #define SIMD_ALL_LANES_INACTIVE_INT (0x0) #define SIMD_MASK_MOV_REAL64(X0, M1, X1) _mm256_blendv_pd(X0, X1, M1) #define SIMD_MASK_STORE_REAL64(ADDR, M1, X1) _mm256_maskstore_pd(reinterpret_cast<double*>(ADDR), SIMD_CAST_INT64_REAL64(M1), X1) #define SIMD_CMPGT_REAL64(X1, X2) _mm256_cmp_pd(X1, X2, _CMP_GT_OS) #define SIMD_CMPGE_REAL64(X1, X2) _mm256_cmp_pd(X1, X2, _CMP_GE_OS) #define SIMD_CMPLT_REAL64(X1, X2) _mm256_cmp_pd(X1, X2, _CMP_LT_OS) #define SIMD_CHANGE_SIGN_REAL64(X1) _mm256_mul_pd(SIMD_SET1_REAL64(-1.0), X1) #define SIMD_MASK_CHANGE_SIGN_REAL64(X0, M1, X1) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_CHANGE_SIGN_REAL64(X1)) #define SIMD_MUL_REAL64(X1, X2) _mm256_mul_pd(X1, X2) #define SIMD_ADD_REAL64(X1, X2) _mm256_add_pd(X1, X2) #if defined(__AVX2__) #define SIMD_FMADD_REAL64(X1, X2, X3) _mm256_fmadd_pd(X1, X2, X3) #else #define SIMD_FMADD_REAL64(X1, X2, X3) SIMD_ADD_REAL64(SIMD_MUL_REAL64(X1, X2), X3) #endif #define SIMD_SUB_REAL64(X1, X2) _mm256_sub_pd(X1, X2) #define SIMD_MASK_MUL_REAL64(X0, M1, X1, X2) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_MUL_REAL64(X1, X2)) #define SIMD_MASK_ADD_REAL64(X0, M1, X1, X2) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_ADD_REAL64(X1, X2)) #define SIMD_MASK_FMADD_REAL64(X0, M1, X1, X2, X3) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_FMADD_REAL64(X1, X2, X3)) #define SIMD_MASK_SUB_REAL64(X0, M1, X1, X2) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_SUB_REAL64(X1, X2)) #define SIMD_AND_MASK_REAL64(M1, M2) _mm256_and_pd(M1, M2) #define SIMD_ANDNOT_MASK_REAL64(M1, M2) _mm256_andnot_pd(M1, M2) #define SIMD_OR_MASK_REAL64(M1, M2) _mm256_or_pd(M1, M2) #define SIMD_NOT_MASK_REAL64(M1) _mm256_xor_pd(M1, SIMD_CAST_REAL64_INT64(SIMD_SET1_INT64(SIMD_TRUE))) #define SIMD_BITMASK_MASK_REAL64(M1) _mm256_movemask_pd(M1) #define SIMD_TEST_ANY_MASK_REAL64(M1) SIMD_BITMASK_MASK_REAL64(M1) #define SIMD_AND_INT64(X1, X2) _mm256_and_si256(X1, X2) #define SIMD_ABS_REAL64(X1) SIMD_CAST_REAL64_INT64(SIMD_AND_INT64(SIMD_CAST_INT64_REAL64(X1), SIMD_SET1_INT64(0x7FFFFFFFFFFFFFFF))) #define SIMD_SQRT_REAL64(X1) _mm256_sqrt_pd(X1) #define SIMD_MASK_SQRT_REAL64(X0, M1, X1) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_SQRT_REAL64(X1)) #if defined(__INTEL_COMPILER) // simd function calls to exp and log via _mm256_[log,exp]_pd is specific to Intel. #define SIMD_LOG_REAL64(X1) _mm256_log_pd(X1) #define SIMD_MASK_LOG_REAL64(X0, M1, X1) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_LOG_REAL64(X1)) #define SIMD_EXP_REAL64(X1) _mm256_exp_pd(X1) #define SIMD_MASK_EXP_REAL64(X0, M1, X1) SIMD_MASK_MOV_REAL64(X0, M1, SIMD_EXP_REAL64(X1)) #else #define IMPLEMENTATION_REQUIRED // GNU compiler has no _mm256_[log,exp]_pd. VEC_REAL64 simd_log(const VEC_REAL64& x1); VEC_REAL64 simd_mask_log(const VEC_REAL64& x0, const MASK_REAL64& mask, const VEC_REAL64& x1); VEC_REAL64 simd_exp(const VEC_REAL64& x1); VEC_REAL64 simd_mask_exp(const VEC_REAL64& x0, const MASK_REAL64& mask, const VEC_REAL64& x1); #define SIMD_LOG_REAL64(X1) simd_log(X1) #define SIMD_MASK_LOG_REAL64(X0, M1, X1) simd_mask_log(X0, M1, X1) #define SIMD_EXP_REAL64(X1) simd_exp(X1) #define SIMD_MASK_EXP_REAL64(X0, M1, X1) simd_mask_exp(X0, M1, X1) #endif #endif #endif #endif
48.214286
146
0.779048
[ "vector" ]
9b578637343ddba82dff886e97200214885ad3f3
1,358
cc
C++
open_spiel/algorithms/alpha_zero_torch/negamax.cc
zfahmad/open_spiel
cb30d812a31f03e6550cfa1141750147b9481693
[ "Apache-2.0" ]
null
null
null
open_spiel/algorithms/alpha_zero_torch/negamax.cc
zfahmad/open_spiel
cb30d812a31f03e6550cfa1141750147b9481693
[ "Apache-2.0" ]
null
null
null
open_spiel/algorithms/alpha_zero_torch/negamax.cc
zfahmad/open_spiel
cb30d812a31f03e6550cfa1141750147b9481693
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <iterator> #include <tuple> #include "open_spiel/algorithms/alpha_zero_torch/vpnet.h" #include "open_spiel/games/connect_four.h" namespace open_spiel { namespace algorithms { namespace torch_az { std::tuple<int, int> negamax(std::unique_ptr<open_spiel::State> &root, int num_visited) { std::vector<Action> actions; std::vector<Action>::iterator action; std::unique_ptr<open_spiel::State> next_state; actions = root->LegalActions(); int value = -99; num_visited++; if (root->IsTerminal()){ if (root->Returns()[0] == 0) { return {0, num_visited}; } else { return {1, num_visited}; } } for (action = actions.begin(); action < actions.end(); action++) { next_state = root->Clone(); next_state->ApplyAction(*action); auto [child_value, num] = negamax(next_state, num_visited); num_visited = num; value = std::max(value, child_value); } return {-value, num_visited}; } } } } int main(int argc, char **argv) { std::shared_ptr<const open_spiel::Game> game = open_spiel::LoadGame("tic_tac_toe"); std::unique_ptr<open_spiel::State> state = game->NewInitialState(); auto [value, num_visited] = open_spiel::algorithms::torch_az::negamax(state, 0); std::cout << "Value: " << -value << " Visited: " << num_visited << std::endl; }
23.824561
89
0.666421
[ "vector" ]
9b5f6bf7b9aa0b854112161391857e2fbb15feca
503
cpp
C++
02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/02_FunctionsArraysAndVectors/Exercise_2019/06_triplesOfLatinLetters.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/02_FunctionsArraysAndVectors/Exercise_2019/06_triplesOfLatinLetters.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
02_Programming_Fundamentals/06_Programming_Fundamentals_CPP/02_FunctionsArraysAndVectors/Exercise_2019/06_triplesOfLatinLetters.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <ctype.h> #include <cmath> #include <cstdlib> #include <ctime> using namespace std; int main() { int size = 0; cin >> size; char firstChar = 'a'; for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { for(int k = 0; k < size; k++) { cout << (char)(firstChar + i) << (char)(firstChar + j) << (char)(firstChar + k) << endl; } } } }
15.71875
37
0.471173
[ "vector" ]
9b6a252ca86476f5541e5056136def0d03af90cd
11,400
cc
C++
src/kernel/transport.cc
Myrannas/runtime
d81f9ec641bb84e6713ae2ad8de29e1e54c65f4d
[ "ECL-2.0", "Apache-2.0" ]
1
2018-03-06T20:08:50.000Z
2018-03-06T20:08:50.000Z
src/kernel/transport.cc
Myrannas/runtime
d81f9ec641bb84e6713ae2ad8de29e1e54c65f4d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/kernel/transport.cc
Myrannas/runtime
d81f9ec641bb84e6713ae2ad8de29e1e54c65f4d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
// Copyright 2014 Runtime.JS project authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "transport.h" #include <kernel/isolate.h> #include <kernel/template-cache.h> #include <kernel/object-wrapper.h> #include <kernel/thread.h> namespace rt { TransportData::SerializeError TransportData::MoveValue(Thread* exporter, Isolate* isolate_recv, v8::Local<v8::Value> value) { RT_ASSERT(exporter); Isolate* isolate { exporter->isolate() }; RT_ASSERT(isolate); RT_ASSERT(isolate_recv); Clear(); isolate_ = isolate; allow_ref_ = isolate_recv == isolate; SerializeError err { SerializeValue(exporter, value, 1) }; if (SerializeError::NONE != err) { SetUndefined(); } return err; } TransportData::SerializeError TransportData::MoveArgs(Thread* exporter, Isolate* isolate_recv, const v8::FunctionCallbackInfo<v8::Value>& args) { RT_ASSERT(exporter); Isolate* isolate { exporter->isolate() }; RT_ASSERT(isolate); RT_ASSERT(isolate_recv); Clear(); isolate_ = isolate; allow_ref_ = isolate_recv == isolate; AppendType(Type::ARRAY); uint32_t len = args.Length(); stream_.AppendValue<uint32_t>(len); for (uint32_t i = 0; i < len; ++i) { SerializeError err { SerializeValue(exporter, args[i], 1) }; if (SerializeError::NONE != err) { SetUndefined(); return err; } } return SerializeError::NONE; } v8::Local<v8::Value> TransportData::GetRef(v8::Isolate* iv8, uint32_t index) const { RT_ASSERT(allow_ref_); RT_ASSERT(iv8); RT_ASSERT(isolate_); RT_ASSERT(isolate_->IsolateV8()); RT_ASSERT(isolate_->IsolateV8() == iv8); RT_ASSERT(index < refs_.size()); v8::EscapableHandleScope scope(iv8); return scope.Escape(v8::Local<v8::Value>::New(iv8, refs_[index])); } uint32_t TransportData::AddRef(v8::Local<v8::Value> value) { RT_ASSERT(allow_ref_); RT_ASSERT(isolate_); RT_ASSERT(isolate_->IsolateV8()); size_t index = refs_.size(); refs_.push_back(std::move(v8::UniquePersistent<v8::Value>(isolate_->IsolateV8(), value))); return static_cast<uint32_t>(index); } TransportData::SerializeError TransportData::SerializeValue(Thread* exporter, v8::Local<v8::Value> value, uint32_t stack_level) { RT_ASSERT(exporter); RT_ASSERT(!value.IsEmpty()); if (stack_level > kMaxStackSize) { return SerializeError::MAX_STACK; } if (value->IsUndefined()) { AppendType(Type::UNDEFINED); return SerializeError::NONE; } if (value->IsNull()) { AppendType(Type::NUL); return SerializeError::NONE; } if (value->IsBoolean()) { AppendType(value->BooleanValue() ? Type::BOOL_TRUE : Type::BOOL_FALSE); return SerializeError::NONE; } if (value->IsInt32()) { AppendType(Type::INT32); stream_.AppendValue<int32_t>(value->Int32Value()); return SerializeError::NONE; } if (value->IsUint32()) { AppendType(Type::UINT32); stream_.AppendValue<uint32_t>(value->Uint32Value()); return SerializeError::NONE; } if (value->IsNumber()) { AppendType(Type::DOUBLE); stream_.AppendValue<double>(value->NumberValue()); return SerializeError::NONE; } if (value->IsString()) { if (allow_ref_) { // Strings are immutable, its safe to pass by reference // for same-isolate calls AppendType(Type::STRING_REF); stream_.AppendValue<uint32_t>(AddRef(value)); } else { AppendType(Type::STRING_16); v8::Local<v8::String> s { value->ToString() }; int len = s->Length(); RT_ASSERT(len >= 0); stream_.AppendValue<uint32_t>(len); void* place { stream_.AppendBuffer((len + 1) * sizeof(uint16_t)) }; s->Write(reinterpret_cast<uint16_t*>(place), 0, len); } return SerializeError::NONE; } if (value->IsArray()) { AppendType(Type::ARRAY); v8::Local<v8::Array> a { v8::Local<v8::Array>::Cast(value) }; stream_.AppendValue<uint32_t>(a->Length()); for (uint32_t i = 0; i < a->Length(); ++i) { SerializeError err { SerializeValue(exporter, a->Get(i), stack_level + 1) }; if (SerializeError::NONE != err) { return err; } } return SerializeError::NONE; } if (value->IsArrayBuffer()) { // Neuter this array buffer and take its contents AppendType(Type::ARRAYBUFFER); v8::Local<v8::ArrayBuffer> b { v8::Local<v8::ArrayBuffer>::Cast(value) }; if (b->IsExternal()) { return SerializeError::EXTERNAL_BUFFER; } v8::ArrayBuffer::Contents c { b->Externalize() }; stream_.AppendValue<void*>(c.Data()); stream_.AppendValue<size_t>(c.ByteLength()); b->Neuter(); return SerializeError::NONE; } if (value->IsArrayBufferView()) { return SerializeError::TYPEDARRAY_VIEW; } if (value->IsFunction()) { ExternalFunction* efn { exporter->AddExport(value) }; AppendType(Type::FUNCTION); stream_.AppendValue<ExternalFunction*>(efn); return SerializeError::NONE; } // This condition check should be the last one if (value->IsObject()) { RT_ASSERT(isolate_); RT_ASSERT(isolate_->template_cache()); v8::Local<v8::Object> obj { value->ToObject() }; NativeObjectWrapper* ptr { isolate_->template_cache()->GetWrapped(value) }; // If current object is wrapped native if (nullptr != ptr) { switch (ptr->type_id()) { case NativeTypeId::TYPEID_FUNCTION: { ExternalFunction* efn { static_cast<ExternalFunction*>(ptr) }; AppendType(Type::FUNCTION); stream_.AppendValue<ExternalFunction*>(efn); return SerializeError::NONE; } default: break; } if (allow_ref_) { AppendType(Type::OBJECT_REF); stream_.AppendValue<uint32_t>(AddRef(value)); return SerializeError::NONE; } else { RT_ASSERT(!"not implemented"); } } AppendType(Type::HASHMAP); v8::Local<v8::Array> a { obj->GetOwnPropertyNames() }; stream_.AppendValue<uint32_t>(a->Length()); for (uint32_t i = 0; i < a->Length(); ++i) { v8::Local<v8::Value> k { a->Get(i) }; { SerializeError err { SerializeValue(exporter, k, stack_level + 1) }; if (SerializeError::NONE != err) { return err; } } { SerializeError err { SerializeValue(exporter, obj->Get(k), stack_level + 1) }; if (SerializeError::NONE != err) { return err; } } } return SerializeError::NONE; } return SerializeError::INVALID_TYPE; } v8::Local<v8::Value> TransportData::Unpack(Isolate* isolate) const { RT_ASSERT(isolate); v8::Isolate* iv8 { isolate->IsolateV8() }; RT_ASSERT(iv8); ByteStreamReader reader(stream_); if (allow_ref_) { RT_ASSERT(nullptr != isolate_); } v8::EscapableHandleScope scope(iv8); return scope.Escape(UnpackValue(isolate, reader)); } v8::Local<v8::Value> TransportData::UnpackValue(Isolate* isolate, ByteStreamReader& reader) const { RT_ASSERT(isolate); v8::Isolate* iv8 { isolate->IsolateV8() }; RT_ASSERT(iv8); v8::EscapableHandleScope scope(iv8); Type t { ReadType(reader) }; switch (t) { case Type::UNDEFINED: return scope.Escape<v8::Primitive>(v8::Undefined(iv8)); case Type::NUL: return scope.Escape<v8::Primitive>(v8::Null(iv8)); case Type::STRING_UTF8: { uint32_t len = reader.ReadValue<uint32_t>(); return scope.Escape(v8::String::NewFromUtf8(iv8, reinterpret_cast<const char*>(reader.ReadBuffer(len + 1)), v8::String::kNormalString, len)); } case Type::STRING_16: { uint32_t len = reader.ReadValue<uint32_t>(); return scope.Escape(v8::String::NewFromTwoByte(iv8, reinterpret_cast<const uint16_t*>(reader.ReadBuffer((len + 1) * sizeof(uint16_t))), v8::String::kNormalString, len)); } case Type::STRING_REF: case Type::OBJECT_REF: return scope.Escape(GetRef(iv8, reader.ReadValue<uint32_t>())); case Type::INT32: return scope.Escape<v8::Primitive>(v8::Int32::New(iv8, reader.ReadValue<int32_t>())); case Type::UINT32: return scope.Escape<v8::Primitive>(v8::Int32::New(iv8, reader.ReadValue<uint32_t>())); case Type::DOUBLE: return scope.Escape<v8::Primitive>(v8::Int32::New(iv8, reader.ReadValue<double>())); case Type::BOOL_TRUE: return scope.Escape<v8::Primitive>(v8::True(iv8)); case Type::BOOL_FALSE: return scope.Escape<v8::Primitive>(v8::False(iv8)); case Type::ARRAYBUFFER: { void* buf = reader.ReadValue<void*>(); size_t len = reader.ReadValue<size_t>(); return scope.Escape(v8::ArrayBuffer::NewNonExternal(iv8, buf, len)); } case Type::ARRAY: { uint32_t len = reader.ReadValue<uint32_t>(); v8::Local<v8::Array> arr { v8::Array::New(iv8, len) }; for (uint32_t i = 0; i < len; ++i) { arr->Set(i, UnpackValue(isolate, reader)); } return scope.Escape(arr); } case Type::HASHMAP: { uint32_t len = reader.ReadValue<uint32_t>(); v8::Local<v8::Object> obj { v8::Object::New(iv8) }; for (uint32_t i = 0; i < len; ++i) { v8::Local<v8::Value> k { UnpackValue(isolate, reader) }; v8::Local<v8::Value> v { UnpackValue(isolate, reader) }; obj->Set(k, v); } return scope.Escape(obj); } case Type::FUNCTION: { ExternalFunction* efn = reader.ReadValue<ExternalFunction*>(); RT_ASSERT(isolate->template_cache()); v8::Local<v8::Value> fnobj { isolate->template_cache()->NewWrappedFunction(efn) }; return scope.Escape(fnobj); } default: RT_ASSERT(!"unknown data type"); break; } RT_ASSERT(!"should not be here"); return scope.Escape<v8::Primitive>(v8::Undefined(iv8)); } } // namespace rt
33.727811
104
0.583947
[ "object" ]
9b6db394ef85e4659c0bfdb059eebfc535af95dd
1,600
cpp
C++
src/Backend/Toolchain_manager.cpp
uscope-platform/makefile_gen
06bd4405afbbd9584911f495ebefff828f05aa0d
[ "Apache-2.0" ]
null
null
null
src/Backend/Toolchain_manager.cpp
uscope-platform/makefile_gen
06bd4405afbbd9584911f495ebefff828f05aa0d
[ "Apache-2.0" ]
null
null
null
src/Backend/Toolchain_manager.cpp
uscope-platform/makefile_gen
06bd4405afbbd9584911f495ebefff828f05aa0d
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 University of Nottingham Ningbo China // Author: Filippo Savi <filssavi@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "Backend/Toolchain_manager.h" Toolchain_manager::Toolchain_manager(std::shared_ptr <settings_store> s, bool del_mkfile, std::string name) { delete_makefile = del_mkfile; project_name = std::move(name); s_store = std::move(s); } std::vector<const char *> Toolchain_manager::str_vect_to_char_p(const std::vector <std::string> &vect) { std::vector<const char *> args; args.reserve(vect.size() + 1); for( const auto& sp: vect) { args.push_back(sp.c_str()); } args.push_back(nullptr); // needed to terminate the args list return args; } void Toolchain_manager::spawn_process(const std::vector <std::string> &arg_v, bool daemonize, bool block) { int pid = fork(); if(pid== 0){ std::vector<const char *> args = str_vect_to_char_p(arg_v); if(daemonize) setsid(); execvp(args[0], const_cast<char *const *>(args.data())); } if(block) wait(nullptr); }
35.555556
109
0.696875
[ "vector" ]
9b71ca62cc1ef7e19b49803b7dfa6117ed237e01
987
cpp
C++
c++/Repeated_DNA_sequence.cpp
parizadas/HacktoberFest2020-3
48cb0c7f2d43d38cb7d8343df18035c9288c63ea
[ "MIT" ]
51
2020-09-27T15:28:05.000Z
2021-09-29T02:07:25.000Z
c++/Repeated_DNA_sequence.cpp
parizadas/HacktoberFest2020-3
48cb0c7f2d43d38cb7d8343df18035c9288c63ea
[ "MIT" ]
152
2020-09-27T12:12:12.000Z
2021-10-03T18:22:15.000Z
c++/Repeated_DNA_sequence.cpp
parizadas/HacktoberFest2020-3
48cb0c7f2d43d38cb7d8343df18035c9288c63ea
[ "MIT" ]
453
2020-09-27T12:34:35.000Z
2021-10-16T08:33:33.000Z
/* Question: All DNA is composed of a series of nucleotides abbreviated as 'A', 'C', 'G', and 'T', for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. Write a function to print all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. */ #include<bits/stdc++.h> using namespace std; void repeatedDNASequence(string s){ if(s.length()<10) return; unordered_map<string, int> m; vector<string> res; // Maintaing occuence of each substring. for(int i=0;(i+10)<=s.length();i++){ string tmp = s.substr(i, 10); m[tmp]++; } // If the substring has more than one count, we add it to our result. for(auto e: m){ if(e.second > 1){ res.push_back(e.first); } } // Printing the result for(string e: res){ cout<<e<<" "; } } int main(){ string s; cin>>s; repeatedDNASequence(s); }
24.073171
73
0.612969
[ "vector" ]
9b76b973e2cbd25bb6d39585789504cd8d434b22
5,434
cpp
C++
src/neural_network/optimize.cpp
arotem3/numerics
ba208d9fc0ccb9471cfec9927a21622eb3535f54
[ "Apache-2.0" ]
18
2019-04-18T17:34:49.000Z
2021-11-15T07:57:29.000Z
src/neural_network/optimize.cpp
arotem3/numerics
ba208d9fc0ccb9471cfec9927a21622eb3535f54
[ "Apache-2.0" ]
null
null
null
src/neural_network/optimize.cpp
arotem3/numerics
ba208d9fc0ccb9471cfec9927a21622eb3535f54
[ "Apache-2.0" ]
4
2019-12-02T04:04:21.000Z
2022-02-17T08:23:09.000Z
#include <numerics.hpp> void numerics::neuralnet::SGD::_check_alpha(const double a) { if (a <= 0) { throw std::domain_error("adam requires: alpha (=" + std::to_string(a) + ") > 0."); } } void numerics::neuralnet::SGD::_initialize_averages(const std::vector<Layer>& layers) { _avg_weights.clear(); _avg_bias.clear(); for (const Layer& L : layers) { if (L._trainable_weights) _avg_weights.push_back(L.weights); else _avg_weights.push_back(arma::mat()); if (L._trainable_bias) _avg_bias.push_back(L.bias); else _avg_bias.push_back(arma::mat()); } _initialized_averages = true; } void numerics::neuralnet::SGD::_update_averages(const std::vector<Layer>& layers) { if (_t >= _avg_start) { if (not _initialized_averages) _initialize_averages(layers); else { u_long N = _t - _avg_start; for (u_long i=0; i < layers.size(); ++i) { if (layers.at(i)._trainable_weights) _avg_weights.at(i) = (_avg_weights.at(i) * (N-1) + layers.at(i).weights) / N; if (layers.at(i)._trainable_bias) _avg_bias.at(i) = (_avg_bias.at(i) * (N-1) + layers.at(i).bias) / N; } } } } void numerics::neuralnet::SGD::set_alpha(const double a) { _check_alpha(a); _alpha = a; } std::unique_ptr<numerics::neuralnet::Optimizer> numerics::neuralnet::SGD::clone() const { return std::make_unique<SGD>(*this); } void numerics::neuralnet::SGD::set_averaging(u_long average) { if (average == 0) _averaging = false; else { _averaging = true; _avg_start = average; } } void numerics::neuralnet::SGD::restart() { _t = 0; if (_averaging) { _initialized_averages = false; } } void numerics::neuralnet::SGD::step(std::vector<Layer>& layers) { _t++; for (Layer& L : layers) { if (L._trainable_weights) L._weights += _alpha * L._dW; if (L._trainable_bias) L._bias += _alpha * L._db; } if (_averaging) _update_averages(layers); } void numerics::neuralnet::SGD::finalize(std::vector<Layer>& layers) { if (_averaging) { for (u_long i=0; i < layers.size(); ++i) { if (layers.at(i)._trainable_weights) layers.at(i)._weights = _avg_weights.at(i); if (layers.at(i)._trainable_bias) layers.at(i)._bias = _avg_bias.at(i); } } } void numerics::neuralnet::Adam::_check_beta1(double b1) { if ((b1 <= 0) or (b1 >= 1)) { throw std::domain_error("adam requires: 1 > beta1 (=" + std::to_string(b1) + ") > 0"); } } void numerics::neuralnet::Adam::_check_beta2(double b2) { if ((b2 <= 0) or (b2 >= 1)) { throw std::domain_error("adam requires: 1 > beta2 (=" + std::to_string(b2) + ") > 0"); } } void numerics::neuralnet::Adam::_check_epsilon(const double eps) { if (eps < 0) { throw std::domain_error("adam requires: epsilon (=" + std::to_string(eps) + ") > 0"); } } void numerics::neuralnet::Adam::_initialize_moments(const std::vector<Layer>& layers) { _mW.clear(); _mb.clear(); _vW.clear(); _vb.clear(); for (const Layer& L : layers) { if (L._trainable_weights) { _mW.push_back(arma::zeros(arma::size(L.weights))); _vW.push_back(arma::zeros(arma::size(L.weights))); } else { _mW.push_back(arma::mat()); // push empty _vW.push_back(arma::mat()); } if (L._trainable_bias) { _mb.push_back(arma::zeros(arma::size(L.bias))); _vb.push_back(arma::zeros(arma::size(L.bias))); } else { _mb.push_back(arma::mat()); _vb.push_back(arma::mat()); } } _initialized_moments = true; } std::unique_ptr<numerics::neuralnet::Optimizer> numerics::neuralnet::Adam::clone() const { return std::make_unique<Adam>(*this); } void numerics::neuralnet::Adam::set_beta1(const double b1) { _check_beta1(b1); _beta1 = b1; } void numerics::neuralnet::Adam::set_beta2(const double b2) { _check_beta2(b2); _beta2 = b2; } void numerics::neuralnet::Adam::set_epsilon(const double eps) { _check_epsilon(eps); _epsilon = eps; } void numerics::neuralnet::Adam::restart() { SGD::restart(); _initialized_moments = false; } void numerics::neuralnet::Adam::step(std::vector<Layer>& layers) { if (not _initialized_moments) _initialize_moments(layers); _t++; for (u_long i=0; i < layers.size(); ++i) { if (layers.at(i)._trainable_weights) { _mW.at(i) = _beta1*_mW.at(i) + (1 - _beta1)*layers.at(i)._dW; _vW.at(i) = _beta2*_vW.at(i) + (1 - _beta2)*arma::square(layers.at(i)._dW); arma::mat mWhat = _mW.at(i) / (1 - std::pow(_beta1, _t)); arma::mat vWhat = _vW.at(i) / (1 - std::pow(_beta2, _t)); layers.at(i)._weights += _alpha * mWhat / (arma::sqrt(vWhat) + _epsilon); } if (layers.at(i)._trainable_bias) { _mb.at(i) = _beta1*_mb.at(i) + (1 - _beta1)*layers.at(i)._db; _vb.at(i) = _beta2*_vb.at(i) + (1 - _beta2)*arma::square(layers.at(i)._db); arma::mat mbhat = _mb.at(i) / (1 - std::pow(_beta1, _t)); arma::mat vbhat = _vb.at(i) / (1 - std::pow(_beta2, _t)); layers.at(i)._bias += _alpha * mbhat / (arma::sqrt(vbhat) + _epsilon); } } if (_averaging) _update_averages(layers); }
32.345238
130
0.587597
[ "vector" ]
9b7ad8af05a3b78d560db273f911239c768cedc3
1,210
cpp
C++
LeetCodeCPP/73. Set Matrix Zeroes/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
1
2019-03-29T03:33:56.000Z
2019-03-29T03:33:56.000Z
LeetCodeCPP/73. Set Matrix Zeroes/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
null
null
null
LeetCodeCPP/73. Set Matrix Zeroes/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
null
null
null
// // main.cpp // 73. Set Matrix Zeroes // // Created by admin on 2019/3/29. // Copyright © 2019年 liu. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int m=matrix.size(); int n=matrix[0].size(); int col0=1; for(int i=0;i<m;i++){ if(matrix[i][0]==0){ col0=0; } for(int j=1;j<n;j++){ if(matrix[i][j]==0){ matrix[i][0]=matrix[0][j]=0; } } } for(int i=m-1;i>=0;i--){ for(int j=n-1;j>0;j--){ if(matrix[i][0]==0 || matrix[0][j]==0){ matrix[i][j]=0; } } if(col0==0){ matrix[i][0]=0; } } } }; int main(int argc, const char * argv[]) { vector<vector<int>> input={{1,1,1},{1,0,1},{1,1,1}}; Solution so=Solution(); so.setZeroes(input); for (auto item:input) { for(auto i:item){ cout<<i<<" "; } cout<<endl; } cout<<endl; return 0; }
21.22807
57
0.410744
[ "vector" ]
f92bc6797bdecbf94ae97ea548a006e26dac5cad
1,476
hpp
C++
modules/cuda_plugin/src/ops/pooling_impl.hpp
YUNEEC/openvino_contrib
6a79637583fadd22e01d31b912d94d7a27cc78ba
[ "Apache-2.0" ]
null
null
null
modules/cuda_plugin/src/ops/pooling_impl.hpp
YUNEEC/openvino_contrib
6a79637583fadd22e01d31b912d94d7a27cc78ba
[ "Apache-2.0" ]
null
null
null
modules/cuda_plugin/src/ops/pooling_impl.hpp
YUNEEC/openvino_contrib
6a79637583fadd22e01d31b912d94d7a27cc78ba
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <cuda/dnn.hpp> #include <ngraph/op/avg_pool.hpp> #include <ngraph/op/max_pool.hpp> #include <ngraph/shape.hpp> namespace CUDAPlugin { class PoolingImpl { public: explicit PoolingImpl(const ngraph::op::v1::MaxPool& node); explicit PoolingImpl(const ngraph::op::AvgPool& node); ~PoolingImpl() = default; void Execute(const CUDA::DnnHandle& handle, const void* input_tensor_device_ptr, void* output_tensor_device_ptr) const; private: int spatial_dims() const; std::vector<int> tensor_shape_from_ngraph(const ngraph::Shape& ngraph_shape) const; std::vector<int> spatial_shape_from_ngraph(const ngraph::Shape& ngraph_shape) const; std::vector<int> tensor_strides_from_ngraph(const ngraph::Shape& ngraph_strides) const; std::vector<int> paddings_from_ngraph(const ngraph::Shape& pads_begin, const ngraph::Shape& pads_end, cudnnPoolingMode_t pooling_mode) const; public: static constexpr size_t input_index{0}; static constexpr size_t output_index{0}; private: const int dims_; cudnnPoolingMode_t mode_; CUDA::DnnPoolingDescriptor pooling_descriptor_; CUDA::DnnTensorDescriptor input_tensor_descriptor_; CUDA::DnnTensorDescriptor output_tensor_descriptor_; }; } // namespace CUDAPlugin
31.404255
91
0.70122
[ "shape", "vector" ]
f93117269188c1b079b5efbe6b1c52ecf31dedb1
3,179
cpp
C++
kernel/src/fs/memfs/filestream.cpp
egranata/puppy
dc8b9bd7620966d94b18cbfaf50c9c5e142b9f6c
[ "Apache-2.0" ]
28
2018-06-01T07:01:55.000Z
2022-01-09T23:30:14.000Z
kernel/src/fs/memfs/filestream.cpp
egranata/puppy
dc8b9bd7620966d94b18cbfaf50c9c5e142b9f6c
[ "Apache-2.0" ]
175
2018-05-30T03:06:15.000Z
2019-02-06T23:54:24.000Z
kernel/src/fs/memfs/filestream.cpp
egranata/puppy
dc8b9bd7620966d94b18cbfaf50c9c5e142b9f6c
[ "Apache-2.0" ]
2
2019-07-16T02:57:27.000Z
2021-06-25T17:01:13.000Z
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <kernel/fs/memfs/memfs.h> #include <kernel/syscalls/types.h> #include <kernel/log/log.h> LOG_TAG(MEMFS, 1); Filesystem::File* MemFS::doOpen(const char* path, uint32_t mode) { class FileStream : public Filesystem::File { public: FileStream(MemFS::File* file, MemFS::FileBuffer* buffer, uint32_t mode) : mFile(file), mContent(buffer), mIndex(0), mMode(mode) { // TODO: should a file be allowed to refuse a certain open mode? kind(file->kind()); } bool seek(size_t index) { if (index < mContent->len()) { mIndex = index; return true; } return false; } bool tell(size_t* pos) override { if (pos) *pos = mIndex; return true; } size_t read(size_t n, char* dest) { if (0 == (mMode & FILE_OPEN_READ)) return 0; size_t cnt = mContent->read(mIndex, n, dest); mIndex += cnt; return cnt; } size_t write(size_t n, char* src) { if (0 == (mMode & FILE_OPEN_WRITE)) return 0; size_t len = mContent->write(mIndex, n, src); mIndex += len; return len; } uintptr_t ioctl(uintptr_t a, uintptr_t b) { // TODO: a mode to allow/disallow IOCTL? return mFile->ioctl(a,b); } bool doStat(stat_t& stat) { stat.kind = mFile->kind(); stat.size = mContent->len(); stat.time = mFile->time(); return true; } private: MemFS::File* mFile; delete_ptr<MemFS::FileBuffer> mContent; size_t mIndex; uint32_t mMode; }; string _paths(path); Entity* entity = root()->get(_paths.buf()); if (entity == nullptr) return nullptr; switch (entity->kind()) { #define FILE_LIKE(x, y) case file_kind_t:: x: break; #define DIR_LIKE(x,y) case file_kind_t:: x: {\ TAG_DEBUG(MEMFS, "cannot open a directory object as file"); \ return nullptr; \ } break; #include <kernel/fs/file_kinds.tbl> #undef FILE_LIKE #undef DIR_LIKE } MemFS::File* theFile = (MemFS::File*)entity; MemFS::FileBuffer* theBuffer = theFile->content().reset(); if (theFile && theBuffer) return new FileStream(theFile, theBuffer, mode); return nullptr; }
33.114583
83
0.553948
[ "object" ]
f935fe13b4334baa919d9dda2ab0291f245d38d1
6,065
cc
C++
lullaby/systems/render/filament/shader_factory.cc
dherbst/lullaby
0b6675c9fc534c606236f40486987540ad098007
[ "Apache-2.0" ]
1,198
2017-06-09T08:10:52.000Z
2022-03-21T13:39:50.000Z
lullaby/systems/render/filament/shader_factory.cc
dherbst/lullaby
0b6675c9fc534c606236f40486987540ad098007
[ "Apache-2.0" ]
14
2017-06-10T00:47:46.000Z
2020-12-31T05:19:55.000Z
lullaby/systems/render/filament/shader_factory.cc
dherbst/lullaby
0b6675c9fc534c606236f40486987540ad098007
[ "Apache-2.0" ]
183
2017-06-09T22:19:20.000Z
2022-02-23T03:31:35.000Z
/* Copyright 2017-2019 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "lullaby/systems/render/filament/shader_factory.h" #include "lullaby/modules/file/asset_loader.h" #include "lullaby/systems/render/filament/shader_material_builder.h" #include "lullaby/util/filename.h" #include "lullaby/util/flatbuffer_reader.h" namespace lull { // Creates a unique hash given the shading model and selection parameters. static HashValue CreateShaderHash(string_view shading_model, const ShaderSelectionParams& params) { HashValue hash = Hash(shading_model); for (HashValue feature : params.environment) { hash = HashCombine(hash, feature); } for (HashValue feature : params.features) { hash = HashCombine(hash, feature); } return hash; } ShaderFactory::ShaderFactory(Registry* registry, filament::Engine* engine) : registry_(registry), engine_(engine), shading_model_path_("shaders/") { // filamat::MaterialBuilder requires calls to its static init and shutdown. filamat::MaterialBuilder::init(); } ShaderFactory::~ShaderFactory() { // filamat::MaterialBuilder requires calls to its static init and shutdown. filamat::MaterialBuilder::shutdown(); } void ShaderFactory::SetShadingModelPath(string_view path) { shading_model_path_ = std::string(path); } ShaderPtr ShaderFactory::CreateShader(string_view shader_name, const ShaderSelectionParams& params) { // Find the asset with the given shader name. ShaderAssetPtr asset = FindShaderAsset(shader_name); DCHECK(asset != nullptr); // Create a unique key for the shader instance using the selection parameters. HashValue key = 0; if (asset->model.empty()) { key = CreateShaderHash(shader_name, params); } else { key = CreateShaderHash(asset->model, params); } // Find and return a cached Shader object that has already been created from // the asset associated with the shader_name. ShaderPtr shader = shaders_.Find(key); if (shader) { return shader; } if (asset->type == kFilamentMatc) { // Build the shader using the matc binary data. ShaderMaterialBuilder builder(engine_, asset->model, asset->GetData(), asset->GetSize()); return BuildShader(key, &builder); } else if (asset->type == kLullShader) { // Build the shader from the lullshader. ShaderDefT def; ReadFlatbuffer(&def, flatbuffers::GetRoot<ShaderDef>(asset->GetData())); ShaderMaterialBuilder builder(engine_, asset->model, &def, params); return BuildShader(key, &builder); } else { // Build the shader programatically. ShaderMaterialBuilder builder(engine_, std::string(shader_name), nullptr, params); return BuildShader(key, &builder); } } ShaderPtr ShaderFactory::BuildShader(HashValue key, ShaderMaterialBuilder* builder) { if (!builder->IsValid()) { return nullptr; } // Build the filament Material using the ShaderMaterialBuilder and assign filament::Engine* engine = engine_; filament::Material* material = builder->GetFilamentMaterial(); Shader::FMaterialPtr ptr( material, [engine](filament::Material* obj) { engine->destroy(obj); }); // Create the shader object using the Filament Material. auto shader = std::make_shared<Shader>(); shader->Init(std::move(ptr), builder->GetDescription()); if (key) { shaders_.Register(key, shader); shaders_.Release(key); } return shader; } ShaderPtr ShaderFactory::GetCachedShader(HashValue key) const { return shaders_.Find(key); } void ShaderFactory::CacheShader(HashValue key, const ShaderPtr& shader) { shaders_.Create(key, [shader] { return shader; }); } void ShaderFactory::ReleaseShaderFromCache(HashValue key) { shaders_.Release(key); } ShaderFactory::ShaderAssetPtr ShaderFactory::FindShaderAsset( string_view shader_name) { // Extract the shading model name from the shader_name. If the shader_name is // a shading model name, then this should do nothing. std::string model(shader_name); model = RemoveDirectoryAndExtensionFromFilename(model); std::transform(model.begin(), model.end(), model.begin(), ::tolower); // First attempt to load the assets directly if the name ends with a known // extension (eg. .matc or .lullshader). ShaderAssetPtr asset = nullptr; if (EndsWith(shader_name, ".matc")) { asset = LoadShaderAsset(shader_name, model, kFilamentMatc); } else if (EndsWith(shader_name, ".lullshader")) { asset = LoadShaderAsset(shader_name, model, kLullShader); } // If unsuccessul, attempt to load the shader as first a matc file then a // lullmodel file. if (asset == nullptr || asset->GetSize() == 0) { const std::string basename = JoinPath(shading_model_path_, model); asset = LoadShaderAsset(basename + ".matc", model, kFilamentMatc); if (asset == nullptr || asset->GetSize() == 0) { asset = LoadShaderAsset(basename + ".lullshader", model, kLullShader); } } return asset; } ShaderFactory::ShaderAssetPtr ShaderFactory::LoadShaderAsset( string_view filename, string_view model, AssetType type) { return assets_.Create(Hash(filename), [&]() { auto* asset_loader = registry_->Get<AssetLoader>(); auto asset = asset_loader->LoadNow<ShaderAsset>(std::string(filename)); if (asset && asset->GetSize() > 0) { asset->type = type; asset->model = std::string(model); } return asset; }); } } // namespace lull
35.676471
80
0.705853
[ "render", "object", "model", "transform" ]
f93aa859368e19d886145849261d5498dc6f1cf6
14,476
cpp
C++
src/mongo/rpc/op_msg.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/rpc/op_msg.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/rpc/op_msg.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/rpc/op_msg.h" #include <bitset> #include <set> #include "mongo/base/data_type_endian.h" #include "mongo/config.h" #include "mongo/db/auth/security_token_gen.h" #include "mongo/db/bson/dotted_path_support.h" #include "mongo/db/multitenancy_gen.h" #include "mongo/logv2/log.h" #include "mongo/rpc/object_check.h" #include "mongo/util/bufreader.h" #include "mongo/util/hex.h" #ifdef MONGO_CONFIG_WIREDTIGER_ENABLED #include <wiredtiger.h> #endif #define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kNetwork namespace mongo { namespace { auto kAllSupportedFlags = OpMsg::kChecksumPresent | OpMsg::kMoreToCome; bool containsUnknownRequiredFlags(uint32_t flags) { const uint32_t kRequiredFlagMask = 0xffff; // Low 2 bytes are required, high 2 are optional. return (flags & ~kAllSupportedFlags & kRequiredFlagMask) != 0; } enum class Section : uint8_t { kBody = 0, kDocSequence = 1, kSecurityToken = 2, }; constexpr int kCrc32Size = 4; #ifdef MONGO_CONFIG_WIREDTIGER_ENABLED // All fields including size, requestId, and responseTo must already be set. The size must already // include the final 4-byte checksum. uint32_t calculateChecksum(const Message& message) { if (message.operation() != dbMsg) { return 0; } invariant(OpMsg::isFlagSet(message, OpMsg::kChecksumPresent)); return wiredtiger_crc32c_func()(message.singleData().view2ptr(), message.size() - kCrc32Size); } #endif // MONGO_CONFIG_WIREDTIGER_ENABLED } // namespace uint32_t OpMsg::flags(const Message& message) { if (message.operation() != dbMsg) return 0; // Other command protocols are the same as no flags set. return BufReader(message.singleData().data(), message.dataSize()) .read<LittleEndian<uint32_t>>(); } void OpMsg::replaceFlags(Message* message, uint32_t flags) { invariant(!message->empty()); invariant(message->operation() == dbMsg); invariant(message->dataSize() >= static_cast<int>(sizeof(uint32_t))); DataView(message->singleData().data()).write<LittleEndian<uint32_t>>(flags); } uint32_t OpMsg::getChecksum(const Message& message) { invariant(message.operation() == dbMsg); invariant(isFlagSet(message, kChecksumPresent)); uassert(51252, "Invalid message size for an OpMsg containing a checksum", // Check that the message size is at least the size of a crc-32 checksum and // the 32-bit flags section. message.dataSize() > static_cast<int>(kCrc32Size + sizeof(uint32_t))); return BufReader(message.singleData().view2ptr() + message.size() - kCrc32Size, kCrc32Size) .read<LittleEndian<uint32_t>>(); } void OpMsg::appendChecksum(Message* message) { #ifdef MONGO_CONFIG_WIREDTIGER_ENABLED if (message->operation() != dbMsg) { return; } invariant(!isFlagSet(*message, kChecksumPresent)); setFlag(message, kChecksumPresent); const size_t newSize = message->size() + kCrc32Size; if (message->capacity() < newSize) { message->realloc(newSize); } // Everything before the checksum, including the final size, is covered by the checksum. message->header().setLen(newSize); DataView(message->singleData().view2ptr() + newSize - kCrc32Size) .write<LittleEndian<uint32_t>>(calculateChecksum(*message)); #endif } OpMsg OpMsg::parse(const Message& message) try { // It is the caller's responsibility to call the correct parser for a given message type. invariant(!message.empty()); invariant(message.operation() == dbMsg); const uint32_t flags = OpMsg::flags(message); uassert(ErrorCodes::IllegalOpMsgFlag, str::stream() << "Message contains illegal flags value: Ob" << std::bitset<32>(flags).to_string(), !containsUnknownRequiredFlags(flags)); auto dataSize = message.dataSize() - sizeof(flags); boost::optional<uint32_t> checksum; if (flags & kChecksumPresent) { checksum = getChecksum(message); uassert(51251, "Invalid message size for an OpMsg containing a checksum", dataSize > kCrc32Size); dataSize -= kCrc32Size; } // The sections begin after the flags and before the checksum (if present). BufReader sectionsBuf(message.singleData().data() + sizeof(flags), dataSize); // TODO some validation may make more sense in the IDL parser. I've tagged them with comments. bool haveBody = false; OpMsg msg; while (!sectionsBuf.atEof()) { const auto sectionKind = sectionsBuf.read<Section>(); switch (sectionKind) { case Section::kBody: { uassert(40430, "Multiple body sections in message", !haveBody); haveBody = true; msg.body = sectionsBuf.read<Validated<BSONObj>>(); break; } case Section::kDocSequence: { // We use an O(N^2) algorithm here and an O(N*M) algorithm below. These are fastest // for the current small values of N, but would be problematic if it is large. // If we need more document sequences, raise the limit and use a better algorithm. uassert(ErrorCodes::TooManyDocumentSequences, "Too many document sequences in OP_MSG", msg.sequences.size() < 2); // Limit is <=2 since we are about to add one. // The first 4 bytes are the total size, including themselves. const auto remainingSize = sectionsBuf.read<LittleEndian<int32_t>>() - sizeof(int32_t); BufReader seqBuf(sectionsBuf.skip(remainingSize), remainingSize); const auto name = seqBuf.readCStr(); uassert(40431, str::stream() << "Duplicate document sequence: " << name, !msg.getSequence(name)); // TODO IDL msg.sequences.push_back({name.toString()}); while (!seqBuf.atEof()) { msg.sequences.back().objs.push_back(seqBuf.read<Validated<BSONObj>>()); } break; } case Section::kSecurityToken: { uassert(ErrorCodes::Unauthorized, "Unsupported Security Token provided", gMultitenancySupport); msg.securityToken = sectionsBuf.read<Validated<BSONObj>>(); break; } default: // Using uint32_t so we append as a decimal number rather than as a char. uasserted(40432, str::stream() << "Unknown section kind " << uint32_t(sectionKind)); } } uassert(40587, "OP_MSG messages must have a body", haveBody); // Detect duplicates between doc sequences and body. TODO IDL // Technically this is O(N*M) but N is at most 2. for (const auto& docSeq : msg.sequences) { const char* name = docSeq.name.c_str(); // Pointer is redirected by next call. auto inBody = !dotted_path_support::extractElementAtPathOrArrayAlongPath(msg.body, name).eoo(); uassert(40433, str::stream() << "Duplicate field between body and document sequence " << docSeq.name, !inBody); } #ifdef MONGO_CONFIG_WIREDTIGER_ENABLED if (checksum) { uassert(ErrorCodes::ChecksumMismatch, "OP_MSG checksum does not match contents", *checksum == calculateChecksum(message)); } #endif return msg; } catch (const DBException& ex) { LOGV2_DEBUG( 22632, 1, "invalid message: {ex_code} {ex} -- {hexdump_message_singleData_view2ptr_message_size}", "ex_code"_attr = ex.code(), "ex"_attr = redact(ex), "hexdump_message_singleData_view2ptr_message_size"_attr = redact(hexdump(message.singleData().view2ptr(), message.size()))); throw; } namespace { void serializeHelper(const std::vector<OpMsg::DocumentSequence>& sequences, const BSONObj& body, const BSONObj& securityToken, OpMsgBuilder* output) { if (securityToken.nFields() > 0) { output->setSecurityToken(securityToken); } for (auto&& seq : sequences) { auto docSeq = output->beginDocSequence(seq.name); for (auto&& obj : seq.objs) { docSeq.append(obj); } } output->beginBody().appendElements(body); } } // namespace Message OpMsg::serialize() const { OpMsgBuilder builder; serializeHelper(sequences, body, securityToken, &builder); return builder.finish(); } Message OpMsg::serializeWithoutSizeChecking() const { OpMsgBuilder builder; serializeHelper(sequences, body, securityToken, &builder); return builder.finishWithoutSizeChecking(); } void OpMsg::shareOwnershipWith(const ConstSharedBuffer& buffer) { if (!body.isOwned()) { body.shareOwnershipWith(buffer); } for (auto&& seq : sequences) { for (auto&& obj : seq.objs) { if (!obj.isOwned()) { obj.shareOwnershipWith(buffer); } } } if (!securityToken.isOwned()) { securityToken.shareOwnershipWith(buffer); } } BSONObjBuilder OpMsgBuilder::beginSecurityToken() { invariant(_state == kEmpty); _state = kSecurityToken; _buf.appendStruct(Section::kSecurityToken); return BSONObjBuilder(_buf); } auto OpMsgBuilder::beginDocSequence(StringData name) -> DocSequenceBuilder { invariant((_state == kEmpty) || (_state == kSecurityToken) || (_state == kDocSequence)); invariant(!_openBuilder); _openBuilder = true; _state = kDocSequence; _buf.appendStruct(Section::kDocSequence); int sizeOffset = _buf.len(); _buf.skip(sizeof(int32_t)); // section size. _buf.appendStr(name, true); return DocSequenceBuilder(this, &_buf, sizeOffset); } void OpMsgBuilder::finishDocumentStream(DocSequenceBuilder* docSequenceBuilder) { invariant(_state == kDocSequence); invariant(_openBuilder); _openBuilder = false; const int32_t size = _buf.len() - docSequenceBuilder->_sizeOffset; invariant(size > 0); DataView(_buf.buf()).write<LittleEndian<int32_t>>(size, docSequenceBuilder->_sizeOffset); } BSONObjBuilder OpMsgBuilder::beginBody() { invariant((_state == kEmpty) || (_state == kSecurityToken) || (_state == kDocSequence)); _state = kBody; _buf.appendStruct(Section::kBody); invariant(_bodyStart == 0); _bodyStart = _buf.len(); // Cannot be 0. return BSONObjBuilder(_buf); } BSONObjBuilder OpMsgBuilder::resumeBody() { invariant(_state == kBody); invariant(_bodyStart != 0); return BSONObjBuilder(BSONObjBuilder::ResumeBuildingTag(), _buf, _bodyStart); } AtomicWord<bool> OpMsgBuilder::disableDupeFieldCheck_forTest{false}; Message OpMsgBuilder::finish() { const auto size = _buf.len(); uassert(ErrorCodes::BSONObjectTooLarge, str::stream() << "BSON size limit hit while building Message. Size: " << size << " (0x" << unsignedHex(size) << "); maxSize: " << BSONObjMaxInternalSize << "(" << (BSONObjMaxInternalSize / (1024 * 1024)) << "MB)", size <= BSONObjMaxInternalSize); return finishWithoutSizeChecking(); } Message OpMsgBuilder::finishWithoutSizeChecking() { if (kDebugBuild && !disableDupeFieldCheck_forTest.load()) { std::set<StringData> seenFields; for (auto elem : resumeBody().asTempObj()) { if (!(seenFields.insert(elem.fieldNameStringData()).second)) { LOGV2_FATAL(40474, "OP_MSG with duplicate field '{elem_fieldNameStringData}' : " "{resumeBody_asTempObj}", "elem_fieldNameStringData"_attr = elem.fieldNameStringData(), "resumeBody_asTempObj"_attr = redact(resumeBody().asTempObj())); } } } invariant(_state == kBody); invariant(_bodyStart); invariant(!_openBuilder); _state = kDone; const auto size = _buf.len(); MSGHEADER::View header(_buf.buf()); header.setMessageLength(size); // header.setRequestMsgId(...); // These are currently filled in by the networking layer. // header.setResponseToMsgId(...); header.setOpCode(dbMsg); return Message(_buf.release()); } BSONObj OpMsgBuilder::releaseBody() { invariant(_state == kBody); invariant(_bodyStart); invariant(_bodyStart == sizeof(MSGHEADER::Layout) + 4 /*flags*/ + 1 /*body kind byte*/); invariant(!_openBuilder); _state = kDone; auto bson = BSONObj(_buf.buf() + _bodyStart); return bson.shareOwnershipWith(_buf.release()); } } // namespace mongo
37.405685
100
0.647071
[ "vector" ]
f9426072d1ef0f2fe62c72e5846e04ae2722ba2e
4,704
cpp
C++
libcore/luni/src/test/native/libcore_java_lang_ThreadTest.cpp
lulululbj/android_9.0.0_r45
64cc84d6683a4eb373c22ac50aaad0d349d45fcd
[ "Apache-2.0" ]
41
2019-09-06T01:37:29.000Z
2022-02-21T01:03:03.000Z
libcore/luni/src/test/native/libcore_java_lang_ThreadTest.cpp
lulululbj/android_9.0.0_r45
64cc84d6683a4eb373c22ac50aaad0d349d45fcd
[ "Apache-2.0" ]
null
null
null
libcore/luni/src/test/native/libcore_java_lang_ThreadTest.cpp
lulululbj/android_9.0.0_r45
64cc84d6683a4eb373c22ac50aaad0d349d45fcd
[ "Apache-2.0" ]
15
2019-09-06T09:36:41.000Z
2022-03-08T06:47:21.000Z
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <memory> #include <string> #include <pthread.h> #include <sys/prctl.h> #include <jni.h> #include <nativehelper/JNIHelp.h> static JavaVM* javaVm = nullptr; static void* TestThreadNaming(void* arg) { const bool attach_with_name = (reinterpret_cast<uint64_t>(arg) == 1); const std::string native_thread_name = "foozball"; pthread_setname_np(pthread_self(), native_thread_name.c_str()); JNIEnv* env; JavaVMAttachArgs args; args.version = JNI_VERSION_1_6; args.group = nullptr; if (attach_with_name) { args.name = native_thread_name.c_str(); } else { args.name = nullptr; } if (javaVm->AttachCurrentThread(&env, &args) != JNI_OK) { return new std::string("Attach failed"); } std::string* exception_message = nullptr; std::unique_ptr<char[]> thread_name(new char[32]); if (prctl(PR_GET_NAME, reinterpret_cast<unsigned long>(thread_name.get()), 0L, 0L, 0L) == 0) { // If a thread is attached with a name, the native thread name must be set to // the supplied name. In this test, the name we attach with == the // native_thread_name. if (attach_with_name && (thread_name.get() != native_thread_name)) { exception_message = new std::string("expected_thread_name != thread_name: "); exception_message->append("expected :"); exception_message->append(native_thread_name); exception_message->append(" was :"); exception_message->append(thread_name.get()); } // On the other hand, if the thread isn't attached with a name - the // runtime assigns a name according to the usual thread naming scheme. if (!attach_with_name && strncmp(thread_name.get(), "Thread", 6)) { exception_message = new std::string("unexpected thread name : "); exception_message->append(thread_name.get()); } } else { exception_message = new std::string("prctl(PR_GET_NAME) failed :"); exception_message->append(strerror(errno)); } if (javaVm->DetachCurrentThread() != JNI_OK) { exception_message = new std::string("Detach failed"); } return exception_message; } extern "C" jstring Java_libcore_java_lang_ThreadTest_nativeTestNativeThreadNames( JNIEnv* env, jobject /* object */) { std::string result; // TEST 1: Test that a thread attaching with a specified name (in the // JavaVMAttachArgs) does not have its name changed. pthread_t attacher; if (pthread_create(&attacher, nullptr, TestThreadNaming, reinterpret_cast<void*>(static_cast<uint64_t>(0))) != 0) { jniThrowException(env, "java/lang/IllegalStateException", "Attach failed"); } std::string* result_test1; if (pthread_join(attacher, reinterpret_cast<void**>(&result_test1)) != 0) { jniThrowException(env, "java/lang/IllegalStateException", "Join failed"); } if (result_test1 != nullptr) { result.append("test 1: "); result.append(*result_test1); } // TEST 2: Test that a thread attaching without a specified name (in the // JavaVMAttachArgs) has its native name changed as per the standard naming // convention. pthread_t attacher2; if (pthread_create(&attacher2, nullptr, TestThreadNaming, reinterpret_cast<void*>(static_cast<uint64_t>(1))) != 0) { jniThrowException(env, "java/lang/IllegalStateException", "Attach failed"); } std::string* result_test2; if (pthread_join(attacher2, reinterpret_cast<void**>(&result_test2)) != 0) { jniThrowException(env, "java/lang/IllegalStateException", "Join failed"); } if (result_test2 != nullptr) { result.append("test 2: "); result.append(*result_test2); } // Return test results. jstring resultJString = nullptr; if (result.size() > 0) { resultJString = env->NewStringUTF(result.c_str()); } delete result_test1; delete result_test2; return resultJString; } extern "C" int JNI_OnLoad(JavaVM* vm, void*) { javaVm = vm; return JNI_VERSION_1_6; }
34.335766
98
0.673257
[ "object" ]
f942b0754afd401157ae8e1c2db3d590cadac6e1
1,292
hh
C++
DAQ/inc/CaloDAQUtilities.hh
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
9
2020-03-28T00:21:41.000Z
2021-12-09T20:53:26.000Z
DAQ/inc/CaloDAQUtilities.hh
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
684
2019-08-28T23:37:43.000Z
2022-03-31T22:47:45.000Z
DAQ/inc/CaloDAQUtilities.hh
resnegfk/Offline
4ba81dad54486188fa83fea8c085438d104afbbc
[ "Apache-2.0" ]
61
2019-08-16T23:28:08.000Z
2021-12-20T08:29:48.000Z
#ifndef DAQ_CaloDAQUtilities_hh #define DAQ_CaloDAQUtilities_hh // // // #include "mu2e-artdaq-core/Overlays/CalorimeterFragment.hh" #include "mu2e-artdaq-core/Overlays/FragmentType.hh" #include <artdaq-core/Data/Fragment.hh> #include <string> namespace mu2e { class CaloDAQUtilities{ public: CaloDAQUtilities(std::string ModuleName); uint16_t getCrystalID(CalorimeterFragment::CalorimeterHitReadoutPacket const& Hit){ return Hit.DIRACB & 0x0FFF;} uint16_t getSiPMID (CalorimeterFragment::CalorimeterHitReadoutPacket const& Hit){ uint16_t crystalID = getCrystalID(Hit); uint16_t sipmID = Hit.DIRACB >> 12; return (crystalID * 2 + sipmID); } void printCaloFragmentInfo(CalorimeterFragment const& Frag); void printCaloFragmentHeader(std::shared_ptr<DTCLib::DTC_DataHeaderPacket> Header); void printCaloPulse(CalorimeterFragment::CalorimeterHitReadoutPacket const& Hit); void printWaveform(std::vector<uint16_t> const& Pulse); void printAllHitInfo(int CrystalID, int SiPMID, std::shared_ptr<DTCLib::DTC_DataHeaderPacket> Header, CalorimeterFragment::CalorimeterHitReadoutPacket const& Hit, uint16_t PulseMax); private: std::string moduleName_; }; } #endif /* DAQ_CaloDAQUtilities_hh */
29.363636
188
0.747678
[ "vector" ]
f952da6925a9c4a9947b0917d276d32901f9b46b
2,239
hpp
C++
include/parser/utility/meta.hpp
gdunton/TextMatch
3a99863b61baac76f92161595f0efcf0be80162b
[ "MIT" ]
null
null
null
include/parser/utility/meta.hpp
gdunton/TextMatch
3a99863b61baac76f92161595f0efcf0be80162b
[ "MIT" ]
5
2018-02-03T21:15:08.000Z
2018-02-11T21:19:11.000Z
include/parser/utility/meta.hpp
gdunton/TextParseCpp
3a99863b61baac76f92161595f0efcf0be80162b
[ "MIT" ]
null
null
null
#ifndef META_HPP #define META_HPP #include <type_traits> #include <tuple> //------------------------------------------------------------- // Function Traits //------------------------------------------------------------- template <typename T> struct FunctionTraits : public FunctionTraits<decltype(&T::operator())> {}; template <typename Ret, typename Class, typename... Args> struct FunctionTraits<Ret(Class::*)(Args...) const> { static const int Arity = sizeof...(Args); using ReturnType = Ret; using TupleType = std::tuple<Args...>; }; template <typename Ret, typename... Args> struct FunctionTraits<Ret (*)(Args...)> { static const int Arity = sizeof...(Args); using ReturnType = Ret; }; //------------------------------------------------------------- // Function folding //------------------------------------------------------------- template <typename T, typename... Args> void foldIntoVector(std::vector<T>& vec, Args&&... args) { // This is a terrible hack but it enables forwarding before C++17 (void)std::initializer_list<int>{ (vec.emplace_back(std::forward<Args>(args)), 0)... }; } template <typename... Args> struct TakeFirst { using type = typename std::tuple_element<0, std::tuple<Args...>>::type; }; //------------------------------------------------------------- // Indices Sequence //------------------------------------------------------------- template <int... Vals> struct IndexSequence {}; namespace Detail { template <int ... Vals> struct IndexSequenceGen; template <int I, int... Args> struct IndexSequenceGen<I, Args...> { // Recursively create a sequence with decremented values using type = typename IndexSequenceGen<I - 1, I - 1, Args...>::type; }; // Base of recursion template<int ... Args> struct IndexSequenceGen<0, Args...> { using type = IndexSequence<Args...>; }; } // This will generate a sequence of integers. e.g. IndexSequence_t<5> => sequence<0, 1, 2, 3, 4>; // To use put as parameter to template function e.g. // template <int... Indices> void func(sequence<Indices>); template <int N> using IndexSequence_t = typename Detail::IndexSequenceGen<N>::type; static_assert(std::is_same<IndexSequence_t<3>, IndexSequence<0, 1, 2>>::value, "Failed"); #endif
31.985714
97
0.575703
[ "vector" ]
f954ff46de0c4add976a49593e5922d6e52f9be1
4,440
cpp
C++
Neural-network-project/Training/MNIST_Training_module.cpp
alessandro-p/Neural-network
c53bb2d612bd137cf250d2eaf2f7af33d57a9cde
[ "Apache-2.0" ]
1
2016-03-08T18:22:15.000Z
2016-03-08T18:22:15.000Z
Neural-network-project/Training/MNIST_Training_module.cpp
alessandro-p/Neural-network
c53bb2d612bd137cf250d2eaf2f7af33d57a9cde
[ "Apache-2.0" ]
null
null
null
Neural-network-project/Training/MNIST_Training_module.cpp
alessandro-p/Neural-network
c53bb2d612bd137cf250d2eaf2f7af33d57a9cde
[ "Apache-2.0" ]
null
null
null
// // MNIST_Training_module.cpp // Neural-network-project // #include "MNIST_Training_module.hpp" MNIST_Training_module :: MNIST_Training_module() { populate_input_vals(default_input_vals_training_file); populate_target_vals(default_targets_vals_training_file); } MNIST_Training_module :: MNIST_Training_module(std :: string input_vals_file, std :: string target_vals_file) { populate_input_vals(input_vals_file); populate_target_vals(target_vals_file); } void MNIST_Training_module :: populate_input_vals(std :: string file_name) { std :: ifstream file (file_name, std:: ios :: binary); if(file.is_open()) { int magic_number = 0; int number_of_images = 0; int n_rows = 0; int n_cols = 0; file.read((char*) &magic_number, sizeof(magic_number)); magic_number = Utility :: reverse_int(magic_number); file.read((char*) &number_of_images,sizeof(number_of_images)); number_of_images = Utility :: reverse_int(number_of_images); file.read((char*) &n_rows, sizeof(n_rows)); n_rows = Utility :: reverse_int(n_rows); file.read((char*) &n_cols, sizeof(n_cols)); n_cols = Utility :: reverse_int (n_cols); for(int i = 0; i < number_of_images; ++i) { std :: vector<double> tp; for(int r = 0; r < n_rows; ++r) { for(int c = 0; c < n_cols; ++c) { unsigned char temp = 0; file.read((char*) &temp, sizeof(temp)); tp.push_back((double)temp); } } _input_vals.push_back(tp); } } } void MNIST_Training_module :: populate_target_vals(std :: string file_name) { std :: ifstream file (file_name, std :: ios :: binary); if (file.is_open()) { int magic_number = 0; int number_of_images = 0; file.read((char*) &magic_number, sizeof(magic_number)); magic_number = Utility :: reverse_int(magic_number); file.read((char*) &number_of_images,sizeof(number_of_images)); number_of_images = Utility :: reverse_int(number_of_images); for(int i = 0; i < number_of_images; ++i) { unsigned char temp = 0; file.read((char*) &temp, sizeof(temp)); _target_vals.push_back((double)temp); } } } std :: vector<double> MNIST_Training_module :: get_target_vals(std :: vector<double> target_vals, int index) { std :: vector<double> v(10,0); int new_index = target_vals[index]; v[new_index] = 1; return v; } void MNIST_Training_module :: training_network(Network& net, std :: vector<unsigned int> topology, int epoch) { int training_vals_size = (int) _input_vals.size(); std :: vector<double> input_vals; std :: vector<double> target_vals; std :: vector<double> result_vals; int training_iteration = 0; for(int i = 0; i < training_vals_size; i++) { training_iteration++; std :: cout << std :: endl << "Iteration number: " << training_iteration << std :: endl; // get new input data and feed it forward if(_input_vals[i].size() != topology[0]) { std :: cout << "Number of inputs differs from topology[0]" << std :: endl; break; } net.feed_forward(_input_vals[i]); // collect the net's actual results net.get_results(result_vals); Utility :: show_vector_vals(": Outputs: ", result_vals); // train the net what the outputs should have been target_vals = get_target_vals(_target_vals, i); std :: cout << "Targets: " << _target_vals[i] << std :: endl; assert(target_vals.size() == topology.back()); net.back_propagation(target_vals); double avg_error = net.get_recent_average_error(); std :: cout << "Network recent average error: " << avg_error << std :: endl; } std :: stringstream sstream; sstream << "./Weights_file/MNIST_weights_file/weights_file_" << topology[1] << "_neurons_ep_" << epoch << ".txt"; std :: string weights_file_name = sstream.str(); net.save_weights_to_file(net, topology, weights_file_name); }
30.833333
117
0.586937
[ "vector" ]
f963992a73c2636a5bdaad65bc16c726643a4f78
12,034
cpp
C++
AI project/A_star/P2_Pathfinding.cpp
DaechurJeong/Private_Proj
66eec4d22372166af7f7643a9b1307ca7e5ce21a
[ "MIT" ]
1
2020-09-18T01:55:20.000Z
2020-09-18T01:55:20.000Z
AI project/A_star/P2_Pathfinding.cpp
xjltruth/Private_Proj
14cb77afd564a4cce7b67960913d1a458cf3e61b
[ "MIT" ]
null
null
null
AI project/A_star/P2_Pathfinding.cpp
xjltruth/Private_Proj
14cb77afd564a4cce7b67960913d1a458cf3e61b
[ "MIT" ]
2
2020-04-21T23:52:31.000Z
2020-04-24T13:37:28.000Z
#include <pch.h> #include "Projects/ProjectTwo.h" #include "P2_Pathfinding.h" #pragma region Extra Credit bool ProjectTwo::implemented_floyd_warshall() { return false; } bool ProjectTwo::implemented_goal_bounding() { return false; } bool ProjectTwo::implemented_jps_plus() { return false; } #pragma endregion AStarPather::AStarPather() { } bool AStarPather::initialize() { MapNodes.reserve(MAX_MAP_SIZE * MAX_MAP_SIZE); m_heap.reserve(MAX_MAP_SIZE * MAX_MAP_SIZE); Callback cb = std::bind(&AStarPather::Map_preprocessing, this); Messenger::listen_for_message(Messages::MAP_CHANGE, cb); return true; // return false if any errors actually occur, to stop engine initialization } void AStarPather::Map_preprocessing() { MapNodes.resize(terrain.get()->get_map_height() * terrain.get()->get_map_width()); } void AStarPather::shutdown() { MapNodes.clear(); m_heap.clear(); } AStarPather::Nodes* AStarPather::GridPosToNodes(GridPos& g_pos) { return &MapNodes[g_pos.row * terrain->get_map_width() + g_pos.col]; } GridPos AStarPather::NodesToGridPos(Nodes* m_node) { int index_offset = (int)(m_node - &MapNodes[0]); GridPos result; result.row = index_offset / terrain->get_map_width(); result.col = index_offset % terrain->get_map_width(); return result; } PathResult AStarPather::compute_path(PathRequest &request) { if (request.newRequest) { start = terrain->get_grid_position(request.start); goal = terrain->get_grid_position(request.goal); if (terrain->is_wall(goal) || !terrain->is_valid_grid_position(goal)) { std::cout << "Invalid goal position\n"; return PathResult::IMPOSSIBLE; } for (auto& init : MapNodes) { init.parent.col = -1; init.parent.row = -1; init.fx = 0; init.gx = 0; init.is_closed = -1; } m_heap.clear(); Nodes* start_node = GridPosToNodes(start); m_heap.insertKey(start_node); start_node->is_closed = 0; // open list } while (m_heap.getSize()) { // Pop cheapest node off Nodes* min_node = m_heap.extractMin(); m_heap.pop(); // If node is the Goal Node, then path found if (NodesToGridPos(min_node) == goal) { // push the path into the vector PushBstSolution(min_node, request); return PathResult::COMPLETE; } // Check neighboring child nodes for (int i = 0; i < 8; ++i) { GridPos neighbor_of_curr = GetNeighbor(min_node, i); // Is it valid position? Is it wall? if (!terrain->is_valid_grid_position(neighbor_of_curr) || terrain->is_wall(neighbor_of_curr)) continue; Nodes* neighbor_node = CheckNeighbor(neighbor_of_curr, i); if (neighbor_node) { // compute cost float new_gx = min_node->gx; if (i % 2) new_gx += SQRT_OF_TWO; // diagonal else new_gx += 1.f; float new_fx = new_gx + CalculateHeuristicCost(neighbor_of_curr, request) * request.settings.weight; // If child node isn't on Open or Closed list, put it on Open List if (neighbor_node->is_closed == -1) { neighbor_node->fx = new_fx; neighbor_node->gx = new_gx; neighbor_node->parent = NodesToGridPos(min_node); m_heap.insertKey(neighbor_node); neighbor_node->is_closed = 0; if(request.settings.debugColoring) terrain->set_color(neighbor_of_curr, Colors::Aqua); } else// Open list or Closed list { // If child node is on Open or Closed list, and min_node is cheaper, // take the old expensive one off both lists and put min_node on Open list if (new_fx < neighbor_node->fx) { neighbor_node->fx = new_fx; neighbor_node->gx = new_gx; neighbor_node->parent = NodesToGridPos(min_node); if (neighbor_node->is_closed == 1) m_heap.insertKey(neighbor_node); else m_heap.decreaseKey(neighbor_node); neighbor_node->is_closed = 0; if (request.settings.debugColoring) terrain->set_color(neighbor_of_curr, Colors::Aqua); } } } } if (request.settings.debugColoring) terrain->set_color(NodesToGridPos(min_node), Colors::Yellow); // Place parent node on the Closed List min_node->is_closed = 1; // If taken too much time this frame, abort and go next frame if (request.settings.singleStep) return PathResult::PROCESSING; } // Open List empty, thus no path possible (Return fail) if (m_heap.empty()) return PathResult::IMPOSSIBLE; return PathResult::COMPLETE; } void AStarPather::PushBstSolution(Nodes* final_node, PathRequest& request) { GridPos node_as_gridpos = NodesToGridPos(final_node); if (!request.settings.rubberBanding) { while (1) { request.path.push_front(terrain->get_world_position(node_as_gridpos)); node_as_gridpos = GridPosToNodes(node_as_gridpos)->parent; if (node_as_gridpos.col < 0 || node_as_gridpos.row < 0) break; } } if (request.settings.rubberBanding && request.settings.smoothing) { Rubberbanding(request); InsertPath(request); Smoothing(request); } else if (request.settings.rubberBanding) { Rubberbanding(request); } else if (request.settings.smoothing) { Smoothing(request); } } void AStarPather::Rubberbanding(PathRequest& request) { // From goal to start, go backward GridPos start_ = goal; GridPos mid_ = GridPosToNodes(start_)->parent; GridPos end_ = GridPosToNodes(mid_)->parent; request.path.push_front(terrain->get_world_position(start_)); while (start_ != start) // last node, start_->parent == start { if (AbleToReduce(start_, end_)) // able to reduce! { if (end_.col < 0 || end_.row < 0) { request.path.push_front(terrain->get_world_position(start)); break; } mid_ = end_; end_ = GridPosToNodes(end_)->parent; GridPosToNodes(goal)->parent = mid_; } else // Wall in there, disable to reduce { if (end_.col < 0 || end_.row < 0) { request.path.push_front(terrain->get_world_position(start)); break; } request.path.push_front(terrain->get_world_position(mid_)); start_ = mid_; mid_ = end_; end_ = GridPosToNodes(end_)->parent; } } } void AStarPather::InsertPath(PathRequest& request) { auto start_ = request.path.begin(); auto end_ = start_; ++end_; while (end_ != request.path.end()) { // check once, then next step PreventOutrange(request, start_); start_ = end_; ++end_; } } void AStarPather::PreventOutrange(PathRequest& request, WaypointList::iterator& pivot) { auto end_it = pivot; ++end_it; float distance = Vec3::DistanceSquared(*pivot, *end_it); float min_dist = terrain->mapSizeInWorld / terrain->get_map_height() * 1.5f; if (distance > min_dist * min_dist) { Vec3 loc = *pivot; loc += (*end_it - *pivot) * 0.5f; request.path.insert(end_it, loc); auto aft_pivot = pivot; ++aft_pivot; PreventOutrange(request, pivot); // partition PreventOutrange(request, aft_pivot); } else return; } bool AStarPather::AbleToReduce(GridPos& start_, GridPos& end_) { int xDiff = abs(end_.col - start_.col); int yDiff = abs(end_.row - start_.row); int xDirection = 0, yDirection = 0; GridPos checkPoint = start_; if (xDiff) { if (end_.col - start_.col == xDiff) xDirection = 1; else xDirection = -1; } if (yDiff) { if (end_.row - start_.row == yDiff) yDirection = 1; else yDirection = -1; } if (xDiff != 0 && yDiff != 0) { for (int i = 0; i <= xDiff; ++i) { for (int i = 0; i <= yDiff; ++i) { if (checkPoint.row < 0 || checkPoint.col < 0) // invalid break; else if (terrain->is_wall(checkPoint)) return false; checkPoint.row += yDirection; } checkPoint.col += xDirection; checkPoint.row = start_.row; } } else if (xDiff == 0) { for (int i = 0; i <= yDiff; ++i) { if (checkPoint.row < 0) // invalid break; else if (terrain->is_wall(checkPoint)) return false; checkPoint.row += yDirection; } } else if (yDiff == 0) { for (int i = 0; i <= xDiff; ++i) { if (checkPoint.col < 0) // invalid break; else if (terrain->is_wall(checkPoint)) return false; checkPoint.col += xDirection; } } return true; } Vec3 AStarPather::CatmullRom_Spline(Vec3& point_1, Vec3& point_2, Vec3& point_3, Vec3& point_4, float s) { Vec3 output_point = point_1 * (-0.5f*s*s*s + s * s - 0.5f*s) + point_2 * (1.5f*s*s*s - 2.5f*s*s + 1.0f) + point_3 * (-1.5f*s*s*s + 2.0f*s*s + 0.5f*s) + point_4 * (0.5f*s*s*s - 0.5f*s*s); return output_point; } void AStarPather::Smoothing(PathRequest& request) { if (!request.path.size()) return; size_t size_ = request.path.size(); auto begin = request.path.begin(); auto prev_mid = begin; if((int)size_ > 1) ++prev_mid; auto aft_mid = prev_mid; if((int)size_ > 2) ++aft_mid; auto end = aft_mid; if ((int)size_ > 3) ++end; WaypointList::iterator points_loc = aft_mid; Vec3 out_point; while (*prev_mid != terrain->get_world_position(goal)) { std::vector<Vec3> vec_list; vec_list.push_back(CatmullRom_Spline(*begin, *prev_mid, *aft_mid, *end, 0.25f)); vec_list.push_back(CatmullRom_Spline(*begin, *prev_mid, *aft_mid, *end, 0.5f)); vec_list.push_back(CatmullRom_Spline(*begin, *prev_mid, *aft_mid, *end, 0.75f)); request.path.insert(points_loc, vec_list.begin(), vec_list.end()); begin = prev_mid; prev_mid = aft_mid; aft_mid = end; if (*end != terrain->get_world_position(goal)) ++end; points_loc = aft_mid; } } GridPos AStarPather::GetNeighbor(Nodes* currNode, int index) { GridPos currPos = NodesToGridPos(currNode); if (index == 0) { // upper currPos.row += 1; } else if (index == 1) { // up-right diagonal currPos.col += 1; currPos.row += 1; } else if (index == 2) { // right currPos.col += 1; } else if (index == 3) { // bot-right diagonal currPos.row -= 1; currPos.col += 1; } else if (index == 4) { // bottom currPos.row -= 1; } else if (index == 5) { // bot-left diagonal currPos.row -= 1; currPos.col -= 1; } else if (index == 6) { // left currPos.col -= 1; } else if (index == 7) { // up-left diagonal currPos.row += 1; currPos.col -= 1; } return currPos; } AStarPather::Nodes* AStarPather::CheckNeighbor(GridPos& neighborPos, int index) { GridPos neighbor_v_check = neighborPos; GridPos neighbor_h_check = neighborPos; if (index == 1) { // up-right diagonal neighbor_h_check.row -= 1; neighbor_v_check.col -= 1; } else if (index == 3) { // bottom-right diagonal neighbor_v_check.col -= 1; neighbor_h_check.row += 1; } else if (index == 5) { // bottom-left diagonal neighbor_v_check.col += 1; neighbor_h_check.row += 1; } else if (index == 7) { // left-up diagonal neighbor_v_check.col += 1; neighbor_h_check.row -= 1; } // Check the neighbor is valid & not wall if ((!terrain->is_valid_grid_position(neighbor_v_check) || terrain->is_wall(neighbor_v_check)) || (!terrain->is_valid_grid_position(neighbor_h_check) || terrain->is_wall(neighbor_h_check))) return nullptr; // Check finish. return original position return GridPosToNodes(neighborPos); } float AStarPather::CalculateHeuristicCost(GridPos& currPos, PathRequest& request) { Heuristic currStatus = request.settings.heuristic; float xDiff = static_cast<float>(abs(currPos.row - goal.row)); float yDiff = static_cast<float>(abs(currPos.col - goal.col)); if (currStatus == Heuristic::EUCLIDEAN) { // sqrt((xDiff)^2 + (yDiff)^2) return (sqrt(static_cast<float>(pow(abs(xDiff), 2) + pow(abs(yDiff), 2)))); } else if (currStatus == Heuristic::OCTILE) { // min(xDiff, yDiff) * sqrt(2) + max(xDiff, yDiff) - min(xDiff, yDiff) return std::min(xDiff, yDiff) * SQRT_OF_TWO_MINUS_ONE + std::max(xDiff, yDiff); } else if (currStatus == Heuristic::CHEBYSHEV) { // max(xDiff, yDiff) return static_cast<float>(std::max(abs(xDiff), abs(yDiff))); } else if (currStatus == Heuristic::MANHATTAN) { // xDiff + yDiff return static_cast<float>(abs((xDiff - goal.row)) + abs((yDiff))); } // default Octile return std::min(xDiff, yDiff) * SQRT_OF_TWO_MINUS_ONE + std::max(xDiff, yDiff); } void AStarPather::swap(Nodes& a, Nodes& b) { Nodes temp = a; a = b; b = temp; }
25.495763
104
0.672096
[ "vector" ]
f9658b6d794a02cceea972bea47fa8647b580245
19,839
cpp
C++
dilithium_utils.cpp
GerHobbelt/cryptopp
138a293696d48f26feb5f27426baa5a7e797524b
[ "BSL-1.0" ]
null
null
null
dilithium_utils.cpp
GerHobbelt/cryptopp
138a293696d48f26feb5f27426baa5a7e797524b
[ "BSL-1.0" ]
null
null
null
dilithium_utils.cpp
GerHobbelt/cryptopp
138a293696d48f26feb5f27426baa5a7e797524b
[ "BSL-1.0" ]
null
null
null
/* * Miscellaneous utility functions for Dilithium. Adapted by Julius Hekkala * from the public-domain reference * implementation of Dilithium by the CRYSTALS team * (https://github.com/pq-crystals/dilithium) */ #include "pch.h" #include "dilithium.h" #include "osrng.h" NAMESPACE_BEGIN(CryptoPP) // The Keccak core function extern void KeccakF1600(word64 *state); /** * Get random bytes in a byte array the size of outLen. * Uses Crypto++'s AutoSeededRandomPool (osrng.h). */ void Dilithium::RandomBytes(byte *out, size_t outLen) { AutoSeededRandomPool rng; rng.GenerateBlock(out, outLen); } /* For finite field element a, compute a0, a1 such that * a mod Q = a1*2^D + a0 with -2^{D-1} < a0 <= 2^{D-1}. * Assumes a to be standard representative. * Arguments: - word32 a: input element * - word32 *a0: pointer to output element Q + a0 * * Returns a1. */ word32 Dilithium::Power2Round(word32 a, word32 *a0) { sword32 t; /* Centralized remainder mod 2^D */ t = a & ((1U << mD) - 1); t -= (1U << (mD-1)) + 1; t += (t >> 31) & (1U << mD); t -= (1U << (mD-1)) - 1; *a0 = mQ + t; a = (a - t) >> mD; return a; } /* For finite field element a, compute high and low bits a0, a1 such * that a mod Q = a1*ALPHA + a0 with -ALPHA/2 < a0 <= ALPHA/2 except * if a1 = (Q-1)/ALPHA where we set a1 = 0 and * -ALPHA/2 <= a0 = a mod Q - Q < 0. Assumes a to be standard * representative. * Arguments: - word32 a: input element * - word32 *a0: pointer to output element Q + a0 * * Returns a1. */ word32 Dilithium::Decompose(word32 a, word32 *a0) { sword32 t, u; /* Centralized remainder mod ALPHA */ t = a & 0x7FFFF; t += (a >> 19) << 9; t -= mAlpha/2 + 1; t += (t >> 31) & mAlpha; t -= mAlpha/2 - 1; a -= t; /* Divide by ALPHA (possible to avoid) */ u = a - 1; u >>= 31; a = (a >> 19) + 1; a -= u & 1; /* Border case */ *a0 = mQ + t - (a >> 4); a &= 0xF; return a; } /* Compute hint bit indicating whether the low bits of the * input element overflow into the high bits. Inputs assumed to be * standard representatives. * Arguments: - word32 a0: low bits of input element * - word32 a1: high bits of input element * * Returns 1 if high bits of a and b differ and 0 otherwise. */ word32 Dilithium::MakeHint(word32 a0, word32 a1) { if(a0 <= mGamma2 || a0 > mQ - mGamma2 || (a0 == mQ - mGamma2 && a1 == 0)) return 0; return 1; } /* Correct high bits according to hint. * Arguments: - word32 a: input element * - word32 hint: hint bit * * Returns corrected high bits. */ word32 Dilithium::UseHint(word32 a, word32 hint) { word32 a0, a1; a1 = Decompose(a, &a0); if(hint == 0) return a1; else if(a0 > mQ) return (a1 + 1) & 0xF; else return (a1 - 1) & 0xF; //Note: This was commented out in the reference implementation /* If decompose does not divide out ALPHA: if(hint == 0) return a1; else if(a0 > Q) return (a1 + ALPHA) % (Q - 1); else return (a1 - ALPHA) % (Q - 1); */ } /* * Bit-pack public key pk = (rho, t1). * Arguments: - byte *pk: pointer to output byte array * - const byte *rho: pointer to byte array containing rho * - const polyvec *t1: pointer to vector t1 */ void Dilithium::PackPk(byte *pk, const byte *rho, const polyvec *t1) { word32 i; for(i = 0; i < mSeedBytes; ++i) pk[i] = rho[i]; pk += mSeedBytes; for(i = 0; i < mK; ++i) Polyt1Pack(pk + i*mPolyt1PackedBytes, &t1->at(i)); } /* * Unpack public key pk = (rho, t1). * Arguments: - const byte *rho: pointer to output byte array for rho * - const polyvec *t1: pointer to output vector t1 * - byte *pk: byte array containing bit-packed pk */ void Dilithium::UnpackPk(byte *rho, polyvec *t1, const byte *pk) { unsigned int i; for(i = 0; i < mSeedBytes; ++i) rho[i] = pk[i]; pk += mSeedBytes; for(i = 0; i < mK; ++i) Polyt1Unpack(&t1->at(i), pk + i*mPolyt1PackedBytes); } /* * Bit-pack secret key sk = (rho, key, tr, s1, s2, t0). * * Arguments: - byte *sk: pointer to output byte array * - const byte *rho: pointer to byte array containing rho * - const byte *key: pointer to byte array containing key * - const byte *tr: byte array containing tr * - const polyvec *s1: pointer to vector s1 * - const polyvec *s2: pointer to vector s2 * - const polyvec *t0: pointer to vector t0 */ void Dilithium::PackSk(byte *sk, const byte *rho, const byte *key, const byte *tr, const polyvec *s1, const polyvec *s2, const polyvec *t0) { word32 i; for(i = 0; i < mSeedBytes; ++i) sk[i] = rho[i]; sk += mSeedBytes; for(i = 0; i < mSeedBytes; ++i) sk[i] = key[i]; sk += mSeedBytes; for(i = 0; i < mCrhBytes; ++i) sk[i] = tr[i]; sk += mCrhBytes; for(i = 0; i < mL; ++i) PolyEtaPack(sk + i*mPolyEtaPackedBytes, &s1->at(i)); sk += mL*mPolyEtaPackedBytes; for(i = 0; i < mK; ++i) PolyEtaPack(sk + i*mPolyEtaPackedBytes, &s2->at(i)); sk += mK*mPolyEtaPackedBytes; for(i = 0; i < mK; ++i) Polyt0Pack(sk + i*mPolyt0PackedBytes, &t0->at(i)); } /* Unpack secret key sk = (rho, key, tr, s1, s2, t0). * Arguments: - const byte *rho: pointer to output byte array for rho * - const byte *key: pointer to output byte array for key * - const byte *tr: pointer to output byte array for tr * - const polyvec *s1: pointer to output vector s1 * - const polyvec *s2: pointer to output vector s2 * - const polyvec *r0: pointer to output vector t0 * - byte *sk: byte array containing bit-packed sk */ void Dilithium::UnpackSk(byte *rho, byte *key, byte *tr, polyvec *s1, polyvec *s2, polyvec *t0, const byte *sk) { word32 i; for(i = 0; i < mSeedBytes; ++i) rho[i] = sk[i]; sk += mSeedBytes; for(i = 0; i < mSeedBytes; ++i) key[i] = sk[i]; sk += mSeedBytes; for(i = 0; i < mCrhBytes; ++i) tr[i] = sk[i]; sk += mCrhBytes; for(i=0; i < mL; ++i) PolyEtaUnpack(&s1->at(i), sk + i*mPolyEtaPackedBytes); sk += mL*mPolyEtaPackedBytes; for(i=0; i < mK; ++i) PolyEtaUnpack(&s2->at(i), sk + i*mPolyEtaPackedBytes); sk += mK*mPolyEtaPackedBytes; for(i=0; i < mK; ++i) Polyt0Unpack(&t0->at(i), sk + i*mPolyt0PackedBytes); } /* Bit-pack signature sig = (z, h, c). * Arguments: - byte *sig: pointer to output byte array * - const polyvec *z: pointer to vector z * - const polyvec *h: pointer to hint vector h * - const poly *c: pointer to challenge polynomial */ void Dilithium::PackSig(byte *sig, const polyvec *z, const polyvec *h, const poly *c) { word32 i, j, k; word64 signs, mask; for(i = 0; i < mL; ++i) PolyzPack(sig + i*mPolyzPackedBytes, &z->at(i)); sig += mL*mPolyzPackedBytes; /* Encode h */ k = 0; for(i = 0; i < mK; ++i) { for(j = 0; j < mN; ++j) if(h->at(i).at(j) != 0) sig[k++] = j; sig[mOmega + i] = k; } while(k < mOmega) sig[k++] = 0; sig += mOmega + mK; /* Encode c */ signs = 0; mask = 1; for(i = 0; i < mN/8; ++i) { sig[i] = 0; for(j = 0; j < 8; ++j) { if(c->at(8*i+j) != 0) { sig[i] |= (1U << j); if(c->at(8*i+j) == (mQ - 1)) signs |= mask; mask <<= 1; } } } sig += mN/8; for(i = 0; i < 8; ++i) sig[i] = signs >> 8*i; } /* Unpack signature sig = (z, h, c). * Arguments: - polyvec *z: pointer to output vector z * - polyvec *h: pointer to output hint vector h * - poly *c: pointer to output challenge polynomial * - const byte *sig: pointer to byte array containing * bit-packed signature * * Returns 1 in case of malformed signature; otherwise 0. */ int Dilithium::UnpackSig(polyvec *z, polyvec *h, poly *c, const byte *sig) { word32 i, j, k; word64 signs; for(i = 0; i < mL; ++i) PolyzUnpack(&z->at(i), sig + i*mPolyzPackedBytes); sig += mL*mPolyzPackedBytes; /* Decode h */ k = 0; for(i = 0; i < mK; ++i) { for(j = 0; j < mN; ++j) h->at(i).at(j) = 0; if(sig[mOmega + i] < k || sig[mOmega + i] > mOmega) return 1; for(j = k; j < sig[mOmega + i]; ++j) { /* Coefficients are ordered for strong unforgeability */ if(j > k && sig[j] <= sig[j-1]) return 1; h->at(i).at(sig[j]) = 1; } k = sig[mOmega + i]; } /* Extra indices are zero for strong unforgeability */ for(j = k; j < mOmega; ++j) if(sig[j]) return 1; sig += mOmega + mK; /* Decode c */ for(i = 0; i < mN; ++i) c->at(i) = 0; signs = 0; for(i = 0; i < 8; ++i) signs |= (uint64_t)sig[mN/8+i] << 8*i; /* Extra sign bits are zero for strong unforgeability */ if(signs >> 60) return 1; for(i = 0; i < mN/8; ++i) { for(j = 0; j < 8; ++j) { if((sig[i] >> j) & 0x01) { c->at(8*i+j) = 1; c->at(8*i+j) ^= -(signs & 1) & (1 ^ (mQ-1)); signs >>= 1; } } } return 0; } /* * For finite field element a with 0 <= a <= Q*2^32, * compute r \equiv a*2^{-32} (mod Q) such that 0 <= r < 2*Q. * Arguments: - word64: finite field element a * * Returns r. */ word32 Dilithium::MontgomeryReduce(word64 a) { word64 t; t = a * mQInv; t &= ((word64)1 << 32) - 1; t *= mQ; t = a + t; t >>= 32; return t; } /* * For finite field element a, compute r \equiv a (mod Q) * such that 0 <= r < 2*Q. * Arguments: - word32: finite field element a * * Returns r. */ word32 Dilithium::Reduce32(word32 a) { word32 t; t = a & 0x7FFFFF; a >>= 23; t += (a << 13) - a; return t; } /* * Subtract Q if input coefficient is bigger than Q. * * Arguments: - word32: finite field element a * * Returns r. */ word32 Dilithium::CSubQ(word32 a) { a -= mQ; a += ((sword32)a >> 31) & mQ; return a; } /* * For finite field element a, compute standard * representative r = a mod Q. * Arguments: - word32: finite field element a * * Returns r. */ word32 Dilithium::Freeze(word32 a) { a = Reduce32(a); a = CSubQ(a); return a; } /* * Initiate Shake-128 Stream. * Arguments: - *keccakState * * */ void Dilithium::Shake128StreamInit(keccakState *state, const byte *seed, word16 nonce) { byte t[2]; t[0] = nonce; t[1] = nonce >> 8; Shake128Init(state); Shake128Absorb(state, seed, mSeedBytes); Shake128Absorb(state, t, 2); Shake128Finalize(state); } void Dilithium::Shake256StreamInit(keccakState *state, const byte *seed, word16 nonce) { byte t[2]; t[0] = nonce; t[1] = nonce >> 8; Shake256Init(state); Shake256Absorb(state, seed, mCrhBytes); Shake256Absorb(state, t, 2); Shake256Finalize(state); } #define NROUNDS 24 #define ROL(a, offset) ((a << offset) ^ (a >> (64-offset))) /* * Load 8 bytes into word64 in little-endian order * * Arguments: - const byte *x: pointer to input byte array * * Returns the loaded 64-bit unsigned integer **************************************************/ static word64 Load64(const byte x[8]) { word32 i; word64 r = 0; for(i=0;i<8;i++) r |= (word64)x[i] << 8*i; return r; } //TODO: JATKA TÄSTÄ MA /* * Store a 64-bit integer to array of 8 bytes in little-endian order * * Arguments: - byte *x: pointer to the output byte array (allocated) * - byte u: input 64-bit unsigned integer */ static void Store64(byte x[8], word64 u) { word32 i; for(i=0;i<8;i++) x[i] = u >> 8*i; } /* * Initializes the Keccak state. * * Arguments: - keccakState *state: pointer to Keccak state */ void Dilithium::KeccakInit(keccakState *state) { word32 i; for(i=0;i<25;i++) state->s[i] = 0; state->pos = 0; } /* * Absorb step of Keccak; incremental. * * Arguments: - word64 *s: pointer to Keccak state * - word32 r: rate in bytes (e.g., 168 for SHAKE128) * - word32 pos: position in current block to be absorbed * - const byte *m: pointer to input to be absorbed into s * - size_t mlen: length of input in bytes * * Returns new position pos in current block */ word32 Dilithium::KeccakAbsorb(word64 s[25], word32 r, word32 pos, const byte *m, size_t mlen) { word32 i; byte t[8] = {0}; if(pos & 7) { i = pos & 7; while(i < 8 && mlen > 0) { t[i++] = *m++; mlen--; pos++; } s[(pos-i)/8] ^= Load64(t); } if(pos && mlen >= r-pos) { for(i=0;i<(r-pos)/8;i++) s[pos/8+i] ^= Load64(m+8*i); m += r-pos; mlen -= r-pos; pos = 0; KeccakF1600(s); } while(mlen >= r) { for(i=0;i<r/8;i++) s[i] ^= Load64(m+8*i); m += r; mlen -= r; KeccakF1600(s); } for(i=0;i<mlen/8;i++) s[pos/8+i] ^= Load64(m+8*i); m += 8*i; mlen -= 8*i; pos += 8*i; if(mlen) { for(i=0;i<8;i++) t[i] = 0; for(i=0;i<mlen;i++) t[i] = m[i]; s[pos/8] ^= Load64(t); pos += mlen; } return pos; } /* * Finalize absorb step. * * Arguments: - word64 *s: pointer to Keccak state * - word32 r: rate in bytes (e.g., 168 for SHAKE128) * - word32 pos: position in current block to be absorbed * - byte p: domain separation byte */ void Dilithium::KeccakFinalize(word64 s[25], word32 r, word32 pos, byte p) { word32 i,j; i = pos >> 3; j = pos & 7; s[i] ^= (uint64_t)p << 8*j; s[r/8-1] ^= 1ULL << 63; } /* * Squeeze step of Keccak. Squeezes full blocks of r bytes each. * Modifies the state. Can be called multiple times to keep * squeezing, i.e., is incremental. Assumes zero bytes of current * block have already been squeezed. * * Arguments: - byte *out: pointer to output blocks * - size_t nBlocks: number of blocks to be squeezed (written to out) * - word64 *s: pointer to input/output Keccak state * - word32 r: rate in bytes (e.g., 168 for SHAKE128) */ void Dilithium::KeccakSqueezeBlocks(byte *out, size_t nBlocks, word64 s[25], word32 r) { word32 i; while(nBlocks > 0) { KeccakF1600(s); for(i=0;i<r/8;i++) Store64(out + 8*i, s[i]); out += r; nBlocks--; } } /* * Squeeze step of Keccak. Squeezes arbitratrily many bytes. * Modifies the state. Can be called multiple times to keep * squeezing, i.e., is incremental. * * Arguments: - byte *out: pointer to output * - size_t outLen: number of bytes to be squeezed (written to out) * - word64 *s: pointer to input/output Keccak state * - word32 r: rate in bytes (e.g., 168 for SHAKE128) * - word32 pos: number of bytes in current block already squeezed * * Returns new position pos in current block */ unsigned int Dilithium::KeccakSqueeze(byte *out, size_t outLen, word64 s[25], word32 r, word32 pos) { word32 i; byte t[8]; if(pos & 7) { Store64(t,s[pos/8]); i = pos & 7; while(i < 8 && outLen > 0) { *out++ = t[i++]; outLen--; pos++; } } if(pos && outLen >= r-pos) { for(i=0;i<(r-pos)/8;i++) Store64(out+8*i,s[pos/8+i]); out += r-pos; outLen -= r-pos; pos = 0; } while(outLen >= r) { KeccakF1600(s); for(i=0;i<r/8;i++) Store64(out+8*i,s[i]); out += r; outLen -= r; } if(!outLen) return pos; else if(!pos) KeccakF1600(s); for(i=0;i<outLen/8;i++) Store64(out+8*i,s[pos/8+i]); out += 8*i; outLen -= 8*i; pos += 8*i; Store64(t,s[pos/8]); for(i=0;i<outLen;i++) out[i] = t[i]; pos += outLen; return pos; } /* * Initilizes Keccak state for use as SHAKE128 XOF * * Arguments: - keccakState *state: pointer to (uninitialized) * Keccak state */ void Dilithium::Shake128Init(keccakState *state) { KeccakInit(state); } /* * Absorb step of the SHAKE128 XOF; incremental. * * Arguments: - keccakState *state: pointer to (initialized) output * Keccak state * - const byte *in: pointer to input to be absorbed into s * - size_t inLen: length of input in bytes */ void Dilithium::Shake128Absorb(keccakState *state, const byte *in, size_t inLen) { state->pos = KeccakAbsorb(state->s, SHAKE128_RATE, state->pos, in, inLen); } /* * Finalize absorb step of the SHAKE128 XOF. * * Arguments: - keccakState *state: pointer to Keccak state */ void Dilithium::Shake128Finalize(keccakState *state) { KeccakFinalize(state->s, SHAKE128_RATE, state->pos, 0x1F); state->pos = 0; } /* * Squeeze step of SHAKE128 XOF. Squeezes full blocks of * SHAKE128_RATE bytes each. Can be called multiple times * to keep squeezing. Assumes zero bytes of current block * have already been squeezed (state->pos = 0). * * Arguments: - byte *out: pointer to output blocks * - size_t nbBocks: number of blocks to be squeezed (written to output) * - keccakState *s: pointer to input/output Keccak state */ void Dilithium::Shake128SqueezeBlocks(byte *out, size_t nBlocks, keccakState *state) { KeccakSqueezeBlocks(out, nBlocks, state->s, SHAKE128_RATE); } /* * Squeeze step of SHAKE128 XOF. Squeezes arbitraily many * bytes. Can be called multiple times to keep squeezing. * * Arguments: - byte *out: pointer to output blocks * - size_t outlen : number of bytes to be squeezed * (written to output) * - keccakState *s: pointer to input/output Keccak state **************************************************/ void Dilithium::Shake128Squeeze(byte *out, size_t outLen, keccakState *state) { state->pos = KeccakSqueeze(out, outLen, state->s, SHAKE128_RATE, state->pos); } /* * Initilizes Keccak state for use as SHAKE256 XOF * * Arguments: - keccakState *state: pointer to (uninitialized) Keccak state */ void Dilithium::Shake256Init(keccakState *state) { KeccakInit(state); } /* * Absorb step of the SHAKE256 XOF; incremental. * * Arguments: - keccakState *state: pointer to (initialized) output Keccak state * - const byte *in: pointer to input to be absorbed into s * - size_t inLen: length of input in bytes */ void Dilithium::Shake256Absorb(keccakState *state, const byte *in, size_t inLen) { state->pos = KeccakAbsorb(state->s, SHAKE256_RATE, state->pos, in, inLen); } /* * Finalize absorb step of the SHAKE256 XOF. * * Arguments: - keccakState *state: pointer to Keccak state */ void Dilithium::Shake256Finalize(keccakState *state) { KeccakFinalize(state->s, SHAKE256_RATE, state->pos, 0x1F); state->pos = 0; } /* * Squeeze step of SHAKE256 XOF. Squeezes full blocks of * SHAKE256_RATE bytes each. Can be called multiple times * to keep squeezing. Assumes zero bytes of current block * have already been squeezed (state->pos = 0). * * Arguments: - byte *out: pointer to output blocks * - size_t nBlocks: number of blocks to be squeezed * (written to output) * - keccakState *s: pointer to input/output Keccak state */ void Dilithium::Shake256SqueezeBlocks(byte *out, size_t nBlocks, keccakState *state) { KeccakSqueezeBlocks(out, nBlocks, state->s, SHAKE256_RATE); } /* * Squeeze step of SHAKE256 XOF. Squeezes arbitraily many * bytes. Can be called multiple times to keep squeezing. * * Arguments: - byte *out: pointer to output blocks * - size_t outLen : number of bytes to be squeezed * (written to output) * - keccakState *s: pointer to input/output Keccak state */ void Dilithium::Shake256Squeeze(byte *out, size_t outLen, keccakState *state) { state->pos = KeccakSqueeze(out, outLen, state->s, SHAKE256_RATE, state->pos); } NAMESPACE_END
25.176396
101
0.582993
[ "vector" ]
f96a1b08c6bb0d234dfb7e9e4c45f1d236c7f5b2
2,437
cpp
C++
Modules/Module12_Classes/C++_Spring_2020_Week11.cpp
makavaile/Butler
f63b25a10339cbf9636e69821f9e995a93915767
[ "MIT" ]
null
null
null
Modules/Module12_Classes/C++_Spring_2020_Week11.cpp
makavaile/Butler
f63b25a10339cbf9636e69821f9e995a93915767
[ "MIT" ]
1
2020-03-02T22:07:51.000Z
2020-03-02T22:07:51.000Z
Modules/Module12_Classes/C++_Spring_2020_Week11.cpp
makavaile/Butler
f63b25a10339cbf9636e69821f9e995a93915767
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; // build me a global string // add in main() send the size of the string to cout. // build a function that accepts a string // then uses a for loop to add a space in between each letter void addSpace(string input) { for(int i = 0; i < input.size(); i++) { cout << input[i] << " "; } cout << endl; } string name = "Darth Vader"; class Robot { public: static int totalRobots; void greeting() { cout << "My name is " << name << ". My charge is " << charge << ".\n"; } Robot(string givenName = "Robot", int givenCharge = 10) { cout << "\nA new robot approaches!\n"; charge = givenCharge; name = givenName; totalRobots++; // add one to total rovot count. } void SetCharge(int givenCharge) { if(givenCharge < 0) { charge = 0; } else { charge = givenCharge; } } // a constant function is read-only int GetCharge() const { return charge; } void SetName(string givenName) { name = givenName; } // member functions string GetName () const { return name; } private: int charge; // data members string name; // data members }; int Robot::totalRobots = 0; int main() { cout << "Hello World!\n"; // .size() is a member function of every string cout << "There are " << name.size() << " letters in " << name << endl; addSpace("JOIN THE DARK SIDE!!!!"); Robot cp3o; cout << "Assigning a charge to cp3o and making sure it sticks.\n"; cp3o.SetCharge(9); cout << "cp3o's charge is " << cp3o.GetCharge() << endl; cout << "Assigning a name to cp3o and making sure it sticks.\n"; cp3o.SetName("C-P3O"); cout << "cp3o's name is " << cp3o.GetName() << endl; cp3o.greeting(); Robot r2d2; cout << "Assigning a charge to r2d2 and making sure it sticks.\n"; r2d2.SetCharge(42); cout << "r2d2's charge is " << r2d2.GetCharge() << endl; cout << "Assigning a name to r2d2 and making sure it sticks.\n"; r2d2.SetName("R2-D2"); cout << "r2d2's name is " << r2d2.GetName() << endl; r2d2.greeting(); Robot ig88("IG-88", 9001); ig88.greeting(); cout << "There are " << ig88.totalRobots << " robots in the game.\n"; for(int i = 0; i < 10; i++) { Robot rob; } cout << "There are " << ig88.totalRobots << " robots in the game.\n"; vector<Robot> army; army.push_back(ig88); army.push_back(Robot("Banana Man", 256)); cout << "The second robot in our army is named " << army[1].GetName() << ".\n"; }
23.209524
80
0.630283
[ "vector" ]
f96d45136e39b919cb68b207c2746f170536e01d
2,616
hpp
C++
Game/GameGrid.hpp
millerf1234/ncurses_Tetris
63ebb423d1397ebcbb03488f9e1aa7a6dff9df9c
[ "MIT" ]
null
null
null
Game/GameGrid.hpp
millerf1234/ncurses_Tetris
63ebb423d1397ebcbb03488f9e1aa7a6dff9df9c
[ "MIT" ]
null
null
null
Game/GameGrid.hpp
millerf1234/ncurses_Tetris
63ebb423d1397ebcbb03488f9e1aa7a6dff9df9c
[ "MIT" ]
null
null
null
// // GameGrid.hpp // Tetris_Using_NCurses // // Created by Forrest Miller on 12/13/17. // Copyright © 2017 Forrest Miller. All rights reserved. // #ifndef GameGrid_hpp #define GameGrid_hpp #include <exception> #include <functional> #include "Shape.hpp" //Each coordinate on the screen will be stored within the follow struct typedef struct GridElem { //Fields (i.e. variables) int xCoor; int yCoor; int colorPair; //Default constructor GridElem() = delete; //Can't be called GridElem(int colPair, int y, int x) { this->xCoor = x; this->yCoor = y; this->colorPair = colPair; } ~GridElem() { ; //Nothing to remove from heap memory (i.e. no memory needs deallocating) } } GirdElem; //This class is for tracking shapes on the screen class GameGrid { private: //Fields //The game grid GridElem ***grid; //2D grid of GridElem pointers int rows; int cols; int topLeftCornerXOffset; int topLeftCornerYOffset; //Where the game grid exists on the screen bool topColumnIsOccupied; //Signals the game may soon be about to end //Private helper funcions //bool checkIfTopColumnIsOccupied(); //Never used bool makeBlocksFall(int row); public: GameGrid(int height, int width, int topLeftCornerOffsetY, int topLeftCornerOffsetX); ~GameGrid(); //Destructor int getColorAt(int y, int x); bool hasGridElemAt(int y, int x); //These next 2 functions should be called before trying to move a block left/right bool hasGridElemLeftOf(Shape * s); bool hasGridElemRightOf(Shape * s); bool checkForGridCollosion(Shape * s); //Checks both at and 1 space below each component of shape s //One of the two should be implemented bool checkIfRowComplete(int row); int checkForCompleteRows(void); //Return -1 if no row is complete void removeRow(int row); //This function can check to seee if moving a shape will result in a collision //Maybe make this function a friend of shape? //void hasBlockBelowCoordinate(int x, int y); //void hasBlockBelowCoordinate(int x, int y, int velocity); //In case velocity isn't one bool addShapeToGrid(Shape * s); //Use s->xOffset and s->yOffset to create GirdElem's. Also use hasBlockBelowCoordinate in main void clear(); // DEBUG TEST: completly fills grid with grid elements. see warning: //void setUpDebugTest(); //Warning!!! Don't use. Will make game crash now that full game // logic is in place. }; #endif /* GameGrid_hpp */
31.518072
130
0.673547
[ "shape" ]
f972ad53603b3016a0bc201ad34152b2cf370be3
2,124
hpp
C++
libstark/src/languages/Acsp/AcspWitness.hpp
ddsvetlov/libSTARK
38aeda615864346dc1ff4c290e0d0d12ea324dfb
[ "MIT" ]
399
2018-02-28T17:11:54.000Z
2022-03-24T07:41:39.000Z
libstark/src/languages/Acsp/AcspWitness.hpp
ddsvetlov/libSTARK
38aeda615864346dc1ff4c290e0d0d12ea324dfb
[ "MIT" ]
18
2018-03-02T14:53:53.000Z
2022-02-14T21:30:03.000Z
libstark/src/languages/Acsp/AcspWitness.hpp
ddsvetlov/libSTARK
38aeda615864346dc1ff4c290e0d0d12ea324dfb
[ "MIT" ]
90
2018-03-01T01:18:44.000Z
2022-02-23T00:28:50.000Z
/** * @file AcspWitness.hpp * @brief Header file for Acsp witness * * @author Michael Riabzev, RiabzevMichael@gmail.com * ===================================================================================== */ #pragma once // This is not needed, here just to get rid of an annoying VS2010 warning. #ifndef __Acsp_WITNESS_HPP #define __Acsp_WITNESS_HPP #include <algebraLib/PolynomialInterface.hpp> #include <memory> namespace libstark { /** * @class AcspWitness * @brief class for Acsp witness * * This class describes a witness for AcspFullInstance. * A witness is a polynomial \f$ A \in \mathbb{F}[x] \f$, * and named Assignment Polynomial. * Such a polynomial shows that\n * \f$(\mathbb{F},H,\vec{N},P,witnessDegreeBound,B)\f$ is a satisfiable AcspInstance * if and only if * \f{eqnarray*}{ * \forall z \in H: (P \circ (x \vert A \circ \vec{N}))(z) = 0 \\ * \deg A <= witnessDegreeBound \\ * \lambda \cdot \deg(P \circ (x \vert A \circ \vec{N})) \le |\mathbb{F}| \\ * \forall (x,y) \in B : A(x)=y \\ * \f} * * In the code we name the assignment polynomial \f$A\f$ * simply 'assignmentPoly' * * Methods: * Witness class contains only getters, * an empty constructor and a destructor. * The only possible way to change its data members * is using the reduction class from EGCP or inside a UTEST. */ class AcspWitness { public: typedef Algebra::UnivariatePolynomialInterface polynomial; typedef std::unique_ptr<const polynomial> poly_ptr; typedef std::vector<poly_ptr> poly_vec; AcspWitness(poly_ptr&& assignmentPoly):assignmentPolys_(1){ assignmentPolys_[0] = std::move(assignmentPoly); } AcspWitness(poly_vec&& assignmentPolys):assignmentPolys_(std::move(assignmentPolys)){}; AcspWitness(AcspWitness&& src) = default; AcspWitness(const AcspWitness& src) = delete; inline const polynomial& assignmentPoly() const { return *(assignmentPolys_[0]); } inline const poly_vec& assignmentPolys() const { return assignmentPolys_; } private: poly_vec assignmentPolys_; }; } //namespace libstark #endif //__Acsp_WITNESS_HPP
28.32
88
0.669962
[ "vector" ]
f989db3d16c6929b5aa60b83c06ebb7a22d1713e
1,821
cpp
C++
aws-cpp-sdk-personalize-events/source/model/Event.cpp
neil-b/aws-sdk-cpp
1602b75abbca880b770c12788f6d2bac0c87176a
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-personalize-events/source/model/Event.cpp
neil-b/aws-sdk-cpp
1602b75abbca880b770c12788f6d2bac0c87176a
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-personalize-events/source/model/Event.cpp
neil-b/aws-sdk-cpp
1602b75abbca880b770c12788f6d2bac0c87176a
[ "Apache-2.0" ]
1
2020-11-04T03:18:11.000Z
2020-11-04T03:18:11.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/personalize-events/model/Event.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace PersonalizeEvents { namespace Model { Event::Event() : m_eventIdHasBeenSet(false), m_eventTypeHasBeenSet(false), m_propertiesHasBeenSet(false), m_sentAtHasBeenSet(false) { } Event::Event(JsonView jsonValue) : m_eventIdHasBeenSet(false), m_eventTypeHasBeenSet(false), m_propertiesHasBeenSet(false), m_sentAtHasBeenSet(false) { *this = jsonValue; } Event& Event::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("eventId")) { m_eventId = jsonValue.GetString("eventId"); m_eventIdHasBeenSet = true; } if(jsonValue.ValueExists("eventType")) { m_eventType = jsonValue.GetString("eventType"); m_eventTypeHasBeenSet = true; } if(jsonValue.ValueExists("properties")) { m_properties = jsonValue.GetString("properties"); m_propertiesHasBeenSet = true; } if(jsonValue.ValueExists("sentAt")) { m_sentAt = jsonValue.GetDouble("sentAt"); m_sentAtHasBeenSet = true; } return *this; } JsonValue Event::Jsonize() const { JsonValue payload; if(m_eventIdHasBeenSet) { payload.WithString("eventId", m_eventId); } if(m_eventTypeHasBeenSet) { payload.WithString("eventType", m_eventType); } if(m_propertiesHasBeenSet) { payload.WithString("properties", m_properties); } if(m_sentAtHasBeenSet) { payload.WithDouble("sentAt", m_sentAt.SecondsWithMSPrecision()); } return payload; } } // namespace Model } // namespace PersonalizeEvents } // namespace Aws
17.509615
69
0.705107
[ "model" ]
f9916cbc240f6db5c556e382df5444aa897dc5fd
1,535
cc
C++
components/arc/compat_mode/overlay_dialog_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
components/arc/compat_mode/overlay_dialog_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
components/arc/compat_mode/overlay_dialog_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/arc/compat_mode/overlay_dialog.h" #include <memory> #include "base/bind.h" #include "base/test/bind.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/test/views_test_base.h" namespace arc { class OverlayDialogTest : public views::ViewsTestBase { public: std::unique_ptr<OverlayDialog> CreateTestOverlayDialog( base::OnceClosure closing_callback, std::unique_ptr<views::View> dialog_view) { return base::WrapUnique( new OverlayDialog(std::move(closing_callback), std::move(dialog_view))); } }; TEST_F(OverlayDialogTest, ShowAndClose) { std::vector<std::unique_ptr<views::View>> dialog_views; dialog_views.push_back(nullptr); dialog_views.push_back(std::make_unique<views::View>()); for (auto& dialog_view : dialog_views) { const bool has_dialog_view = !!dialog_view; auto widget = CreateTestWidget(); bool called = false; widget->SetContentsView(CreateTestOverlayDialog( base::BindLambdaForTesting([&]() { called = true; }), std::move(dialog_view))); const auto& view_ax = widget->GetRootView()->GetViewAccessibility(); EXPECT_EQ(!has_dialog_view, view_ax.IsIgnored()); widget->Show(); EXPECT_FALSE(called); widget.reset(); EXPECT_TRUE(called); } } } // namespace arc
28.962264
80
0.719218
[ "vector" ]
f9917ceae4f9872a54580e1c4a9a745eb16e9297
6,059
cpp
C++
CARET_analyze_cpp_impl/src/pybind.cpp
tier4/CARET_analyze_cpp_impl
e4c6abfc3f76ef036130fc1cae4e904c685d69fd
[ "Apache-2.0" ]
null
null
null
CARET_analyze_cpp_impl/src/pybind.cpp
tier4/CARET_analyze_cpp_impl
e4c6abfc3f76ef036130fc1cae4e904c685d69fd
[ "Apache-2.0" ]
null
null
null
CARET_analyze_cpp_impl/src/pybind.cpp
tier4/CARET_analyze_cpp_impl
e4c6abfc3f76ef036130fc1cae4e904c685d69fd
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Research Institute of Systems Planning, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <vector> #include <unordered_map> #include <string> #include <map> #include <tuple> #include <memory> #include "pybind11/iostream.h" #include "pybind11/pybind11.h" #include "pybind11/stl.h" #include "pybind11/functional.h" #include "caret_analyze_cpp_impl/records.hpp" #define STRINGIFY(x) #x #define MACRO_STRINGIFY(x) STRINGIFY(x) namespace py = pybind11; PYBIND11_MODULE(record_cpp_impl, m) { py::class_<Record>(m, "RecordBase") .def(py::init()) .def( py::init( [](const Record & init) { return new Record(init); }) ) .def( py::init( [](std::unordered_map<std::string, uint64_t> init) { return new Record(init); }) ) .def( "change_dict_key", &Record::change_dict_key, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "equals", &Record::equals, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "merge", &Record::merge, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "add", &Record::add, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "drop_columns", &Record::drop_columns, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "get", &Record::get, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "get_with_default", &Record::get_with_default, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def_property_readonly( "data", &Record::get_data, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def_property_readonly( "columns", &Record::get_columns, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()); py::class_<RecordsBase>(m, "RecordsBase") .def(py::init()) .def( py::init( [](const RecordsVectorImpl & init) { return new RecordsVectorImpl(init); }) ) .def( py::init( [](std::vector<Record> init, std::vector<std::string> columns) { return new RecordsVectorImpl(init, columns); }) ) .def( "append", &RecordsBase::append, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "append_column", &RecordsBase::append_column, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "clone", &RecordsBase::clone, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "equals", &RecordsBase::equals, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "drop_columns", &RecordsBase::drop_columns, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "rename_columns", &RecordsBase::rename_columns, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "filter_if", &RecordsBase::filter_if, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "reindex", &RecordsBase::reindex, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "concat", &RecordsBase::concat, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "sort", &RecordsBase::sort, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "sort_column_order", &RecordsBase::sort_column_order, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "merge", &RecordsBase::merge, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "merge_sequencial", &RecordsBase::merge_sequencial, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "bind_drop_as_delay", &RecordsBase::bind_drop_as_delay, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "merge_sequencial_for_addr_track", &RecordsBase::merge_sequencial_for_addr_track, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "groupby", static_cast<std::map<std::tuple<uint64_t>, std::unique_ptr<RecordsBase>>(RecordsBase::*)(std::string)>(&RecordsBase::groupby), py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "groupby", static_cast<std::map<std::tuple<uint64_t, uint64_t>, std::unique_ptr<RecordsBase>>(RecordsBase::*)(std::string, std::string)>(&RecordsBase::groupby), py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def( "groupby", static_cast< std::map<std::tuple<uint64_t, uint64_t, uint64_t>, std::unique_ptr<RecordsBase>>(RecordsBase::*)( std::string, std::string, std::string)>(&RecordsBase::groupby), py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def_property_readonly( "data", &RecordsBase::get_data, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()) .def_property_readonly( "columns", &RecordsBase::get_columns, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>()); #ifdef VERSION_INFO m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO); #else m.attr("__version__") = "dev"; #endif }
36.065476
100
0.705727
[ "vector" ]
f99c69aa6dc31a350d7b319abcb18732c4e4b55d
632
hpp
C++
lib/rt/Saver.hpp
craft095/sere
b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9
[ "MIT" ]
null
null
null
lib/rt/Saver.hpp
craft095/sere
b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9
[ "MIT" ]
null
null
null
lib/rt/Saver.hpp
craft095/sere
b7ce9aafe5390a0bf48ade7ebe0a1a09bf0396b9
[ "MIT" ]
null
null
null
#ifndef RTSAVER_HPP #define RTSAVER_HPP #include "rt/Format.hpp" #include <vector> namespace rt { class Saver { private: std::vector<uint8_t>& data; protected: void writeData(const uint8_t* d, size_t len) { data.insert(data.end(), d, d + len); } template <typename T> void writeValue(const T& t) { writeData((const uint8_t*)(&t), sizeof(t)); } void savePredicate(const Predicate& phi) { writeValue(phi.size()); writeData(&phi[0], sizeof(phi[0])*phi.size()); } Saver(std::vector<uint8_t>& data_) : data(data_) {} }; } //namespace rt #endif // RTSAVER_HPP
18.057143
55
0.615506
[ "vector" ]
f99ced0c1bedb7796f55352bb14fd1ade7427601
2,764
hpp
C++
code/source/util/mesh.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
12
2015-01-12T00:19:20.000Z
2021-08-05T10:47:20.000Z
code/source/util/mesh.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
code/source/util/mesh.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
#ifndef CLOVER_UTIL_MESH_HPP #define CLOVER_UTIL_MESH_HPP #include "build.hpp" #include "dyn_array.hpp" #include "boundingbox.hpp" namespace clover { namespace util { template <typename T> struct MeshVertexTraits { typedef T BoundingBoxType; static T extractPosition(const T& v){ return v; } /// @brief Conversion, other to type T template <typename P> static T converted(const P& input){ return MeshVertexTraits<P>::extractPosition(input).template converted<T>(); } }; /** @class GenericMesh A base class for all meshes */ template <typename V, typename I> class GenericMesh { public: typedef V VType; // Vertex type typedef I IType; // Index type typedef typename MeshVertexTraits<V>::BoundingBoxType BType; // util::BoundingBox type GenericMesh(); GenericMesh(const GenericMesh&)= default; GenericMesh(GenericMesh&&)= default; GenericMesh& operator=(const GenericMesh&)= default; GenericMesh& operator=(GenericMesh&&)= default; /// Conversion to be used like converted<A,B>() template <typename VV, typename II> GenericMesh<VV, II> converted() const; /// Conversion to be used like converted<Mesh<A,B>>() template <class M> M converted() const; /// Adds a vertex to the mesh void addVertex(const VType& v); /// Adds a triangle to the mesh (also indices) void addTriangle(const VType& a, const VType& b, const VType& c); const VType& getVertex(const IType& i) const; void setVertex(const IType& i, const VType& v); void setVertices(util::DynArray<V> v); uint32 getVertexCount() const { return vertices.size(); } /// Adds a triangle between existing vertices void addTriangle(const IType& a, const IType& b, const IType& c); /// Adds a index to the mesh (remember to have indices.size() % 3 == 0) void addIndex(const IType& i); const IType& getIndex(uint32 i) const; void setIndex(uint32 i, const IType& ind); void setIndices(util::DynArray<I> i); uint32 getIndexCount() const { return indices.size(); } /// @brief If needed, calculates and returns a bounding box util::BoundingBox<BType> getBoundingBox() const; /// @brief Sets bounding box. (Not permanently) void setBoundingBox(const util::BoundingBox<BType>& bb); /// @brief Removes vertices and indices, and resets bounding box virtual void clear(); const uint32& getContentHash() const; protected: bool isDirty() const { return dirty; } void setDirty() const { dirty= true; } virtual void fixDirtyness() const; util::DynArray<VType> vertices; util::DynArray<IType> indices; // Mutables since getBoundingBox might recalculate bounding box mutable util::BoundingBox<BType> boundingBox; private: mutable bool dirty= false; mutable uint32 contentHash= 0; }; #include "mesh.tpp" } // util } // clover #endif // CLOVER_UTIL_MESH_HPP
26.834951
114
0.730463
[ "mesh" ]
f99d199f2d99bcfa03280a35bccf53851f3a8ddd
594
cpp
C++
icpcPlacementTest2020/questionA.cpp
SarveshOO7/Competitive-Programming
b8c67425f641944d87d58e37da63251ea9cbc79c
[ "MIT" ]
null
null
null
icpcPlacementTest2020/questionA.cpp
SarveshOO7/Competitive-Programming
b8c67425f641944d87d58e37da63251ea9cbc79c
[ "MIT" ]
null
null
null
icpcPlacementTest2020/questionA.cpp
SarveshOO7/Competitive-Programming
b8c67425f641944d87d58e37da63251ea9cbc79c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define rep(i, a, b) for (int i = a; i < (b); ++i) #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() typedef long long ll; typedef pair<int, int> pii; typedef vector<int> vi; int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); ll n, temp, ans=0; set< ll > s; cin>>n; vector< ll > v; for(ll i=0;i<n;i++){ cin>>temp; v.push_back(++temp); s.insert(temp); if(temp>ans) ans=temp; } ans+=v.size() - s.size() + 1; cout<<ans; }
20.482759
50
0.521886
[ "vector" ]
f9a0b69019d5aadb7739a56b5dd7e87d52bb8a0e
6,134
cpp
C++
assets/objects/actuators/WheelMotor.cpp
artfulbytes/sumobot_simulator
f2784d2ff506759019d7d5e840bd7aed591a0add
[ "MIT" ]
null
null
null
assets/objects/actuators/WheelMotor.cpp
artfulbytes/sumobot_simulator
f2784d2ff506759019d7d5e840bd7aed591a0add
[ "MIT" ]
null
null
null
assets/objects/actuators/WheelMotor.cpp
artfulbytes/sumobot_simulator
f2784d2ff506759019d7d5e840bd7aed591a0add
[ "MIT" ]
null
null
null
#include "actuators/WheelMotor.h" #include "PhysicsWorld.h" #include "components/Transforms.h" #include "components/RectComponent.h" #include "components/Body2D.h" #include "SpriteAnimation.h" #include "AssetsHelper.h" #include <glm/glm.hpp> #include <iostream> WheelMotor::WheelMotor(Scene *scene, const Specification &spec, WheelMotor::Orientation orientation, const glm::vec2 &startPosition, float startRotation) : SceneObject(scene), m_spec(spec) { assert(m_physicsWorld->getGravityType() == PhysicsWorld::Gravity::TopView); assert(spec.maxVoltage > 0); m_transformComponent = std::make_unique<RectTransform>(startPosition, glm::vec2{spec.width, spec.diameter}, startRotation); auto transform = static_cast<RectTransform *>(m_transformComponent.get()); if (spec.textureType != WheelMotor::TextureType::None) { m_animation = std::make_unique<SpriteAnimation>(1, 5, 5, 3, SpriteAnimation::Direction::Backward); m_animation->setFramesBetweenUpdates(1); m_renderableComponent = std::make_unique<RectComponent>(transform, getTextureName(orientation, spec.textureType), m_animation.get()); } else { m_renderableComponent = std::make_unique<RectComponent>(transform, glm::vec4{ 1.0f, 0.0f, 0.0f, 1.0f }); } Body2D::Specification bodySpec(true, true, spec.wheelMass + spec.loadedMass, spec.frictionCoefficient); m_physicsComponent = std::make_unique<Body2D>(*m_physicsWorld, transform, bodySpec); m_body2D = static_cast<Body2D *>(m_physicsComponent.get()); } WheelMotor::~WheelMotor() { } std::string WheelMotor::getTextureName(WheelMotor::Orientation orientation, WheelMotor::TextureType textureType) const { switch(textureType) { case WheelMotor::TextureType::Orange: switch(orientation) { case WheelMotor::Orientation::Left: return "wheel_sprite_left_orange.png"; case WheelMotor::Orientation::Right: return "wheel_sprite_right_orange.png"; } break; case WheelMotor::TextureType::Green: switch(orientation) { case WheelMotor::Orientation::Left: return "wheel_sprite_left_green.png"; case WheelMotor::Orientation::Right: return "wheel_sprite_right_green.png"; } break; case WheelMotor::TextureType::Red: switch(orientation) { case WheelMotor::Orientation::Left: return "wheel_sprite_left_red.png"; case WheelMotor::Orientation::Right: return "wheel_sprite_right_red.png"; } break; case TextureType::None: assert(0); } return ""; } void WheelMotor::setAnimation() { assert(m_animation); const float currentForwardSpeed = m_body2D->getForwardSpeed(); if (m_enabled && (currentForwardSpeed > 0.02f || m_voltageIn > 0.0f)) { m_animation->setFramesBetweenUpdates(0); m_animation->setDirection(SpriteAnimation::Direction::Backward); } else if (m_enabled && (currentForwardSpeed < -0.02f || m_voltageIn < 0.0f)) { m_animation->setFramesBetweenUpdates(0); m_animation->setDirection(SpriteAnimation::Direction::Forward); } else { m_animation->stop(); } } void WheelMotor::setVoltageIn(float voltage) { assert(abs(voltage) <= m_spec.maxVoltage); m_voltageIn = voltage; } float *WheelMotor::getVoltageLine() { return &m_voltageIn; } void WheelMotor::updateForce() { const glm::vec2 currentForwardNormal = m_body2D->getForwardNormal(); if (!m_enabled) { m_body2D->setForce(currentForwardNormal, 0.0f); return; } const float currentForwardSpeed = m_body2D->getForwardSpeed(); const float diameter = m_spec.diameter; const float angularSpeed = currentForwardSpeed / (3.14f * diameter); const float torqueApplied = m_spec.voltageInConstant * m_voltageIn - m_spec.angularSpeedConstant * angularSpeed; /* Convert torque to force (t = r * F => F = t / r) */ const float forceToApply = (torqueApplied / (diameter / 2)); m_body2D->setForce(currentForwardNormal, forceToApply); /* Apply sideway friction to mimic real wheel */ glm::vec2 lateralCancelingImpulse = -m_body2D->getLateralVelocity() * m_spec.sidewayFrictionConstant; m_body2D->setLinearImpulse(lateralCancelingImpulse); } void WheelMotor::onFixedUpdate() { if (m_animation != nullptr) { setAnimation(); } updateForce(); } void WheelMotor::setSidewayFrictionConstant(float sidewayFrictionConstant) { m_spec.sidewayFrictionConstant = sidewayFrictionConstant; } void WheelMotor::setFrictionCoefficient(float frictionCoefficient) { m_spec.frictionCoefficient = frictionCoefficient; m_body2D->setFrictionCoefficient(frictionCoefficient); } float WheelMotor::getFrictionCoefficient() const { return m_spec.frictionCoefficient; } float WheelMotor::getSidewayFrictionConstant() const { return m_spec.sidewayFrictionConstant; } void WheelMotor::setLoadedMass(float loadedMass) { assert(loadedMass >= 0); m_spec.loadedMass = loadedMass; m_body2D->setMass(m_spec.wheelMass + m_spec.loadedMass); } void WheelMotor::setMass(float mass) { assert(mass >= 0); m_spec.wheelMass = mass; m_body2D->setMass(m_spec.wheelMass + m_spec.loadedMass); } float WheelMotor::getMass() const { return m_body2D->getMass(); } void WheelMotor::setMaxVoltage(float maxVoltage) { assert(maxVoltage >= 0); m_spec.maxVoltage = maxVoltage; } void WheelMotor::setAngularSpeedConstant(float angularSpeedConstant) { assert(angularSpeedConstant >= 0); m_spec.angularSpeedConstant = angularSpeedConstant; } void WheelMotor::setVoltageInConstant(float voltageInConstant) { assert(voltageInConstant >= 0); m_spec.voltageInConstant = voltageInConstant; } float WheelMotor::getVoltageInConstant() const { return m_spec.voltageInConstant; } float WheelMotor::getMaxVoltage() const { return m_spec.maxVoltage; } float WheelMotor::getAngularSpeedConstant() const { return m_spec.angularSpeedConstant; } void WheelMotor::enable() { m_enabled = true; } void WheelMotor::disable() { m_enabled = false; }
30.366337
141
0.718944
[ "transform" ]
3903a95f6fe33901ad4d4440a118da281bb44e52
963
cpp
C++
backpack.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
264
2015-01-08T10:07:01.000Z
2022-03-26T04:11:51.000Z
backpack.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
17
2016-04-15T03:38:07.000Z
2020-10-30T00:33:57.000Z
backpack.cpp
ohmyjons/SPOJ-1
870ae3b072a3fbc89149b35fe5649a74512a8f60
[ "Unlicense" ]
127
2015-01-08T04:56:44.000Z
2022-02-25T18:40:37.000Z
// 2009-04-07 #include <iostream> #include <vector> using namespace std; inline int max(int x,int y){return x>y?x:y;} int main() { int T,VMax,N,i,j,k,V[66],I[66],u[66]; scanf("%d",&T); while (T--) { vector<int> attach[66]; scanf("%d %d",&VMax,&N); for (i=0; i<N; i++) { scanf("%d %d %d",V+i,I+i,u+i); if (u[i]) attach[u[i]-1].push_back(i); } int dp[33333]={0}; int res=0; for (i=0; i<N; i++) { if (u[i]) continue; vector<pair<int,int> > pos; for (j=0; j<(1<<(attach[i].size())); j++) { int tmpi=V[i]*I[i]; int tmpv=V[i]; for (k=0; k<attach[i].size(); k++) if (j&(1<<k)) { tmpi+=V[attach[i][k]]*I[attach[i][k]]; tmpv+=V[attach[i][k]]; } pos.push_back(make_pair(tmpv,tmpi)); } for (j=VMax; j>=0; j--) for (k=0; k<pos.size(); k++) if (j>=pos[k].first) res=max(res,dp[j]=max(dp[j],dp[j-pos[k].first]+pos[k].second)); } printf("%d\n",res); } return 0; }
20.489362
69
0.494289
[ "vector" ]
39097441a1b42423cb621caa69ce95ba26584c2d
4,944
cpp
C++
cpp/lib/graph/tree/centroid_decomposition.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
cpp/lib/graph/tree/centroid_decomposition.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
cpp/lib/graph/tree/centroid_decomposition.cpp
KATO-Hiro/atcoder-1
c2cbfcfd5c3d46ac9810ba330a37d437aa2839c2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; // -------------------------------------------------------- template<class T> bool chmax(T& a, const T b) { if (a < b) { a = b; return 1; } return 0; } #define FOR(i,l,r) for (ll i = (l); i < (r); ++i) #define REP(i,n) FOR(i,0,n) using P = pair<ll,ll>; using VP = vector<P>; using VVP = vector<VP>; using VLL = vector<ll>; using VB = vector<bool>; // -------------------------------------------------------- // References: // <https://ei1333.github.io/luzhiled/snippets/tree/centroid-decomposition.html> // <https://tjkendev.github.io/procon-library/cpp/graph/centroid-decomposition.html> // <https://atcoder.jp/contests/yahoo-procon2018-final-open/submissions/2376520> // <https://usaco.guide/problems/cses-2080-fixed-length-paths-i/solution> /** * @brief 重心分解 (Centroid Decomposition) * */ struct CentroidDecomposition { int N; vector<vector<int>> G; vector<int> sz; // 頂点 u を根とする部分木のサイズ vector<bool> centroid; // 頂点 u が重心として使用されているか CentroidDecomposition(int n) : N(n) { G.resize(N); sz.resize(N); centroid.resize(N); } // 双方向に辺を張る void add_edge(int u, int v) { assert(0 <= u && u < N); assert(0 <= v && v < N); G[u].push_back(v); G[v].push_back(u); } // 現時点の部分木のサイズを求める int dfs_sz(int u, int p) { int s = 1; for (int v : G[u]) if (v != p && !centroid[v]) { s += dfs_sz(v, u); } return sz[u] = s; } // 重心を探索する int search_centroid(int u, int p, int cc_sz) { for (int v : G[u]) if (v != p && !centroid[v]) { if (sz[v] > cc_sz / 2) { return search_centroid(v, u, cc_sz); } } return u; } // 重心分解 // - c_root : 重心の根 // - c_graph : 重心から次の重心に有向辺を張ったグラフ int build(vector<vector<int>>& c_graph) { c_graph.resize(N); auto dfs = [&](auto self, int u) -> int { int c = search_centroid(u, -1, dfs_sz(u, -1)); centroid[c] = true; for (int v : G[c]) if (!centroid[v]) { c_graph[c].push_back(self(self, v)); } centroid[c] = false; return c; }; return dfs(dfs, 0); } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout << fixed << setprecision(15); ll N, Q; cin >> N >> Q; CentroidDecomposition cd(N); const auto& G = cd.G; REP(_,N-1) { ll u, v; cin >> u >> v; u--; v--; cd.add_edge(u, v); } vector<vector<int>> c_graph; int c_root = cd.build(c_graph); vector<vector<pair<int,int>>> E(N); REP(i,Q) { ll u, k; cin >> u >> k; u--; E[u].emplace_back(k, i); } VLL ans(Q, 0); auto enumerate = [&](const VLL& cnt, const VP& dist, ll c) -> void { for (auto [v, d] : dist) { for (auto [k, i] : E[v]) { if (0 <= k-d) { ans[i] += cnt[k-d] * c; } } } }; VLL cnt_all(N,0), cnt(N,0); // 重心までの深さが d である頂点の個数 VP dist_all, dist; // (頂点, 重心までの深さ) VB c_used(N, false); // 重心として使用中か auto dfs = [&](auto self, int c) -> void { c_used[c] = true; // (1) 頂点 u, v が共に 1 つの部分木に含まれるような組 (u, v) for (auto u : c_graph[c]) { self(self, u); } // (2) 頂点 u, v が異なる部分木に含まれるような組 (u, v) // (3) 重心 c と他の頂点 u との組 (c, u) int max_depth_all = 0; cnt_all[0]++; dist_all.emplace_back(c, 0); // 重心 c の分 : (3) for (auto u : G[c]) if (!c_used[u]) { // 部分木に含まれる全頂点について,重心までの距離を計算 int max_depth = 0; auto dfs2 = [&](auto self, int u, int p, int d) -> void { cnt[d]++; dist.emplace_back(u, d); chmax(max_depth, d); for (auto v : G[u]) if (v != p && !c_used[v]) { self(self, v, u, d + 1); } }; dfs2(dfs2, u, c, 1); chmax(max_depth_all, max_depth); // 重複分を引いておく : (2)(3) で (1) を数えないようにするため enumerate(cnt, dist, -1); // マージ dist_all.insert(dist_all.end(), dist.begin(), dist.end()); for (int d = 0; d <= max_depth; d++) { cnt_all[d] += cnt[d]; } // 初期化 dist.clear(); fill(cnt.begin(), cnt.begin() + max_depth + 1, 0); } // (2)(3) の計算の本体 enumerate(cnt_all, dist_all, 1); // 初期化 dist_all.clear(); fill(cnt_all.begin(), cnt_all.begin() + max_depth_all + 1, 0); c_used[c] = false; }; dfs(dfs, c_root); REP(i,Q) { cout << ans[i] << '\n'; } return 0; } // Verify: https://atcoder.jp/contests/yahoo-procon2018-final-open/tasks/yahoo_procon2018_final_c // Others: // 1. 長さ k のパスの数え上げ // <https://cses.fi/problemset/result/2405620/>
28.251429
97
0.479976
[ "vector" ]
390bf9ea7fa0aa3e45f2f8847228edd0cfbb578d
675
hpp
C++
src/Client/Game/EntityHandler.hpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
10
2021-08-17T20:55:52.000Z
2022-03-28T00:45:14.000Z
src/Client/Game/EntityHandler.hpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
null
null
null
src/Client/Game/EntityHandler.hpp
fqhd/BuildBattle
f85ec857aa232313f4678514aa317af73c37de10
[ "MIT" ]
2
2021-07-05T18:49:56.000Z
2021-07-10T22:03:17.000Z
#pragma once #include "Entity.hpp" #include "Camera.hpp" #include <vector> #include <unordered_map> #include <SFML/Network.hpp> #include "NetworkManager.hpp" #include "Cube.hpp" #include "Shader.hpp" #include "Model.hpp" class EntityHandler { public: void init(); void update(float _deltaTime); void render(Camera& camera); void destroy(); void updateEntity(uint8_t id, const math::vec3& position, float pitch, float yaw); void removeEntity(uint8_t entity); private: void addEntity(uint8_t id, const math::vec3& position, float pitch, float yaw); //Data Structures std::unordered_map<uint8_t, Entity> m_entities; Model m_entityModel; Shader m_shader; };
18.75
83
0.742222
[ "render", "vector", "model" ]
390cbc966ba57fd1253efc7d4a358c57355ff740
51,315
cpp
C++
test/test_cluster_manager.cpp
tisuama/BaikalDB
22e414eaac9dd6150f61976df6c735d6e51ea3f3
[ "Apache-2.0" ]
2
2020-04-09T02:09:19.000Z
2021-12-23T06:56:22.000Z
test/test_cluster_manager.cpp
tisuama/BaikalDB
22e414eaac9dd6150f61976df6c735d6e51ea3f3
[ "Apache-2.0" ]
null
null
null
test/test_cluster_manager.cpp
tisuama/BaikalDB
22e414eaac9dd6150f61976df6c735d6e51ea3f3
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2018 Baidu, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "gtest/gtest.h" #include "cluster_manager.h" #include "meta_rocksdb.h" #include <gflags/gflags.h> DECLARE_string(default_logical_room); class ClusterManagerTest : public testing::Test { public: ~ClusterManagerTest() {} protected: virtual void SetUp() { _rocksdb = baikaldb::MetaRocksdb::get_instance(); if (!_rocksdb) { DB_FATAL("create rocksdb handler failed"); return; } int ret = _rocksdb->init(); if (ret != 0) { DB_FATAL("rocksdb init failed: code:%d", ret); return; } _cluster_manager = baikaldb::ClusterManager::get_instance(); butil::EndPoint addr; addr.ip = butil::my_ip(); addr.port = 8081; braft::PeerId peer_id(addr, 0); _state_machine = new baikaldb::MetaStateMachine(peer_id); _cluster_manager->set_meta_state_machine(_state_machine); } virtual void TearDown() {} baikaldb::ClusterManager* _cluster_manager; baikaldb::MetaRocksdb* _rocksdb; baikaldb::MetaStateMachine* _state_machine; }; /* * add_logic add_physical add_instance * 不开network balance,正常流程 * rolling and min pick instance */ TEST_F(ClusterManagerTest, test_add_and_drop) { _state_machine->set_global_network_segment_balance(false); baikaldb::pb::MetaManagerRequest request_logical; request_logical.set_op_type(baikaldb::pb::OP_ADD_LOGICAL); //批量增加逻辑机房 request_logical.mutable_logical_rooms()->add_logical_rooms("lg1"); request_logical.mutable_logical_rooms()->add_logical_rooms("lg2"); _cluster_manager->add_logical(request_logical, NULL); ASSERT_EQ(3, _cluster_manager->_logical_physical_map.size()); for (auto& _logical_physical : _cluster_manager->_logical_physical_map) { if (_logical_physical.first == baikaldb::FLAGS_default_logical_room) { ASSERT_EQ(1, _logical_physical.second.size()); } else { ASSERT_EQ(0, _logical_physical.second.size()); } } //增加一个逻辑机房 request_logical.mutable_logical_rooms()->clear_logical_rooms(); request_logical.mutable_logical_rooms()->add_logical_rooms("lg3"); _cluster_manager->add_logical(request_logical, NULL); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); for (auto& _logical_physical : _cluster_manager->_logical_physical_map) { if (_logical_physical.first == baikaldb::FLAGS_default_logical_room) { ASSERT_EQ(1, _logical_physical.second.size()); } else { ASSERT_EQ(0, _logical_physical.second.size()); } } //重复添加逻辑机房,报错 request_logical.mutable_logical_rooms()->clear_logical_rooms(); request_logical.mutable_logical_rooms()->add_logical_rooms("lg1"); _cluster_manager->add_logical(request_logical, NULL); //加载snapshot _cluster_manager->load_snapshot(); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); for (auto& _logical_physical : _cluster_manager->_logical_physical_map) { ASSERT_EQ(0, _logical_physical.second.size()); } ASSERT_EQ(1, _cluster_manager->_physical_info.size()); ASSERT_EQ(0, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_physical_instance_map.size()); ASSERT_EQ(0, _cluster_manager->_instance_info.size()); /* 开始测试新增物理机房 */ baikaldb::pb::MetaManagerRequest request_physical; request_physical.set_op_type(baikaldb::pb::OP_ADD_PHYSICAL); //给一个不存在的逻辑机房加物理机房,应该报错 request_physical.mutable_physical_rooms()->set_logical_room("lg4"); request_physical.mutable_physical_rooms()->add_physical_rooms("py1"); _cluster_manager->add_physical(request_physical, NULL); //增加物理机房 request_physical.mutable_physical_rooms()->set_logical_room("lg1"); request_physical.mutable_physical_rooms()->clear_physical_rooms(); request_physical.mutable_physical_rooms()->add_physical_rooms("py2"); request_physical.mutable_physical_rooms()->add_physical_rooms("py1"); _cluster_manager->add_physical(request_physical, NULL); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(3, _cluster_manager->_physical_info.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(3, _cluster_manager->_physical_instance_map.size()); for (auto& pair : _cluster_manager->_physical_info) { DB_WARNING("physical_room:%s, logical_room:%s", pair.first.c_str(), pair.second.c_str()); } for (auto& room : _cluster_manager->_logical_physical_map["lg1"]) { DB_WARNING("physical_room:%s", room.c_str()); } for (auto& pair : _cluster_manager->_physical_instance_map) { ASSERT_EQ(0, pair.second.size()); } //重复添加物理机房, 应该报错 request_physical.mutable_physical_rooms()->clear_physical_rooms(); request_physical.mutable_physical_rooms()->add_physical_rooms("py2"); _cluster_manager->add_physical(request_physical, NULL); //再添加一个物理机房 request_physical.mutable_physical_rooms()->clear_physical_rooms(); request_physical.mutable_physical_rooms()->add_physical_rooms("lg401"); _cluster_manager->add_physical(request_physical, NULL); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(4, _cluster_manager->_physical_info.size()); ASSERT_EQ(3, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(4, _cluster_manager->_physical_instance_map.size()); for (auto& pair : _cluster_manager->_physical_info) { DB_WARNING("physical_room:%s, logical_room:%s", pair.first.c_str(), pair.second.c_str()); } for (auto& room : _cluster_manager->_logical_physical_map["lg1"]) { DB_WARNING("physical_room:%s", room.c_str()); } for (auto& pair : _cluster_manager->_physical_instance_map) { ASSERT_EQ(0, pair.second.size()); } //再添加一个逻辑机房的物理机房 request_physical.mutable_physical_rooms()->clear_physical_rooms(); request_physical.mutable_physical_rooms()->set_logical_room("lg2"); request_physical.mutable_physical_rooms()->add_physical_rooms("py3"); request_physical.mutable_physical_rooms()->add_physical_rooms("py4"); _cluster_manager->add_physical(request_physical, NULL); //加载snapshot _cluster_manager->load_snapshot(); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(6, _cluster_manager->_physical_info.size()); ASSERT_EQ(0, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(6, _cluster_manager->_physical_instance_map.size()); ASSERT_EQ(0, _cluster_manager->_instance_info.size()); /* 测试增加实例 */ baikaldb::pb::MetaManagerRequest request_instance; request_instance.set_op_type(baikaldb::pb::OP_ADD_INSTANCE); request_instance.mutable_instance()->set_address("127.0.0.1:8010"); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(5000); request_instance.mutable_instance()->set_physical_room("py2"); _cluster_manager->add_instance(request_instance, NULL); //添加物理机房不存在的机器会报错 request_instance.mutable_instance()->set_address("10.101.85.30:8010"); request_instance.mutable_instance()->clear_physical_room(); request_instance.mutable_instance()->set_physical_room("py_not_exist"); _cluster_manager->add_instance(request_instance, NULL); //重复添加实例也会报错 request_instance.mutable_instance()->set_address("127.0.0.1:8010"); request_instance.mutable_instance()->clear_physical_room(); request_instance.mutable_instance()->set_physical_room("py2"); _cluster_manager->add_instance(request_instance, NULL); ASSERT_EQ(6, _cluster_manager->_physical_info.size()); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_physical_instance_map["py2"].size()); ASSERT_EQ(1, _cluster_manager->_instance_info.size()); //加载snapshot _cluster_manager->load_snapshot(); ASSERT_EQ(6, _cluster_manager->_physical_info.size()); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_physical_instance_map["py2"].size()); ASSERT_EQ(1, _cluster_manager->_instance_info.size()); /* modify_tag 给实例加tag*/ baikaldb::pb::MetaManagerRequest request_tag; request_tag.mutable_instance()->set_address("127.0.0.1:8010"); request_tag.mutable_instance()->set_resource_tag("resource_tag1"); _cluster_manager->update_instance(request_tag, NULL); _cluster_manager->load_snapshot(); /* 添加一个南京的逻辑机房, 把lg401 从lg1机房转到lg4机房 */ baikaldb::pb::MetaManagerRequest request_move; request_move.set_op_type(baikaldb::pb::OP_ADD_LOGICAL); request_move.mutable_logical_rooms()->add_logical_rooms("lg4"); _cluster_manager->add_logical(request_move, NULL); ASSERT_EQ(6, _cluster_manager->_physical_info.size()); ASSERT_EQ(5, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_physical_instance_map["py2"].size()); ASSERT_EQ(1, _cluster_manager->_instance_info.size()); _cluster_manager->load_snapshot(); ASSERT_EQ(6, _cluster_manager->_physical_info.size()); ASSERT_EQ(5, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_physical_instance_map["py2"].size()); ASSERT_EQ(1, _cluster_manager->_instance_info.size()); request_move.set_op_type(baikaldb::pb::OP_MOVE_PHYSICAL); request_move.mutable_move_physical_request()->set_physical_room("lg401"); request_move.mutable_move_physical_request()->set_old_logical_room("lg1"); request_move.mutable_move_physical_request()->set_new_logical_room("lg4"); _cluster_manager->move_physical(request_move, NULL); ASSERT_EQ(6, _cluster_manager->_physical_info.size()); ASSERT_EQ(5, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg2"].size()); ASSERT_EQ(0, _cluster_manager->_logical_physical_map["lg3"].size()); _cluster_manager->load_snapshot(); ASSERT_EQ(6, _cluster_manager->_physical_info.size()); ASSERT_EQ(5, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg2"].size()); ASSERT_EQ(0, _cluster_manager->_logical_physical_map["lg3"].size()); baikaldb::pb::MetaManagerRequest request_remove_logical; request_remove_logical.set_op_type(baikaldb::pb::OP_DROP_LOGICAL); //删除一个有物理机房的逻辑机房, 报错 request_remove_logical.mutable_logical_rooms()->add_logical_rooms("lg3"); request_remove_logical.mutable_logical_rooms()->add_logical_rooms("lg4"); _cluster_manager->drop_logical(request_remove_logical, NULL); //删除一个空的逻辑机房 request_remove_logical.mutable_logical_rooms()->clear_logical_rooms(); request_remove_logical.mutable_logical_rooms()->add_logical_rooms("lg3"); _cluster_manager->drop_logical(request_remove_logical, NULL); ASSERT_EQ(6, _cluster_manager->_physical_info.size()); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg2"].size()); _cluster_manager->load_snapshot(); ASSERT_EQ(6, _cluster_manager->_physical_info.size()); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg2"].size()); //删除物理机房 baikaldb::pb::MetaManagerRequest request_remove_physical; request_remove_physical.set_op_type(baikaldb::pb::OP_DROP_PHYSICAL); request_remove_physical.mutable_physical_rooms()->set_logical_room("lg2"); request_remove_physical.mutable_physical_rooms()->add_physical_rooms("py4"); _cluster_manager->drop_physical(request_remove_physical, NULL); ASSERT_EQ(5, _cluster_manager->_physical_info.size()); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg2"].size()); _cluster_manager->load_snapshot(); ASSERT_EQ(5, _cluster_manager->_physical_info.size()); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg2"].size()); //删除物理机房 request_remove_physical.mutable_physical_rooms()->clear_physical_rooms(); request_remove_physical.mutable_physical_rooms()->add_physical_rooms("py3"); _cluster_manager->drop_physical(request_remove_physical, NULL); ASSERT_EQ(4, _cluster_manager->_physical_info.size()); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); ASSERT_EQ(0, _cluster_manager->_logical_physical_map["lg2"].size()); _cluster_manager->load_snapshot(); ASSERT_EQ(4, _cluster_manager->_physical_info.size()); ASSERT_EQ(4, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); ASSERT_EQ(0, _cluster_manager->_logical_physical_map["lg2"].size()); //删除逻辑机房 request_remove_logical.set_op_type(baikaldb::pb::OP_DROP_LOGICAL); request_remove_logical.mutable_logical_rooms()->clear_logical_rooms(); request_remove_logical.mutable_logical_rooms()->add_logical_rooms("lg2"); _cluster_manager->drop_logical(request_remove_logical, NULL); ASSERT_EQ(4, _cluster_manager->_physical_info.size()); ASSERT_EQ(3, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); _cluster_manager->load_snapshot(); ASSERT_EQ(4, _cluster_manager->_physical_info.size()); ASSERT_EQ(3, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); //删除一个有实例的物理机房,报错 request_remove_physical.set_op_type(baikaldb::pb::OP_DROP_PHYSICAL); request_remove_physical.mutable_physical_rooms()->clear_physical_rooms(); request_remove_physical.mutable_physical_rooms()->set_logical_room("lg1"); request_remove_physical.mutable_physical_rooms()->add_physical_rooms("py2"); _cluster_manager->drop_physical(request_remove_physical, NULL); //删除实例 baikaldb::pb::MetaManagerRequest request_remove_instance; request_remove_instance.set_op_type(baikaldb::pb::OP_DROP_INSTANCE); request_remove_instance.mutable_instance()->set_address("127.0.0.1:8010"); _cluster_manager->drop_instance(request_remove_instance, NULL); ASSERT_EQ(4, _cluster_manager->_physical_info.size()); ASSERT_EQ(3, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(0, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); _cluster_manager->load_snapshot(); ASSERT_EQ(4, _cluster_manager->_physical_info.size()); ASSERT_EQ(3, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(0, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); //删除物理机房 request_remove_physical.mutable_physical_rooms()->set_logical_room("lg1"); request_remove_physical.mutable_physical_rooms()->clear_physical_rooms(); request_remove_physical.mutable_physical_rooms()->add_physical_rooms("py2"); _cluster_manager->drop_physical(request_remove_physical, NULL); ASSERT_EQ(3, _cluster_manager->_physical_info.size()); ASSERT_EQ(3, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(0, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); _cluster_manager->load_snapshot(); ASSERT_EQ(3, _cluster_manager->_physical_info.size()); ASSERT_EQ(3, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(0, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); /*测试选择实例,测之前先把数据准备好*/ request_physical.mutable_physical_rooms()->set_logical_room("lg1"); request_physical.mutable_physical_rooms()->clear_physical_rooms(); request_physical.mutable_physical_rooms()->add_physical_rooms("py2"); _cluster_manager->add_physical(request_physical, NULL); request_instance.set_op_type(baikaldb::pb::OP_ADD_INSTANCE); request_instance.mutable_instance()->clear_physical_room(); request_instance.mutable_instance()->set_address("127.0.0.1:8010"); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(5000); request_instance.mutable_instance()->set_physical_room("py2"); _cluster_manager->add_instance(request_instance, NULL); request_instance.mutable_instance()->clear_physical_room(); request_instance.mutable_instance()->set_address("127.0.0.2:8010"); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(3000); request_instance.mutable_instance()->set_physical_room("py2"); _cluster_manager->add_instance(request_instance, NULL); request_instance.mutable_instance()->clear_physical_room(); request_instance.mutable_instance()->set_address("127.0.0.3:8010"); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(5000); request_instance.mutable_instance()->set_resource_tag("resource_tag1"); request_instance.mutable_instance()->set_physical_room("py2"); _cluster_manager->add_instance(request_instance, NULL); request_instance.mutable_instance()->clear_physical_room(); request_instance.mutable_instance()->set_address("127.0.0.4:8010"); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(4000); request_instance.mutable_instance()->set_resource_tag("resource_tag1"); request_instance.mutable_instance()->set_physical_room("py2"); _cluster_manager->add_instance(request_instance, NULL); ASSERT_EQ(4, _cluster_manager->_physical_info.size()); ASSERT_EQ(3, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(4, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); _cluster_manager->load_snapshot(); ASSERT_EQ(4, _cluster_manager->_physical_info.size()); ASSERT_EQ(3, _cluster_manager->_logical_physical_map.size()); ASSERT_EQ(4, _cluster_manager->_instance_physical_map.size()); ASSERT_EQ(2, _cluster_manager->_logical_physical_map["lg1"].size()); ASSERT_EQ(1, _cluster_manager->_logical_physical_map["lg4"].size()); DB_WARNING("begin test select instance"); //// select instance //// 无resource_tag, 无exclude_stores std::string resource_tag; std::set<std::string> exclude_stores; std::string selected_instance, select1, select2; int ret = _cluster_manager->select_instance_rolling(resource_tag, exclude_stores, "", selected_instance); select1 = selected_instance; DB_WARNING("selected instance:%s", selected_instance.c_str()); ASSERT_EQ(0, ret); //轮询再选一次 ret = _cluster_manager->select_instance_rolling(resource_tag, exclude_stores, "", selected_instance); select2 = selected_instance; ASSERT_EQ(0, ret); ASSERT_TRUE(select1 != select2); //轮询再选一次 ret = _cluster_manager->select_instance_rolling(resource_tag, exclude_stores, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE(select1 == selected_instance); //无resource_tag, 有exclude_store exclude_stores.insert("127.0.0.1:8010"); ret = _cluster_manager->select_instance_rolling(resource_tag, exclude_stores, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE("127.0.0.2:8010" == selected_instance); //无resource_tag, 有exclude_store exclude_stores.clear(); exclude_stores.insert("127.0.0.2:8010"); ret = _cluster_manager->select_instance_rolling(resource_tag, exclude_stores, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE("127.0.0.1:8010" == selected_instance); exclude_stores.insert("127.0.0.1:8010"); ret = _cluster_manager->select_instance_rolling(resource_tag, exclude_stores, "", selected_instance); ASSERT_EQ(-1, ret); exclude_stores.clear(); resource_tag = "resource_tag1"; ret = _cluster_manager->select_instance_rolling(resource_tag, exclude_stores, "", selected_instance); select1 = selected_instance; ASSERT_EQ(0, ret); exclude_stores.insert(select1 == "127.0.0.3:8010" ? "127.0.0.4:8010" : "127.0.0.3:8010"); ret = _cluster_manager->select_instance_rolling(resource_tag, exclude_stores, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE(select1 == selected_instance); std::unordered_map<int64_t, std::vector<int64_t>> table_regions_map; std::unordered_map<int64_t, int64_t> table_regions_count; table_regions_map[1] = std::vector<int64_t>{1, 2, 3, 4}; table_regions_map[2] = std::vector<int64_t>{5, 6}; table_regions_count[1] = 4; table_regions_count[2] = 2; _cluster_manager->set_instance_regions("127.0.0.1:8010", table_regions_map, table_regions_count, {}); table_regions_map.clear(); table_regions_count.clear(); table_regions_map[1] = std::vector<int64_t>{1, 2}; table_regions_map[2] = std::vector<int64_t>{5, 6, 7, 8}; table_regions_count[1] = 2; table_regions_count[2] = 4; _cluster_manager->set_instance_regions("127.0.0.2:8010", table_regions_map, table_regions_count, {}); resource_tag.clear(); int64_t count = _cluster_manager->get_instance_count(resource_tag); ASSERT_EQ(2, count); resource_tag = "resource_tag1"; count = _cluster_manager->get_instance_count(resource_tag); ASSERT_EQ(2, count); resource_tag.clear(); exclude_stores.clear(); ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 1, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE("127.0.0.2:8010" == selected_instance); ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 1, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE("127.0.0.2:8010" == selected_instance); ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 1, "", selected_instance); ASSERT_EQ(0, ret); select1 = selected_instance; ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 1, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE(select1 != selected_instance); ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 2, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE("127.0.0.1:8010" == selected_instance); ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 2, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE("127.0.0.1:8010" == selected_instance); ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 2, "", selected_instance); ASSERT_EQ(0, ret); select1 = selected_instance; ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 2, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE(select1 != selected_instance); exclude_stores.insert("127.0.0.1:8010"); ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 2, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE("127.0.0.2:8010" == selected_instance); count = _cluster_manager->get_peer_count(1); ASSERT_EQ(10, count); count = _cluster_manager->get_peer_count(2); ASSERT_EQ(11, count); count = _cluster_manager->get_peer_count("127.0.0.1:8010", 1); ASSERT_EQ(5, count); count = _cluster_manager->get_peer_count("127.0.0.1:8010", 2); ASSERT_EQ(5, count); ret = _cluster_manager->set_migrate_for_instance("127.0.0.1:8010"); ASSERT_EQ(0, ret); exclude_stores.clear(); ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 2, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE("127.0.0.2:8010" == selected_instance); _cluster_manager->reset_instance_status(); ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 2, "", selected_instance); ASSERT_EQ(0, ret); select1 = selected_instance; ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 2, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE(select1 != selected_instance); exclude_stores.insert("127.0.0.1:8010"); ret = _cluster_manager->select_instance_min(resource_tag, exclude_stores, 2, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_TRUE("127.0.0.2:8010" == selected_instance); } // TEST_F /* * 测试不同intance分布下的网段划分,和rolling pick store */ TEST_F(ClusterManagerTest, test_load_balance_by_network_segment_rolling) { std::string selected_instance, resource_tag; std::unordered_map<std::string, int> pick_times; int ret = 0; size_t network_segment_size, prefix; std::unordered_map<std::string, std::vector<std::string> > resource_ips = { {"tag", {"127.1.1.1:8100"}}, {"tag1", {"127.0.1.1:8010", "127.0.1.2:8010", "127.0.1.3:8010", "127.0.1.4:8010"}}, {"tag2", {"127.100.0.1:8010", "127.100.0.2:8010", "127.101.0.1:8010", "127.101.0.2:8010", "127.102.0.1:8010", "127.102.0.2:8010", "127.103.0.1:8010", "127.103.0.2:8010", "127.104.0.1:8010", "127.104.0.2:8010", "127.105.0.1:8010", "127.105.0.2:8010", "127.106.0.1:8010", "127.106.0.2:8010", "127.107.0.1:8010", "127.107.0.2:8010", "127.108.0.1:8010", "127.108.0.2:8010", "127.109.0.1:8010", "127.109.0.2:8010"}}, {"tag3", {"127.100.100.1:8010", "127.100.100.2:8010", "127.100.100.3:8010", "127.100.100.4:8010", "127.100.100.5:8010", "127.100.100.6:8010", "127.100.100.7:8010", "127.100.100.8:8010", "127.100.100.9:8010", "127.100.100.10:8010", "127.200.100.1:8010", "127.200.100.2:8010", "127.201.100.1:8010", "127.202.100.1:8010", "127.203.100.1:8010", "127.204.100.1:8010", "127.205.100.1:8010", "127.206.100.1:8010", "127.207.100.1:8010", "127.208.100.1:8010"}} }; for(auto& resource_ip : resource_ips) { for(auto& ip : resource_ip.second) { baikaldb::pb::MetaManagerRequest request_instance; request_instance.set_op_type(baikaldb::pb::OP_ADD_INSTANCE); request_instance.mutable_instance()->set_address(ip); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(5000); request_instance.mutable_instance()->set_physical_room("py2"); request_instance.mutable_instance()->set_resource_tag(resource_ip.first); _cluster_manager->add_instance(request_instance, nullptr); } } _cluster_manager->load_snapshot(); _state_machine->set_global_network_segment_balance(false); // case 1: // resource tag只有1个实例, 不开网段balance,正常rolling resource_tag = "tag"; _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(1, network_segment_size); ASSERT_EQ(32, prefix); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } ASSERT_EQ(pick_times["127.1.1.1:8100"], 40); // 开启网段rolling _state_machine->set_network_segment_balance(resource_tag, true); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } // exclude包含唯一instance, 则pick失败 ASSERT_EQ(pick_times["127.1.1.1:8100"], 80); ret = _cluster_manager->select_instance_rolling(resource_tag, {"127.1.1.1:8100"}, "", selected_instance); ASSERT_EQ(-1, ret); // case 2: // resource tag下只有4个实例, 即使开了按照网段load balance, 也退化成按照ip来, 不开网段balance正常rolling resource_tag = "tag1"; _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(4, network_segment_size); ASSERT_EQ(32, prefix); pick_times.clear(); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); pick_times[selected_instance]++; } for(auto& pair : pick_times) { ASSERT_EQ(pair.second, 10); } // 开启了网段load balance _state_machine->set_network_segment_balance(resource_tag, true); pick_times.clear(); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } for(auto& pair : pick_times) { ASSERT_EQ(pair.second, 10); } // 一个region有三个peer,进行load balance, 必定会选另一个网段下的instance ret = _cluster_manager->select_instance_rolling(resource_tag, {"127.0.1.1:8010", "127.0.1.2:8010", "127.0.1.3:8010"}, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_EQ(selected_instance, "127.0.1.4:8010"); // 如果4变成migrate, 则pick失败 ret = _cluster_manager->set_migrate_for_instance("127.0.1.4:8010"); ASSERT_EQ(0, ret); ret = _cluster_manager->select_instance_rolling(resource_tag, {"127.0.1.1:8010", "127.0.1.2:8010", "127.0.1.3:8010"}, "", selected_instance); ASSERT_EQ(-1, ret); // case 3: // resource tag下有20个实例, 网段分布均匀, 不开网段balance, 正常rolling resource_tag = "tag2"; _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(10, network_segment_size); ASSERT_EQ(16, prefix); pick_times.clear(); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } for(auto& pair : pick_times) { ASSERT_EQ(pair.second, 2); } // 开启了网段balance _state_machine->set_network_segment_balance(resource_tag, true); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } for(auto& pair : pick_times) { ASSERT_EQ(pair.second, 4); } // rolling一万次,每次随机挑选三个instance作为peer // 完全随机的情况下,应该每个instance被pick500次,最后每个instance的pick_time相对均匀 for(int i = 0; i < 10000; ++i) { std::set<std::string> peer_list; for(auto j = 0; j < 3 && !resource_ips[resource_tag].empty(); ++j) { size_t random_index = butil::fast_rand() % resource_ips[resource_tag].size(); peer_list.insert(resource_ips[resource_tag][random_index]); } ret = _cluster_manager->select_instance_rolling(resource_tag, peer_list, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } for(auto& pair : pick_times) { ASSERT_TRUE(pair.second < 750); } // case 3: // resource tag下有20个实例,其中一个网段包含50%的instance resource_tag = "tag3"; _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); pick_times.clear(); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } for(auto& pair : pick_times) { ASSERT_EQ(pair.second, 2); } // 开启网段balance _state_machine->set_network_segment_balance(resource_tag, true); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } for(auto& pair : pick_times) { ASSERT_EQ(pair.second, 4); } // rolling一万次,每次随机挑选三个instance作为peer // 完全随机的情况下,应该每个instance被pick500次,最后每个instance的pick_time相对均匀 for(int i = 0; i < 10000; ++i) { std::set<std::string> peer_list; for(auto j = 0; j < 3 && !resource_ips[resource_tag].empty(); ++j) { size_t random_index = butil::fast_rand() % resource_ips[resource_tag].size(); peer_list.insert(resource_ips[resource_tag][random_index]); } ret = _cluster_manager->select_instance_rolling(resource_tag, peer_list, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } for(auto& pair : pick_times) { ASSERT_TRUE(pair.second < 750); } } /* * 测试add instance/drop instance/update instance resource tag三种情况下 * 网段信息的动态维护 */ TEST_F(ClusterManagerTest, test_load_balance_by_network_segment_add_drop_instance) { std::string selected_instance, resource_tag; std::unordered_map<std::string, int> pick_times; int ret = 0; size_t network_segment_size, prefix; // 加入"10.0.0.0:8010", 开启全局网段balance开关 baikaldb::pb::MetaManagerRequest request_instance; request_instance.set_op_type(baikaldb::pb::OP_ADD_INSTANCE); request_instance.mutable_instance()->set_address("10.0.0.0:8010"); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(5000); request_instance.mutable_instance()->set_physical_room("py2"); request_instance.mutable_instance()->set_resource_tag("add_drop_tag1"); _cluster_manager->add_instance(request_instance, NULL); _cluster_manager->load_snapshot(); _state_machine->set_global_network_segment_balance(true); resource_tag = "add_drop_tag1"; // 只有一个网段,且prefix=32 _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(1, network_segment_size); ASSERT_EQ(32, prefix); // rolling 30次,唯一的instance被pick 30次 for(int i = 0; i < 30; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_EQ("10.0.0.0:8010", selected_instance); } // 加入"10.0.0.0:8010" request_instance.set_op_type(baikaldb::pb::OP_ADD_INSTANCE); request_instance.mutable_instance()->set_address("10.222.0.1:8010"); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(5000); request_instance.mutable_instance()->set_physical_room("py2"); request_instance.mutable_instance()->set_resource_tag(resource_tag); _cluster_manager->add_instance(request_instance, NULL); _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); // 有两个网段,prefix=32 ASSERT_EQ(2, network_segment_size); ASSERT_EQ(32, prefix); // rolling 30次,每个instance被pick 15次 for(int i = 0; i < 30; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } ASSERT_EQ(15, pick_times["10.0.0.0:8010"]); ASSERT_EQ(15, pick_times["10.222.0.1:8010"]); // 再加一个instance request_instance.set_op_type(baikaldb::pb::OP_ADD_INSTANCE); request_instance.mutable_instance()->set_address("10.223.0.1:8010"); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(5000); request_instance.mutable_instance()->set_physical_room("py2"); request_instance.mutable_instance()->set_resource_tag(resource_tag); _cluster_manager->add_instance(request_instance, NULL); _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); // 现在有三个网段,且prefix=32 ASSERT_EQ(3, network_segment_size); ASSERT_EQ(32, prefix); // rolling 30次,每个instance被pick 10次 pick_times.clear(); for(int i = 0; i < 30; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } ASSERT_EQ(10, pick_times["10.0.0.0:8010"]); ASSERT_EQ(10, pick_times["10.222.0.1:8010"]); ASSERT_EQ(10, pick_times["10.223.0.1:8010"]); // 删除一个instance baikaldb::pb::MetaManagerRequest request_remove_instance; request_remove_instance.set_op_type(baikaldb::pb::OP_DROP_INSTANCE); request_remove_instance.mutable_instance()->set_address("10.0.0.0:8010"); _cluster_manager->drop_instance(request_remove_instance, NULL); // 现在只有两个网段 _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(2, network_segment_size); ASSERT_EQ(32, prefix); // rolling 30次,剩下的两个instance每个被pick 15次 pick_times.clear(); for(int i = 0; i < 30; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); pick_times[selected_instance]++; ASSERT_EQ(0, ret); ASSERT_NE("10.0.0.0:8010", selected_instance); } ASSERT_EQ(15, pick_times["10.222.0.1:8010"]); ASSERT_EQ(15, pick_times["10.223.0.1:8010"]); // 更改一个instance的resource tag,同步更改network信息 baikaldb::pb::MetaManagerRequest request_change_resource_tag1; request_change_resource_tag1.set_op_type(baikaldb::pb::OP_UPDATE_INSTANCE); request_change_resource_tag1.mutable_instance()->set_address("10.223.0.1:8010"); request_change_resource_tag1.mutable_instance()->set_capacity(100000); request_change_resource_tag1.mutable_instance()->set_used_size(5000); request_change_resource_tag1.mutable_instance()->set_physical_room("py2"); request_change_resource_tag1.mutable_instance()->set_resource_tag("add_drop_tag2"); _cluster_manager->update_instance(request_change_resource_tag1, nullptr); // 剩下的两个instance,每个属于一个resource tag,每个instance对应的resource tag下的网段只有1个,且prefix=32 _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(1, network_segment_size); ASSERT_EQ(32, prefix); _cluster_manager->get_network_segment_count("add_drop_tag2", network_segment_size, prefix); ASSERT_EQ(1, network_segment_size); ASSERT_EQ(32, prefix); // 对2个resource tag,都rolling 100次,正常 for(int i = 0; i < 100; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_EQ("10.222.0.1:8010", selected_instance); ret = _cluster_manager->select_instance_rolling("add_drop_tag2", {}, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_EQ("10.223.0.1:8010", selected_instance); } } /* * 测试开启了网段balance, store通过gflag自定义网段的兼容性 */ TEST_F(ClusterManagerTest, test_load_balance_by_network_segment_with_gflag) { std::string selected_instance, resource_tag; std::unordered_map<std::string, int> pick_times; int ret = 0; size_t network_segment_size, prefix; resource_tag = "gflag_tag"; // 初始化&add instance, 开启全局的network balance std::unordered_map<std::string, std::vector<std::string> > resource_ips = { {"gflag_tag", {"11.0.0.1:8010", "11.0.0.2:8010", "11.0.0.3:8010", "11.0.0.4:8010"}}, }; for(auto& resource_ip : resource_ips) { for(auto& ip : resource_ip.second) { baikaldb::pb::MetaManagerRequest request_instance; request_instance.set_op_type(baikaldb::pb::OP_ADD_INSTANCE); request_instance.mutable_instance()->set_address(ip); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(5000); request_instance.mutable_instance()->set_physical_room("py2"); request_instance.mutable_instance()->set_resource_tag(resource_ip.first); _cluster_manager->add_instance(request_instance, NULL); } } _cluster_manager->load_snapshot(); _state_machine->set_network_segment_balance(resource_tag, true); // 一共4个网段,每个instance属于一个网段,prefix=32 _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(4, network_segment_size); ASSERT_EQ(32, prefix); // rolling 40次,每个instance被pick 10次。 for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } ASSERT_EQ(10, pick_times["11.0.0.1:8010"]); ASSERT_EQ(10, pick_times["11.0.0.2:8010"]); ASSERT_EQ(10, pick_times["11.0.0.3:8010"]); ASSERT_EQ(10, pick_times["11.0.0.4:8010"]); // 模拟用户自定义store网段,更改两个instance的network segment gflag,自定义网段为bj-network1,模拟汇报心跳 baikaldb::pb::MetaManagerRequest request_change_network_tag1; request_change_network_tag1.set_op_type(baikaldb::pb::OP_UPDATE_INSTANCE); request_change_network_tag1.mutable_instance()->set_address("11.0.0.1:8010"); request_change_network_tag1.mutable_instance()->set_capacity(100000); request_change_network_tag1.mutable_instance()->set_used_size(5000); request_change_network_tag1.mutable_instance()->set_physical_room("py2"); request_change_network_tag1.mutable_instance()->set_resource_tag("gflag_tag"); request_change_network_tag1.mutable_instance()->set_network_segment("bj-network1"); _cluster_manager->update_instance(request_change_network_tag1, nullptr); request_change_network_tag1.mutable_instance()->set_address("11.0.0.2:8010"); _cluster_manager->update_instance(request_change_network_tag1, nullptr); // 测试现在3个网段,一个bj-network1(2instance), 剩下两个instance,每个属于一个网段。 _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(3, network_segment_size); ASSERT_EQ(32, prefix); // 正常rolling 40次,每个instance pick 10次 pick_times.clear(); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } ASSERT_EQ(10, pick_times["11.0.0.1:8010"]); ASSERT_EQ(10, pick_times["11.0.0.2:8010"]); ASSERT_EQ(10, pick_times["11.0.0.3:8010"]); ASSERT_EQ(10, pick_times["11.0.0.4:8010"]); // 3,4被exclude,则在bj-network1进行pick,其中1,2每个被pick 10次 pick_times.clear(); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {"11.0.0.3:8010", "11.0.0.4:8010"}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } ASSERT_EQ(20, pick_times["11.0.0.1:8010"]); ASSERT_EQ(20, pick_times["11.0.0.2:8010"]); // bj-network1,4被exclude,则只能pick 3 pick_times.clear(); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {"11.0.0.1:8010", "11.0.0.4:8010"}, "", selected_instance); ASSERT_EQ(0, ret); ASSERT_EQ("11.0.0.3:8010", selected_instance); } // 重新load snapshot也保留用户gflag信息 _cluster_manager->load_snapshot(); _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(3, network_segment_size); ASSERT_EQ(32, prefix); // 模拟用户取消store网段gflag,走update_instance request_change_network_tag1.set_op_type(baikaldb::pb::OP_UPDATE_INSTANCE); request_change_network_tag1.mutable_instance()->set_address("11.0.0.1:8010"); request_change_network_tag1.mutable_instance()->set_capacity(100000); request_change_network_tag1.mutable_instance()->set_used_size(5000); request_change_network_tag1.mutable_instance()->set_physical_room("py2"); request_change_network_tag1.mutable_instance()->set_resource_tag("gflag_tag"); request_change_network_tag1.mutable_instance()->set_network_segment(""); _cluster_manager->update_instance(request_change_network_tag1, nullptr); request_change_network_tag1.mutable_instance()->set_address("11.0.0.2:8010"); _cluster_manager->update_instance(request_change_network_tag1, nullptr); // 恢复4个网段,prefix=32 _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(4, network_segment_size); ASSERT_EQ(32, prefix); // 现在1,2不属于同一个网段bj-network1, 模拟1,4被exclude,则2,3每个被pick 20次 pick_times.clear(); for(int i = 0; i < 40; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {"11.0.0.1:8010", "11.0.0.4:8010"}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } ASSERT_EQ(20, pick_times["11.0.0.2:8010"]); ASSERT_EQ(20, pick_times["11.0.0.3:8010"]); } /* * 测试添加集群 */ TEST_F(ClusterManagerTest, test_add_cluster) { std::string selected_instance, resource_tag; std::unordered_map<std::string, int> pick_times; int ret = 0; size_t network_segment_size, prefix; resource_tag = "add_cluster"; // 初始化&add instance, 开启全局的network balance DB_WARNING("start add 100 instance"); for(auto i = 0; i < 100; ++i) { std::string ip = "12.1." + std::to_string(i) + ".100:8000"; baikaldb::pb::MetaManagerRequest request_instance; request_instance.set_op_type(baikaldb::pb::OP_ADD_INSTANCE); request_instance.mutable_instance()->set_address(ip); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(5000); request_instance.mutable_instance()->set_physical_room("py2"); request_instance.mutable_instance()->set_resource_tag(resource_tag); _cluster_manager->add_instance(request_instance, NULL); } DB_WARNING("end add 100 instance"); _state_machine->set_network_segment_balance(resource_tag, true); _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(13, network_segment_size); ASSERT_EQ(21, prefix); for(int i = 0; i < 1000; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } for(int i = 0; i < 100; ++i) { std::string ip = "12.1." + std::to_string(i) + ".100:8000"; ASSERT_EQ(10, pick_times[ip]); } DB_WARNING("start add 100 instance again"); for(auto i = 0; i < 100; ++i) { std::string ip = "12.1." + std::to_string(i) + ".101:8000"; baikaldb::pb::MetaManagerRequest request_instance; request_instance.set_op_type(baikaldb::pb::OP_ADD_INSTANCE); request_instance.mutable_instance()->set_address(ip); request_instance.mutable_instance()->set_capacity(100000); request_instance.mutable_instance()->set_used_size(5000); request_instance.mutable_instance()->set_physical_room("py2"); request_instance.mutable_instance()->set_resource_tag(resource_tag); _cluster_manager->add_instance(request_instance, NULL); } DB_WARNING("start add 100 instance again end"); pick_times.clear(); _cluster_manager->get_network_segment_count(resource_tag, network_segment_size, prefix); ASSERT_EQ(13, network_segment_size); ASSERT_EQ(21, prefix); // rolling 40次,每个instance被pick 10次。 for(int i = 0; i < 1000; ++i) { ret = _cluster_manager->select_instance_rolling(resource_tag, {}, "", selected_instance); ASSERT_EQ(0, ret); pick_times[selected_instance]++; } for(int i = 0; i < 100; ++i) { std::string ip = "12.1." + std::to_string(i) + ".100:8000"; std::string ip2 = "12.1." + std::to_string(i) + ".101:8000"; ASSERT_EQ(5, pick_times[ip]); ASSERT_EQ(5, pick_times[ip2]); } } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
49.293948
129
0.714976
[ "vector" ]
391c7a840d828f9b6583ee380b0767245124e340
116,378
cpp
C++
00076_minimum-window-substring/200121-1.cpp
yanlinlin82/leetcode
ddcc0b9606d951cff9c08d1f7dfbc202067c8d65
[ "MIT" ]
6
2019-10-23T01:07:29.000Z
2021-12-05T01:51:16.000Z
00076_minimum-window-substring/200121-1.cpp
yanlinlin82/leetcode
ddcc0b9606d951cff9c08d1f7dfbc202067c8d65
[ "MIT" ]
null
null
null
00076_minimum-window-substring/200121-1.cpp
yanlinlin82/leetcode
ddcc0b9606d951cff9c08d1f7dfbc202067c8d65
[ "MIT" ]
1
2021-12-03T06:54:57.000Z
2021-12-03T06:54:57.000Z
// https://leetcode-cn.com/problems/minimum-window-substring/ #include <cstdio> #include <string> #include <vector> #include <unordered_set> #include <unordered_map> using namespace std; static bool debug = false; class Solution { public: string minWindow(string s, string t) { if (debug) { printf("================\n'%s', '%s'\n", (s.size() > 50 ? (s.substr(0, 50) + "...").c_str() : s.c_str()), (t.size() > 50 ? (t.substr(0, 50) + "...").c_str() : t.c_str())); } init(s, t); if (debug) { print_counter(); print_index(); } results.clear(); for (auto it = index.begin(); it != index.end(); ++it) { char c = it->first; int cnt = counter[c] - 1; //printf("cnt = %d, it->second.size() = %d\n", cnt, it->second.size()); if (cnt + 1 > it->second.size()) return ""; if (it == index.begin()) { for (int i = cnt; i < it->second.size(); ++i) { int a = it->second[i - cnt]; int b = it->second[i]; insert(results, a, b); } } else { unordered_map<int, int> next; for (auto it2 = results.begin(); it2 != results.end(); ++it2) { int a = it2->first; int b = it2->second; if (debug) { printf("check [%c, %d, %d]\n", c, a, b); } const auto& array = it->second; int i = find(array, a); int j = find(array, b); if (debug) { printf("i = %d, j = %d, cnt = %d, array = [", i, j, cnt); for (auto e : array) { printf(" %d", e); }; printf(" ]\n"); } if (j - i >= cnt + 1) { insert(next, a, b); } else { for (int k = max(0, j - cnt - 1); k <= i + 1 && k + cnt < array.size(); ++k) { if (debug) { printf("k = %d, a = %d, b = %d, cnt = %d, array[k] = %d, array[k + cnt] = %d\n", k, a, b, cnt, array[k], array[k + cnt]); } int a2 = min(a, array[k]); int b2 = max(b, array[k + cnt]); insert(next, a2, b2); } } } results = next; } if (debug) { print_results(c); } } int min_size = 0, a = -1, b = -1; for (auto it = results.begin(); it != results.end(); ++it) { int size = it->second - it->first + 1; if (min_size == 0 || size < min_size) { min_size = size; a = it->first; b = it->second; } } if (min_size == 0) return ""; if (debug) { printf("{%d,%d,%d}\n", min_size, a, b); } return s.substr(a, b - a + 1); } private: void init(const string& s, const string& t) { counter.clear(); index.clear(); for (int i = 0; i < t.size(); ++i) { char c = t[i]; ++counter[c]; if (index.find(c) == index.end()) { index.insert(make_pair(c, vector<int>())); } } for (int i = 0; i < s.size(); ++i) { char c = s[i]; if (index.find(c) != index.end()) { index[c].push_back(i); } } } static void insert(unordered_map<int, int>& r, int a, int b) { //printf("add [%d, %d]\n", a, b); for (auto it = r.begin(); it != r.end();) { if (a <= it->first && b >= it->second) return; if (a >= it->first && b <= it->second) { r.erase(it++); } else { ++it; } } r.insert(make_pair(a, b)); } static int find(const vector<int>& array, int x) { int n = array.size(); if (n == 0 || x <= array[0]) return 0; if (x > array[n - 1]) return n; int i = 0, j = n - 1; while (i <= j) { int k = (i + j) / 2; if (x > array[k]) { i = k + 1; } else if (x < array[k]) { j = k - 1; } else { return k; } } return i; } private: unordered_map<char, int> counter; unordered_map<char, vector<int>> index; unordered_map<int, int> results; private: void print_counter() { printf("counter:"); for (auto e : counter) { printf(" [%c,%d]", e.first, e.second); } printf("\n"); } void print_index() { printf("index:"); for (auto e : index) { //printf(" [%c,%zd]", e.first, e.second.size()); printf(" [%c,[ ", e.first); for (int i = 0; i < e.second.size(); ++i) { if (++i > 50) { printf("..."); break; } printf("%d ", e.second[i]); } printf("]"); } printf("\n"); } void print_results(char c) { printf("results(%c):", c); int i = 0; for (auto it = results.begin(); it != results.end(); ++it) { if (++i > 100) { printf("..."); break; } printf(" [%d,%d]", it->first, it->second); } printf("\n"); } }; extern const char* longString; extern const char* longQuery; int main() { Solution s; printf("%s\n", s.minWindow("ADOBECODEBANC", "ABC").c_str()); // answer: "BANC" printf("%s\n", s.minWindow("a", "aa").c_str()); // answer: "a" printf("%s\n", s.minWindow("aba", "aa").c_str()); // answer: "aba" printf("%s\n", s.minWindow("abaa", "aa").c_str()); // answer: "aa" printf("%s\n", s.minWindow("aaabaabab", "aab").c_str()); // answer: "aab" printf("%s\n", s.minWindow("cabefgecdaecf", "cae").c_str()); // answer: "ace" printf("%s\n", s.minWindow("b..a...cb....a.b", "abc").c_str()); // answer: "a...cb" printf("%s\n", s.minWindow("a", "a").c_str()); // answer: "a" printf("%s\n", s.minWindow("a", "b").c_str()); // answer: "" printf("%s\n", s.minWindow("a", "ab").c_str()); // answer: "" printf("%s\n", s.minWindow("ask_not_what_your_country_can_do_for_you_ask_what_you_can_do_for_your_country", "ask_country").c_str()); // answer: "sk_not_what_your_countr" printf("%s\n", s.minWindow("cabwefgewcwaefgcf", "cae").c_str()); // answer: "cwae" printf("%s\n", s.minWindow("", "").c_str()); // answer: "" printf("%s\n", s.minWindow("abcabdebac", "cda").c_str()); // answer: "cabd" printf("%s\n", s.minWindow("qdsvbyuipqxnhkbgqdgozelvapgcainsofnrfjzvawihgmpwpwnqcylcnufqcsiqzwhhhjchfmqmagkrexigytklnrdslmkniuurdwzikrwlxhcbgkjegwsvnvpzhamrwgjzekjobizbreexqqewmwubtjadlowhwhiarurvcsyvwcunsylgwhisrivezrmvzwwsqppuhnreqmtkkgrjozbhjwlkpzgqwejotylamcgeqzobihmwinduloecqmtoqcejcpmqusukulncsbabodxbtbeloxzgbesdveupyocuzryutyxjdulzvpklokspqkslqodqfhlgajatkxfntqorhzcxlwmdigoyxtrcccidnlyxidnevdveczbpwpugyjhveyxhcfkpqipboehjhcombrdzhyghjncnnzwpggezrvcfzjqjngvoyyqhwwohlsvarrpzavatrcasnqbazyrzxhivfydsqasjtjiteloxposdhtfgswhrfpomnteftyonjyiojxnznfeubjctijmnyaanwgsphieqhpgsoutbbxycjaxrklekogakpsbwdimkxvelpyosvmxgnuxzgejwmjgbehxhpmtohzbyxqsvepbrmzsufcqrnwttfscxgxlpxnpufirjxtdjuvfzzvqprlizelwmkjchwtcdbvpbosminsjpncehnmgtzegknkrmdvrhrgihywsoobdedhltvtmxzuhmeaakysrpybyzxqnouqszzfswahtzbanidoubilsgoqfnjubdmvclaxkaedbfeppj", "fjknwevk").c_str()); // answer: "" printf("%s\n", s.minWindow(longString, longQuery).c_str()); return 0; } const char* longString = "kgfidhktkjhlkbgjkylgdracfzjduycghkomrbfbkoowqwgaurizliesjnveoxmvjdjaepdqftmvsuyoogobrutahogxnvuxyezevfuaaiyufwjtezuxtpycfgasburzytdvazwakuxpsiiyhewctwgycgsgdkhdfnzfmvhwrellmvjvzfzsdgqgolorxvxciwjxtqvmxhxlcijeqiytqrzfcpyzlvbvrksmcoybxxpbgyfwgepzvrezgcytabptnjgpxgtweiykgfiolxniqthzwfswihpvtxlseepkopwuueiidyquratphnnqxflqcyiiezssoomlsxtyxlsolngtctjzywrbvajbzeuqsiblhwlehfvtubmwuxyvvpwsrhutlojgwktegekpjfidgwzdvxyrpwjgfdzttizquswcwgshockuzlzulznavzgdegwyovqlpmnluhsikeflpghagvcbujeapcyfxosmcizzpthbzompvurbrwenflnwnmdncwbfebevwnzwclnzhgcycglhtbfjnjwrfxwlacixqhvuvivcoxdrfqazrgigrgywdwjgztfrbanwiiayhdrmuunlcxstdsrjoapntugwutuedvemyyzusogumanpueyigpybjeyfasjfpqsqotkgjqaxspnmvnxbfvcobcudxflmvfcjanrjfthaiwofllgqglhkndpmiazgfdrfsjracyanwqsjcbakmjubmmowmpeuuwznfspjsryohtyjuawglsjxezvroallymafhpozgpqpiqzcsxkdptcutxnjzawxmwctltvtiljsbkuthgwwbyswxfgzfewubbpowkigvtywdupmankbndyligkqkiknjzchkmnfflekfvyhlijynjlwrxodgyrrxvzjhoroavahsapdiacwjpucnifviyohtprceksefunzucdfchbnwxplhxgpvxwrmpvqzowgimgdolirslgqkycrvkgshejuuhmvvlcdxkinvqgpdnhnljeiwmadtmzntokqzmtyycltuukahsnuducziedbscqlsbbtpxrobfhxzuximncrjgrrkwvdalqtoumergsulbrmvrwjeydpguiqqdvsrmlfgylzedtrhkfebbohbrwhnhxfmvxdhjlpjwopchgjtnnvodepwdylkxqwsqczznqklezplhafuqcitizslzdvwwupmwqnlhxwlwozdogxekhasisehxbdtvuhrlucurbhppgsdoriyykricxpbyvxupencbqwsreiimclbuvbufudjrslsnkofobhptgkmmuuywizqddllxowpijhytvdkymzsulegfzfcjguojhzhxyyghhgbcllazmuuyzafahjjqgxznzinxgvgnbhrmuuljohjpkqpraahgajvzriyydengofskzgtppefzvwrvxadxjaydjydocqvsxpdyxyondvmyrfvqiaptanwllbaquxirmlqkmgzpbnputmldmcwoqvadwavqxeilraxdiwulmlffxsilvgcnbcsyeoqdsaolcorkmlxyzfdyznkuwmjxqcxusoxmqlxtzofocdmbiqzhflebzpbprajjqivhuvcvlhjnkwquosevfkzfzcwtcietqcamxcikltawrsshkydsiexkgvdidjbuldgkfqvrkxpdpjlakqsuurecmjkstomgrutzlqsxnjacuneedyzzrfbgpoykcmsvglwtdoqqztvugzakazlrhnxwdxifjccsozlrpckpxfldglpgnbauqzstxcaiecaudmotqyknfvsliiuvlurbvjwulwdsadmerazjyjydgrrobnmmjdpeplzcjcujhhpbhqmizlnhcgwftkrcnghctifcmbnvifwsvjcxwpeyycdrmwucedexnlbznquxvtpretoaluajxfajdwnhbugofjpuzmuxflolfenqynzxubjxawgbqmsyvhuwvotaajnfpaxqnwnjzwgzvmdnaxlxeiucwpcyzqfoqcegaspcqybnmgbndomkwgmvyqvxgblzfshimykeynslutaxjmjgvvdtmysubfvjxcrjddobsgombomkdvsatvvfwnzxsvgszzbccrgxzulclzpqvhsqfnvbcwywrfotgsxlldilatnntcfqmxgrkdsozsktzbogtlrerzrtuhiplnfxknqwsikudwncxdiqozxhaoavximjvuihjzdcjpwmmlploxeezbmzrmwrxlauficojhqtxohlzwwpwcuvfgwzuvqrgqmlaozmxshuiohingzjitgobcnwzdpfvdsxrujroqlwhvgubgdlzjzdnozptqwqurqnlzezssvznctokybljdoyrppngmdcdvpqvuppmmqbqlrajsmuvcupskcawhcbdrrangrbuhcnstndobzjgtyydcabkccpvtpjbgmyprljkamaelkkgkkmnknzosojnfupnhncyalkazlemxoshaewkuvymjkzqeqdlfflfsygrjmdidypdcmoyjoktykldapqiwenpcviniovnmkqqygpivbdvloaoftwcxltzhbmrrhedtuuudleamjvaxwqfrohozcpidbzxkfafcwbfjffwocyoaotrccfdeumjxngjthrvfsapyhnojlcmbxddzlidhwnhktqdcjykcazcjoqszveaskfsvnxckkjwgczknzupbvtkjmeihlkzvptqfrurdgnjkouxpqpqmicvugebrqdmgyenpbethrerhaqwrfodoqaiyemqxredpjqhkwctpgmwjcsaiifyyfiwmuojntmdeemqaolpwxnfbffjpmjnssleocncxbhbhttjjeyfdllessqjfzwxtjdilsmivvlcqglzmlepyrwskmbrnzqhivrwnfgiasmsaxrnkxeipaaboduccklmfckuhrcjlqblnuaxrfhihjlwofyqrleynpswiwhvmigbejavojgvsrtgztysefrrulpekwzwghakqaigkocehxnirlbvqspmfgqpdrolzowrqgycuchdzumqhnmyhdmojfeowsaxiypyenbapidoerhletlnyychdgwbayziwoicbjcsthixzplfkwtiwvsbdodfocpksxmvhqnczvaylnexjxgguyhzomecotoiqcdzuqctoesbrwyavgiresquewyvrmdhqhjkzleppwqgupirxtkcncytyxqpjuyadhmeuqulomtidcbbxlfmndfnawcmsdoxkadhtzshmmsrotsnfxzudgifcmtwpjtamzhfybmkneedawqhwrbzyjgawaznjunvtwcsypenvirvhhcdbgezrkbnmadyvsvopyippnckxviedmjgsnfkaizmjckgviwmghdvwhhtdpaicjowxvgzdglokyufgtroawjwesrhirrmbfiacrzfzmujmqpujiilftjlmdswulkxquzslyzkltuzmluxtcjawulkxfguqqrikrcwreiezeelpyjlaulyqziogqizgbhtsmrmqzqreudvsogviuvyveobuyadakwuwngomxfsrkomywhiqejlixnfwpiwzesxrznfwvapfobekkmdpxqzvdettopusjsliftgatwijzmvmaydypcvujopxfksocfxjydmrbuabiwpkwsklwfihtxhahzpleoxftjwvfzynxnzthkhfppnloulyvajbqigktdhyefnbunwdxfiowxzltljonuqgfwqybxzhemkybjdyolnnjmaczjtpfjvmhlllkkuoyhoaqrageptnetsdelumwpyfclsoxpewwsymlasqqofuhzxomucijaqookclzhjxbhjniefaukudkrrwlthxwznklpvnyfkaowpyauyugsxsmrrzmayiblsmdqzdxmfniuoiqoezjdtvukwhmxrnkkcncbtzpyoxvchnrlmarixnuvwhsowfayuccndrmrpjuwwnklnbtmqnhnwcbthbrbfvpkndbemxaikmvzpqlgettcxwvezpfgmwqzzrfnriybutdmkosqjnsglqkkhsqtogvqzadsibudvzphnjxxyrfjhsvokniyvdowfupovlrskizxtwwroecxwzmgmwghbxdgruumfnfpxensdlltpnqloeraayjdxpmojiapwhgvotorhbmypckdjdgjdrpagbosjrhhyndojthsutqlwcrfizqlqhozieruvabwpgmabusynljlncsvbljusztddkxbkyzbhlcifugthsexuxsykdsccnfixcljdkkkvmudjbwstcppbkplnhqsuvctanedxppudjxomvhhywzbgonwydquasoahsfejuangybsvkctjbxppknnpfirxyugszmcwnpcnswifycobbfrltgcaovaopghptjngartunbzofppgvitqpxqftquixbzqmmwmdrituijaxaiujckabbfwrbfqeggqveeaxntsxcuwfcrqgbqiexgybnofuxypdepbrltqpnnurgkyjcioaoobcciybgnflegerzvhokdfqofzsnpsedvgieejmtoxzuervzajldrbtwcmmsgqvcyfiepuzduayyrvztfkxylquneihlyfpykxczrddledlxykrfwofjgcznkgyllnjwkovdrarxfcvepmllatvivuvfcvsoickushylirjntetkqhwsatcvpyctvvheztardaenrncnrwxjfvbhqechegbzdifcegvhiauapwnhukqbiuiyamgethfwrnbvvyedyadozsxvfpxnlhllutrpaxnumorhnyknyqdziavpsucdbqpxjimmhaitqzadxltybwxlzsbrofwqxlnjwcvdcfxsexyektcnpbbqucjkjgahtqqpsntwssoyrocchgrzispewzoghrpajfqbulxmdnmuerylxqmhkenhfcpmvemelehfretwtftxwrlwjxfwdtdivuwsalwlpdsjjlfcqyapsnnbmsxqlcaiyxayiylzbdimoophorygelkqdhirmjzmgcloaynecyqsofbcyzjemtvscfjqokdumqknoarsyjnoroqpqbucwrwbwhtlswhgouvfuoxuykipbagreavatudqbxdvvmekgzpaqowobgfchlvlosnhotxsqcnnptxvtowlduzebgiirfvfzkpofmgxpvlgpibkxzvcuwivcqfvxcbwoqkueqrvmcbdnfnmeioaewxiocdlgehvwurdkkyypcdchqonaeoealmqqqbwwktvemyrxyrocvqlngzokpsmahcszfrvrmsyzsryrkmvfehvkgjwxdixkmsjtjhmvbkwubwnmiitopoaxxwudgunumznxiasjmrfqnscybxmsonqnlmquigowfetpeoasfgiuymsbmhuawmphagbjmsftwbkcpkuusdqrrjudqqdmetvfbzqprvkpwurnenjxsaqkjmnbdtphomorlegecqtammoqazpuzhekuunzpcidpxwcdcjhueigryytxqnzzujtqxufbdkscgxfkgpgkxmdxmwwemxegjzwgudjxncbvzifhxlrwzvtntssfpwnyxlgrosqduryvadcxqvupspdmjxtbvhbssimjacowwntysvvjsraljfxscqvxzxsuhedjirfegyczvakntkycqxxuqsuprmlysqhakofqojrjjbzdozhgxgapbwgskstciafsrkjfvapheqmsptaoccddzkxjeqomttfkfqpcsgjywvqopsctviwuuvfymvkhortvhiycrhapftdwlipgqlcmikkufwdwowtxhrbybcpgvvcidrpvethmdtjlpmhfjadqugqxifffchofafcgylueefpwuybdagvunntvuydxhrehwhpwukazrrvlpyqsflmsaipvguuolyxjhniczkdqcyetyuldiaxiipfojzexacghpqlqboidomwnhispkqzshfiqgnngpwqgmbwnqesgtrtabmrleqdlxldeatmrrcxfgvvycneveaxhoossgxfglimlbydudcajavhcilzpnwwbmrtuoaazjmlmlqhqshzseiwotxdjvckhteeheejprueemlwguvbydzmyxshswscpygyemhwfdajpnhyhczhhytivnpqjjsyjazqmgmsmoddblbipcpxbkhyawqjiiktkjjzrxrflwjmjmwbpnysahqafhjnrvjegsdaswfdsqsedofuefmemegrnrfhnolviovakdgetaiyonuusgyeneyawdjltugdkegwhobcojdezxztgzatgyvcdhpwbxbobhkixlnlxqqypprvotquroyuvpsynumodzzbmmmlecjvtdtiwjeozdiusdvhxhwcgxdvlsgpwqmqvfarrehqjsnevilurjwagcvrwbistviockitprkyjxcghqayzzygdtzzvirqfcfhmpbdgnesmgatydrycqgflheipxzwbggovjtdwxxigydedwefommausilphirpohmxasvypfepiksepzvblvvdfhvnrmehvrgvjbvagbsqmmwdmrezmcfslaheonljergpseqafkstwowiibkwfpoqrxwfnhqryyjsczukjmdfcaqkdchirxakxwpkfhbffkxkltuwfxehxwscybkpymzvkqfpzjuevtqjmkfrilbhhvkfwwwwjxutpzlokfviblrnwyhgkinrfzzbwxzhvtcmvnbhvwpwjilfhsntadmhclkyjkfgdksaxviutxqdgckpuyixbugfiretblzgvthvpppioilwmyliwvhzsoeafktgwumtnvqckinbqyxcwlkugstygaankttinhedfuhrcusstswrdjojbjkjjkyugtcvcgyhdgzfaravlwpohdaimktwwtscmwypdywigvnjppeaotrvyrglbbjzvbchxcwcctkjqashpykdubzssfdvgowbpalnchrhccsvekctkozepazjhegntdridcxilrpovjlzvnufctmttlfcpnqiqjtwnsgajxqegbdbrygvtuopfvrvjjfbsyxhrdkaaahickjtksoemetuakpjwwmqvkyopiqskxamkkhuexyqctkegbpcybsvnsjdcbvnzvbjhjfligekzoqhshlqjenwywbbxwqyurjbcpnlvrxuhqezxprgvefucgxcfnazgkalbpwwivqslwtlmlthrydwhaampcnyopjpfhlpcehqabdmowwhxzdecdsrihrwwambjxrmbaecbhqpfmxcmcioichqjbmgbyjlyczzdfbeoswvgvysziihlszwtocwomjmqkmtrpafjwdqtbksjvcwpdtkrxiglsuceivwyvdjtgbmjohvljrammmgkumvogztpvrpswaodeaosjjdsdfhprnblbzajyvavmpqksenwgcoqntkqytirglehketlbtiplyadepzntpdhkpxkjhbptfzfmsspnbfybfbiwcvqtyxdpwpyeqqzyrgklzbycgxdnankfiayizeyvtybmoakfjwsixrmgqptsffxnfywgcwcxudjjgvqrrjzralxscskhyixfitmkpqjjttubonsiwtbygaqlscuskrysmmedcopxjjbzytjupksxkkifnfxzyxuljyqloflzrmzpfikwveuhremejmfijzvtalgotrqkdpblznhwsdelisrtewdowyjwkpmdjcpmtqzvehrymxjwqaqwytmuuvsgnhlwjakfskayttwfrhejjufipsejpxrcecypeluxvwvqquxhdbqnxxxnpbyfyqjcukszvowsltibpfktjcggzdvrgwwfofjipdjmshefbmisuslfutlvyjmfhkkvstfhxpwrwawzpeslydquxdpvmeatomqgiwqflmyjmwjdadoaieufkldwpfseuimcgejtqhdfdoiftzfbfbjpmmmctginqwpxbysthxymljreiyinzrdmdrqyzampydozejvngtaueraosicrzhfcaxdzzrqyuhzaquoyqoswhtlzbprbyyfywizvbrvwyvyqrmpjajgicrjegaheboexzduauqyvnxngjcqmmwwqpfwvidbjufitkctgusbjrpqatiohekytsuqaatjuytpkvkqsesdvjvwedmmjxmepgupinaenvtxseqkiiogtlexpqlynxdeezvopvteqoejuuvfellxxpwofimvfrzlrvaisvmllswgmtlqfypenmsuugrbyrnropbgkptvipdujonqocudooykurmuibnwqofceyzoqdiztvpiylloblzxdnsnohmewtgcrfqhkaieyzowmbmnplluafhomvsioamiiersfaydboboqnbfbobbtiqgekqsldcthunouorvcsjuinbjbcmvlcdrptlayoviikweyqzdklxsabdbdqyqubhjxvlxjiftvexvuyyejyzlzcncuntprcaoxmniwtbrzynvxnbilaumdjrxykopopfodtwboyvpyikxxlilmcxrnoqlahdrwifbdberbzgahsxhefssjrjygbkiipzgxehdimujldjvxjebowtaneyvgkgqzfxzmgcusydgdpdbyjcohyowcpskzabbfyatecnzcthgimhgvlucllyqasazsdcadctkgjljcurmgaudnqhzbhpdarduxfwakqmqbxbfrurzuncidljhtykvrproxorhgdzhbdouxhusuycxkleflpccgttdjkkppmyqpmnmthgnhintvtygkclrweufqhxftvyiklwfudtdlixjbxpmaafygzfyicebaejmpirllmoyunhylzknbrlissgbxmcxqojhwcsjpjhjwphjotwpkjzfcigbwkynyjuwlpfaanmweviupelbqnguvovrzvgxedwrubuuqiqwdyqufcwxrermtofujotprpintchjkziqaykhcietnxhilpcudvlwntjgysrkrbaralyeteyibhsmwuibsvxhpippaizskalknkqiqqrsyjeugpwakvhbeyqggqyqskcfwtnmlggjqlgyceymzhqfhgmnwmgqykvufljrrpajcghgkhvmqltxrhlqutgsdepjpaairasujbcvjxhzidxckksedazgeopvqrehsybbbgykdimmllovxicaidiprakhrqqjqumsaledtsrgfhdcpfcailpbnbkeudokxcexplaifsqlbunrbstmdipslcwffmscpyzejbppvfcxbpqdhjrmtgeeibknnepecqjosafphhmjyeognfuglznwczlrddwfthvnjadqjrbiwpolwiskjhgngrhjudqqmmdvoinycpgagwldgfnqmtfsmmbjruzdgeawnqurfarlwcodidvuwcplpquimtosxormeldlouzkxnphrmdppsaglwoxpcsptjbzufnkbmvabmhublmsfoyqlooatiportpnacybovesjnmkaycgncwyrmakwsannpdnsdqiyuchipuipyqebpesdheazgpovsbpvtavqcfatzkjxbpaquutdyveelscdtrboryeudenepyesoeikzdpzztgmlkpgbsuvrzrwfgdufhmvnwhocwqdpypaigilzcgsdxqjetflcuiqspgulwxcuoeevmquowouwedcakncevuzkbtxztbwhfacrqyhnoblvgnvrazxxwwjxsgynhuwoxbfnzocqqnnyakrcjpzfniehqfuzbrnyssmthqlzeyxgipjugkbttgblnxloqynkrbgarrzxqyganpuvbwpuesgrrtfiruukvakpslmkmskbjhxlfohjgpczijjaeembexqykdiwxvyjevujjdurtwsdhcdliqnopfnbixyisyrytnheqbxjzpnhtsubkjqbpddzcbjxbavundaegxpgoepizljjvbnmgqljtvguxbqlgqrnpitdnknmvxxqakehcqqvnwpmzfxgxqtmzosoafcvebofosmqkemzcdmbllhiccxdsrtswvodweimwudjaricuudfgnqirpnkigcedshbyrovnreniopejtmpiezztolduqhzkrajkoeyhklrybwjwiaembfhprkljtktmncxdivluievjaehkhlyithymrjvnwqbjtymdvzyeevpgzxrikprdzprqaofyfhhahwffvdlbaaicxbkksbprshktvprcybcixinunyyoagqajckbeztwgdreulgvmldltshisfyunquwteyzgtvowpusabpomsbhmirgqqbdixcbeaaktyarnvlpwbdkvgtkqmqgetmnrooxqrhjrjceepvcqaooghywwqdamrnffecvxlgoukuzzrdsrsgxbgvxyaykrnrytttsebgblccntffmxnlzvhwthwgbmxzhtvaxwiaklcxgietfregonfhxdpyppzziwzhthifukcdsgyazegnslwrpmrgbqflpgskoapkntpfznhauopoblfszwzcoendlipbienvxfdyukaoapccbjuchvhwcubncrqnxfkvknvfawtalyeojbtrwapywqnbjfohlyexozcovyqjyvzhysywsnvpgkqpseydecasefibdzmdumkuelqxanmgyeyskyvodxjherkhqxmmjxgpkxmkkarkercqpzfszqzdhmnajzmuyvjiuytgymrfdvvsxclwsmbcaocjqqfolrzhpsopehwjcsbbwozpbbtbpxnhnuwblvicpwsvdqeiiflhwlwxmradoplbmjezencvlwqroubxbmexxcwjvzpjqamcjrepeikrgaiuwjrzwxxvbvhwuwflwuphltwrdgijiregcxfaveyyafxubehzyzgjueaymlhwelcgjhjgoheombkpgsqgtwqncslodvkhgmqrvzzjgezuhklpebwxxombgapkvztdnjxiiwuqctmkdxbhyzgxntywvngqobvblsmtpgmrbydfwfowgxuwsusniadwbaamtmikuubvufcsmtpuqlqifkxnkcmmcoavakfwgjrbqwtepkyhvrrbboqmqeasscqsnxotgiwwescvcbcyuvbvjrjzwjtoojjbhzwpjtopnqkptopnjqlskutigpyuyhxhjtxuonkbdwtzliowbzrlwktczrwabtjmoigfvsibpbacmqynspaocvqdoodrjndxvmetgnuvqwzcmyrgprurokvdaaujpahnmnguacstyrxmpptfinyxataawwklwtykggfjixegobtgsondblcdfeedaqoxlphrvocelimckhkevxhzilcppisqahplwyftnjxasmeetoiplsqudujtdelflarjywenheozqsdjhoaugqojnaeqepvrpocqmgdukrvcmzovpopvheguglmmcjdsyhimnlgafecrfsmuhbpqhxmpkabnjghjnrybcedjihanaojjsabbyptkpuxabemoxkrcqwlbeoqgeapwasaahtlwpiyspkjmuaqnzcodselwecvhuvhbqszfdzaskjggjxtkbhntoapscmzwjjzzbaheahykqhsbgmmjvbcjcteegfdpocrqdawdhxpzehamvovtqxeusiaaodseijwnjtqsqhrwqtimkdhcclwwuyxkcrqmanzlgrfyywworgcbljfpxbltakfebvqdiroqitogrmwlszodkushvgcxqhdudvxlmmcuhscbhzmzyafkuzusfwryexshspuhdybnreqadczdegpbgjvnionmlfvgxpncqqrhuhhzjieqrutxfomneabqhwyeoljebanyiwztgejxaewhujvzlyrsvpzlairdkgbscbokhzijegsyrnxcmqvjfwwhgnlqvmlzpzjyytjeacdrrcwfvrqapmivbtnwhavzbhzcalgcnlugqqmljclarvxuomrynozovyqwjzaykufcmtnxvbzowwjnjcnyqmmomfkyemyqhdtvwivujukitvxexkcqyqemvqkbcjulophnxejjavtvrqzocbeasimpyzrbknmacvnbbymeufzlxzbzagbuqqkrpduzqibsgpthpgnjnnwlmykogojyetrtwlumwvgcmzlehznvmmgamsosixsmqkhoxdctbixnkjrrkhoyvuyhpmbxktmcfttdxvyyewnofhhpqwnlsnshzvhlovowohznexlivbyaigrycgjutdevyngoiwkyflmklzugavjibcifjtbeyhzwwineexfklrwysqgtlpdosovdhxhggjedrrjxrohehdcawitjayyumvzusicbrgekanirervnvxnthicjjcfvyersnvtgczrcnzvtqqgnpwiygnippplpueihadnedgisfdlyvtnkrykylunakaqehanhdalihvaoynotjefacpynkopuqhaxjnepprxymanmndfwjkznczcmnsiebiblvickbzjqzycpdilnumcwmfkzzsfaajnvtpgurrkqpnhsxvhrhmqtravstautlirezzzqqljhyqbxllrvxhoojjiemcaxkrcmsdekqnrrguotffocodsaoaecdgapxedrjibzvuqdphxuonzdstfhwjjbqlqpruhaekcbfufubeqqrpvkjarhjcibqathwakammcrghlincaetvoevhlgmticwblsdvtphxjqgwataaxuxoysvmyjhindlzwqurieoruwnwpowmkvcknaynjgyxljwjcsakwqbsmqodgmsshudwubkejkdvtzevrfhqxkkmbzpjnjcxehtyifeuphpliticasuacemfddptntqtalrktyekhvxqpguraorcsfiyjztyslruykgrkncsibkzjgrjukmoqwobvhzpsslrerkpgohrqtqzzjjvuxjktalohmfceqvihfzqughmbzncjyxfvjrojeesqjuwbrglxgbtokhqjuuutszqdshowlgoxdkyurltzmonwvfisacluedxwklvwtjvwwvtphoovdduajcslgffmjcjtpgrirohnkcetsuqvykyjoquvyzhjdscuawcsklhwporiiifiudrjwngumpdrkhlmdqgqbqotegdoqixkoqvkedgqvlifsvtylaqpqeiwmlkcvhnjaiveobwjmgqhcjhnjxcbbmxozksvtfgtqcxefupucfbeoisahwbkjbailtfeyoyqsxwxtltwquaheuhlrkwclymyrsfsidiacfzwstujpuqurxhijfkxeyvvsanafyckfcgxxagmwyinxsxhxjedibbacqbjoftthbtgdbtaadpxvpgvykyimzjqqmzgrvcbwvhawccygtwdicajpzrdactsoubipdloasqyxsxfnviyzjhqkytmbofrjgbalmonheleykjohtmhctzmttzwhgosortbejolqbrqoaevtseylemfznditrbjjwkphacxetqsvwpqpwoaadhbqljmemvpkieskirobhiyeypvufxwifzbsinyxkohuuzhdrvgagfggwbcdzyogzpajeygqoonlpuqirwjxdrdbtffufvaekcoqaugrktcanskfqvewnixinecvzezlipbimibwdfytzjyqecotmlbcsfxtjwfrmgcaqfwwlxpkgncmrqgeejgwpdpabwupdwpvdorolgbtvdhnuntyzbwoenohkizpgomkeeapmdikhqxdfsdetzuzojgytfpcwcoagqsuucebudgcvjiqkdpyoyzjfoldqbgysyvmczpxdvzaghtqmiqaipkogxrwzxxtxsfarwzwryzzhupuchwnzibfgudhuaatuhtodsmwslvafmwktsxsdaxjudsqfskazfoeaaasovuvhsfcnevqgubdxttdnffoltsltsfjpafyumchrxxxuyattwygbdumymzsgfdxhixbvajoziltjopcknjntfcrublaipapxxruzcizkwstkhywxjlsonjipxlxmnplmgimkqlumfqypqwmziepxpaomlmaadmmjuyvmjpbphbgxyswiyofnouczicblonwkorzxiaoqbupboojmcrcqnervgsixhgjvxivhkjzmgpnwdzlfqpxftoabikapqmlpwgwhrwvzlkyqjjxbyugtkiwsszjklwzhewoyslxfwxvhisjgorbyaasuzbfkaetecicuvcbrzwziqkqebueduwatahfalyeqijmenoxmkwwdgphklmpfkpakwhkkhraqcmwpatdnscqyrzkelajwpliouvybmarqmpfpjkcbmubftojhouffhnvbitdwvwmimtxxgbasvdaqrjxhgennskrceuzzsnjgjifpjfjgljzcvykddzqvjhxpdyryocgzlmowtzfelejicvlfudcfncxscoqqszpdnfcifhnsnyaptnxpqbwddtygjoycpohcvjlcsaufawxtjukcvghbafjjwhnlxvqtgbvbdsgdofyabiczolaqrjcnqpyqmojvrgwuyezpkxrlfvkwgmmxvqkogleubpptvlpwspncmepuzaqfmefkvradcexevnzsaoosfbwshmmgoeoaitmdmmgpsgvnvwgvmwqsaokhayoocermzdqlsyckezazvixigpagdmogkewokpajtsunrzxxyzzuhwconewqqmycqvqakqlfjischsbftabbyfrllnebccdszvvmoirzqmdzgehzficdqtrbjxdlzifbgcnulgvduydackahscnkygmjdrwebdfhgudtbywvwzwzjyiecxocfclitjnvnuetpimsikpfkngvlqbqosstugeoptlcprxeblykworgbxdpnffdxzzrffhxyuznmxupkuzgismmpsbfxikujlnpqvmornefmyvxswddpspekslhcydljqcanqqfeumsuhppevutnlzzdnihlluudxwrnnytjkmeudvayptnaumfhumuhgplfnevaeokqcqkgnkgcfueagjjdxekfvxnidilhyvybnkjavpeclkestoxsujzphmzkukuthswwchwzycckmgehwbbqkbhtnhgiradbubxwkwyiyasniyuhzyxmzhfmolwhnbihegeocexcgrpoqmvpkvdlcjxswwzkzkreqxsubrwhjoyzavqmsuxufwmbsonuyfyqeskikirvwpwwnokfkhcpeqtyegsensuslgaxprunjqmwewdpefgkwzicgdhtvdnimnhdhbqstcqaztpfbxpxxxbfciyyomicbsfktxcpaupboggrdxoawpfzagzquhsvzzivwmkyhbbxhhokeeldvscxybnskhqmiajhmvfvwhsdqgnxkaagtedtftorcgdlgmsuhzqfikizryydyalterplkdcmliztutnetflbqucjscmscamirbtbgyprgrkckzidfuhxojgiouaqumblpuovsgmyxybhyjnffuctfibtecmzqnkgjzbehqeeohlotatyuvscfvxkzjjqyvyiwbodrshiavwtxqrsnlwvhtfifqadnynkabptwzbwuaptsilhujcddjlizmnpmbzoeqiaplylnpffysnucrxhbkpcwerlhszmjhoyvpkierqcjdwlwvsxgjceotpvopjxyaxtpjetauykzwxvsqvazxepswlgnwflwdhlonhphhbidydxoazqzehscuyprecpjjdxwkofrpnwotwcvvuvbcndwnuptxfcgicfuqmngcluxhysfvngzcmxqgnjduomestyifnqhymeinxnimvhphghotqtpgftyytjeibnjourbrglfbuuladbwwulcahdacoglpuufonihttownlhqoimkfzpfishliowzisfyfnhajvyyggqvqchvewcmqkzyyxyipfiwuryfmxetfuqxzxtfuxrkjrljoltgqbeksdshawchssetrzynxsaijlszylhopmajpsqrqsajmeegedvdvvngifhgtpwidzturmlkgnvtrzbxewczuqhcxrlqihaliwfcismofhjwikwnjaodqyfqpsixcjikhpmphadohnmszihijvlbvtrklajnltasimhrnmfwbsqbcxlnvxpqsiddimtvgvnqjwiylpxmhnpmlbzgaoyszbxhosfwnumzrwxemusviihvlhdnxbfwfegtzlrofdnyalemhxhrfrmsyrfxtmuasctrpmiwpvvribdsynjfewxenebiqxilbdeqpmnhikyslekkrurxsrdhvesoeczfidwxqlgavfuglhscdkbxbeeykymobnwjrsijdplawfghmblrnooqstoctdtuqpdjjosofdoblwkzzxrmlhefcvhwycqqtwackuspagslfcmebftmnxrpsalsfejyajbmfvdfcvsjzfnckiozghpahctmgenipqwulzanwsyxzmzkunjcuadefyslefwtvsnhspwqkvojjntfbfixhndmnyardwmbqzkkribbdpkoegwfnefwtkjiijbmhnpzozkfhnincvbgbxoqdvmyfviogjcpytpnsbubodoqysybrorxjdxrbghjrlzqeqfyrzzfeqxekxhbmyaxeyqfgzqxkppqhuoyuqfagchqaotonuntueaadqzqgpgpjxofntgvynnadgoqcbjwhlyncydkplzaingxjouhdhhgqxzsakrkwrxyrcigpjhazpziduribaotxnozafjwyiuqmeycnhemydwbxnlbpcuopiorpznqijgwngadqeroioshddktfhhxpxohxexhnfddnegdixusnmcrrmmztvyltosssrzgwejjirptqjnexrxoelnzgnmbcgvuxwcvblhlewgvhwzenystjivrvhvxoqunnwjqksbookjvgkzvktpvdmnztkyjasxprihbalpqvbndnoyyhptnbimxsmgvhfmypubrfshatwfjkdhuvchynvvfhecqjpobjrsokcqdyvmlavfvaounjrusvzlhozkztcpdefgdavqasvysluhwleqjdbstdcswghzlmhqocgqxdorokzmyfcjiedbhhvdnccyqjqgoywnbnerxfdvkggukjxrquweyyeojxwzvtmxitqhyuflclhmvhflbbrabwqmtnmqiapqtgxuceheqqslxxyzaqbdorpjgdzqepizxitzmcfctxnswotyeubuoqdwuenavvzsdvtqxyusvkltyerebsypldlhhajfwixbfrtdroxnyiiypacqucfhfsqotztrktspmoudcsscabcrbehxiohphxdczztjsnagbvjfncjpdlhgrqfbfmqmkwqlvjupywvcrgjgivynihvcxddcpuqbqgmnriesfbwyhffscfhlmfnjisoxmebenptgyxyfyufickcerjrdoepwzdwnjzswonfonftnczvelxkdjcixixwhauvktpihepwrvrfxsadeanjjrriapejragbtvmdcbbtwuavndytdmeofvwfmdredxhzvvexxfsvbttowrjzfnplllsxojduhlvcizbhgtfhmyyirhjxvykgmcfaojwvwrzesaoattkiriskrchmctuoycrmlnjjhipbkdcfymnrwgcnklcmfwdfyurljcwskmuwrybqkrhizjvlxxzcwchwyaiicgcoswmmwnciglqhvmsujswfwfcvhmflshznglzcabnjodqlplfbfbibimyradctlbitohxrkkayoskfdpiitrmdfkvgoxbbbjwpqtgcgicwbmbeempzfbeknzsbzteaccruwaweizalnbqtphuukzhxazbzthbxkvsgvqkfrmrhpjafsvzcugzuicwbkzyuuscrlozcaqjpbmwthyxdgyzobvrlvqhrkjlvzkazclqfxnyelxhrvjiwezjbrqvcbgzcsbbunuzkjzpwwyprhxqoxbrososvuuymvbiixhtggkeekuyutokqpbhjqbhmvhbrijbgrwozgtgtpeniuxblyivqlefhlgavpddiaskgnqzeuomolnzmxwcjcjsnpujfxmpxgzgvphzjwozhbbvbzamcjgpzaagxpvxvvdtkmswigxskynlanzcxftwhucelxdgsizfvubdaavmbjzbyydvfytmsvtfvwmphnucjxfmadyboycmyhiefbqazlfuitlpjitshyehddirdmebtohzrybqjgmtayklgddnekxhnfbsshvnvdmmbnfmwriyrsjzwmpcwmlltmfltbzqenfhdmtbdbzxwkwuwlwvxhirwqerrfkxvreydzzgdafzkcvinrflaqeygiqzqcwltcjwbkegmkfymcgbtomweswmdontqlejnphqbmxnyelmhtnchcynuxbxloqezwpmlxfolcbjgoxnkkqtmqhhnkgbzzfavupjtuxgwbpermsbzivlaesqqbrpawsvsheobeuzfmdwavazfxlidfytgpjgndehkkvloqmvcpsenuesrpauwyndpylebpmnahaqzmmdcgipamjtdmnzmcecdqggfuuhcuydhkhlqrcsfllizajmcoqfewojrirveralbjytaclfqyppyzbanrirqwajgtgkmgynqwiszvyptngrmiuzbcsravcgqiqdpoqhnbzowzdqpljbtddxhvqjstpjdimuyeblfdzecewrqfvllaiuxzequvzxflservpxyrddxzungrbrrjopkshgpgevtyzktqjuhmxfntuulvnehbvttcajkeedefqxvbtdoskbmgxzcldlmbegderokxtocjoxlhcbaoeovcnzpskbtojzvanfxiubsizfrdirsmfnqumfnwjimshhtwnsfjwztxgkaoesclhvgtavrlfgennzjctqlppgmxrnlvhqgploknlczridexepcxinnzubxnqiiyaqplhzzsdajnfpnjhpgpevoaxnnnwxnwqekxglrlldzsuobbdhshfjkcwxruvhtnldkrqbddgevbuwexfxgkiqoeqgblnuyyzkspnxsudpxxnbwsyefgvtnlboyokypjkjazgutjjsiwuequivbfrqssgshqsybchdcnxxyiqgemmwgushajzsdfnkxfkairdmgcjekbmqnynuvhdvsfpvmcgkiqmskqeqspxftjvgkicfriajnrfzwnledyypqcgktdpmonvyxxdphfyuxdwvqhbwhzlxdtkwyzlpmgnmftbpyzjxdhuvpvryufwzagyzhjowrdiyylnzkzwpgtlxoewllskmainjtdhkiplhaygnzecgxpdmwzxjtjxvsmhnpoaaglhijpvltartrwfpyezrpypjlwxckxcqilztawewyxpquwhsailrhabuwywjvbbfmcanzfjxeypywxswhepogqkdoholipswutjtauseukfqjxoqbehiwrnladyiuthomqjmnesjoxczvsrywyivsvgsagdvzkjnctzrxubnrfmmxfnwevrytzqtfvohfyuktwbsqefhjtwjylfegwczxvveqjlyjgkeelwusbddwbmvmtztreuozptpbgpmozrsnnofrsknvziiskdmozcnrveseuestxlilbncvaprzabtkehyfklwhpqllxehurphufjqfbhgbizlohjvtwuankmzjsigjxndezvjacrbmtocaxyvvsviehjobtwkrjqvinhkqynerbhtahovbmgfvrvxlrjedbbnpiyhjllcnuypdolearkwkhtvbczegbrvlrcudnzskzhnnusqneoynjtontstwmohdqeggfaqeidrcxjsbxqpgjfueynckcknuqwavyqbgwultedxdvokgtglttpfxbvurruopnryjmleqqbtlrfrnleghumgvjapaxfrkxrvjezbwdwhwcbjphsybefznhqpeviqsclbgnedsbmofpywxqvawcbllrcqnmifowjxlpcdqqrxgrufjrhhvjugawyplhxbfgyqvctotmnbgjirapzvyvebscqfjpgqvhgtjbjeowhwipnkfoifkmieobjaqrqoyzjkasqqqymynclustcefkivntveloslnbvnvmenksozwzwpsatxkesaxqekeyytbtgwhmjthxtdyruqropdukdtajgghezixhgfwsydrtgqmdgfrwjngogiamqhqpsqyyvuqvxirgadjgjceurmkxukmkucbmsampwfnwpeepjnvurcokobhllvxhyztsbikznxvedztmoqhhsxrjybumwrtuspptxztmyqqbqjpebwmuudduezgdqcxjroeqpzcpqsqgdimeeaaagfvmedpxfpgwdmovoqkekdmnlaupbushantgqjdyylwdylymbjsoogbzgvqhskosxiyqtcqrpmunxtbbevpubsviolpgygavqanjedauqwjprnsxihrmamuqalyytavjajsfoubgrkyixqgiazucmqsodsmzujiwudbjxerqppboghygiuiwkckqwypsizoecsncwhsnwtceccmlxwhjauzwuqocsdjuvwwtfrhcmlipnvckrlwsfxqaohegmpcjobctsjxewgvkdxwulsosqhsgqzocoqncrpylbvsxbpjepgbaarsqanyqomucfhhyzfkacezetlkitnktfdmhqkyezuiecrcbyodbuehqpraihlcooqvgcvmbquhummvmcanxewpuqpexailqyiydekewfoqtanhcnvbrrqnhgsgictbdcbgimketywmajtfwqgpkxdtfxcpzvscxuihivnbvjpyskdqbjgnijipikhjgbmfxwnftagrmvpegsvjdbyomgdurmdxorclqrrluzcgxtmdnhorkmhyumulzaiptncjetxavzgsttxiclzpzgnttifuipjbelnlhklclswgntppgqefxuaschomzxpdkcqtocxawtijoxauofbnzchdjvrkugogleazizbgtkphjscxxfmyhtdtqudmattlatnisqpncgxmyblxgyxqtajkuowxirkimxshqjusqtequsobqlrlocxiqwhynsiarbjhkfaczgttajwqupeitbtkzaknutpmwatifvleegaepyxlqdwjepvgrgvmbmaxmthrrsyxyabpyabodxakovqhblvexvblrlckdchecktdlwtqvtajpstsdoxckanblslruuxxescrpvikpiwgbpygfxjpaysnqfenbbmguoxljhxyqvetmfbscmjelesdlwqnacvwqujacgyuefnqkokodutoalrljkajmxhfsqfuxfobmdtwtenwaimavgneqqqenxjhooblwroiwhhqnwonebpzjddzvvditnshdtubnkmjttbhrswvvmwerbdmxiwqxoxdktgxdsiwnmdegabboxhfzmtwupmuglzqefphyzflnjsvltybrfgqrzooqaiyljorofymhfawossblqcewkuplidekncxwtolyozhubektwohmslkdiaosfudvxcrqreqhgydheqbaekowvbzddqwikbdjdxzwbsgjqjrwzuydemcbpdhsvfdiggrlftijlosdzjzzfxellindmuvhzyphhjumcevpuqsuztvhsbsdkfiybefcexjnggckkxzfnrzpkwwexqjjwshzwnccmnsstucetbjjukyggwkfmtpklwkjlmoxzgrvavzvykesweacakjpgybrxldkzrkbzbwbxxwxjbqffqjidszjtacsofcpymqxqoypnxmwyedfvmpahqjcrluhtywrnprdfpsvoetojxugllgucrwvescxrarerijzxbuohncsmwyykgumzrhejlbclsidcreauyqcnsuapvabdundnuhzfkbsfmxhfbjabzepsyrjvrkznxebtlaaxducpsmvvvxxxbmpbfazwkyjjcmepmgmqarhudesybpvedmgimfgyfrhjenyqvmiwdqsiumjydecitkshrygwsphwdhoyuxwzprilfrljxorsakaskgqcxyaafpbbmzbdsloyeajdqcwqmwkzebdbbeegthihilkdyadccmfuobldzxcdyhfblligssnafzfdciheumzjqmopjstkzallnvrfphhugnzivgpstodjcraljvxkxlvkgprwwbseqspnyeftuiewbfjmajxyusicjayhdtmtlbglhofdwjbaqkmrvjrpezspbsxeljzymgkvurysczstlhkhsbywcsmgnlmywmziujdocdiecdxnkjwcmvbrppxccjdyxcgrnlhpoqtsvthfeejrbmiqdhvfsydscljrwrgmjbeewolbswstjclolgufgxxklhbhahwllcphqcikycfjgryrzszgrwqcfsmfbiqomhwdlgpkjvtrmrjllktfgmjmgvtjfkystwxfcmrnhmfveqjraewgqguydoklyiftecaiqtwagbxmtgdtlcbdkwepkoakwffcjgmazichlztggxztbdylzcalqbvoicssifskpwtdvnjdklwnovapxaaqdxemzxekeywtupwrcgvortbhqbwqeygjvmxwldgpbclxuhrwponihqpyunqylwhikhfwklnmqylmieixsxiaozainqiaorjayowjbmxtmkfupquhncjdblnqbvrrpcsnqqytcvnrgulvkfeajodnztddqwwfyotqhrklpzcvtqsgvyihmnuogxtxupcugxlnpvagwfbrvvxsthzivtybtrypidjoaudrrexnjahgxgytoydjtbkmuldcqnrsjwkdcjqnmxtleseuqhdjkpyecbjsqclcyxfbixouxigdamxswadirbnufyoxazbyyizhgqddyliayfswhveyztsgrjfrkjsjrrsxhvchhkhhpbdyzhxabriuanmlwewqxophlsqueabwbeucotcrlklnazayfwodmgmayeueewaicxksqnjdzvrburccqqheytgwxbdezfmdcwwvlfyncpozjqbbjihhdogcpjgqosttrpocxopzggapwbshlbpopxtgizwyusrnhhrewjgcpgtnknvxomoglhmtilrcdlrmsjtosbshjlutyrrnfhtqohlwudbzosmibhztirarfxldqesylnobxcxrfyrvtfdumeouwqlbpygiebgrowslysffsycldigpmwliowlgxsodtwvjspxthcycabnfjvwvthgkftqcleggadsuspnctogvrvacrwzmffwkzopmsxvuanrueeyxueulawntunhzuglvuaipxflzucwyjuxdbrrdpeyjtfkolvjiwtxtyivsnrqwlpboisrxxpiqxseioqqkjpfiacanttjhkkvtdpscedudvbmlrexawdiwhljbgsiqefljuglbjieejssazpavulrcycdgwnyaskmpszqbhuhqpzsopvjjiclgeqmadkcywonoqdrxzbqoaierdndlrqtxhfzmscmqszfieyggzywagbtmqwzinthwahiujvldwsmdqujsshuainobkojzjsvlzfgicroblcebwptqwnshdhinxtogljrlqzvtsludnahlpabnqwwtfgiczyknjdazfxsxjobwoiifklvchtvmafqzfcooioonmikvxntnvbvgnqiwjgllndltgbhqqxdegpzfdusywnglfrhrzucoypjgrtwjqznwqodtiwuglcrrtbkuvolteuzxnxggyvepjiiteearhrkcsuxqlilpenoukuajpgaaoituptmwnyyhvxxgfjvmwjggfirworwdcpzrllnymnfhlfnsoiektksyskwjdsmfjlwwzlwlzcsmjfexpjjkvdkqpgztynajaxgzkcmlggxpncoenxokbyasgblgomqplyqvcfjjlgazirfxouiruikbmxhcjxrwxkuapdlcjnduejtvdbozmaayyiajhugfgchxfszqfdmmmghrjvqvytvwbyhkspparwxyqwpybdkplrgvozqmsokvmsfgjvgbtdzmbqkdwwshpbcdcvsulepxwwdgrljnqkbtdlyzjtiyundykvuvajsyfxgzkpoccpvfcuglnoljbohlmbgomamtzvujkklobjtddzqsqbdrskfennsbqgwpbtbodocfxwkcxbunexhwjmcyzuzrbyherksuyvbwrmaopvevuluexwcyteqwezavjtrjothhhixwdbtxmndlmimfmedsddnoygxobhvipvgswarlpvybfkitolltpahpgheiobsdwzxtbqgqnesspalfmwzdwgufpypdahiwihrlyzclewgvwrakqzpoiktxkkdmuljctcqtesgiomfmefzuhqirceonotzkfkpapfttxzdnmibspcowtynvcektxkdewsglzbeybhlprpjhrxfmvviazutyeyfdtlosnvrqcehwtqdnpizkdjmeeffkgknbvevizmydtfzoxedmndzsolzstefzoualyvuzkuffcevzjzoyenssyrnrvsslmuxnstmeprjrygtjfhjjubeutrmqjgcxbbkvuzzjskdqqwbydkjzonthehzpobnrezmyynkrxnjpllnqxxpnmkurswiixvbcvncvaomzdyooleekdvypguiaqrkqolulawhcnvdqvrhgxlrajpqrjatctdsiqmvqkeuxcxoxqveoivotmgkxhdzagrkydioominohdmyasmlpaebjpysuaudrfbxnqnbaaskggigyurpwyqfnqxjqumkzohoguriwjscpclpwcevawcpncbfwnrxdynjueutqovhrixplbknypfnrgupvoozobijheextbfkkczxfmkfbruuxrltfzutaeejjihckomusnrxbdfevzauqlpvmjrmovyxefbqvpkncdmggrkdtlajwphjbyxrvxqzcrpzgbmkgzqpsdslouxmkgxngxebuwdznsyvwlhcmargdmurgtfsbdhhcliwhnxwiwrejbixbcdeozxwscpthwclknktahsidloomxlnzrtpqqllvceebjqnwaiwhafnmtdysrorihgaaulvyszzbrmzrvvbxcqjwtkomyiuhqxhmkcleekhvzgpwcqtgidcdptqpdmwvjgiuktaofimeobastwzdzdgqywfbjdxujfquarkfzwknzmiuihxjmezlcgonklitsynspaaqwmeyyosjxsujwuuacjomwygryvlovleuxksyamhxedhcxddcotoltuersphnbohaabybohyulhxklcmzxbmqxshpirflfmlfqmggthagoztbbfdyirqikaxsrcdwrqdhcmpytpgjpzlshotpfjzplxjcboaufgdjssjnkqwzpjtyzmqfypwlmioqwqkdwopqiydsoctglnglbwsbmqnaydqxvdautpkbqqwgupofevsirmjddyeddwazbdtuufykxurrlhzqcryugjxlidolcrmdwhaqnadkwwchdbzguzccjbntfegjxtmtaolpoockkeuqhtydvaggbvzizhrwcgrfudulrwvecrwlnuriuzovupewyxsbdkiapclgbimfaitncmxwlnufcabcxwdbildxqoftyuaycvnhhkdszzabzdexbjajxdiptoirikqmgftnsziryivalbxnkzyjchyvximhtevzmpoeqwvqgsqstnhgmhpqqqnnyawrgsssjjwzfupmmggivpokwfcnxqcwqzpytkrctpdylumacuialykkfmxdebbucqvvamztdeupzipdfzdqxpaeezhibifdbabbocxrjtikbzngyrxxgzckzlvcwafxaiaonzhwsqgwptcqmbnvdrhcdcebclaeucujccfwunslgvdvyrqbixdnajqevqjrtfcvjhrdumrchuxhnpjyponpaevvugonmqkvzebvqsxzoxgcorcdgpugtqdqwtdklqgkwjfobeprdvvspxvvpqdiiiygberowzyuifiljxcpuahjzegowlzetznwdgkbfkxppfcbegqbgzmgdvwagvgcvtaabncizzxphzsngkqojdumyrogovkjqlkuaoczpcqybiojseabhwqhpeqebanulzolpqnfsdfwmthgyhkhearvghzkhpevosiekvlfzqdnkktiudrafivopxyxmcsawagiytnxkqkwddgzjxzqgwextcwfgoicrqlpkaowryswdyvmxwdfsjdmmztsqdxjukaekocdouzruwgrslzluczgdubvyaeskgyuucyiwxcsuilotkbnoawuxzpvzwpjcpdxrdhpdlhxtunofpcvrapozflabajdrocksmzvxiutdhhkwlhqlxemeqmfsxkkopwgdydcgxxlgfxfsfveczsirhpkgzwuqsavqfyzcvmlckqvrnbvovdgcssjtqfkiihbnfcsdqdhcvctifowbredlyofourzcyapgehjumqxhvsrahqbauhmtvtjrkivikloouzljskqpckrlatowccrzxbrhjoruzikwjxhbhzsmjkzlfpkhtbiqezxqormpzwniwumdwgrfqrrxibecenslosbejnwillshignengldzcbifhkmwexnwarfppnabiklozpbfafhfipmrbaofxbcxuhmmxppfbatcrvjrcqymhndintqnwskrzzdyqsdtuzvlugeyzdkgsprfjhsfzfyagdzyxertdoezwjxvojcgbtnmaitbnsdvxetxjmqoavqwgnuwzwecrrotzhwobzlzeeypqofslvrrllpkjtmancvojrdlqqmwvklnyrimobfzovlxozzdbuslnxwdnkakunaugigvlmwzhiyxhxbjttwgqulfenqydqsjabglnfmwnktwjwhcrdkjzvpdjhdmxwxzxgmmlyiyidwtcevtjhfjcumndqzcozbnfnzqnjqxmmqqsnkcuplylzmqrnsfmvutkvjxebutqmjibvmvmztzzfpqthyhcubmqmlwqhrgvbqwyfrlenmfucwnlwxqqyeimqfczwkvzdraijnmyzssbqipoffgfjprbwubugwwjpwrajgyiarmszbgggolrdctbywyfsuohsikbqilqzziaaqgierckwxnutlbnhswbcgcspqiqpsrskxcqrecnbqjudljnfgohmtzbjjsadlunkxfbdiqfaabdnlqsrhzdayhljbnmmibyfgaioqposrufemxxtwcvwjgfmwtaeuzldzttrlkkcepispfonhjmtstfongujffmgygzlqlpwdxosccfmorfinmyausjbxyjxgjjyuyuxwkpapxofqvndilfcfrgcppbvykttlpsjzklqhavzviffvkkabqesfgpgsibfztobdcrmcnozxthtfrvhjabqirwabxgbtwcyytlcibcgulzzeuipwkfebefcbnfwljvkdgmnhqtdduehrpwnbcsegzijoogzxdlclyquqjxugdbxsakteexkfgvvwdvtggwrgolzzktfowciwpeavbmdjkyfnvbwexpmndlmnesdbwmznsaltoofyokoklkqkzcxcoksuexxcjxsdzdxntcojocvcolmpqmugymaejygvxayyfxnabbksfhuttillwfruttyerhbqjaopzepdfbvnjrieztpwaistbtyvczllbccdgugnvdagulkvebtfjmalfagjatudvxidtototvxnghlllesuquhxvpgxjdcgclkvbflvaiihsvudaoxsihqfwycfdfofqactfoofwzmouituwtnhafmwfpejwsomsrhzhwedvturbnmagbhiitfnklwgfluzecylyeqvxmmbcadkdktlfazqlvwsirrotpzttsqtgcwifztklmwqmvgzsfrbwkrrzrmulcprgnanmvyzhuqvrywjdpmbzeuaxgwkkmdrzfeoacnjyfepgcbjrpnsvjsuqpgcdkvepauqekzfpgwvkzhepwwmfrjxipanzvrpxmheyijnohlbhufyqbkvuttcjvpkqhbqviutrfihmvitpnrfreblzwokrdvhmwxjhteyyphnkqiafchwgiiheysxdpfslebsaisaxanjsylxatwibgpighhjwmbktfevpzvoblxtjjsjcqrfwipcsxoqlragyhbngzbhkzcvkugmnztjhjozieqtvsauzdjhcloomslwprkcqfnaqbbyhrsdmuzlzivcvlsjeehtxrxqzkqporovliaxczkbkffftapxewsdqptrzjgnbuloellinvmxdrewtvvxunbmcwddgjtjgexkriteffdiykgsfbrbounsrqwzcrikxfuoppvuwafxknpspitdfhyyzwxdnfnmmkcdzxzyagvkumcjwyobfozgkykzfzlrjowlnwjpceaysehoeyslmrsxseyxdkpnanapjjfophmhnwxswpdijxhbbiyhspwudwlofsewztdprchnsmxbkhenpcujuqdxoqntjspkluzcxirrvouhvyukcptwhytwpjrybjiofksesjvnzpuvnrhqidmpbinsrhsusbixlccflztmppjegruoujgxrvqkckgulquysyefxzrmqbrxunnqwtnprfbtqhqdxmerkkwjloybrraleobdjquayywqfovfazymlvvwlvacmaptoswaksciqyyymwfmvdajywflrfpggezwyvyjpbrgzsgoolclodupzcasjqyruxovuoempvurpahfljtbmpqnrtibjgsfgiaczeqqckjtkqzxauzojrcdkkgtsabajbfkivakikfscgscattmkvpvhvqbvtcgvjqfetrofwhhdbmfufrecgbjdumbnohkxapevguafbjiexnyehdipgttcguqudcufsaaaucfyopcnfdsmiadowwrcsjyylsdfugirkppyftmmwgaeidvecogwzfukzaswgcnqreryzfmwlmcvszcuniqmplzrltntvcjogcpfhbduqiqihscvcujuhilubanyczpibepjhvdxdvhkplhsgronbzidzxdbwslyycjixofckpnbawvgpjwrigwjdzmauzauclcbzkelztnzpkifugyemuopvcrrctmgeqhgalrbegdurlbntzrftfwqkoimhwsomzuplnqrwtlngoazntgizdbjrjxahpqtqkidybvwwijfxlemenxfqyqhjpjsganxmwamzxivgtafehtlwqsmqlvbaethghgtfgfggodmjetqnmbjdvxvgsxjyssfbyaigfomvsyfyrvneyyjvvgenfnlyhsbfsklayyxsyeqsbdyzbhxypbnvqztxtwemgpohplzqqqirvgtzpqxetlzlmukfrotxfhevvgnlwvetdzssrsykdyxruhylvslbbrywxljvioplnhfhzdredpxyywluoyxrqxqpkzlspcffjkmlnfrrwprvlcrbboutnkixkvrbxwgjgswvanowefrpkksnaninxqmjodlnbrwjmuhokvkodegpoycpnkelcrwswhgybejpzqdjmpxrtfgkekbrwfeyydrvmzvpdeeevjnjznausgeysfsonymlbfiqgdfmimqdvgmwvorpwxooficsiqfmyocerhqzvjerpsnmigbeersjzwdiniulwyrohkpdtwukqjwzsxdwpyhqukahsuurumhcwyfrubbnmxmeurclpjckvctozqftcoxamcthfuusriynzbbrkddghwwgmdcqrzsdelmlhidaqeosfrjrwozdmxmbaqttrmxxzljhuohmsxexoprkdqqsoctqsmkjyjhaushqgqdzohyezppeghwwjpmdeyoehxeepnuwexvuhvyilpmtwlrhcfkgezllwrrmfmkllhfscdcpvpircbzehlllmyyjpqxwejhpqmkssmkndugfwhkdtxofvmqmepjiyqaodkjvytkcpqhlytorqcylrpaxejifzitesebszlupceaaxrtovrbmgbmnmuumcpswuuovflmhppjmgccbugqcjcrwwlkabcyxwmuezhnowxdczhfvnvazztvxfhzijxhimbmlizcgyfkamqvcnxbpryoyfogqlpazqmlbonhosuogkmkzjnqanfauvglgvlgoatpqgyeastiefvgqiwtwdtqycdhzrpnriejqdnqxiacpvkgggbcmuukyaryrgnkqutgzgywpzagwkmctngfkdpkdjiupyeisxorfnpwoqdmarpthxytaqdfzozqmfygenzkcoisgnejfveotfhvvkbwacmmknuocvaemjwswcddyirtnaqiltglwsaghwwjsxneglyeqckokbjzczjptpcrjexrbtatsqzadxftzrjluskwstnniseswbjxwlspbtpfrwasnkgicqgwmwjwonqkqbknneeqyvxruyljirtmkcjwysuoilyymknzptqppngllruvloivqttqnnevyewlpjmgdexusfffwzdjpnefgzxvnbrngpaxypfdtcxnhevfgypvnvdvxaqkejzkycjzrockscyzgtgotxkgtndqptctfdfdfocwehjwlhxtceixdsfyhiqwbssgyxmdmqcsxlpiumcwsktweawlinjjfbsfbglpwnhuaweulisfundynalvnvguyaazglofayzcufwhqqnkfslsswphtxcuyevgrmlrkmteurokjbuotfioezvxwxtwbpfsbqllfgrbzflkghycpisthnsenmcqdhleayphfgigmvrucryraqmjghpvvsnybycbztkebsmnnfkqxkjzdyilhagcstctugxtzhzcalsptchqotrrrbcabictegpymotnvspxfhnylwqaphtgjwgkgkgksvkejdtgxledstdgpuifbbnmxwxgidsbadhjibrimvngqqmikwnoycaxyzdjcwkebtpluhtiegrvzfdjcszauaxvzdeezqicjynghjqlrhgqnlcpddpadovfrblstvucvikctbokiwdvihmlkbnosivjlicedwjzgtdzwrmforcyypliszykhvuvdyzhuiideleafsftjkrhbcqtdqelmagpyhyuqixuwcwbuewgonnprfivwoikoqbozajpkilgkihhodncsctmidjgstqijtzitiagqnmdxumlzbpsdignmpvginqthpdczfistvvsrjeqkvkneqdshyaroskvkqxjvgbqdyjuhpmtkzjqrmkzmmqafdxptvaqdchicqemhqfrpokjcuirharodrdymdprhwzmofyvvfonwywyvgregjsmaxkoabhkziynnwkkdzzzzxaudramcsyepkusmdenlcbaalldmmfokhinalbddzjvmgpajtnxvqxxckaqxhejopwrayufzfcnlrnvkbuhtrexehodqumhjkylkurmztznnnkxqehjxnjbwxgnruwdfuorohdpdfeqsopkswvqmetidcxxwtadpqvdyavbfzrxqgjifharnwbryzouuqykgvpevkfbmyachkmmtnfglgzjhnfcddmkydquoyvcwvgfhstchyjshibqyhsdmgpnkgjaggecdkklcdnkeyeljidhpwkdecqqizqohuslgeyjilvmmzzvhceyaqehswxayoqfklqrpoczczloamlirpitfoaylyajotoaeftvtvvxuilvxyfonphvekvpivawqoywvsspnpokzahwaomofwljggaqdaourmqmekbuzqgzsnxsdkiiitsobugfvuzmgrylcchduneoccifotnwohmqcsvzmwnupnhrpovldzbfdkkrfapthdjlxgkjexgulnncekqhktnpfzhkbyejcpubyhlcgtyrgmwkwouihjynihxmfdvjtrlrayvhruazgwmekgnspnhzuelbiindcywcyrjrlkqtieavkppbcwdwcozmzmpdmlfkfrbsduolaogndxoftrdwickjramdntoukrnpnbdqpjdujtbcneaxilgbnufcnvxaompensueexanqbrfhscrfitseywstvuhhllwehakeazxdqckkhcprvjwtiqodkxlvjhbqklxmkwqdaanhcfzxqvsyngexepupywhijgvwclzfnomsvnrmkkmxsquyhrpgnxqwfnskatpokdgfrxtbjgbeyxcgosobrgawuuiwoxmadsfuszxdhahfymnmedqxkqvgmeccdpcgjicdjcjqcqvcelpkohhazfiljlqocsxncbtlfcbiuzmzmbjakrdjwlxhynxafuqiyjtdlxlfyaekdqmohpxfbuobhlepiuxgdsjqrxxpxezaumqbdoiekyiujmjtgiblcldukaljeljyzcbcqjjchrwtffolpqysdbonbzyimjgnlisbtbeducyzkmmzekthnhwojuyxeflppdtkgzpabnblcnnizgqmqoczlbyrijgzobjuazweoxpsmeblltzbhccufalpmuoavzvyatcptthfyitlbsolwqfdsrsengfigcggxkxqghwerrrvlfgivnnpggutobeufmdcxctdjrjbkawvheferttabptpsxmxmpcjtxodqzeabcvigbmxwfzxxtmpsyneprpjofoegsehubrcedbalbxiwmxommvefmnvubzavfkrjbtnhuosxnctzbkmqhqvvfrpissfaeyjhtyopoinckgdmqrezjzvosmynefpkdaswygmnpbrbhupamtbvvwmpjmcpstavtsuuyihpjyrsugugawexuqmdcpvukvsenoynyhdhhubbcykcuozqgouifpfpmztzptonarwjnznqxxutnwktkgdrxkgjlckavapysnhhnuzktwgiuqbgyhxxtdiffshduxbomkwzhxmcvslpkmvkvuhpapuhjdkdcnspyqohncjjuuagjyqesxtuopcxvmbxcvmaldhyfqjcnkiwkzaewwzlnbkipngriuttxcufvdhippeboggncfasimaxairidmecryhmdqwvgcwwiclnjnfrahpaqiktwovnmfbqvxldbjakmlzxzgpbngbdolwkauambbeyzrcabcmppnmqtdrhjukzgjmifmwgnbeougrxkfoctdsmgmvqgipordwwptefwkvqtooduchpfcdoozewhvlybhwsccxymvrfjfldjssruyfixlfeisejzcccebcswtyiajlmdgdyekidxpjhhprjrvnxyppvlpflasxeaceeomjlesvnhowajlzjbpgmglzhexnebrlqfudlpyzwmxzxjyhkpnywzzfdwshaluqspteesfcecdelclxryxpzxucvomvbilwxhcdzhiflnjxpwwjvuautxzonnmpvxlvepafwknjywintfyqbzmuynklcyaawnvccxkaixkgvsvqzwicxxyvkjgphjpfymkbjwdrtpzqkvjlrroqomlbxrqhafobraecwhwrzvilsrwlkkbzzmcyesfgzwjswnutvqkwmuhgndsyqtzrgbpmvxuuteoprikobvknrtvfznfphginjxbeuvanboftypjzmwoepkloxsfeypthnwnjsnzvdeqbtadiwtondbedtljrbdaoznztcypfcfiyhngfhutkvznqkzhlcjbdwbzybqfexpcfdkmkgfwdemtrlceplgujjtjkloqjfuqiecsmkrpqdkhoomdbuxkftvrejippchzjmuvwlnooxwcokhpggalzveghmvyrfzcrtxnembumzyalfprmrelpjryxpyouxqltqaxeduqfssqykkkdoxuxruvislcsepnwrkawetbznuxxejdsixszunhoalgectavgdsmyvllpklttoocngdhvnwvaecdaeagjsuhqitfsgboursjxvruiprlttotaobjjytzgogauhoqyizxesrohlzbgpwggyspwlqebwevgvngdmgjfzymkzprpmzvmrmiecohaseiprptgxenwcbhcratfzortczzenhghlpzfguldyyzbzifskyxmoqfqpgwencobrngzhtchreismpnxpmjddqvuwrbmwrppgxpnqrujvfdkwqhmfsrikneigfwcwlscijraaojyvnirfrfklzsvmxdueczdntfyczyenkckxkdcbjnmihjwgpslrrogmvgouftjpvvoizqlifyspjovyiipayymwedslwectzqdyjpiqpafyqdxznobompmrseeqkhmkzpkievbtvisolrpbfsrshdlajrsuyegawskcnlwluqbhjqkoibipgvrsnmonqwnmoypclnphfqrogbeqfnhnkzfzltndpcsgcjkoyzxfpotvqznxoukzvqyilnodqgjsrtiruiwjwrgoqtlfpwgloetbsjgkpreimnzgvxptovihqtogruthaojuypenhjytyzcvxrqnpyuhsinlegtfvczttgicriyriamfrcuidpqxzfieobljfmebsodlxbchdqovtifyxvvzdddrhocoagpvwvgvwjcazsxubeuacpzfveweuysvgkscfaabjedlxchahealtcqqgmubmnysxswesyhedlpapyayccjygzonnjqzyqtxisbaqietvvvlwxlaavagwpvkanladhznzaqrkwnguitqgesibtoykmimzvofcnudpkvzhihdsctyhngkixiulsikowrslowaytahbjktmfuvvcfdzqykiixyfqtqeprfktmlezgqgclbftfgjfrtpquugnnnegsobgbffjwomjptcwzndqjtidnpsccwiwkjcnpkwnykyndbkdqpvbieeyvyazulvgwxtnhsafczvgchluwgwfmcfhbfgxsdepbzcktdsweneiurcqzaxmdcvgkedchjrkjuxezpcfcgpyzrqzuonxsifcoifysyidufjvumcyurwulntfdievsjyhrfflfpqavaxrmasgroccdxhgfncywcfqjmdobuqywoqkqkshavmesvmyjoyhsfxbrbssxirvyjfovzyvukzphmpqcnyxsxyjasdxdwubhzsczqyvcxkjlzcooclgblrcgvbjrwmzxebywzuazgmkiqawundvzwxhrzqlxemujpvhrpiqxwcfmdcgqhbrdbaxcqizvwvglqpchzshvxmjaqpsxtmdwmayfkzcguitnxwwzqdunqepivkiqwlmknkpzlthibavbwtanxwcpcsxycfoasdkfncgbvnjzogcmzcbyaendyndauranumukobnmqwlecntdrucrarwygzabtcqppmbfporgkemotfumcygepcfycfbxitmxfoevcwbpcpfyvbkzzqdrvipzqqwyjixqybldzoucebabdmccdhtyskzicvgnfdeeerjeidimekpjwrmzyhzqsyauvgiblmhsfqynvibbsqlojzqkgrcyqdtlldozrvtwnrkkznmtgzhpyzbergfjjauwdlxuiqqyhciiqwdwvnnvmrcdxhmihjekwcgeswccblmthsrffearxcxuljcsuheqlkvfjzjkkyfuqwbvcdmagjutvxmrgsitdfymeiyrgdnybotdrhfztcvozhhhzpcewasdkqusvjqyzlcstjumlpamwhtxzxcvywyknufkfxjejnxcwroigquezqbanfwncwartfdycmdlbcpytdizvefvwivmotbssblniolldqyesqentoopttmrchdsdfmvixirnvesoexiudwqsmhngtekckcfroabnksciyvwfsezxcrrpyevrlhuxjbozcpookqwklspfzpdbgwqhdnyouundwdeassoelnpwfecgvhiedylimlygglmcosejnsnyfeunlytihdmnezvqluythmvwfzfstuqbbmqmllwupjhtkflvbjoiwledmlviiljjzzxmmthbeqwpxhmytbhrolubzplhcuqbvpqhixlpphenpqlktsbkgvlfmwoosgrpvhyfgjuwrajitwsoptyxqlccjssbyjsttrazavxtxibqfvfwqdtipxkypccnouijlikofihdslvxiavzgqhxnuxeyztmwdvjmgxtqfwissiaudbaujxjfxodyjsunnebvdulirwaledfheibphnuebadmszzhdcdjxqtqmwbsziadqdtaqpetpjghjhrokuxjmrzbnctmmvrfzmfrclntvtdgcuuoquxclydacxopufwtubnyoarlvurxqomgiljvmovonlfiqddmgqkvqcglyalpozvymgtyvopizwqrauggmqddumqtmdkcchapotpljetkdmddijlucpzwbsrpvdtaltpbogmznhlqvqvdagaexbcaturrzkrmfintobublhtgyomyxoewpgxlcoccbvogdecrhwvseobcfnccbiysoxdrohvpclxhrzbzywtcmugrjktmsufitibhsyyukwcdvdctbyxnufferaqlwxuqixxawywiualrdqngokuksboldhxagtqoqpqonnwjnkdtaqzqcvauyrgcafcgyuvqlnfbadkqpnjrfkhiikegdkidrmjpggisunvwsfmivxzakjksvpaybjbtvkketsyphtlaaakxzlalukfrzgpdpqwmdgswzsnilaioculcgnpcyvuzbjcsaagfhzditqqhqbvvvixdwogwjavmlaenalsjmvtfnmmgnjbksaoqowmayjmjjrxmervsnrxcdmksvlepnsfeqteofqyojvcpmyhbrhgutqmqeqgrlnvbjzqosqednhvzhcdyjluebgvfydzlsupbwhpqxwvkdqlmvqmgbglfoimonlafirhgyywvutfzkqnfhznkfypvickvpmbxdkdbibwfvdehvsoerbpzcewkigiyulxzvbadcyixbpgxhudawsbyzykjgshddfcaifemdomhfsgonjrjeshdsrmbmwgpdiqnnwztmlcseiirtzaxsjcmcrponvgsgyftueoisqcwalpukpteawtcnitcgzumxbhthwdzogvptkldbekdadgnnzrtalhzmpsunvvbdtswfdchimmkrsagtrcvdjuryonnmjppchohnqqvedhvxhdtzfoepjvpxldjusbybphohylldtiaaltbrifitdxqoackudiwupmbpamsvwtxhozaygirjgkxgojdrrbnjnoypctkymifcjibpqsbweyfskklblymaonqqgcoumwwvexnwsovyoarykecxfoxtbnkhsadeyacczpztfusvwluipyfumeqquczmcdsbfufelgyqcsmydiiugpruuhmojoanrsoypwcacctfwhfbrqwzfptzyiphwrwnknlbjpdluwsqfaswqqvxfrxdzomvgiksxxtgowuivobcotbglyesrdxqrlnxtzprykznjtxeiyiytjfgijybmvsdghdcjsvjfwyoqysawcasmfawqzxcwrifbljmfgvkcuausswqxxkjenhvogzkahrbucpckkongpjajgtgffrjsyeghethnmikpzmzjaosryubgpjlvbupbbwihrpudzeuyswkvmemmypuozflccaffyomrfgvhnrhfptacxnqyelmdszhuznbadnrkuorjiboxupbuessifgoxfvsgktgnjyyfmrouucuprvlxpdgujusqpmwahdpqdpxrhlmdoiuhfffvknrvhllyxiahnqzqfxhokvuydoijupgeezallnlkvmtictyjsiacdudhknsecalgzntkaexyqqiujhgdpiguejbowvvaviivvdhxhgvaxgwinememsysdchzxebvmjsjmzgvgevfkunzyzfntffwjovjsweehwptvwrdcmioiynhxuwrbbplslukjyrtugorefxgshwcfljfffwhjlubyonkoedknrdrxaarkwtpkfupmsyvguygimsyqxifpmzoozhyxcqhjmzwhztnuuvegqdynneezduqebobgglrtmpanlphfmolcrjqenugspwwsmaatnsmzjooudwzpkksdwkjlerevncqceqxrkjsuzhqcfqtrcnuyxfmexsbmurobilsuwnoxufzbxvszkoaitooqgpfchtdrhylflcdhjekgbchmqjwjxkcdzhiicnzlllrypwhyareevlqlvmxuwzaxiigkvhwjupjjlthnknribjtwvssttstbaboyimjdbsoolwdyjvgmgbicudxpvqrwrhwatffwztklrnldkrptuavqdugylzwcgsebzlxzhjmyyxblqtektbbyvhyiivnoprrpfqomzckzzokrhobcrecnnaxvvklneccjssvtuhtvvfmewpinumcjnafkksxoxzzrtunnegkblwihmsxifzrsbycmtacqbcjvywkeevgqtozhgwplyjfzjinckqulugiuctzhqhzjvardzirxtwyfgmhqeeeakmuohvxzcyjzzcdamuzgsxlzjuppatpmimdrharmbcnaeqcsmbyfylekivzkrpxzdcsmcjydlmfrejktkkyjyevizusqlrrotkdyvbdjplawukrfxrqvvldwhxptpgjksmioqoxhzzftmwajnsgkdjhniwixetixisnygmhhnpbzndibwonbzuoisyhxsrwamlaszjamydomiypencioxyyrxiopzmrlxrgyaglblzntxeamgkdfidxhlnylcpyziealmnmzmbvlfxalhftriszwfzhhrhjzmjkywwykzvxeszszglspftlmtuukbflpqwoouoaujzadzucfhuwmojzjfvvjagyseoizeivnjxqksuszromhalqfgloirpcwdkxiuuxdrqojkglbwxiykagslucfjedpqaxmuurnkfzxnkymjjmvlsnzpreaxhpnjmzfhqstytqndrbocojngymvpqwmznbiacnjvicvbvihmmxoahbihqgzgenirpqttgcoohjpcuyqgweifhqmxwngabouqgnjmsaczjsddsvlobttkkiiivqlwgfoouabmadnlxsrqnegoyczkkjuhbfgjmwxhwyvyejmbdftrjchheitqtoxwvfficdradmbjxnlbugudibnomgefweesjjclotoshpbheoiyxedhhqwtzabxefpqqtdfmrzwicdmtnmqtqzaivwjwxhceyswswbgpccyfhmawzqpppqznmjllsnrqinigrrvtvvadiabhsrykjzzxikkczbthqdphundsifxsiybcrzocbnblxloxohgfmyojlrbvzyohypjqrausnwdlhrkyasdpqrydlzzkzptxgepxekrsixfrqrprlsgemghxfijgxedeivdnhxhpumgkfwdqqlucrebymkemokszhvmosvfojlzojcgaqdehhggvsmhjybifzwvrraiaohqxlwzbzelgmteeflpenxlmvhfmjnoxwexkdwlccwlorpvxcmdrmqfhxlwjamgzrdjuawyevjvmyslbeosshaaglypnkwobzzxbwyithdfixrldhfwofwvsukgeiwikwhnufvnpasxxlidtnzjtvglrttxbshnopbiwyvlzpkydudwichdxqqqjmomexauobelbbycqldtfgrpjbsirlzcxpodmoxbrdoteovwzyshflwompwfaxhzmwcbmbceesxkisgkrarwmnmaeiiggpfunjvamzestdccvlmoldmzsyaxjidrzllpwjplivdcyievtskgxygpzioisubrhmgdvxoguuiucoqxicdfalwztljlhkfozntwnkchemciasfkwipyuoapzjbgwiwvvptizwqdiunlosxkdnkzbkocwrkszgpvvifxgxcrrqefibrlqcktmzxkshcsptpneukmsmdlcjtllkydolxdkunceswtnlgtiqgcflnhvguittljeimqfcujwtejeldmdloiweqrmmbhhnrlxfdehandtupxfsmkdctbilvvzwchltslzypiyfotzdsgxeqcjldryamyxrfimzvnzlwzsmsrrlzorpsadxudyidvzkfmmbzloxlgjdzaqyqipiisgeyenbbmmgayjalzxwfjcelseccuknosrmweqztcitcrtnttkyeofpilrlfeawwrivwyupceieyesrzerdsysckmppqplohwlfwiuzmefkkxbjbvovtjydvpvnfidmeprdxnejtjwejzpmuekonktkzozexcsdrjioymasyywhxlvsrfigpbspsrvruowlzfcyteqrcoazbwttddbvhumzlhshvovxvzvpdlihbjichcxmhzhottpgbhoyyjxtisknfvuggcjnggbohjcceujhbzibkfxuyhhdcdmihvxodzclkgpoaywexgfjlcdjmmpqpbzxyyndzrqlxgcaeageglnrqtbcfsuxtvutujwvanhztjbzjhdpvtglmjptdjqyfkrbtqwvdfvyowxzedqzyzmmkdfomwmtggwcwvzbaubrtaszdjadimpspvidrvzzdvdbqdctzdksdcrjnrmvfeqwzyaqvbpyyvbpydixiusoyjzmdnhirzhqyhivkawivxzvbjuldmbcyaqbqzlhzsazbiunkqwhovcrfxekjgohiekyeyifqieusyhfrfmfbpygocsxihhrltrrrzwkhcecbnhuttzwkxeyzwykdfdryuisuhcdjihmxogqkhmwgqvgnvsscvjapsujbwpkgwxelduxljvrbqzqntjpossemmpnleardxvqcsnpdijebkvoegguayapkqevwepzdkpgeexhpiostlizrotrmugxmluipjktwbbagakxjapelxdcmytyucxgnureddzzeccmdojooasbyxdmxymsakaperwjwxlbappfdzvtzpuzmzllxyfakgroznzwlkznzosennxpctoqscdqcjsmpjcqzbokmnxncrsreriilzadbdvdmprdztuyukkiyjycaqvgjeoudqagtxlgncloxhorsycqhaujsppbtfwyvygovtwkviaspomjmqzvqveklvlgajfvhnmfhkreuszmglvvbxqtsxddsqmtatqjgeqppiujctvkgtfjqyckvhqnxcixvbjbfztwjnilifwoybxqbbbwkrmhtwhoxsrdrkbbzjohpkxnowepzfojwatrychwuablncommdwbpvqfsuxrblbznwslyzhsakdpnubzxzcovsuppriselurhmefmoxoyddlzgmyiqmfliuazcudoowxbbdppcfnhkbgqneaerfpzbrbgngucdtfgwwxbbminnpdbtghmlyonpptevpgainihjfimsqzfhfidlrpypflguglsxtugjdpukxjcpikzpuccmtbdzokvvxnuskabprwzofcgpofhijjwcmabbmxylmsdwvhlmdndkrlbfsipbsmfgojhaihlucqtzxglctqomdqrvyhysvezjpijxswtuomtovgsqzhdczwazfauagvjvdusxsmtjamzxvrqwavabrabxbvzhqldvhxtclmlmbklydbugwuhoxinadmhvzmrhmmjxywlbixznyvtxsblplaproymonfxzriwqeitmhvzfqveiyrzjrqcipryewvdodbghlzvswwanrexpwzbppfxgwvktsnhvrpecqbxnyzarfzjbymtqrqwoohhiwqenfksvmrkmqmfvmozmcscukziagrjejnsozklndwbtihowxnjahnwsmgsuxbziqtwqfjfifhbqqrmnhxpollizrbwqexyxqwpxgufnbiftbshirwzckjedmawrzwortdobzvqdfwwgqdrhcsmmbsrounhtkvkfaaizvaccwzkoebygvmuxemlabsvnpfsphcqedtgzuqqauohpcdmirzivtdikkbbrdsxgndijvyjposhqytypvikqntbxwcqbwnkjssspsefiwoyujymeiwxvryupckrzzbirvdgnhnvdbvanvmrfkoacoutrgkqfnayifgvmwsszpummgerqurulnoetyuyowwwcduqbokaeenqktidpbxapneioahczfydkuvljgmnmzfzuncjpbkepqmftvhsbhxncszlylynmfmgtopkrbqiuennawhdeeqgyprzcrmowywroobfptqjyfyacfdglvmklfjpwvguvcmjqpqijitjosjqzmwnhkxupimnfshawvlpnbxymshakqqmeoznyykniwcnqjpohafwdeupxdpjthvzvwmtuyicwkrowgddgibmnvbmytvtatuwpgpmhyodkisgoxlxfmjuhmghfecgxwcmftymrprezjkngwmokxkuktbpxgxuczihtjtmynqxwdmfbbvlyffiyjaxpxtrzczuluilhzkgeylfziqynwiohilwifnhjobwljhuktcotpvtxmtlkbzrkmpstebctcyglhcycfmwwipuwkhilibxuqrqussputxicagfhuddeuzcegkpqnnndedaxvptqpdtrjyygddkxfpbnzqepfrsmuslrkeibibstbszexmbcbescuwrcpmolgzcsdmtnpljqfiwdwzhxdzcyxvcmhqxopcguockeptwvdvyaufzyhbyezargsqwhufdjhnpwinrmirmdzldgpdkofbwxuteoyjzhzofheztmqhrptwvkziaelwbfphwprvysmgzqfvcxcwpxsmhsuhygeanvhjnafnsrtuhyplwrjlpczywuguamunjezwgekbvfveemrcddpsfotdizxknuawazvidhjamggsszuycjsjylmikktzgvwgutozaaboihhdibblntulfhvrtotzlphfkxemzfaiohlxlmkyhelmnggixzjiqqqaqwopcoxsyirlwbjeiwsxeygbzpmpieryafnewlxwvohssqyaoqxsrdwqviidobbojqtfdsbziktactcqjaicfetcodhcekrnbmueexfohapjtrzdtkfboaffdnhkxaxyoufurkjzlykermjnwrqmrvrxibhgdegsylmsyvtjvdpnrbcnssclntiwwpeawkswygowejhznymgzouriwfwrnuofyqdkizkqqiuzpuoqivpzrjhpodgdxwixmlkwnunfdjeudvkoscnllwabciezfpzrcjqpfduiobfuypisrxdetfhvnoxudwohhexojtxxucrutzmnyptsudnkrmewksdtycihwfhsjyneaztyrnsnqizjuehhykazpiglnpdyqsfquyqlnlaftaopgvwgixfxfokvdpvtialczeporpumribxgaeozlnezxbdozywzmaaqrpjjjvatwybyepxpeepdfuseuqggriyixhricuebsfzyxxndbehiazpvpvbidctdjmnogtpazqyynobquibvjqsbnvjsxcvjplxvgoyfewfumjkhrneddweqrnjpsgyhtxealchrbnlnwywplaurwyhoosfgzfpsctspyaibpwolwncjnxamxkclchrbogwqcqhaqrbhnrujgxtwwvitfmfivwljfhbhaijsbmapfuamtvkprulwgqebosktbncbvnuyzunhqovkjfzczmzfcfitxsozfrccgwagsqpjgktrpuuohttlabeyvtzcmbgsaiasapbgzwaqtueapznpcspzlqbzsjrssumulqblmbbfxihohvfmnxlanpbfyszsomnacqnqtqwsyfgianupkhrywsfxnfrbtgdxyqnrhljhtrptfllrtcprxvqkcinxqrupjjgqvsyolpjsbukwzznywekyoxveqrtabcsyusmhixalukhvjwticdiqcgxtxsvyupyqikyskydeimztksbnxmfzscupxpqrhoipbgjleoroaqhkklzhxhipjdgiuyabnisqqbbwpsmrktcwgdffknwwsdendeqqojigkjecdqtpmxlsbsangwjabqnfwexlpgtzrybxqvmcuaxvsxjatubxkqchwzulfnlxnoueliigifddcofyjgvvxxctywhgmudbizhwjqeuxjxaycajlxekwhdufkatgfxpeenqwtkuchwclylwvqirzolgyocftbwahlqeeaaijwlwwwvrodiprvwsjazdbxfiivooxowgmheigzbudjkwfioqintlmatuvkisahanqhxwgzrlkdirlyivmdgaebvblfwooybffabmbuzmxhfkinfwtnwxrraezwsnvvsawwozqonqxtafiibbxyaopbtqxleshyvfujelxsdvldavncxlazzrasiagounmpujzywyqztdcwzsaydcxetaxdaftuuikorlmnjfmfkqbliblldjqyjpelwxhqhteyeslqzxvmqwzyzlmeueefvisrizjptpoxjbpjbkxriwphhdndjskeccxkcgcvvsufvkqwwnnflfoticwswjyylwlncpkahhfctxbpmowxvnqgrpanyynlwybbplbwuibnfeftsdqqqjwhaywawklvkmwaazyuhzkofrhyuxqlimuikriibwdlibliakfjlrxtigrcgjpoxkxhbhredxpoydwbpdkcuivcqohwxyluikdlrxpxuhlumjxbnifjsboirvfrtslecrrvojskqdgcpefeomnipbqhyxyuplyrernuahgqnnuctbgjotrdxjmvjmpyapsehhbhohybwudrwlamftrcfgxospmsegzlnatejtfgplxlwazdtrfyxforubmajnmxnhdwaiepvcdueexzxdawkoogrcgbpuaebdcdnhvllafpecochqarfqxwsgzhaznceqhsxcdkcibjkpnuinlneljyrjgtktvplfjkhmumwvvinkcvxqidbtcueknrflgrqrbzdylbtilgsodsgnxhjzdnjsgpdmivdlvijildtxlnnrftedcnehdqzjhdypadavmmgzpzycoltwgabknfrqvtacyytybuupgcrxdpbrdxnlxoykupdrkfuidnhgjdyrfrqiguzlrpxodvaxmfpxklhpaoykrwdynwgvqihhxgxadzarfrqpeyfemdqebwcqsllivurucowfnyxuppkvnrcauugxqknixassxjozzlhpjgjbvtwjkylgvrflduwbvovuaktzvaoggyhetgnggyobrunuojvlzrfzdbbydremroqludtadjcudrquamhbfpbiqeitvofncxawctzfcbbisseuglvnayxscfoatvnytnuvitdmwguqaakimivogsjlxxltsarnnnlxjqjhwgyzgkhusdlbxumxtzqlzjboymnjcwracrzlbjfumqvjkjgfiyrjjuzkgmtkimkndmyhvfbjyyukjdqrdjcndbzlnuvxhhmmvmvqsybqwwafbsyebctefspsnkswuekprgilejddhfkiylpznigtbvnqihmemytfebslnxowcafcluezekufhjxprlvfkpmqsebhdrefslkfhoelaathkqzdcuiolueeaildbrkvcubjkhvkiouugtxkphybdfhdpsiqmsoonpazwvkglecrzzcoicrlhyowtwpfrftgutfsqrzbvbvwdxnlzezjdnhwmydddyjxuoqkgrodujcxipljvksyzcwlazqeybdsqveymudjffinwtzsftsfvpsyqlcqmhkedrerliarpjgoefimbatwrnukyyalgnrlewergfixqrlwytizwbynpsxptycbnuorqsiyztvrkjoieykaciotcnivnlyahmrxfcxgxsyhdorimbiqlyjomsjzfkamwtldxikuckbiyvqmyadkzmyngjmntobsimvfwhabrdjrabezbhlcvjpeuerqstichfkgnmhgrsystetwnebipsojwibrdjtkpfqerzkjrkdkowjbckmrcacbieslpnyetqkkqvvhhyuwwdzyplptouuwymknckuvaehqbdajduhazgyqsqjgkeeksqzuavrbcztdetojpvjoekgyaqgmwkwodxjdtagvbaahvprlmabqkiomauywhwkkuvppwymzamhvbygqakgnsxzutyqawamswehuctvcgcxjcgzdqiqkfpeypubowpgutoqvjmzpozbrhawxkmjpdpqvlrjjgpecduzngzexyhqhkmguapmdgcytvhcdxgfcdfrlgyigfanpotmokyuqaujxclabugfxnzktxvzevmwkfiapguhipqftdfwzndwccjvbewgzkclpmmgsgpaxhhslookesjguseywaexlijcuvlodaqdkxvvnmhresyameyieeirorukohytjowtnuqbgysmssmfwnndtxwioqseztyjjwexqvaytuknpzsnoiqhfnrufmahfysqvwpnrpmmmwabxsolahtiwmedyekfdcwablnsdbfpafqxzgjcneklqoppsbwxgsxhenzjogyqnoonuzrkdbxvrmmjqjjwbgdhvesknqaaeqpbpgnujkqazempnvnrdsazytlljnmqebtvkiqtsiwtmikcfxtipvjoouzainqorljbtbunlqhyatcfrvqiqzwhuyhelzuekfffjcsuubuvvwcorswksvrotaugzoljvsoeuizpkvmhsovljrvdmorhonqnbdyyvodqxehjztsrjnfsgavvroehbuxexvdtkiljmsulnmfybkthmoedfjlifknffsyralcmfwzskeqlolvbczghktpsdexjyxcaifmndohoszzjlwknwsuimlapszaqwdrekftnvadoadzlzlyxduipfkfzkfsgijluqeimhlchqbssmsrrmzhtkmtutlccwpyowgcduekmhegvwynkzwdliyhblkfjzgyvocyijkxsodomddwfbcqjcymoiuzjazhocfzlsydgdtvjyrozvekyczomvnwxndlrkmcemhnqdizbbndxtnvwojkjyignnueyiievsrlvzmybbbaurvqhgdrglzuztazeldzdvmawyyxzcztvumccptlavfbqhausetxzfxvfyveauavroxvftghonjgvjbpnunocmmhkhomdqjwghslcyssmdyjnzycwnraadjmmzbrpkoxtgivgdnsgobvpcylprlrwvgkuhbmrrjnzuigzyahmedbgdpxwcrszxcwefkxztkypvgovjwhnbkvebuaelufiybofloehadwvlnqujzjmmgsnbutmozxoaltobyvcdtzogslrtudhbvvepqqfrptudnienfiqykgfctwxocfrxcvpsnwmdqggfokstvktfsyjmxgczlvypqpifmwiecqjsddlypedhfmvcuzdgudvmtfshbcldtuxwziwopzvwntahsfpninzbstkwwvbrrzpqjleamcwbvykndacmnephxafvvhmnidfrokscoqdjpoyuodgdhymgysevzqkhuqakcunqlsbcgbwwgfbndowdgaahslqodqzhnoxaiacpdankhpzmfvrlxsuqfkeicfppvoreqtvtwidfzdseajrybloixuqcchtxxlbngwhchmigrclslespqixpcqreznexyfkeetjlittzvgtillzdvzsypmeqzknxsadwtojbhcbelwpwkqzfptfgfmxewkdokhkgxvhfaklljcjttiyiberjqonmarbnantxlcenpsyyuhrnrryuvpdnftahmdumsplfussjksjebasstspphscmletxjqlefzjztekdwtjyvdspvhgecksnronceaglbsnuwxzutlsqolhmunqwajkrxztbbcofubbsbbowmhmcuuoojfljqxcnywqzyeguiioljchxlvbhrqwdxjmngrcgnshnyojgwzrhdaepwhwpxuswdhllynrnfzaenlmlkgsniwegfdwdxqbdxnovagiihkowvahhizvrxzxccvhcmjfjythybrikcwgzznhhmealfaoivxmhgrtgmcfotnyxmhzlugujmvwrvkbqinaqgvxtxejstjqfqrsnznyliucdfevptxhasgtpmckincnetitsvrfdlhisnfjhdtjvzcnogxwtzlzutsmolrtxabpqhbzmuihvmwjsthnutpomjcdvvwswyjohkntgvcchznbuvqroffcpkfkfcedcnrlaeegbikkjyletevjjcnamtmsxsvzipmitsqxabhkbvqwznhkpuncpbwmutncizmercbufiggdwcejjpagcevfaizuxbexniqsjkzsqgxokcxwtyexezcfjcbhffgvowpxjorzwrqhtnfonjlskpzurabzhhuvfjvozoqwfgfyvkojvzdfpebigchnldlrogfowvkcbpcxbriyqnfhrhsxjbmxfxotftjcrteskgrnxbnqotzharglttiasyvysfclagfloxaoaogrhfyjzhwuahwufrszwukxcqktpmhpangjuhuvorrqankffdhdzrcejoxybgqdtynpfjnvaelcswizbpcaihesvdsyjkcejrwqajmdpxfhtpiwenxpudhrhbqsmuxxltnnebqtbydwnltuyqluvsmevexjywglrwyvzroaptxefqafilcdfoibuhkudtfurdrquhrlboqggqnocprhfbkzixtnqajjeazaiqmjgcrmueayuugzvsbgpwthxdqbdqdnipwrtnfqsgoocwpxpqdgpzomcgphysvjktafhfvbnkrpigpxzugotucxcthblekxxmdgrajhkayvhnsiiaydwadztkagqkenwjupjdywgxrpklxumvaivdhqpjwfvcutlqjxwhtcgmrrxoljlnugqdyhnumizjcmznjvwexdqowoejzpxtxpzvxmslwruadupnpmtnrkdpaiyzzvvxluskikvedqfhkuwzipobbsqbcpbbmyyzstjafhgjxlshiqishzujtkkvbnyqlzpfsbhziokfbcojsycaxylqkxnmlmeyntehwlggbrndvdmqcqsbqdsbahpnvtmiosplfyrhrhmmkaemtwojzikcrzrnudxjxpufnnogwashaxtvvjfxtpzlrqalwxuvoqcbgqhesclvbhqysvvmnwzepzrlyoinglqobatueerfnhfgdbsqxtwmspzsfihmvyayyvuealjntqvwrnorimdabdvhncvkcxictdgvorkhigfzvvqehwglbduogryioinjltgclrltzrswolawhjjimfyuwyfkgswulcwwvhpuakrpxtnecyordolzoqlwihqwkosfykcauvrtoeztcnmhdxgrqspabgwnwptwbxxvsooivndzcphhnpafhpflxcyuttquqprkghtbwycaojhdbhikynvwrusmniigazqgiljgklgaxpdyylixaetualgnvptvqmdzxmfjymjxdovcbfzcjswjfczatuykgbjgoqpoeblipikrnjvzdrkkvjkrekbmomscckshlfpcnzvakqbpjmzfxlydwzqmlkqnuiwhnlkamfcywenhsooramvylnkwxamuiibxunzivbhrhwablptnbqlndvlcxxyhgaecpfmkgvdqsetftosuefjjavozumgcomgertqzouriylptzhpgmzrowfnqsvtihbmaufalzrvzelugsjohkfxglnzfiunsvcushudioyhujbcemqnxwkfjzgoiadcyhyqovtyltfffiilxaywykdhkkxumbykiwczrxxcrfkypujouhktroadyaxmbvxlsbmlzkqsraqiuzxoghjzvmdvmainyhasindjztbqvrypqvgyfpycbdynficdrdvbsblrwmjsghjwfpvmhvokyoadychphetbhesesbyylhxsxsegpuqnjqqhvzzegsgnyarscrrpzojyipexjwmspeckebqmvwzvxtnbkeslubjeqpbzmnubuynybdkwclrbgecrluchxomndporfkuzihxjnjhrwasdhwwsqyzponesdsjifehpngbcritnlnssjombpnqdbuvephounvladmfuxyjiocaxqozhbrlcmiibpwxctkfwxksuiceygewysxgvoryczgdrfcvypavmknivrmtxsrwmoehdvhfwqlpvpltelosweatvomvgeruuvezslhqbuiwjtqqggkemlxibmfksyemvimnwvfxppwaioqpubvjottphybzwglrqzgmunmldimlwecshabxtupasqbqwohpqpbmdnygvkttqymyynvtkkvebwvzkeoauspxfnfdzywpwknwalpkvkoyilytqovkgmjozorympqladhaqzkmjamsmmnebkojxxxylozzepmgsugjtsxeujygynmzacizzixmwwoclaigworriowdzwlxmyymajlcrkqphgsuhcaftrxbhvgjtsifsjrssewlppcwvuseztmsmjvwgchzwpfoyyisdhfswiqteiaddmxsxvqdzxcvmjlnithncnfyxxubhuhnigffbxicumxiykvggfvisajrzdsgzbthiaolxworknaiyxqeelmwnxpmaivbjoitpwfouvihiirihiomvdklaaxdksevjnralyoitwpdggoqqceohoziqylctpacerespsairrnxxbpqgtenkfvadifyafcgygynzaxsrkprohjuaphkufnznsypzcwxjwkkxjcqttjhasbbhlndqadfudvtftsopeaoncfjwosyhwzqhpuzpxekczfhsaykeyyudddbuxzdtbtcqnbfmgrqhzyczymfykbbqecmeepxfkcvadcolwftxfxyfjddvfhnllzppqpwdtrdwwtkuyfrfcpkluqibxwnkxeaqvwvoqanotxiuczzgqmtkebmbzblzhnrfmmtcmiqhfabjzdrrrkbvopypsjoazhfltanhjfpqfscgvtxogajuqhjktaksjrfdsumbzdrgwvotpnixnrrfbcquecoouttmnfpojiwhekavzksoclwfnobuqpimkbyzipntylaexbzwntkpegwtuxpnmxzyaaxjpmcpzftwiusvnfntnjpkhexvcyweytpqiuhhzbghvyelfretbtdkychcadibzytjsasrdyazzekewqzzmclmgsojywkzufimhaflzfkymwekoelaiwmpqcyqbkpvrzkyarjbzvblthvilgkuexlwzjncvcymekkgdwhcrknnrkxfshbygmviviksmiequqwymfagrqtlcqqvzttgfoocyyuljadfqcdfjgldygoaygvxzrdehtigsctdcyiucmzmumpssfssnqqojvuqrcyletoiswcukcieqzyletdtjvhutbmkdnvjgjrahwxsahwqhvbnohhzcovvshhxuehdnafvyepymlrtiugybpzegubyclxypedfhlcfprgbcxuntdlvulbaheajpykfepmnaotqfbrjaowttkopxrqewsqnscuzrgmsuhkzidlirjemtscsmuxionvhpqiiyuctemuoqfxjrbykvadhucrirprihzqfwtaahvozcnltqjgojlxfppngghongeseztgjqviukvobewrnjouyfkelrsyzyteaokjghtaupqvvmolxcfvipzvgtwisrmufyfniyncpgzlunysrdnbvpxbitjckxwrybegctitbhgwweonkdpfsmidhsfrrekphqvljfflmljkszyccnhxbpaijhbdnlsxdqimvnzkbiuvhuxmjgjkxlujuxmikgfnwpcufbggmcbvzajiguvffrocpckzjrnhipdnsjtgowenynxeismpkarbfdaowpxfebszmofcmlplznrjhdytgqulvvbskyzrbrsohzqulihkxytectykjsvhpwzcwyvyrnobmexzoejlcesgyssjmnqclrgkrbijowmccjcrnnerswasqsbdiuftlnfdonoelagqjkjyynpsmpkcinfqhmlvztypgmtuockzmtxmiogueszogggpttkumkkvydrmfbluwkggzndffcvnibfdwpalakiypznxcaralzgkojrwnmlypqdlgdyipgihhvejwxjjysvpbmlrawppnscvwbdnjnurlachzosygnnjbyabwrqlkugixlvhzsaksctssnsyafkdfkebewposvyqjvzknzwidraweswgzgjetphxnwnfulvfgupwvlebcgziavozcxfxomublhghuemcabawoezsmyamvonznswbhqeuzkbvopypqyngfoytoygjotjbohevaipzuqxjfvaxvpfcfdwtdecrznunvyixizwcrvnysnxoecsjfqckwhbwwvltvwqdvpgpktndjltpnnzvedfcmjajgmeeivjfkpuwlizwvulkimfoqnqcyrngdsknpuublpxyzzuwtigbumrmbirzbgfeystpmnqzeoyfpubicimzwdlzneyolfulznbldrljhlpwfshictjayuzmbzamhvxgkyupsfzzsqyxkffnyqpwnpkoolcvizeuaykufltxdtunyccwssvfjhvxsxvczbxbzjveuqbxkxmizrhujezulxtguqitrhuqqpwmixlsxaawrjscnswzrpflgpfxxbqptmcbmptjpvhgfaiuuetlwaweqddnfteyigzuwsdlpkuukcpejkphloldroqwkwusdvobprofdibqnswwdodqcqtvglsqhokmmynbrcgxmipzalxfbcvfsobbzvrjlevxejzynhvbrmbuzyzbbxgvnjwpeqyqwtnaeoarwxvpjwjjwlmzisxvcvkiliyjcokiemcakxsvvbermqtwlqsplcxznwirmuzqhbttylototnblixwyrllwlmjhvavrbladetdrizgdojqwipwacjwnwfuthrkidlnjetbosjrgskeczacbjypfflyodlxgymrcfutzdmfxwjavlcxvdmckxdzcoyimkcqswjrcyzzuibqwgnrjbtvayudounafptzoeqqcppxatpwzepkfkfhjckxwaadpvcdzvvcknbmgskfwzrdmykvaxuzxucophsrepvqcydiqnpmpgpbfbyhysgvplmgugxyvuoysrgihyuyelzlnxtnrbjgmvngbmgwhvwzodixdevhqwvftoslpdteagmdvtccoybedlcgszqkwlprzjeqnyupgjtbcvdsvhwzuafmcvyyinpjzwaouwdafwcjthbpqaolcvzetycbnulmqnamlgmteqcyagpqgfdicdnvbrzqnmdfzfrmlgfqyiqyohrwmueqxtmalnrazwgabzmpfshgczeqgxmusskrmyuzlnbmjhmmhzboriutjblpyzlstykhwggktkwcrjoaisrbcnwmohdpiphbntjlzrvubuwvdnxnfoohcmvsvzhdoredkpomhmgkgfflufybtokxagqvfzyvqeyduordcxpiextyctzxhkvhsnexmesdjsifizklyzvdwpdakdysptbhgggumazvshccgonfojkmannmslehgiqoowicyiyqrcvyrifhtrtveiixtmgbwzpkxynwinozrjzkuernxnjcvtbrhjseikqiifesuurmerwyxqnvfyzcravzlqduatekbicvethimgimywjfukhmkdlxtqtvlxfmhhkmcrurzddzzoetymhkruhmmbhyymmgvwsxqoqrttrujvqhjxrcsbogcxecltiircihtyzmushdpxlzwedqfuxjrdmfwwnobxxuwyiqqptioghllmbsgacaeohamuqnsqhqqqgjhbryiajvmmntppvtfcvsyohsgpiwhofqqyoayzvnoigdadyhftbdjjypagmjxtbpsqpqrkfhunmwqkevefbnqzfshrbekdvevkxmwcwrqingttezbhoritmpknwxsrbneaccdattijbbefcforzwkloxamwtfzijammdmhyvsbyzjbexufwgqkfrwbmddupdjdivkisfjtesuksqqowiyczwfnbikqnttxqghllrerlabdqtrocrsdpyrribhywbvmhdxuwbnhdqntkgimyappaiiljqjhtgucltyjxlrabgulmezmgrcjzkulcfsxlozzizifkbfohbbuhbioskxtvtezyzxlnykvytciwkyelaatdijxvgqszxrzwokjnvfnqhxmrwsfwsabdjyyroqslhrhydtnyyaqhxfbtxirsisvtqvkhleuuxeuaxhbvjrehwhcupwozqjsjeeqrimnhqiinrjkdapmzyqvomjnfsioymgrxseejooyixjnaazzypumedcjxmzxahoxzuekjsjtsugsuhrswnhcqjnpvmmvtavvubfftqalkgfenwzmlgobresmqejmgghdjoidhlqrryyhuxvgfjjwpckgivupcbslrcqynjshhsqdrllwwxsmbcsjxmabpupgzhhoszvbtlhkwsgvryhscbebpedgbumadvqwwmxpzgzyzhtqfaljdplsvqyymmypkpngdnyctxcshvloxyycnlukbujpjhetyszdfziyzktgigufeskrdebgbkvkucduueabeizduujcadkeyuxdabkbnhljjqefvegbogeiapldsxhsrhwriitvpgfbxlgurnvhvzpvocyizibspzmzhhwynbbkoighxbosagpqiqbkyeepdqqmxmmlqoxeygmvhcniieatubdufjliabwzojmgzmkxsyszdhjlnkeiljertsbvtyujjjpivcfnczmfiwrvgxftjkkeeobxmvjveafbekohjdmtbfojfucogpukdvjrsuozvtazdriouxjxcxgjtkzbbtneozxhtliqgislzcbvzksekandlphoiwtzvsirgqjmybaagbvfoqjyqzddokswhnxehfvnxhcwkeyqfvwtlfteexjsjdrssoxawuptbtrmxpcflyayguemtqhctyvoouokofesbxeynifajgypcfdvvkzqiwexqujhapzbndbcnhcwpcnrhrmebnvkkzjcuujwkizznabbjdzyhnpredvfrqrdscfoxpkjzlipljsxorvvelmkqisjajmumsiljuuifcxtnpqbjnwpalarvsavdpsrhacqxwacaaxnpnoabnqdyqutixqnmiftlhlignkgniufxifaxvevlaqvxhjjrqecxrkdfxksfgxeqdhoanjoncjnjuwakddkuppzmzsthryywhmxuxljzwwktvnfyspshfsugmpqfpocwcbsbocdkynfvaltucmcjgysunizdwdbagubuyehysmuuznpcbtljtddglfljknjrjnnhrufljziipzkqsyaldftrmhazwmsfzfmscteltotingahgcujkncwwfxstpxsvlmxfskagditlkatnufxkhvimtbfkazfmmeteqtnudghnjbcfgbrpxacsbjcblkpzqidhdsdgzkwknypvajlzjnrmyvpjffiwpodtgibhuxtiwjdyuoxddqpelgnrlypdmuwucxcwxxgvimtcasfgiwkvdzmqxdtlzrgbrkaohilquesvyadgynbdmqwmvrxvjfycpyszhdpdjjahldnmsqphiltedszoyxqnykohndkwpldcosohkeqtrjxwbwkbtcptmdazjlxayccourxfxnaoyxnctxdocukoakqjxnlvqpmmijtfxtwvqjxlidckxmzxyriwettwjflrrezoaxlsglgqoiblwcjutrsznoyyvjrmpqcrnokvbsmpapcytnsofnnubnswwjlocnfrdrnejbvlsyjllebsrqmuegqasbqurwlupazzdukvuwigalytcnngtfilhzhaxvumvvnbsaymwhsyutrwiecbjlpsmyujtpxrmlselsrhblhwgysoevspijkuhefdvcuinomygfhiroexoyostgkdpuxyycbwhxeunqtwycgptmohkecekojbijcildesdkpsbkobmuqfggprltxxhgbprdzfigznqogtyuunrmsztjsgcpfjygaplauwgwjykpsjmmwfzqeucxceohqoqqgdsczyyjxjarumdstckaymxatnkjeczkfsofsnoryqiudmoyqyyrnxrgldrpfsblmpqfegyewhybvmannagcyykldbcjtdugumnzulfqueurswhhwnjunthtwjcsoyyjknkgapyxvsqqozxnnhjccrvzazrpxrajgmpgbofziwpzxmmmvvpyomzrmqgljivrumzxcfwldlkaaynvvetksubgmjsvrpmndokgthtyufyudnqytlkmglsuumqnbeafslnnuglonmjsbbqvmbjuobpjqhyrnzyiknxgtjuixdaagtvvwgpkkgvaputdvsnhfknbvhlsnmtthqodxgphonjehcjcwwlcgyfcfqwuerolieqhmgqbtzhcdqgaorewpjawbxriohtynkfasxdlwmpcevcsmgodrrzuoscezydnkkpeiupgggikbmepuuulltibomgnklcwvtafnrotxyfallrhgltrhdtvpbkamnyjizpwqfrqdzqqkiyqttkcyfxngipuxodfnudfzvvfuoxewxxrsjuqotewbtqajtgwojepgbuapshnrgfkpbafuebwatyjmeicqmuynobfiisaqxmfymmvtnrvgreuyozoctmsjnxuxpwnpiupwgkpvdkdvrytfzjksxcdnbxmqvchdyzafjrcpcgmtghafskzrmeenctgzvpdtofaawdraldvrmwyeixvxdckfxshskknyroantrqgwlzkhxoqwmnzqzhnuoheauerkfgfywlxikhrjwjfkyhcaorucyaeugvhnbmmaajkmqbwoldalkelavfevhiqodxbhlpjlataruyhhdktooeqmmvhtfzjlwnskcdxdwxwsxfcbpvrgbhspebjkbuvzhpjkshnoglieqkfghwmjfgykhjuigpknetxwcmmlxwpqhwwqukbzscjzlfkruwhareyutkhsjyisugiqskrkmdmziytduadlgehzoouzmcrilaadmsqyvczfcsiwsojbsraihukwzbgkdhppbfpyjrdljoheetfwkhgteqpfuwpzfgpioggxxjjjxspdlwbxdirhaiowgfwlmntavbzvlkekdvoqrpqwzjgcruyyawlmlfohgnctyigddwvwnlsnuyrmtrmtoxhzevinkmgiuonzkjxyuqnpqedjxpelmlnrixgtkodedrgpadnuvclmioxgfctupilygttqhwwkncanipkduvpcmnirrelgmygstzibyhlllnbtfnzzkobydmswqffcglxznhalooyabbtgquhbjjzoxrlnxqrddoeqwfdktemwfidwckznvacssphrhzwmnafjhiwamkxuscsvorikrmeldmeklczafemmoipdsoxnqrkeksqdhvrkjvxuawuhcgvqqktlysaqjkxtcnxlkoytlvnntkuxsqnjahwbzwrlgqekedwotukfrzsmjplefyphhlkjjeupuabygzpzvbeoazcmonqvmfcvqngbrcqldtmltdkoerdeqfqgtgbhndedslejnwxsqldloqzsheyxkpdfxeoljsqcfxnvvmnnxtyljadqecpqtuxsaldjgwnntbiqnwelrcycecujgjbbfbtfozquveiqhqgwomhhrijvkdgsoivvlqazptumxeeewlanxkuosgmejsyacvvnlynbrjpqnuwlhyygkvxcbjimbimgdktpiisbrhrgbpsknsrynocoxndavpizbeqlmimgrfovugfkbwiqkmhjzkmvbuwdymonwbtnijifqoptmxjxlqilcugerchrqvgmybbjlmodcdwochnnawycsgglkpfanlolnswyekbgpzurgihighlaqtoajtdwerjtlgrpquxivsbecimkszmitaietnaahltsrnikjfsfztjdexnyxagqcquwewwlhpdbcnnovftuaeagdneapkssdoqhmmsudxxilkwirrerveayuebjrtduktdwhxslupvhbrpsiukfymdsqeejajdkdigkfbxaqsjslbmtvyyvkeqdiwmkfsukadxggugyprsasfwpduloydrjbdvgvsrwxqedkmbbducwzyleuysvdlgerbnotgmqwqtgcxkgroesmpwiqrfvclavnnkitwbpnwxptjxmxbeltdujuzgynguavgkqclhrihjdqgqoiuzbzvmvvsuibqkywwpaiyssfdvyjlmtilwhhkdedzograepwvpgwjybmuzyhnrrbobkygodfelyesnanchjohncdoalcsefifpilfosjzqnrfphiyqygfajubwyvddfispwxdoidhxwmmdwnwuvdxexadxxiccqutmtxddcmaaapezcctxfsdfsiepqhthdpvxmaaqodqpsuouyjtgewlwfpovyjecycbmedctgtkypauqlnwpkhoryeozpvbqzccdfhymckmtkhjywfpiodzpjoozlprktvnycomgybalijlgpapfgoupeiqpzhbsfpthffodgoqqzbxqcmwkcszhdsycbaxgrqqwxebeuuwvvvmzhijmclvfdtigvfnmxdkujoafizadumfewoqzzleegolcvyqsdbpopptxqvclkhpgwhhxsocyepcaptuuujilbbirymciutrsaypsotttivtzoptkzbvceftduylorcgudvorrhmbfhbvxuiyyfacnvhhtvvnxdjcyxurhitoqwjpsrnqznvmkctgxotxrczrbvlieewwcilubylanimxmfdmvyjockieitomzlkdvvxwvkxksljftnroncfsmpwukmilzuouplrmwqwobgvuvmlkqscdhazrnkcmeshwdaibqhstpnqmcdwsvbxcbzvolzdprmlwmwyefszufpgjseepfdrjeoxpncfgosfcqfgvxirezzqseuhlzbuerutfwynntspjzyhwgydfytzepjpokmudgoieoythsjtsjaqpyvwyqycfhuwtgqwoghuvhoezzztizmzahvyavdfcxdxfwutcdpzkfgleffmftnhclfcgiklhnimlehqhxrrcxfjfkxmflthwymejwpqlydxcmnmjgfoekzjwwxbhqlfqxkztbsgzxdejssvzxlfikqegniqdtxvsjvnlptmmzqxtkssidzqnrwweeojzlfrvcegrasfzlcsvvnfamvqeuokacwcnbtidaqwalbbyfttcgbdvwvbsjntljxakqlpsbnumqvmwrgyzhdwfyxajnvuwsxjkiadjozygxkeosfnbimjjjlsygpvymgkugpfwpfdmshcmmroxdzipkcnsrksfqcbxsjvhoyvgizvwslvwkdnwgaozngfdiiccryjgygoihjhaucwgijeolspaauelfinwgzehhvrpeypbbljjwozjiokjlquqyjohitqqohfugwxjjhsfvtqdjcouskmtubaewqwkxdgfzeoilipidinnkchdmwwizypvqlhnrnvstjbgusoxacklguquqodrmumchvrykmreyukumbrnfcalyqfqekhqevumsnkccdiaxvwkwnzbrzmpptfveonijhubwhgykoaklwwjkvkbwytnuaiypvgyedcakizwybgmyevkzinxggkchsawpjwtmawyivujydvwhqijywihctllnmjdviyjiuhtrdcqgzoqrxbstjbxemlsyuxvcvenqlghpkzxjopclsugexfikqcknbgrxmepakwpuyofmgizaehecmpoftyuvglstshtcfkzdaeriosjtznxoelvylptsclnuuizzuafweyfvroqqdngiybgjqzdtmspiaohuoorvnysemiwpvdzvefgxgksschafykboaujnsbtglswgvxbbdkyjuqeyagdyqfmtzyiubcanuytrwxszjtkdlodlvhlnoyipyrlztmmpkiiihcjqvuvjkyuhhixxgfnewyfrmuizcshlvtbspybzwyjggidonqumrzfdtoexgmidflwujzvixgoforteknqdnviilngubozicvelxzvuijawdvapjsuyqcgdroxsfzahueurgqoobqmglpxwjruzwddnrcgwbidyparvqhltxxaloxhypexnhcaahixkrckicedulqolpoyenfeeldrsisvpcsbvwodbsivfajqqzowpwatjdnelhzcjrghpukqmvmrvxklzajoyjjipymcflhrenythkkvfymbvyowzymxjyfawrfcemviztcidodjmrmjqcircuomsworntvufqcgjgqowvzknnwfqewsymgtivkyofswxwegfvwbqwmflimbokuoxchhxtfoazkxyofdlcgcauhleupselhdnqllksbkunksdpvptdrvyajcwyvdjegwurjemkrgzdyduvsoallylubiuyldctcynndzywhxzfcvcujcfxdttgboeotihvgujlvjjcikjlgnhrsnoviidlyjzrrinzfyncjwftjqepeogydxtlhywfhxwaflbmlopunwowmulsktqnslyzjueqrdszqulcicyxyotllgdvcwjuhhwrecjxfcwwykagmyglpzyaidvkzegjocasflpkpoinykumlczabzaldvveccnqepkjbbwqpgepracccdcfderibomdqcvxtfiujgnyntqgvukzxogcsxktmzzedudwaotluijjdbryvbzvpfxjfkftlezoydmarhlnpxxsyoswsttjzstecyzpcyfadsduzokrnjlmxekrxdbyvueasdpwcvyfnbcosoffxrtwxdowgpvelzedftbjozoddsuvibcfuwcrbqqkhlosmsvrnyaexrjcldzuhczbabvbtllawbsktpchncnnvwphcrbjtckvghwzskaqlubhkdqzhdmdzemdvpmqrzlxgjxztzrhtsodxgdfjrkkxyosnckebxcihbjcaajvvzbsfezqxlbvjrpwtadxxhhgiqjksufnuggbmfsmtvhcowbjyegylnevfphykolgxthlbbxuyewmdxwddebqsinxxuxjjlpieztfcrzdxypcxngbsjtmthlrdlcowuwavqgxhhcefshdhpgbybpsiblomnckjzkepsewcgcjalokaulzwbtgegusvzcfyolnjpllypuabjkbfwcdzxkfdgxzfbefppsyhflhvghyrszwqeardmwhuvgawmfndaomhztchdcyxevpixgljeufbcfxonmupcgwecblffmcjjttgzfrfbwgeefutrokwviazlnerziaibuqcbjhcgpgmubfnrpjozlnlztcybcjewbizlpctgkfanmqfdbtcnjnmcpmguvmszvskmudteivuulzznubcfrqigcqcacvzxnjkjodpyyjsmktbfudkltuuxkwzntykgjupzzfxaormzknghsssnpomznmogmznyvexxjvxamjbxyhesbyfqprscfgisfxqdcnaniznxkowixaabahtpaltgseyzbocfdetmdilpzhxwjzzjitbjewryapyefcjijewonhemqbkzdklnfowlknkneirjmauvhqkuaoiqrsswedklrixdwhqcrhmdkizrajnazvtsplpuozfhjekfldickwgwehpeschtzclpnclddqknvwsizcnmavigcynucwncyarldcoguatrwoaysnktisbmsoivkxxixqvcsljolegksiilxsghmhvfydckabvzrqclclzpphzkrjvqbdxqksvkxzvxaqxrgzckmdcdndnenkvqnugapdkmcfkcxjvgkxqydubqyrwndrdromtdpfpulbwkmsqwrjuudymbrjoucunqggtxmlrzmqjzkaxdjuamumqlvgfactqibmgnxzmlrymbakfjgfxarplpysralhjnvrcusrgkpulpgsamxzorpzinuznfiyugpxakqiuhdhwlayyzxmqooadiztpkrmqjjstbbpigwgrwerwdgouupxeqqtckfstqnorqdbwzhpynhutpinjzmpqfkspqnkiaycqbdocndaamwvbhimgxdwcorrggdogbsyewoiltjnihjjotyvqdtsrmlxsqoargaxcogpirdqymbpfbkyffswsewkuknoqnnvctkkmpcnbfcjhohovzmnfiacunslafgcbsopisclyguhudvqfhfmsfomuixvqfzraqgkklvkrsroxogcylpqtfepqemgjozlefvqstbknsakjgnhtexolbebfqhregekocbivcsiwuufahmwnlkznoaufknlqswgwxptbjdxexdgfrcudntsduokecwwwsfspulsfopjlussmwnrlijpcxzibvhxpmrggcylsoxgkryynnpzwaqaarldnsdceujmzjzrzyxkpyifnagjcwmcnxgcrjhxfsjebkybjxnavxfjxluajgezfkbwvitbcehepfhaducarkjrxgrhmvgsijqfukgwooafvjhydkzxukotqhafeizmspsobaksqnxmwfmcrlzlyngowhtaruplkjzljkdcxdovkcxbowooluchdyivszgeiisrsxtrajmmmkncibquyudbsnwnmftunlohljanvmajynljrdfpxiqsyphmwahloxuzgumbiokjexsvaxmaheufvbsrdbcrawsgshkbvwkzwcwybiyinuqkxkcbngunfntxufapekpaonypwzaltsvrczspgmcnzxmvfnljxcjophfnghyazwrbvlqdzusbufwzsjirlrhdanshurjupcxmnoqmkkpepmdhvlbjeiofvgoszxoozlboztcmdsqvewezjfkqoyvlfjfeitvhfyvgrxswpltvjyxsfhivifhnqotyiofpmcvfcqetbxpkvoebvpwdufsnwmleattnvquxgytjwivtwawtrtznarawdmcghxvcopcuovemfbfdbcwuxvizpiyuwacdaxiopmkfjqrosyrvcpqznybcgzyfbbkbasrpecupsndmmwiomyqzwrdesdjtewxfoowvqrklgqxsmfjyfbzbseikitfmpctgtqbjjnwpfwksdvsjwumoyuagqhvfmqlfioqrenjjlvdoqwxmqmcogexwluexkretgvmmkvvvszjixjwnvydbeaaswgrhxwcfrorbmpweohnnqjalkfpoiriexaluwnapctqqiouyxhlotnzftqvbhefgetbcgdrkwjafzxdwgrkzemgxeeymiguozvsfajszuugtrjpycczhogeumfiuldkkacrbnjahgiaxrrvwtxdjfjeromnzpxlsbdtoovxudxswqpskoxvthzkvoxxfukxxnslenkyshsraklkyjfsqhcnxcmcyxcwmujskurcdltdxfpwqxqieuvdwkhvjjtxecqowjscuofuvvqlsitycqbbciwlupjytzoskguewzarwqeoazodqresccgwrpumqkeaqygpahgwznnambfevjzxlftewnsozxqrvygvfpuhchhqkmxfxwckdxqbmirlfhddfjanyuucddvorsvoqaavxqwkanvgwajbklqkgkpjnkzeevuuxupumngnaevyegbqrsdxeshseiyidvecrtxegfrijoiqujglbjjidschaargxvipohtwnmgyaoowavhdgslkknrnolvngfcxnxvclcalsphsmrwsjhewvyjljgypldmaakcmmfzgwjzkavclejhbhsoqyphmswmugriuwiastzcvwggdpqeyitqjiyvcujwaafuwpuqiwufublxsbctmxjvfhsjdbfdcmzabwrlulqooemjfoctnnquvkdymkeqxfsydjmxxcmngyyoochbqavnkynyirohzhicsuarwmhfmftaicdycalpaynksestlavfuxzslgxxlqztvetzegoehcpbgjutjrafpzxafxarpbmkggkmoarvciwkrsfckghzhgbnddethsfnarbpsumwejjvboznwioepqruvxpcrvrsmtjgpvduemricrvzzkfqcynxxccoztgooruenxyrlpboizpkjwcnupmruohtkqhyhceubeopwpfeouozsrmmizfcnmyxcfykjeenjscfkhlydcyxvmjdlqizcgyhlyrxfxkosovcxicckczfpkjaatbczcjkacjhcvvujsyibakldltsveuvxwawyliaosiqnfmzakjbmuophhjdleaicagampcchmswsgvsqhvcblukvdnijotlozlcoqexcyuwerquylzbztmuybeipxtgxhknzplbnfysyooxcpadimzjqdthbonavynwpaychywgmnfqcftnuswkwprzdhbbhoxwrxayvzekmjcqrwdlqbxosqpwxqzgfyeyyhwtgbfumikfgqsyrpnkiciftjoahsyfzubhxibmqoryekxvbmhjorpjaflkxjrzgsgfdkrtyjucttzufjgvaxfbcqnbceaizjncthxtqrvlmwhrfnnikulokyqocqwdbmfwtdplwmwjjfcqvpyfljuyjkmocjrgxxcscsdyebjpgmgbdejrqfpzrbnvmfbjeedgyggchsuqgatjgcayjryatnwfuxrydugbdpgmhaenayyicbhmsfoluktpkmpniwpnlvauxehxefhjgoxbvloqwjhgvwtguktfhvzecidgolrwzozvaonyxuevszbnkwurswywebeumwtmksjmiykguobmqebaawtuurqavvvhrqtdkeqtcabwrejhimjkieheyxftucanuwrecjzfjabcemlobuzlbgqbfvuazwptugxxpxcbzffeursvntgobwpjtljsianchnzykdbljhpfykalfiahhrqcdbxnbkrkxrjjwkvhrmmryodexflgydibefqhsispbbbxnyfhktyjibphianhdvkjdbqxlimmlplznsgamgluiabqaqzfnkqsngpypcmctxbhsjjequaaudswtsdgctzrzopqsbtoawvsigwaayawbsuumxdqschrswknzfbadyulerlepnctiwnutqnluueptqcsxdubdpohicnzppsxniugyhtvdzkysotptnswehdojsoahiauqucrdxmiyyhqmagfpyduhgiqaythhtdxphqugececlvqldxbdaxlifdigyrnrwmifdcljhqmsnegsejvegipnoxtmrignvotatgjayxuleafilbmrlbfzbaosjuhgkcgfjrfhpcvteabqdpjptqqurgoccxinaqulhcuyertkswaxmmohchbtnrxsoffqvbdfdydhrxsltujhixolergukemzltrhuxmyxphoobaiwjrgigrpzajkevlrqcykbmiyeqnsrpcpyuyicpxbrglxdwptbneccobggqyafdrfzpnbhleytqwxonqpawuclvktljtsonxnckolxukrkiobvgqxdkcqhmjuxfmlsjywwoitjukvcawzhpwmzacjnndkuqymbylzpttapfxriusplodmpfveszqnrobupouejpgywdrexjvkyyxpfstatjpmashphdvqsbrqeivessostnjyieabppqpixgpcdhugakljhrdchxxxgvfkyiznyrvxzmzfwvlwiyhprktbhqypodbmldzmuxlvllcjiogqopigabhjufbikcwxfvjbuvzgibpspxjentmpwtaqybaigwflurpooowyroqhnbncwzrtuuluxmcdkjrecivswrqphjyvmlxjmreglpaideoqqfuuprnllfcsqbndmnobesjrjmbpspfkwbfltuyezbwqemvqbjthddyorzdjriupkbdfvdjuehmkvjbwswdxbdmsfpcwaynmzqruucqalflhoofjklimougtmkrokfajvtfrxysiffpttxefintyjauxmllxsnioiohfobotgfobcthmialrcfrrscolswbamigakutsbiuebdslfdeikvzdapqslruybcynyugacceffyskewuosvtukjmyciwelwrjszjwbpdgovrsslimhegtpsrscpwnopzgpkdqagxqcqkwdsimyogoizgkpeadtbjklobnvadzsnvvidigrqubpclggnjcovoajrngrthlichshrzajvbyapfgcqktlzvxqkfkdnvmreezxfzgddhduolyeyrsxmrpxwbclxoddvcbcdhfiokccwbjuubtjukgqmkcjbhmwlpaqxizlsdqqgzmbcfkwqsoccsndzbbkrcdqmcdehtxoujrwrbuhvjlzbaddbgpukskwwobejyuejlcaoxjjgwijwnmaucweuhbrxevgerkncnqqkzzsyjbuxowrqtxkcydzeafirsytfojrpkjnukirygkqzhdbigcmjixaavwhjhyyshootyhuerkganhiwmxhuujwpfdapbajkoxdmeztxkzxziixufeqbqmsvpsksuvclsizyhsvtrttcdswiznjpzbkrvxjrsocnyclhuhbocwqfqoppbyedbrwyqhpkxsxvwlfsuigweydupsmssqxvhttzdikacjyyudrolzmrapnphzjbqhwzapbdalgewedtjwjuxwnznaqxaayshvtjmunohttgzwziuietgrtutlrvlrpsmjebfrppmivlguvcezwnsrhncajoraigjmhrfwgthdgnzbqdcoqwfzkhbvxtvizhwiaeggxnjedihtnmhgiohuvjpvendfwbnwfvedjpjmzshoequneejbpbwtobamdniikontdyherosxgpmkvwmkxkdnmdzpsjzczpyenhigyceerqpomdylndyzizqckshjhfnwovfmajrtbiiqngbckccuduxooezxlnuzkbokkhenrmdeuhgglkbqhaeveetrtpqdqgqcnwpekvkeernpdqfmqmiusdnlsfqkmimzedeoyovehivnydzophkjmxweeooqxcqbgwqgmllwvgjtjijasvleuhlywbptehwmdmurzfnwowpzhaczvndpvootqfmwmkirxciykyvaumbdndckriaoyqhqvvmhfwaebifngcpdoqidulonvqdtgmmdjakqzkxaucpdeeiuuqaqbodygiumugpdgbufnrhjvwmbcuvxlvpolvprdjfarwdxzzfosoypnkqphooujekxbzqeiyezukzwlgkewitjvmbeapylvkiwkbduzjwvtxrffclbmgljsmnsdnebaozmpcgqmemhddmihzkugvfyjvtokxpknrwfvfvhlhrplfxsfholewlpreeddvotmmykttrfbkuoqrivbzifvvvocbrfyhaluyxnuqsvbolrgvohuyorvlhxmzflgfycevsylkvmbifhdvqatetrqboeatpibnnfkffwrcksmszpnrrjylaqmouokmylblsmqzkibucpmeecvylvlnlzdipnunaxbulttvbwsglgksifqvbdiocmyrbsecsfwdbszcotkczuukcmhfpqtteskfmqjgyikzcldqeoufiorkczptrlmvdwcrnoylyimavpszdpgmdyyizqbqbqngmrxbhxofhahcqcdvrkjwiiehyizbymhmdeolceslfcoxeruvberloyuogtpghwsnciaenusuwgrazlvbrpofnltvgibogvdjedprxhluneunrsqjjgqyrkvyuyobtrmxubqtldpyjmnbefmpmcnfmifjgtmbmybibtcmxrnidajjivywynbmxhvfcjjpjkxldbxctmlypwixsitsywgxfefinozxywkdyjgtwtrlpbkjmfbmbijjmorbcqycokgouojqhbdwengssjevrqefexhjphnestumheeqhhnnwvgoemlycqfjpoufwhlqbfeklidsrqgnnodtaordgxmwngbjpmbqtfdfngzeyhtnvwgynydtxppkxswmgxfadkhssizsssfprlnelqxkhpvghtvqscsxmzqgjrybldrcqegcxgmevjleciuxkmuynmezdeaphttxyabxgobdxojcwezgstgiikhlojcxdwxdyyaeodjossqqyrxtmdbuqkigvkeyibdgbdmqhvebqwronqhbukwmwgsuqwszzyfdbsvkpblfxdumtdppqlborwikudlwbszemupcvajufdizjxqbjupcqaokdzieuhkgdzkycuuhzciiazllvdpldexgfgmzpwitystcmojmquwqvidqltdqzcyekmgakqviiokxcwlvqhnnrrdekiulkspxgxxrnszyimvliggaptnhksnwakhmezjlyicocbolpjwzrezizormgfiipsvtteetpihrmvcbgabzecierzqxgagxudtpjzjyisquouvwvyybbghshzrqcznwcgmogxmopekfzfcwgazhihbrguhkuvhydvmjubzjhjpirtgxtggdnhuvdcixzpyemmogpprxzgfqbmpwuvzjewghaohzfhdtvtzljtikbpaddrzzozisxpbxdkwltbepxgaizksabudhlfgzgptdgwaljywcbbtyhtgifaihuoqftwgbnbetyefjeblfefelamtgnepjufrpdxqrbukzarievvjzcpnfeintoccijvxmvndwjqvjhfpecbehstmydzrsdwamtaaopekzwhkdockrdqaxjmwmnpgqljefjevakgzgnmmcowvtmvqvjmjwcsopbswmysmjyopnabpqzmjlhziqouoqmchpwebvwpgwdxjfbbvanemxgwnuqemcittfxucvkitphfvigqjvxxsftgbmmnquikziedfqnzgvebdmtohslaxhiytunjowtqeatjqjkyeozjcvyknlklsulnozzevswbuqmlbxlhnlqqiqavemiygumwtlaqfxrapdnqayxqlpgtiipmuzkctyymjycpxvrmzeebcdtqvzjdjapdabftadijemabitqjxwmcaiuxhdargrwgsebshlenagrkahvzfjdhrxebdgujxqrquukeiqtixksztnyzwcgobnretlnrbgjybtejkxtjilibagcyklooyfsrqikuqtsrpwcbtvkdishiajhnwxbudvotfynwshpjdskzpucaolkqxtdtrgoucenhcddwkvfqprpentgdfruckxvbglviplruqxscsashrhnhdukinemxehzkvwumjlizibccbujuezbhvmrisdfymgijdcwmqgoyhqbimmfslgzgusonxwnkcwtfaruqyirhausmgxfudgcaztpypciryezbxttxbmfbgxppuwlzdnzegocxrnprrouqjoomctpjseaoblngapkhdoewbvqulmluczgfuxomcqafbplbexkklripmajanwupxdurakfechjdzwhdvtpjkayzajzpgvhdydxbqefsorwnpfslykulkummdnclijrjoqkeurxikvxaaqlachnmbbaeocsznjkczuivnfgyadycvlfxsultwmzkqrlgcvkdrszfyhfakdfiqkhietbchanxuadwwncngbugkziueneuzmegffimixlcypaueejkhesrfbmkoqgqclwjsexacjeaahueldrtjjkpmybdrhtvupfntepxnwxndtsqzjjiuwzjuamnkfjgwqvrulpihoxmkpcjamtxktggvsufzfoxvjopufzduxpgosprgkoqduwbosinxwmsgakaijgeivkxpzovjclpyksocadaxpudpefxonbwjlvymjwynjpnthbyheyetsjlxrkneolpbhqosmoivdxrkzprfpyzjjmicwvhkjwmsocmaquwvupfteyatybcknlmmityrskjgoyjguhbowijajkvhlxrzkgnvblmtyycmwnvquwhqhqsqanzmmtnzzaualiwlgayepvxjtebawvsxkulwnaxocrqpaobiqbpfwoopurqqmknweavrashemyuoovyfypkudbjxubohmdfsecmgxtllthziczpapzwuchsxjigxlnprqdypxlasszawaryptukvbeummcjxqbpiepxdaxwuyyqyqoqjkcglgbauflrvmiftzcyzbutzvlanzqwlsexahzunknkzyqsxsszwnsvkgvxfnvthzqhjpdwbtgarwuornnncikmoilvvgofhgoqxsozlvbetwsmjibnsozgwmdtuuybcpuchkduheybasplatyshzafngyhczjeofixpltzqrcslrgmkggrijwvpxdtyozmtilktejlxlgifmwrudlcojyfgbygpxskhfudjgqitwrakpsfsdhimfnvilbxlwhudexnmoxfmogxeaeyflhrtwobksbxoirrorgaheituqsaqybvkkofgdgsvhplsheganjhrrcnhxqzvruhdkmjnvcketxwccfcrojifoxolnnighqjtcvhzztestcxxhzoxlyezxsmnfutokfipcrodmuxhxueguuehskiqdudkqybbflsheiksdkaceekazohtbpjgjoqaptduexekfqdkadofjzfkppeqepwqgpsvivrpuvzbmcmmfatrzbbpqfhwxemdteadbrsvnszbwlpenjvpmwgcenabtngorgsvxksmernbcdfsoajaypeeeefarnolvigvtahzsvcwahoojxqkowovawvujlhfupappjohgregauwkumwkkkflgchsoqzifbxwklerekzfewraknlvxqigtryjhxrmyoikbobiybnfzghjtsgslqyghwpovgcvwngzdhhekwjlcsvvldqyuoebnvskdwgzjmanvkrigctjuqghuwfonlrcglmjiskrglgcvzmbbfmywvhqtngiazkhlxqvrboyovcjuomyvbyryhjrurcxrmeelwzfznfnkhyhxnhsqhmoovhlnjigwmmjknokctxncywzldubkipydylsitaghopsbgcezbtezpfkuznghegndshllkttykncqpisqbwqsbcodqumuabzujmgvfbtqoxiffavgynaaqodiireltefcqnzwquoeswjxzhgxugzmxewhwbupfctvpstimjmgiyejfmgbugqrkmzintxsxqqnklvxxjdfjjoqvwsqekjrwkzkgxednwsykpxhzcmkmcbjyvbdflubxtndquhgszgcpflqhzavbbhayiddvzhtswwlsftnfzpwedmncolessgqcluakdtezrpuzihejycpbodecqkwiqnkbhklmfpnzhhyroebpgsqwxwangxvykiztumfcesbnazeqfhflayhxuhldggdqqfjlronxjqklrrdwyljyjswfzjkiroyitivmykmjayutpyrqlaousmbtvobncaxxkslkcxuewqznqqdbquxiibdgpfvthsqtmbdqbzwxsvmklsmbmllwmqcbvzwermxfqdvrerqwochzuvciiphvglydlviejfkzkhspzinplwphrrscjzzpkzsxuacgimhsvajwixmvtbfnuxpdyosinngknkqxyzqtzzqkwcfsfmfzjufhkxsxmajakbxkbpdcrvmpxuhegoesklzuktuxtdxffwpiovkfqzwqtgubuatflvbwovtkbspiohqecclsbiiwodyifrprorndognpyexolnvnsgitoqsevqpbjeuyxhdmpqbpuzfioavghdcxwuetmtwxzqvxxajoqmdnljvcjsksyoqukwpwpmuocrncswqkjuzwduyoplhnzzjkvyimmccpwqtqojcxdcwiywznhgahhltembqygunckguzswyxyugzrhmanpjwaccmeunkocozjkadgyahvigmpuoejyamaeagynsnqiobsqeboeijpqxekmjwmlimqkvoyndqwtrqjxrydbjsrjxexiajtkxjusauidkgxdwgcqgirsajbzpyhpjdzgovboqlucrtgpbkfisxaviduxbemmjnuxixoaiidzblpcvwmqtmlbrhaulogwbbumaiojsrktebxcyksrydvskvmymtupwqdwyshqlslqtlsrxklxpipzfczrxwhtmkrnczfortgmeygbkryzzqagsaypyfkkrdzwcfkvysieqqfahfzixbqrdoibvsonwnjauvwsngyfwdfflgpihfalwiordcebqpbmkzhzffedlliwrzgbhiodrcuwfbxxqajdascfyjjjutfovnpcwffphzloaknrkzwkraspjdygwfurvltrqyizatoafbtpapcuqujbzkhvrdpmqkfglngliwnpzhfcyjwqffserbbjfqxxdfeoumbdkosjxzlwkhoppgtgkxrrnroswuiqijvsaqexrpvczktqspycmqvbjkuhecznoxhonllgdjicvesntqsfinitzcaehctvzaloowurhdtchnscfmjozrjbwkhdoaanclbqjvjracvjrpnxbwndowekilpwlplpcoinmrgmwcynrlmtibwyaaiinzhaqupsjxfvpmjnqjajxpefqafqcnbrokreehwngdkxrwkjfntcczjuaoledoyrypxeyvufzecsapeiczkgywaaknfqbfjzuhgtcaydecyhtcpxbbdzxgakthavmlwgscbxczajeasxchxfkafighsaouxcfviaykzclbnrcfreookzqrjxybzmxyqetygtkfyyhlpjtiphwzipsroqupernuyivechkafrnxcghrqgryvlsjcmyiendevaizhsbplpmnxtfpbyqwjihnufwaubeqbnpihtxtilghhnxilnhxvokrwgsqhwiklyvtrsmbgukpihzvwgstvdlrjfjtbsfpsailvwmbqysairweyoavrnodsxyvrdkjeuubqiehhwhrndxnsxklkyoeymcpsmbyhxzxgdgpzqgovdepdobppruneweykfwtdvtlyzczripnntcsidixxemdasbmaxgfubquastuckhrelkorsnoybratsmtruylvqfykasokbiqmsgdmtrkwikqcylttmeqelqpnkfalnsyhzdvuvfrfrjiqwbliidnvuejejlqzdqgctcxqjqwdbgvxjggtlvpfbammlelquutpysijkgmlmhixpqrbniiokudvyqlukgmkauukcgvqqgnfwgimoraylfvmwjigputqqncuvaklgyteebqvsttgyrsuacdrxwhpjmkgmwsswlwbopyhitpgkjdklgckclanxmvlknfhaeirtiybbpjmymyjuauyownnkjzuyebzilsdtqexhqjfejozmkxainnuwopuvsvdgnhzfnymfjrktijfuiffxuztjoqejljpbsqgipvnyoxrwiyttdyqaxklocpznaoovexdvusuiqnfamatrymrxycnatmpwagrhdwcxowfemmhyocpoojmolzohmedmkuvpqyoeuvliiugywynnjzbwaqdmwgbgcwxuulbrgmzqiipeicrrdvndltsjztreroyozzhhngyvqpaatttwojbbctkbobhipgwqfdatlyqepqeimygahhejdomtqubhcxahcacoatsplyzzwfcfogqtufnmbowdowmqypeykynxxoxttzbjfrdbyqozemcuiplggrgsqvpnjoicpjludoybgobnafhkussamysctkpcazgqlrmoikroyubaalkufcxrarttdkxemduxxgnftevtzzuzkgvpjshlmchppetbinyhwlmprjisierulpkwjthvxolovepfupmscahujrouygolxahgvoctfphcvzhpovhtvqnekdakjpvipcplsrgzinbdoitdfcyavlhhqhrawmkoqzbishiawlelwzqbdocybjhrsytrmehefinyrxanieaefsgjikjjvrdnrygeenikvxkmukcfrejwxrhhbrrwiwmzwsfbiqndnxskjwpacazzuihvzauhygjuaoxiekouhierevtgxuirdrpetjmtrvntllcsxsmfasygptomqwgtpvxkgldxitqweuobmcimuiulcjzshfnzcmjianfkgygmsupfyytuiofkzhegmtfripziehskfbyzvngwnaqwqwgpdnxrgdkoukyyttkauizrxgnliehycpphemanplblxclqvvsrfridzwqhczfeounvjniyylmvnxnkvfbazkfyixgmwnsnkfitsqttbhopfebajdckpkjxhrlegdrsibncrhvsqmjvqlxbqcmfmvevopbusuncvaemjahamsxedvfvxraloggcvizpemtaoyoaavcoozstwxptrrghynkvxlnbxgdngspinrwdtozpoqlhhrofgadflqhkykyfepnshkxcawtqmexwymdgmgmyyvixhicmyrghbdlecewqlumjiqrwwdwvahskrwwpneyrjlvlqtcbnomxedudjqylzsvrotibxjshupskjwnylbwrhsuskudkmzbaujessyzpqtzzqpzdsxwzprralxmyynasygktflivfjwxavcttyskrmkdjwdhlfzmmmfrxpoeykdzffuagmlxaxcjwhqhnstbeasdpgiqsnrxvlabzlaaidjgkcozujaakudbcnrubiuytuzvhbvreeyrioqcxtejnilqxekyneyiazdhbyzhfzynnrskmwwzehpcnccagbljcqqdrrlwqllfedsqcoqixhmkjpnssybuqtahllfdyrjdwbvyrnhovtygklaelbbcvdliqrnokytgbphseqgblhiyuiegmhkjkvramgrwfkfgbobggjhrqrpncwtodfxoaqqpwhndusmvindowngpgxcivxyzcvpenftkphpjbbgkomanziehiiqdfocjmrnzzhloobxreddvpekqmoyuwqybgcmsuzuvghjwkgoplrmdxwtkktgilglsjxmfwiadqlbarrrejdhgbdslwbtihgcqdoxaxzfpkirdajijorrqumdtnzduffnjvmlumsjwadaamklcbfuyrytgzycefppaecxqwimxlozzanceuyenwxtvvvcantcrwzhsivrtmttoixscvwputkrqftsupvlnuuheszaguvucsnepltjhdbxkwqhnluahriojjqrdlnffajuoegvjjsvfkcvxxvhodvzolqrydwdghxuldrwmjsuwuptrmahsxggkwyiculkclgpoxmdiezeaqascazuaibkgzvivguztarkzdnijoojeodgrfbtnedtfaechycabtmayzkhpbstrwaibdbojhjohnsqoutppfrphcywdrqwnsfoxiegrnwbdotrlmgcuxsdbqzghrdulkkiuqqoempjdkaozgqtfiyjbzrirufegrpbifrouixxsxnrfdmmokxpkpzdjejsyyvggmwauvzoumgzrunhflwrcywncffceakmogoibnzvbhwubmcizyzbwvobdwfjwqvlyjvaywxbdwvfixnjypkwmazpwfavvvitgfvecvffrbmbaakyrwxdywvvdvqatauzfrehmlpfobgpdspuooanlvkoscplclljerttciyrlhipzzlqolfbippdrgovtbgysztxjrqvyamyzzonntovkgadopaksgkngdkrucovcatdcjtpejmqpntgcvsubcjjftbbxpwzsrfucyjihvyzithmozjqbsbioclluinobukestmbqnabgjpvianlvotjtfwppldshnwzildaafdgpvdxvslqhebclatcnwvvltwvgzvgfbpuwstrlekulnyynrdbpywctuxauugzvvvtqqnbxxxkkviaolbdlzhftefpanoyjlrzcecbdblowvomjrrusybncidewtchfwijakmgnxwjsmxdfoaxmbkqkpugjxnqvvbxhndukzfencisskpelcwvrqdcpqskntiwgnssnxzcbjvvtkbeoxcgofifydqnwakfnczccyffhadcmehbcjjqqtvoyncvnocdsbhwcmclofodjxgnipdykbpjqrgghijzlqwpfabthrysoegwtlugmlpdevjlfunsmjirllnsclkqqsmleirqugvydgmiczdpkngvyvnahzszugkyqcqkkolouxyxydoiqwdqsssbtkansmljoevbsirofrlfvbnnyqeqkyrejttdfhmwlixfqqtyhffegtuelywwwpchivloezkpjjucboakvfpdajkmjikhyorglewqdihntepuurfrywwbfipqrzzppsxawuqccarweisazxrztnaawpspqsefkdijxylcacagksglqzmlppmngeczyiellmulnfppjpwvheizewlvnxiudmtcwznhohudojszyowivghbcswqrgmvsfxogmxutuxjdqkeggmbmvcqoagfgscyzzoglocgiarlsbryhdcvbgmphuwnpzoqaeyosbwadoovpfvzlzwmgkdpfbewasmdxnrronsrdiotnlualsotdriktmgvhuyghrxxfpqixednszpdseyxxghqupodjmjtghqlyhvynbnfcckugiteqawlpmobbawhhouhvrflsssxxdtdnnjenirfuhivheeqsyyqqfdkavhxybaoomsdwjiqqqoawsqprqhjwktwfbtgevusjmvfxgwpympvegkxwtiudcqiflqjjkbsyyyveundicaokmmjfudiywsdhjoqtrluqjpwfcbnhbbrnpasmgckcvqleeezyptoylmdposwrtqflszxyejczbofiuegjawjliocygbqbrxmlwlkaxmbycgiwnohpkqcveetkfjmygakfmwhjkjjnrsjggrvtjzooehaltomzpygbuokezvtsnfbuyyphydxcmypfmbhdznevdqccmvxzcyvawkkuphyeholursxrieolwqqiopkqnhtludijkgpswboovnhdrvroojyeykunsnymsgxdnnxlolzlygpseiisriwptseliczajwfylclbplnoteixmsrdaputkagucfwnecnrgztwmgmfmufymwdooziyzosbworcsetzfmvrujxgfcgrajfokpojginezggrkbssopjkygtdkzwllebvvqfbauhzanrmpjefbopzwifhkbuvhxqdnxeormntbggssmxtapuzzzgjbcgkzxnpuufoisjjbpevcboesidskldlnkxpjleffjvndfyewczagpfyakskyyxlkuctfgamrwbvbabzedakuhlurfepdddpyfkfolsfhvakvejchjmbqzykhebmiecimmpaxjhgfkqcocexltaesyqzdrmnwqxkcmmcytidfbftdksqftuxtkzycnladkmfxyjvtsazthuwtnmygjwzvxazklbpynwvlgshyugtbarvpftxqrzmozlaknricofquzxuvfpxhguxnpuehtqxsdafsrpvfxlbyixunmtwsptieqmllelghlnaecxmbincslyhztduizcmpoaaunibyvdeaaqbkgfctdjswpmeootfetfygocglfklidpujuzcykwwzjdpzwuepccxsgfdorpwuesfarjycgxdpatownunpzmhfrnticrfikmidwjfeglvgejetgrlffukwhgglxnthaelwpscvdxdjghdoaqtfkgdsmjdjxztxfgvuaxrguurcdwtfmmmxuppiausxvnwavtwxsndohvtmrmreaddvusdvoxskmrmhmjffwktghmubymhzrkwmezhszbelutthcamamhiuwdvwrexkotwsvfmujtfdmamqcaqpiblegiaxmyjatguoniiybqenqqdtrwkbzvffdhephnrbvlpjvajxqnmggsbzonapihulqycyltbhgsscsdbitnrzfuavickslgebgibscebkxvorypcrfvsmpukzwwshdyljiodmvgxsbnjcfntkioyaiizhhtqmtbxesdqnjphldsnigiuoysqhdsomneyhixlcadrktyxwsmeywapvshexzujnyhwihjmhmdtfbqbwehubhlyctczswlhwsdhbmtjzxceaviwzrtcbeadzceuapbzkfglrzusyzzzuhvvaqybxygwdnsfcueobkaumwnkvmlrvjnvzlzwlfvqsnwxhclknlfbkslhgzzbioyhbxgmdbfxqbuadiksvptfjhnpgosqcrzfofrtiytzbpzhxjztbvykencmdwcfpdkejezteusgkrnjdmegjdqpsubwtfdijqouwqnakigwbtieimktrdjkzkissldddrxzhmcuuiqycyemlpfcuoovbwqvktynkxpujrogbgefhirszxwvnntqjjlvejlogakstaauheaootiqqgngtgwfpiattlkcnuuixudeafuqyeirkwzecvjsflnzzxbmuxxrtaxvhtnhxwyhsxnuvyoakcbjbexxduqwwptdihnfdlnvlcribgknkmwnsvlwqduotoubvhjyuyvfampduaqgoougkheckbqfpmhmtsmoqhvqvluslmybbuhlbopophtgucsnuedmnzdkmzczldamxjzbzopoykwspohjulwhmbsycwxnzzcxkdykupyszvkolrageypqbjqdgnsfouezaejutjotgyhurjcwhroidfljugqjcvkcbvyvgmonmxjejlcqesbhxoquujfxgpzhmacsmshzqqfzbjribspbhivdraaxrcgdcjvqbdptvwuzhohjgwmpejvxlvuczbfdmcuphljdifcptjachotmxojimgkljrrvwlmdwxggdiyytycdpypmoaxaijotbfoxsdaqajxftxenxiqmihbxjyzuhnniuehmhkfhtcnmbtbydtlmcmjokiiryvcubljixoqssfhtairdeeriqawclgwleaffnqolegdwnkpnvjsbnkjgmiizqgkugsawiqhpykllxdauouvbegjroushafbjxdfhvmwtykgxnirddmehvqalkvsmawvzzagxofsppbmejghounypdabnvvavrxutydsoikdxlsbxailuvlmbmnqhkqfcqzxqcpekbkhpekmeuzyqnmtzbjgmalqsnnipemchylwcwkiqmjizvbyxlgjnsbfhqpwubabcmagkkpcyanxvqvudedqygxfwmdsqewuswaeirghrvepmcjpgpievhlswokougimeiqnczutuaigesykhgqenbwjsjxmrfzwqrlssfnnhwvmqtyxbrbpsaymjyzafayvtjpmqdbyzympskovbrkwrlkcjjfolfmfpbrfeuffstwmekihesfvfqaobhfnmrsbsljzfqezkbmqnwzrqfpwxpmyyrlkkfodqxexpixzjjrzhrqxyfvvwivubhfmmtrfsvchdzjpkaottgrrmmoiwkdytkkhdbmxwrgbqpsdsgwnnpfbcvjyfoyaaiifjwchnjjgabjskhizznadkldsccsckaiwxmdmvoswsdqcnydmnfpyqssuukzhnhdmtiyrxrppwftjgwvvbmvtfnobynilwnxrwxitqxknfdwnzuicgevnrlprazcwnbojbyeryoedrdqsxaufertydkpfjucyxshyslqqbwvsznmyogeuazsfjikucmvbgeazqsrtonmoaymqhslhrdmcnwzrluttytuqnmkbzyrzygqfydosgcuubvlmpehqzcioouqnujotpgaqjpisrcmsazgrgohhsswgoovjxlcpuefdtnxnrlhrlojtesaymwebmbmkmqziugoqtldmxkgkardglfeyckbqlpaafbibhwrckuphhxthowozbsxfdawqpyswabyjzpojkdstalaqjqpljpsopqghpzdrcbcdrqpdvhwvvylepdraskqhcwqrxukzxndqdsvzbtwwskdjnulfgbojzfcxbnwyazrftmevgdtanwjctuhzxxkwentfcsgetxjnlqkrvdriacktytuvshsxwneyfmczlnmxfyqabkkbmwwlptgkaajyopwvcauppiovgfxipilbekowfvghxrflgdjiddauoorutpekxsodeczjzhqxyxkfatpfxpznethziokhgykmckvcrnzsmlxmfmtecsrinahvotcwtpkwzfasuzkgmhurwnvaioivprrfnvegkoelwegsfqzsatlyhhypxikobdwobaxlqdzokfhpxgjzzvxievzbfmqhpmxsouggafvkmczjiljjgguketnjffsxtqphmxomcjyqnaavllgrtadxwqjdydartszippwuavknxmkixqbrteqpwbsufvoappkgehagenvbbfjbxmsqqkhomcltzztooeuunxarmvuncfozrisjvzxhdiacjvqxzntomvfysbnugewxoogjpgstosvaqozrdtgpqnpjpefvkbvzpbkfjdyyxvanlzfoulflauupbbnldimslxzvcxvzvvngwuvrhachxyxazkleuaxfzwcbwxctupzrlwksxoawozwnljuhlrmkprnnoqglhieteonbcpzqoxfbhzissxfkoszeigpsovlsjawlqxdgvjickswdpdpfwokgubykxlfiodueaxkviuztnyyebnkzbwiyziiwwpfksbovaaslvuekscqvraxsyfqynbwlsdvlelghmasjuwvoalktohlmoekdhhpzkkmrwuykvqvpoqeqbqjpzwcncoqjxhlkuxbssbcprxehnkxqaigzekohahsyodkidlaxmemfdsosdljfvrfzdvidcbdtenbhaegoksvoljgqwrvrictlybracwtjmxsodzdnradekmuidscmuvzuwsxzpsibpcrubukvxnzhbwrfottkosfllcmcuwfmywgarsvqiwzjsqoikhtacalnczpyvukwqtwjltztrydmrtudbpddrrstqjuofekxxihlbigujjgcfbfisinkzffqqzgvgqsfybqbmxvvicznfevzmkloprghsmcycvecywdktaheegtjkrlxbwltpraifdghamlyjqleqskvzegjvtiwqvpfosptxyczkpxvfiaydkvcqbnlvwkntbuitkdqiipuxpqdzsbcewevzugwqsjjugtnqzgyhxseokjockshizeitmglfsuzyqoopwoyuicktmyxytghskrnxzycrudpkrfbovbkeeuzsvwsodbipuvmuvqlptdcnifdghnknjlhgjzwmdeexbqrwhfockqpuvuachmrtxyzhyyvbczagsuebbsdlkvfipgmzuessctbcrydwygeqaitbdwmnrtvjbkiwocqqvrtppynperhgzahexvuqprzsbjoplegjvbynzlcgcmmdmwklreeivfbzppoawwjtzjgzulhyxtelpoxjsdtpiuozmfaiblbdvkcrvjqueufwiefcharsvirjnttqfwtcgxtdijxpfdlpjsrrsllpvcakwtcdsyfyxaegmbxrgkhqcahwnuokwquumzzexeeuficrkzkqjtgnwpmljcwisqeepeioinjpvnihpvayoiomycyjeutymydeensocdeyrohgjhgaqwmqykbegxdtxgzbvrpyxvyokfwvnexfbkxbwygfvjasrztmqlkpgifqqbofilklxhmwhubfdbzwcvlugvkmgpfwttdbgpmgwacfvfkagkzkfkenfozneelzzoaidoobqqjlxtoffnpmxtzeizsoffnhunrzdfdtxmhuhxznkobjhbnrchfjnssjhjimqninbpjjmkyyazhkcubgcjqrdkanukzkyhazylkmwikwkrgmokvstljwvjjrvjetsevrphdnqqkchsqxclpvwyuujdlforajvxanffcvvmzfhpcjbshxsbtcehhvyjewhglmlnjjciqjxusyozyhatlhauczdivkogybvhkxrcgpxbplcpufjfmjzqkfyhpmpqnlxaipcrgbsxnunjzypnhqduvdbnprdfecfmtjfblzzawojvmalvtqrqutdlmiqqlvegfkisjjshxbdleqgxgyncttofdexqcdxjnhbzqtgnwlycdgzmgpobkcinjfgljduykxzaqipovprbvsnehbftgojrvpcgsyhevggnqvboksphncnuftqljzceogniguodcuqtrujdoymbaayhvovenzkdgzlotbswxkroeatvafwchwjckeizevcmupaqqumnffdlhwgjeflnbusmbclhxqtufvkyqynxfrimppvvuilxedjffxofpjzwfjuxjkuodecsvxqrfbpjgarnxhsorrlychvnrrbuxdptchkjkzvqaodzvyqmpbkukhhcalyyoprtydcifxafleghcwvtzgpkpzoqkoqaehtcmynrxnwlrfuvdprfxgpnhffrtvszcncqlpijegwylqtrfmwfvnscsxunuonydropiwamdwkooghtsfypsssmroclcpjhiywsuyexwrokxxgrdghxbbmspogtfpanpzfmzllwcbibzovexebyfnswbypiorxfqcrqqdouewyfntjmxnkcacaebporimwzqqrgvhdbfbhsusetfqxitxowocpwonxfdonyxqadtjxpbcijuhrpehnsjcraqofvfuwcnwfghdwkhgtbomtutgpdjgdbukwbgsetqjczoakxidzwsutlaiqlqtmmfloofshwdlvslhpulqsdmnqnxhancpakaqyhiffntdhekxaxpvccktriatveixoknmsxuxlnautltwkjrnnbiglizhokgduwpmvjmiwmdszwomhhzwkhcwreffoniijaxhljpkxsczrqlyzmvjtxhmdmrracclezspkizjcbittvushpeaolmsaglaknnomifyqhiuksqeokyvzewpqkhqstseihuxpavhhfcryuxmeyhfcfwusemkzgrjolgdlclujpohjntplduqiqkcwznxfehtrpxdtkzdznkidgxoltgtltwksljzrstiisndcngdctnfbmwmhefsxderqorhikssefwiuclzxagymektjsngxuyokpxsbplhxjprlcslczjqdwlmoyvluvbekzxnqkuntlhgnzrradjezuspupapketwdsjvefjzqsgftzyuchaddssykvpuzkrefczjkkjcerkysisxquavmttyqktpvmvaqwlajwfnnplgxfdpzfloygmqrhfmtcokzzmiwrxlglrgswvsciicpwtieauzfklejyohrltaymgrjdlnotrdrmlvphxuriaciokcbdcarkrapcpdxhgottmkcletteyeukgwpkygurjjvypshvidruntfspbyphtznrozpuvidgdevvltfqkagfhywkylrrkgiyfzvchyjkeehsxnijpopyollnzegjlpksqfvadgkikuakjktyzkypwjcxolgbaqvsvssbyfljzntkzmkaxiqvuuskfalhtiaqbutzzeiatdktswtrflobgilliytdgvujrnjruttnxgircckjnykvgxhqvcuezonqbyjvsdlrltipxsznsliyjpqgtkmuaaleaubszmjmitcfnbsfobfxswgoisijuvpvqqprfzepuiwilpnzstzmpfczzliwgztysisxjyoegkorbbstwrinyknyxxwexpepzyolwcpemfvqgojfhtsggfeddcjcrotsohdllupzznpidbnkwfqcnwgsyrurfnkuwnhjiykhlapodcbzkrcxqkpobjgjysfwfmhnkrxytmowrpybjcyzmnnpyvyynfuttbigufeousmlkkmtmksazhqzdqxsyrnruyxqddexyriibwdqivqjegijzfcxyroupolttpstgddkzgaibqtgzcpyhtxglnaablvxdoqlruvsaxceowmpydpfzmnkzqmddiagyssrmnlplotbkhqkkfrjtfvsxkvauxhsqzleowtbkocwvuiibaruhppezmetknncoygdwcejqjfmdquhqndxcsddfjyrzlvnldqifxrwgykloeuetydyqibxuaotnlgzpzhuwaseycrpgmvckzacjbaddqyrcfqtgzncbgizkzornktzlvcwweccwavahltnmjrnrzobbfuornqeksajyelufgvotochxvuoxkqypkogaekkyntwrgryomnhcroaokqlvilmtatvgfhhuddojuoyibhluwnlifwfoishknesulzpodfaztykxhxtfmeorbtflloxyspverkuwruvkuhhcedjqhxkitpveesfwiccboxxftupqczuicdblblwuaragkhdujhvxgscamuqqvkzznckqngmpanwmwbgiidfpxkrlghedtfcihozwxnlxcjjzkrhvwokvadggmmlfrnpyeoudeicgrnfeeozcflxhofqasbhjrwkvngarocxipfmvvnxcawkqdasxbzjuxtrkbrdqtdykimffbekbcurgwjfzkouhjluldxbyabjkposqvcrxwkfuvltfznmlzgwegzcgcntrclhxpawlmchhnamooazpjvvpuzxwnsprdyosymfkomrbpfqfgrwpnrejqdifwxwbwmuwzbhnqaphihmoyidnbjzrohxketmcgizfliudklksuwgtglihwhbloyvvtjxbtyifgdirqvjltsgadohayiloiijesjhlhssqxdhnysytketqvdqtndhyltcfejtndldaqmoqfmkrtdhoizjwequqlyxpjqfneinuxbleqvvjafzjgihlabdmzadktixxtltqoeuebrpeyophwwszzxlaxqksbipwvjojpkqtbfxcumjskdrjaelzxvuyfjwaukmkucdxhczdqkyapplrwwtttntbypdtzpftrksbmseeeceuurnspglitglsxpnwesrwcjxqddukgaecrrugahqtncnktaixubvwmuoqykagkgidzclzlcvygkkzluyfvuehouzofburjcvjggkrkhrqsdrfxsmumsecndrsfllqqgbynmsxvlqnpjsobhlpzpsmslgzwsqoyrnnfhndsdqjolaqulhtazgukoujimzhfownvjqqmizdvbtpmajocrjohfxqtxzanvnjffztqawnerfquqhwhqmqxkgsjfswbihipibfjyvnraflqojzgwpdiwvtdqreyzonhqvsqqhhqpvidghkcynmulfabxgzwvofljydbfmtwhbaoiksjzffkkfnhmofhdluolzqsljpvlpjvbdeaiknvraedpkmsxiikhycvkrqxibujezkplxkezoioawizhrjqrmlbfdaoevzlwjahimnicxyduhedaotrchvhkvxrqxcmievtqjbsgzxcichiqbcskzbuuznnypbgvzzliceqebvmfcxvfzppyrmuszhqrjymiaascgkghhvnkskptahrttnnuvflgdaqdakigwqpeleodrfyrmpmhfzccepkjpcprmxzknrobvegmmffywtgbukdyznkppzidyiqnzeowlvlxasxwmfygpdhptrgisooqyedzkswvpjupbslnxlwnpdckwiuqyigxolyzfuwufrlhlzwiksvbvzltjgjiqrhhffgmcejhxuqitnrgfojdqvyzdkjvbsciakvcpelmycxurqayejbwgcylmhhpcjycutglxrxxvwtmmtntfoplspzexgubpsdlnjwmcwlysfmhyzafqrtihspgylhpfkbsvzgxvrxqwmxxlxcdoxoxpddpqkfvwinthttdmqtjesispmvfkldzqgrgtwbreqlnjesywlhbdptudqcncfpsngbgccaitlverocnblqhcjdgcftemiyaoziseicxvadmqgctrscwegcgnvmagkcwmkrqvtpqvsflahhszjqdrsjhpxhvkluwxlosgdlcxqpyxwsyiiczangplpnxahtaujsaofelxulusdvanzcnmkfzcsyebrevczxsecgcyryqxttksxyhjfilzhsaawxfvwxaydewxcpuykesjebsjmgktymvwjasgaugfyfccwwagdvrhwjtirddrqzobbgjdcqjavlerkhzncquybpjttmkllampgwskmbmjprczybmatiauyjprwcejcqalovvawilnbnmzqabjjbghlxajzeuewvrlqmnowbcxoqyhrzqcbylowlzvrtbpqscghqxdtzdhrboidhmgfxudkvzdocthvvncnkhglmqdogntpazxzvakqbngeinzgddvnmcbzugpctisvhpvcphsruaxdoylrbggpkjoepdjjlbgssdwhkqahrxmhvxaydgoqscuhifstgzoyemirdiyuimbdlbeojsgbwblegdapeqpjcxcfiazqocvzfzprrwsqzfuhjwwnmmyplautcwjqafrgghxadrqcxmjijixvuwmhyhbdfmvftnnaumazgsbfgmnpuknqizyjizmplhxfukhqzjpfbskjfxzzjosspqbarppeyolvbslabdfevpoaopcxfurumuwdjojkcvfdnqdrtkxrbntpevpjrggfdckoquytpdyeucxpoxiqkcfrzuardgygjjubdtuuytauxyklvsbhwjywfznihnqswnubgqvelwziwlwrfzacizyoanyhapczcyakoyqcwrmueinkinosmoiodhyfyaeayhmoheqdwdxankmxzcsmsacvjabhahjaqxrxcjayozaclpblttzmwbjfckneuyhkwyiyhkywmyaxpbkjvjvrneyprlvnmcxiahgkseggegduhodezaxmewdxjbkvdkdgrlqlpwruexqnntsmtrbzpgxbjjyntevnplahjsdnrtaemushmvgdcfelrdamhvzyiafruiendhrpbjypfftjmzwdezqnwrmfttwpedchmtzpfxfmeaxrbvwguotrihwbbutfzvmlrnbwlikpkjilehrzvnsfuqjvmccmxrzqecopkyhwhpiowbpuohblxkijmlxmexeiztamthidyqrvugrkpsvmfexrrxfvukdvddhymsblksieazpptmdyqdshazcwjironbnavqnfjvmlwbbpneqghiphjsftczjpcyrxpecazolvrmnhrdnanckwwpryodqqbjnqosspielcqajjdykscwqzlkzcnruqbijpcbemfroyrzhwxtqcphddtcfgwzyzjhqnjuaqoqohqyeprwrjfuoyztgvufwgomvxivqwoegecmvwinhojvmiqvfkabsonoowleuzkafpmbnxqulzpzkfurruvkliabglhdnrfuisvvpnpcpgbzlwsfsnpfypgecnjrhpmrhjnyxeamldnybhduvubtlkzqxjhgatyjdnhatjogmdfomkkhhncuxckxnsdnldwqsfsmqgselzuymehtsmproaodsssfxqwqxocnxwrkwmkksufkgucwuszoktukjsagievhcmsayekrypdemhcgadxmwtwhlypvekdjxxjxdwocnuizblidofqnyowlnmgtylcxiovmklqxfaxjnfmcmerktnvizdbapgxzusnegddleawrhlvtpofkcasdgwdvcduyvkebnhptknntykpqzuadxtidroyvrutoezsugjpswemxpbnqxpvukdxbrxwkurzyqruzakryqdvfgkxeasykyyorvmcpedqwwmvwynwpssubeuheohrmfhedtiuznkwjzthxidmbvjecflitsbgaimdewxdjkbsjvzidcvgagkelxmesomswyvcwsgfehzneawiftofbbjmyxsqlfikffmcaujeejuijsqonhvoigaieuzpzjbfrohrkqvobrxljpbywzmefonjjobizcpqsyjdphtsyqfkihiegxlnlaxwqafpewixvrcmyvezokjwttczqnmcplyflfxqefpzytlzopyebjcucfvtukxmvxrjfqbjvsiwltvbkvgmekigpebmoyylwrubixkfpubapycztknxuygmchasgaderyhzxthnnkpcjtdedtearkovronzqqfhqmjofqdsaswlmaqrtutmghhzxubpmgxdvgtaywvaqrmctewmypagzhfydiospnxkvqmtohtebfjulfjjulrvtzwyhkqwxnisfvntegahojezonlkyegtdeulomjncshhpudvcddsmhucwhmwlusrymcoaldcfkkwgpslsvdgeziciwywrqnrergfejhkwtgciancvtibusddpcziumbzfjgjvnvrjcvrclwaggdazhdqleafsdgxnohiccbngwelhcnpjqqkzvcmaesshaqupzctdfgkcmxlpmbaetkeooqoskjznbueayzdefpitovkawkhrwlgkdwcqfedgyjiyioepfmiuivwgfdyeqequavmizpqzyzxincxsofoyalfiqdohjedlzptyekzelxoablursjqtwvdmartjxwuxlqxrcxxnwlpxwjopsekobpdbiwmfvjeibccdbzsxnhwlqkclrozsdcwlbktwtxgubizeirdxyzirklcbzdvfgrsjclhxlnumwtrgnudnwnegygjamefuwxdajkzwxtivnbbayepusucsclsopzinxlpixpevioqxquzqapkulmnnzheohmegatqxiuutknschushleewsrlrapgjekpgfffqbalmpdowzjfknjggcsxdhfonretxlzpnbabqfrofavpohwwjqvozbdnujgtuhijiimyoeotgkkwrgscyotyrylnhthdbpplabmqhajokvkdeficvbaobnbijinmaexcijspmdfwysccxmfsnhioxjygunuwsryadqrpvxntpryoddismqijzirvwlrqfrqkjjzegoaxgylldtepjmblvuiticjntbzdkajtojqwhcimxmejafuvbcojezyaaxflxoeoyukhyswygahhfdeghtsosqovqtgnjkbjgothgpfnpouuracytumoncjdxrshduqlijsqyzfnnbjecofxktlxywcvpvcsrvebgyrfyxulagscuzaeunesmgobdswuncvuapbaoxooditzhtgbikuuskywcwsqyomafpbtmpjsxcrgxzjgjdcepacsyukwkwzrnakzrwtqylwwkfcwlecaheufaeencfepfrrynkolxmjirlgesihbobiqiofktkaabtyodobballuytasdhttlejtspdobfoeypuedvhgiuahnabqkxlvbuovltjozaszpmfukoasiabxddpnaaidxyyirizsiruzebtoquiywkyzpnopowslwsvqcuikmelsgfiwbqwxcuzriniymcjixeyzzjmnnxftcprfhodkkcduposbsbmpikpjtbwjadcfuukbkpnwrtrjhjmbnytxligglepnjusdqdecsuymnpxwbjxqkqnxavdnbvbkrtphyvjrpjfcbcyclwsxohupcaedxfpobexzzisprxtszswnqqmezjvdjaiihxykbvmdfeuwenrffpsvihchqxlbztjjthvwehzjmthqhyvoqqkyxofpnsqpobyhivdmddxpyehfdeuvwgtvuakhtcyhdyolutzxwwovdvcibydyewtayektgiamhqzbkzaixofclikminkplgpkmbdukggtwgwihwtgkyjxitjrhwgscxcozgilopgkxcveaqkmqtjznssuqamszriaztlnktzhvulvmvjdrseenyydamyzfgcezprjjrsgndeabnfsgjyvjyyjkwkqfmwgcosnhktwqxyrldltojoxhoitltlshiyjyqyfbsdtrckcfxxwgntpceipxuheehqcyojbimuaqgeydeulrpattikqerxibpmzdvcokyoaeuyjyuuqkulfewwjpvtqkgrpdtfptvqxqqgolcgxwucbqamfxfyhnpztleieayesrmieppbnlfqbicifkipzyoslubrwbvoskxyzobmzhdcphkwttlttblgwozsqvjkhgjgwkuxrzzihlfagqvbuhhqxhknetylbhtzrnwlnvvwhawptsrnbafyhronlmaovtoojkzwivurxqgskzfnamojecxrqzfltvzeibasyujvmrozrvmticcoebfwbmhwkjasmckkyvhkmvlftaydcdrjeyfhkpdwydomfawdvdqkbbrubsxevqnboujajmxjqnvxordlxtxyupuyjteejtfxnqxxdwivkeuyxxluqjunaoljjppskwpxnpwqnfnxjhxgfjdxuxkuoxfxouqyqhwfysxmzkliujrzsuyotjihinhxjzxzivhjoevnpgyjrpkljizetjmcwvbhuyjeuqnkukzltxwkogwzrxemhsofnrnjqwnmmdyinxugxqrnzpnsotevlvdamqjeoyscbqkpqgvnxoayfpswiwrvruvgmemaffcgxpxnvvaujdursmndjgycdukpaxsfeuobllphgrdsuylpkyuvguyjqkbrhtynpmpbagigznyuljlwjhrsbrbsccllvjzlyqoyywgxlhtxqgvcnourgxjkawvxhwkfmyfmwokivdhnkcpzqlqwjzgjveifavkptsbsgncdtjqdlgebrvacwinumwzprlgmdjglxiqqrhvepzgiuilrqylfumwnxccdniqkthcmoxrdxzlthwmzvzgrlchjgjoutegoljbbgsefrszaqlznlghwkohrzvnuatjncmplgvqznpzgdatqgcotqwkrtzmvsxjxlyirvyqlqprvrmlypzthxfzrenmymxvxxfqtegewxvtojeoydhidmjuswirkgmjdszwyfawcxpshvhhyqrddaxvygoiobrrvqqvxqtbqiuzddidtahyagwzokjcnbuktkfrcysuiotnrerlealgghhvsrzhsvsnhzekazginawfepskpdqxlaufruolpgyxifjiepstrqyxhshywawjasotmceeledvjmfpdzjvshuzacyyewhgoxbdbfhmjkjvyokbotygdthfxhdddkjujkxkrgzcsixqxitnbsvelcjikolpywjjiiubqtdidbaclupmmmtzpejztwqtuadckzdbsijvlkawgpjseetticudakzumcwxbbyvljsxtstzketoiojtsdyspxmczkzcnzxbisyektdwyzkiptbiyaaoxpqzbrdpqdqavqehjkehjqqamtikvlavaswbjzsbcicxaifksltdblepfmacxczzvvbexvibgkzgsgqntkqwvwmcjmhiogilelqdgyemkftenltgvkdtgpxrdectnmftxxwfxasjgnptajcyvfrdwqvbvzuilbbiyzpxzjghwwbzfdxakqdggahbzdlmfowfnmdpvlwuhztocqqmgwuowbqyhdmmujtjvwysivmruhgzzynhuiwtlmtsrfgloavlwvegqqanaimzgbhbjduxrppkuwwlytwwoafhtfwtnkuvlbwvgsuxjjkehgpfbnerojyjouedeyysaxngrjgbuqheyylblpsbytkmporwnqoppdxgmdhgvokvowwalrbkkoybeqxtilixogdclnjjdvgsrfufwxrilpjqhjjruuolcunpjyyoufilkcsiajsnbbfkkpchlssnohcxgdoakwnwbggdpyqszwdmnhvyznnowrncudcgcsedykgpiyikunyjuthtiwjeozhkcltedxjbiptsqdckqcwkvffdcriqqrcscvzgvijdacxqfccveyhaepfggnywecqjyrptayyabxqizueetngxclfibdgfhzofqfaseashykpxfvdajjxnveywjedqfuwybyqhbjozvgyadeaonzckdaimgodmkbklbatcljdhrcjvgmjvnlirnqfugkiqnucpwxtkixtabcvjqgeeumxhfednrneejivihpspolpppmygtemntlwapangprnzbijizbypopefcenvlzkekgecitiynvzogizhjxxzodeqkslvrvzecfgmyqklojcwtbdeacdogifqcslvqmzuthgtyrfocjkwmnamqgcyqjoscbpsprmiysbylimotymfmorewwcmfsgjvwdknpunkvoxgclzbzfnqytmwxzcphlmfrwugqksnyqvadvbfcqvcjhziibzsolxfhuozeipcakeehgjlwgoinnsyqsqgdpmnjcopkdrlqwrzeclcizmxofvexnkadynoceephxazvtzzvkcfloezvcfsprvuqijumpjwmlvieuhbglircnsxpxsgpnbhxmdmbninafxhcfkistcwiwuzuoflbiuywxkxmsnnakucremkzqijneijsqutaqsxneuczjpzulblppxrgiatmjcfbyybosydxvfwewxahaozplqxtqsibwncungkggqfbvdisaibawarkspfjhnmecraqxnyfddhygrsibwiawzkpqrayhoejfgzetzkwctxkmrunnenmezdwrduytajzhlfakpxpkubwnwkbaxngxqdqvzqoazphkvhxmgmxcptqldtmdgucyxsvxilzjdgwyptmwhjywfqiijwnrsprqjmpraodduzdlsphzzixeyhoidezyvrofffyftbkpancudkvestksaacgeceavuhcbfkwhuljkngpzbvtwfmxfofmslmpftsgaecjaptkezzgcuzzbnyjedvwohovcidcmhmmyhzeiamkxmlybjhfmeecnsxpacumliajrzqzcclzqxzsghzvndxbvxqvzmjnwmwnnoopraohzobfxbckealaxexysjlpvkciytartobuecbddeokebmdhjdaurprdtcbmcvhswdzyfcejqopucubnxbiqsztobvcdsmyopxmuzsfsiumkonyoriejhyzlvcqnoobdnpynkdhsatfqidebllnulmfgoyvcmyiapgpzlwsnrzebckfpvslietovrlzfjhhbnyabuuonturxfwocqalutbrmnrtyybzozcpwwflsacphaejqewnzyennvgnwhnkjrbfngshivxrxbdohzbixhxkddyznnlwgmdtuvdfsawqdzembhuyorltwlujafhgrkboietaerqjrwvsfrsukfnhqisspayhmcvugqxnhpwaouutlnpwudflnxfczglmiiioyfdgxcilwdejqufkzmxokfsllextoijppnxmrfxnicwayenxqkncpfoclnvaxfpnumznrxacbycbepaxcnbtsrwghrgeyxrulrheojgrklsqasnehrybiuhpnpuoolizesgudolnzfgcztggmeivapkohgcvumvygdtkrezrmftlbbsngckgrxwadawzptyvwrhnxjgjobvrdphlrttkqslwshvhatfymmnkvutmxqfcfmnwijjybuutbsddlkbywqiukdikunmbccakljimdfhgxmlkwmivespryxbumnvorvacgjqjqyrnmczjqievctmasnwecsvupvyygpjwpblbdlmwvqrxlfafuwmyqhuictgjkpfbsteyeruzjnyvsacoxompvjzychjozoprhtpnmlmwyntsnvimkxehgdhklqymhpdqkvexgsvhfobvjkhvhlfnpmzcdxokotcyqgxzbsgigjdsvlpewutnjsrmrhyfdagtjfskyasgmwahjqmhmfxvaojryjxbmfwvkphirbrdzrnijzqygnvgdfydqxeccdzmuivlkorjfeurfkplzkuersiiromtroflwczgqqsyumpzyemzogdianqreemvsujrwkxparnwfexdileysiguxyobfazxukotuokwhzsndrsncxlwhuteuhgzjhzgrpzlflhnkbcnuuayrnxajqfeznfkugqlwrwbcfqogsbcndagrxhapogobobxutislgwplmetfhvulxaevjgkxpbadcxzvfuinqaacgtjnqfaoielrlvrayrfapgywaikqimvoigeymgoulblyzcaxwhalnajoitgribhqinouufqhgbfhgffcmfpbhyppuwiczqshfidzptgyxnffskjgrykywzqsxyuxqogwxmvohemgrslmeuuyuewtgoldnicdwlzvxxmgbynusagxxdvrhtkniytvgvaegacfzomcobwhbfeaibsruchccazixapectldhzfvadcekieujyoedvifvkqsmfyoykthlaeofjsqrymbxahavrhsbxnneldexwnjwsxcbruurivqjesgwabxzonebqkbnymlqlptejnvslmdrelngongcckgswjhuvtmgifmuvhoivrzaepitcoxgafyxogrjberlldfgnvqioqktftojhlpirphfxyryekmsotadprldhyworkxayokpdrwbspbyanqqjrtyigbpeafxkcakqmbveyyypawppnhyeawojafpakpmmpxebybhyahocefrtnsxpqnaqssqchfqycubcxldxsrzwytpnnofdbhutzmxgrngvjiahtdgnwikubbkosptvynrycogvcntnxtwswdfslrmovyenpxionzmpoumshfhgyeauhgmuzbiuzojplsfyttpjncdxhldgpecympsnscirsridlpefivqwxuthfypuerusiogasoukhepvutccpsyomtvrumnygjtoxzrpplbyprtjmvodqmscipwecleivxyuwpmnanmsgfdvdrytgsxoivumhywewwyummiocugkbkfedezjwzzgutubssfopgibusrwmahommupswzrvyzpsutmmaadikgddyzryihmxebpaagxbgovchhqkhustavyaxqyhxkebowdqearkpmoytficbdybawczmchmplpfhtvmtnykbplxwtzxyzazweykhfwytmdchaqcnrnriyoetnbunbtlgrvpzupuiuwruptkgiboipucevwtyregkcvjymfigczbtslzbmpjdjnhglbgcfnpjkyhxgpfioibjvcmjtvmelumwvsbchqmsqvrwnwgdhjmcnymgwymhsadptguawiupdnnskuwrdkttlhzhgoqaovsjcmmauirzwfuizqbecwxnezwkpmmdiepmqdmmleohjirkysocpmqtnmfcbrhjwwvobjdnnrwyzoizgxbxltqaivcjnjulipzjyeyovxmulxvtwzrhsjhaflluufheuiqvnolilxfywcusbnzwwiydvkzspgwmpmjcdumqtrrqunixaktyuseqcditkefbtqfykrogjfwfuecwqwvlobbsellqprtkjyiuqzabeygbekxvgsiwvloawasntmyckiyahaboyjpdumachibctpeprxemjcrvlrwssziqlxvhmxjtfkxaccrvzwikybflsdgkfodsoazayktdxqgzuxwttefuflhaqpkxgnpuqouobptyhzzexvxscfmjswjiluirjxlzohppyjniimmfjlalqmviigtucbnoyzpmifdhoqpwebeqoebfsynbhixjjmxklnwuscdisuezxkplosqhtgkaojjyvhijwgfqiiydeccbntmdldmelwezhqzfxjovqvlafjfjnjkacwgqbsuorboarpfqzvlrqyrvhzeuiqxlpdbqvxfoyvprkujjsucisugbvkwdbtoqyrivrpkrmbjzvsipplyjheneqjhteyleruzillaymlxkfhzuuzgddthuerpkpbogvppidripcfbhpbelamrghyclprxgsnnpceyfvgxzoygfbmqcyjkfimszdpiycxnhbnoywnxkmfrpsjrqtbwdpqetgmrkjgrmuikqvhcjpvzhesxzwvclmjguvzehgytagesdnwncrolxgjxcgboukwqgwvpctieboygcutgljskqdhuljiivhyddtshoblrpjytftcqdwcvbkpmvawqhvukqorhpeahpacuugmzeowfyluvnqounkgeyznqfnzuodokkalorhwruqniibewllclmpbseamsedeqfpgwycotudddghbtsdehuizyintoqzeypnuppkikpnpvvqopvvwrdxrnlmedmibdvysnkdzaqoxngmddjzumxnbkafnmqrrnrjabozbfpzsvnxyyxukwiniktxwjopwfyzjpamuqnoncomanimjqatatqyefncmodvdeizwxpjadxaqgnbwnuzilzmspqeduciamjwjahjefkwlxyjmukuhkizzygeukmwwxshxarbfdascabouoieysfxslbnxpjtmebjgunnxnfbnipjwzpwrvvjgyygnkzbqcnwyalxpsyeanpzofxfatrirrohdqituvrtxcqoursxgkyvpvcrovzinqpsgzmaxfvwkoleffdlpbiezlxpgxxvnmovocxljvhtjsaqydbphkwgxtvfqtbfhrcvvciexqygkywkdzaklysirookjrrsiuqdwyjvqhddhbnlapxonqyfgorpfijpczuayexqnatvbjieyfsovqvbfmsmwcczbybbczuqznndyvhzaznyrkbyywnuaptdnxfsybizoxcpsloumbsenwelsrfsibvyycqyfaxwxclrnzlacggpckawcfqkgnkgsaexaetzgeqtdcvfibummwkqcackpnrhnxfqbyrjfidimaqwcmiojselugvjvorjmybpyszdaeooegkgsuwbocoilmugcnpqlsgjlhpnlfcrloadjwhxzxiklesoriecamnntebejfwutyacujcvgmhuqakhiolkbaawfbbqgzlzxnetwipewwymwkvgzitcktyrwbiecvdbijvgtkkpildhvapwkiaxdbozcydhtjidudlqpyhallhgnwfahhxminmnmruhcenzkypzwwbhjiqzhxzoeyaplocxiyhmeulosaorzrykaqjjnkzuibjuqntancmrwygrawkbnkmnbvyqixkqzvmpkirxkdpjdvagtmhgwvwxtuqbscrrygikoziyexjkulspxzvuxrtqojrgmkzmqjygkgfqfqabcsqzumtrfnjvyabmmcaflzlvfsmnjooljhkdvewatfwrhzetegypfmnnebanpqyaxjdspbvkgtbpuhlyqjqvxdicgkpxbqyabbvsdscllfbfpmgfxwaxblzhxqeaicbjgydlqfyblbicnohnkjklulusdzumdvvjvzwlgvotwxvmncbymnliygcbhxnkulwqmsdsnsompjycmzcaoqkmynpfmfrgsnyegcyvumhlyhpkismwiwkglanxfegxsedaidxcshnqofaxxovhkgpwgcvngbmagraouytmficvneumuqthwifekattchtkywauwtjbenyrsteolzvjkapwbipfrlrrhrldnwgrkekezqskqqtcqiytsoajbrcijonymvpwbbcbsvnkljmdtkxmazxbralcqaacvrbzsdamapwnyktuxsgzrfdifokxrmcmdflwknilfhaftvzqnhsfnvpujcuaowpsbcqlsayxhbcdwctkjlryiitskpuzlltoojbgjadtdhwzlrlxfevnnqhzfeasptgdeilqkqlnyhojacghicvvuexcixuyrbdxjpnvfyifhypkavrlzoiwvfyddsdwvhtgyjbfjlltkcdmzwxbngxilxnqprolairatthcesxqwadwzcxmiwwwtjoicdvcnpegkmkqgihdkmzjoyxzuvxnflxhqtmdkqlucwkjgroqfnculbvhxsueftlwozbyqnsulffrwtjeilyvptcmnyqssdqgdsfvhzrsezlduuhdihyxcdjpbbjteaajuhebiyvnxgsrazuigvhiyqzbtivykxjegohooeblmtcnuzxcwhkuzlxtusterclxsumgbprnlwchvckrjwniikbcfwiwzvwtsiatztimplumnefyaugihkmmixkjugdmqdhqyseodycsckqfeypnkebvbmexuhklmtdlljbqidkmncrudjhnnjiqxnntwzgjtlugvvzdajpqmjmpstehepxdekxakdjfpfnmampdwgtkphbjafqhwpmaalbkrmriseuurjzprubjbcuejnngczgcljoeyhmqmgmfrmwiixtkbookbbsdczinkwriefaslpxedvnlsivtwjfxmydpzleljyupduhrlgvobkavtvqrhwrvwukxfriqpcguzpnkyjbbvbxqynihlzdjtpgagpqxtyuuqhhoqipojoehempplubgjhgqyzpuzjorrvhjfxxoncyrqpjcjkkuttksscotlclcasofrlwhpwyglhkwtuqnndhhfvbqzovbijhaufjmbhsmrcikwazkdgriduzdiwerfntbscntlfhejrrgsqsvzjgcgfhodohidcjygztugbyqspwmgqihbolhvvyajhioktmssgmzjlpdcnqkdareqdmnymnjtvzfqmyjukkdxbgaqyktyezohnbhzqsvlracfynzlzeiankslxlmbmckaerbujwicxmixbjiaorcdduqahcdvfnvlgzhrxruudcsgncibvmgzixbpzhlewirdjzwhqqdwuxciallvzswipyzqfmvbxmggndpevtcsqecsrnorhkbwkaprnkvkybsogisebuwtaymuncnxoovzokqdulnvpgjxodbrzxmbxavnciktwfsnqkqmygjpmsmcxovynjankvamekhcrzphmiumofbcypgxfbwtkygwtilzuselutvgdrurwvtwmzuscslpqtlldwlxprkjkfrqwlhtidpuelmhfzyvsjjviuuznfkzkbpjoxewavqghdnmcnkxztuhppicwsbitrrjqvfsrxyacoohbyeatajkprmnjqwejnnblutcsteuhsblthnmixxzqlnadjgoywpjqknkerhnmkafsotclsddgqdjbmaakplcabnguuvggwnykhcxzgafwgraurceingkqtslporwkfwwozvnfxvdfofzhhdpxmcnhuyzisxuztsnuncblzhqnmsuwxmtjoitihstbpnakgpfvrigrpzectbyqptcdbvnkpgleunoccvxuegntfrxauxsjquourcegksmefbikygeemratkxthxlspihjzlqiviucpxkzwqfaeyaxlassxgkoqtypeoxcyuenropphwsnvuniufatnmidiivoyuqyounilcxuzphwkuegcgcpumveuqtumlsbgfltiipjawhmtlsvtumngjucbnwoyorgucbekqpmpwykjrhcntrwflygyxwznnhjpjnczeoqanajghltdfpiqqqrpnscazmsibukgkagxdsfkfzpkqzdiquxdmafnmzwpvgvgieflwlybmpocprlflikzkrmyrkomsjsbnaollonzebbtsoyfzkgjbuisfwhxhbaxbpiofxnjareufebeohqqeykjwrif"; const char* longQuery = "tjcwallfkarlrvfxchdqqtiutvfpoovjxzgxmtextvintpmvypnplyletrwhftreszdhshenfocadoxegkvrigxbzvleqckjdnsvvwkckncpdztjloauxaxwvibmmlxpbpmwnzaxmcopdiboydkvdisbqvpfiowjfjhsihrwlfnopodosnjxxdyqynvhbrqgcyamhrktzyhoomcgcoezrerssozvipekpezxyjqxjzlymqeqgkrzpjrjxqgfimszrtwrcoqmqbketqubbnbswsbwljdvwxupqtgtjwhzztdvjzwmnzglsjjftnapkwedpmybkfalyggjffyueegyopfhefyreeuvsswczznxfwimbghhlpgbelklticxoyugsrkrqzqxvyjyhqiufqvmdfzwpdvddqlvjvozwewuehslyahfsctwjsuyxsdaiqvtnlskpqewxyjxzrfttypftkdqcjtmzofnczxrrbpqzboastuntlsovyhxhalgqqtsrsmivbzxcnzwivkdhesccbcjbnsrelmvgygbbfyguyeetohavbfxehjfwbzconaulgwolwwhwblsruumyzmcivkfylhmyhjlphbadyjczwusrohrotvyqfdosncqwldmsfoyfyaeuuynifeyyaxqhcgaplsmywardorimtohnmuxsbysdxlkzrmrehfdffwitnqigepvslumoshrpserlsiqzpteupmneexkkmhdabrquyilqocegmuibpmxgbnkhkwszdxzeorapbmhpqlydhggyueevrqfdmxcrwdwmvwdwklmbykeismgmqnkjdpnqopjmtfyqeemopapnmvveierardkuuzmiqwwldwbhaowpqnfdjchrgarxfduzeihvedikakraapsqdxtmzdfidyfjebiiksfqxoazaucajusotmcuphcuikfmlqwxkcohsqhsmluyfmmaypupyzmgjtuwjrutvkdncmhpxbnenzeoqafrztxknuhwldsinxxpjegihtmwvsmnsseuneeaynzlqttdqqvzwbhdxvbupohjimdvskyqxxdosytioqjmusrrpsleiunsiroadosanxqfvknlcyxwqqpflcltxymfrciuscxfankvzzhcxgypxqwishdpfrxztftljqsjgcfhdmjcskrpapzswdkeujdqoydzryjxaoegcqiuccmcrnwosiunrzfhxkhoiqnlgurikzemdqqvgolyxfnqesydfhspxhadbtnntrzwkrtqgeoflcvrwvvdcptbwteanrnilpgvgalogbtsfrlcmifpxaswuzyjsltdazyjblxintcskpwwyenxeitahtjzfcdhebqfpqpcjtutltrjxhgbpccwvnxcsakwecdtuvvdqrybkskhbtlqvposclvwohusjalevijnbkrmcdvdwgvtxlmayhymotgztrfqbrddbwrfamkwvfqsseuqltfbolahfizgzelabehbtrzoyriqvfiianjozmxewwkvayxdceevvelvvwlrbtzbhlrgzomvmwqowpsbtwwqcknygyrjtsmcfdketwbhvrvripsdorvqbiqjgjsceeejjpqclrjglgatwsxklscmbvxjeplkvquehmgsdrzoyzkwthifbmtehtooibyerukygrtkkuaivkgotovvbrzkkpyurzaktljaeemoymztzfjswfpzyrjkgiezhfkcsvcwzomxblsatbupgkogdzqjjvlscvvwsxurogqpsirnjncsxsycrrmbozvsuqomoifcoxtifmvqzzkzrlblcpoqojikayyqgduuanfhbaacakbtvfezwurlezxgxwwfzqccfhlihlkjyodvtjvpemckoasnwotxgvbncnvlahxyvauqlrgrfkbtktjijeirzjgdydqzlnzgptxbmfsspwncrwmdcuudgdiegzdrodaeyzhngbfxxuzrtouviqzothvaiatxdvdewkrclyalsbclpyhaoiqkpnmaohxtdaxbmqexogkjjmwbmdbbntndhzfviconeopqgtpxbagkmclbioevkrarsfoajeonuddbytyzvejhixkqloovfoozweaflqtfvygttguomfyvcinqxdleuceqggxrysztrfomoibcnbzsjniisvpmxvcgbcxzuwsnegauqdwfgwxrlfcddrqcmuinwiotgigkqiggndlvblnmsppvghyucgjaqxtxfchxmqfctqxudkiwbxtjfrdjamlqjhnqjxnxpsbilzeqlomplgyszcdbopuawjshiigxcihpjngwbslnakhaondecxeahzjphpnjzwzikfhlzsacekeuxhzzfdboekflbuxbrwlbdsoenpgtzkowsnxzsypxkuilpfmgdyjisxnfmvzngnjacibugqrsmaebhqjlquvlsisggrumgfoiorfwjwpvyvzilkvefqpxbhfhbzvjfjuvcztlviiwdherszxzpowqvbxydukkdehhdaualdyomchgdgftublsflqkfculgbulbpmmsmdepmnstsnnwbhboynvchijkdunsiamvfsmtfgmywcuzjxnjkkmttxdwrqqcscxzwltcrhcnjwmvvbefmsafpddjvvlqzkpvvixoszebxqysufzgxznpesycnjsmvhhqshekiingboaxtafsbshikfkzqcllludddkpmufuxtuumwzearoidvseowrbhmfnprcdljxjcufqsfxsynceiwiwsayaofnfwrjjdiufcayxfxpfkujsqsrjurliwynuryduhaclackhzcmlwwfmqwvkngulgjfailwrlyenapubrimpgsbwqziehepqoxqyimrtnxinoerfmdutxyroxcuggjwwgmuqbnloltdzxuhkadfxbynaahhjtffbsasvpdjazoawjjilmnkqmyqohzxafdezfwuubfxatxzeghruvckjcdzjcxmjcqijoefrjcsfztlhadexfoijriswhgflyquouzggcaldtwntbrrihzrbjmxqsedtuxhpznvdpiiigxeiqvqywkziwyaocejxdrocgjhwtsezpijgfcgemhmifmyjqiiwbwahhidaakcrsnzapfedmqltemfxwntxktgtdkufuyxolwodesgsksopgtmcghbsahoetklpiievhsylnffxztmfmajvhmpkvdopnbevkirtdrgqwlnvfccrclomzewvhmmvnqszblsedywbkjxrlbkqpzeodajmovjboebrpvvuwrwgcvzqwjilimcnonaclldzpgshenbagzikuhatqigbwiokyqmjesktacaereezfojavkvoubprmdbkwqvakhvkjyrccxbhmkjjuexpimiwsliqbdqnknavlrxpqyxeiiofplwzaevurdkticiupipdbossorwyamdrabqchlwzqiuakcwblnembxgpofpqrvhtwxvekrfcbzenbaponvdqulhjqxbksjdogbutuzxwacjecysswxiqjqbbndlfmrvussnmtliupuyrusjqqshbkicxloezhbuztjlnuwjjshdmbodtgmuqwxpinvjuxdvqnifjgovyxalboquxcpnyofidaszxxuqkcxwjorhntuohkjemaunqzxtbpsznorzqoxbeqlsjfgrqrverprjqpcsgwtvkmxdauehlpzuvhnnzlrsclctcgnkdggpsfsuzxdmocjlmyyljsfmdjhhqurvczkwefsgcwusydemcezlyfzdqgkiacdcdqaivtqzpktpoxcsebfcifgznqhounsydtiamybdiusyuusyyacgfifubnivcdvfyfhmdipoejoyejwejzkqjqkkfvihyfoylvkqfbgjkxiqgguphfftxpdemnnktbkeyuwfxdoiayaghxxqeejbvnfiauuvvfbvbyazdojfplnwikmmowpjlwtnqolltmgwmgvpxgumshkctyphwethboxrcifxuluhurytathucrwwrlfosyxtnumrcrrzflibegugbbaeuxalihbagzvvtioybfzgshhzpbftegxafzmngpqoonlkxaizfhfaqnzhqeaxmzxrylhhbzvpmjzmjjlqsqqifrsywsvksscselzfkxuygwkrfvjyocivtatrvocnhghnrhsdgobomohsjqszucvofqhafjporwbkfvnllrbyfisqbmsvonltdttkekayhdimawampbmumempsemgrycxtxjximvppedqcfcrjonxuzmmeyuxywwruipeumvjqyzuednptcmpcybiyyfxueoqmfugsrpkqrhwwunqxzhbxjlxjsufwlwiqsqkkivcbcaxynpxoxalilirefwaqulipdtblqfmufmuubsiauvigfbmmaocubnjfgksyphswtmswgazdxhjflxrllufnjrupdmpvvhrovmneomhmvsrgpircezrnqlevavqvckmawzeknnyifrrwaiygjqwbdcxfynbcxpevoigdxgncyeyapzgyreaujxahmdlmsqhiaplywycwdbwuaestlunutpdgsoumgdujtfhrgjplmlfopzhauxwnmzvhqptwtqfovofdauoohvfyvmbplxeaxahnpclistwqhdtjzkyihdhcritdhydgamvpohahayxjesvdetomyvorfkuokzvknqzczblbaknecijjbxvbulszvpqholrcdtgdurgudtahbkqehlfczydwptefgvjkqpplivhlritsslxzxedyejutcyzjwivmamzijhwaprvhcuibaozfxwazubksmhfmvewfluhclelqyutzkvghrginivgucliareffbohottetnauzvcgmloztjfposzokfvpglyvgrbagbwfwzlkkcmfltwbmvpycmpjyngehhgnjfvheisqkgxyztznqrnsfcddsjkbtsqcxlldudtelsellgydxmycqbiknungoekmpvplblsmfwzrcywbmugeyqrnmevaihmacelfrfuwctpgtoifkqmigdxshussbhsgnflelfcnbsvugfcqvobdtaxcvsuwbmcosqsdxwsyoptwvxpsnsygsvippdmqrqeliyqgvkglazkvyzplrnrllcbafnryfxkoyawvlcgnesicrzoknhwyjxaqmtptrzhrbfmoiubonlqglgraqpyzmysashtlidcliqasmdgbpzicfbcvqcxecpeuyxhialtldvdqzkrqjbuqcwosanwceazcaikcufnxbrpadhsokmgnkuhkjeongnpiwblshyrirhkwqcmaqtnapvmzbamjqesmffgofxyzeivumixedkeshsrkvgulkozrvfgacezhpxdbhagknmewhwhccdnotmfotnqvsqehpkkwksgzfkyoifqmkdcfrivkvlhpdmwswjoibwkijiwrpmgbrigisbuomcfqqcimnzwovgzeqvyfkggbqomjpizemewcigqvfnmdvljmijtspcwgqkpiuomhuijdocywpmzmxiaiswajyypokgwfwkorsxujzsfqfgfeohmidpsbpjsaqqhmbvdtuxewsjozptfgbuqejiiasaaiqjwreanzztxtfluwfaciutofdwfvyifrrckyezzdtwzyhtuotxypsnuvlctmkydbcnbgnamiwngegaucztrtiopvqkhaikdnafvpfjxewdkdfeffzyyhmpdezkgkxkzzruoyencasmfxtkeslfazwfeyrkkowjpndfohsqkmfpmycsqnxsmwxsurdefbpxrscfcxxmjcdvcfovunnjlnbheenlickzvnezkbnvgqriyhfuwtdiifpolfbthmsezydlasgijzsjgyddthndmerxjutrglvhkbsmtbweaopjotohcbkqhdpraikguhqgikselokoeaxtvncxqpnxueounabjitpsdjypxjfdlcygpbdfssemwvhjvkufdjagsyxrjcxugvaxwfeqxldwgkhbwcjzljhghhztlwnusorqtyhtjkppwwsuydvmmcswlrpxqetiskaokhhvtymruhlvkghzlbvwumvkqoulbvzneijygvpccbxnjemuhjtcxompfjagebtijcirayucbrrkwdfdoyhnowdtfdzlfvtqzcizcccdttnrzuxpsgdjcgchjesqzohasrautezoxmiyjhqbntkqzpzktudukmucduyyyxoylwyufoythklizmvsiamsmhwrdurerfcdeczjrxeairlhgicoiojwxfndcehvllapnabgxhjfbunherxmfgkfoxiqdrlocmgrmjylqhrtdgcjxaxeihlygvojmczqqfieqgpjpicuqfdphcupjhopdeyriziyfqexyugneljvqokzqgqzogqtlokvpswukauiwaxblgydwicmrtnhzdamtkijfefpgzydcxepgetcoxrfsgmummgfzqqgwyvdzvgbtmrzsmdglumebaynpguoxnwvlrykngoiuhjmvmvgjjkmjkbyrvoqkklvemituwbrfmfayaghjtvvdwtuukkewycamkvgiwznifnjhtsrmomsmhmgtzlqznslzothmvuxahijcaarqojdyxjrwwjxleiksetgzndbwlkbonseddhbatvzrgwdkhpeljlmyonvczwqoqustevtzssqzrvlynqjwbxurmrvlplafiuyopupkohjfdwdsmooplkjxcelrsnzcjzqythkiovptstlejbwxmfwqlhjdwkhfkzgdgqnvmfqeackjdggrndjzmteldmqplytspipdnfhpjtzpchgpmqqblvmqjcgubboslfvbleqwzplbzstlkjmxgynpdvmgwaakgxltdbpcrdesvzdhisepstexpqdntfxzciufklkdoqvlpasxswmlqtihlouevufaczfonrrbhonyphwhgkuwfffrvbvqvbqacyoppitzwixnpvvvirtnwygrcckxfaxjaozswurucqitofrwyklvlsonwymdbkmbantyhmsldcfrjwpiiafvutisuxvvjiyjxshfebsjgxcpvrzguebqamjujersopbmhktonlztlcjivkoppqgpcrjlvafmriazstpfgobtsmcowqdlilckclxancmfmogehxmplnjeznuvdxjojlynzynmcztpnbtwyhomwzsvmmtrlefupgkoexdgzyvoarlyybmvaesoqnhcrpyhvixbichhbfvbwibwjotlumbnbjptypcvazwicdpdkmggvjdezwsukthmeyfenjzpivzmborlbzuyjzeivwcisluwjbdzmcouaojdeaqhakfljkthiypcjlztoesagiwiyhlfkcmmouxygqfqowtajutzynbexxpwhabrepdtlatrsakjwdjhxcgvrhbogsmntpezfjuqjnkenunlzwswyytrhwfqpsdkhkjotehfttjhpwuosnmsnfjxbqnskqcscmgyspdniouxmplgexatelqgbdymudgyrmwjebympvkdmxjqvjjzuahwdikzlqacewniylvpghtseckboudiwkgbsqdfidhnbwxziurqbmjiovjcronnzvrtmubwzilahjcpfthjfsrvocafrpvskmnyiovhzijgrlxxgeinxzlndnswcnoozenhskqrsaxmnwlubtjaswnxjfunvkcuopejbwatwafmwqizjrzdomdzuznplplcgplhmncknkwmaelmynrozunvtckfrwjznuibhlmxvklxrwlpjddlxsgtvtaopjoefwgojslgewevvpkguprukanftptkajofiuvrohytfeqctdjoscicexjzofjooavwwqqnzoifsyjnbsdwvlazkmbyrmofmlelcuybkiicgsrkmvijikjtwmtnykvlvbyxxwbheljmfcysxgbgrmbpyufxgckcdibagehmqsaxuzpuhtaahbqgxxfezriebjejqnvghvfdwvxeqzexcwfatmgufqygbeprtmxaidggafksfrrjpxjllrfrhgxlkpcebcglhoshuebbvsknrwydpfuzltkwimcmoixvxpetufurygepeeuukqtxkdturvgggebfviypnujncnfhubbeswbcbxysufyclchgkhyzdhpgwwpqxswpoarpxsjtxiwkmdsynqxszoyykpqihnxxnromjyfiidsujkswdroeipcsevaoialxtalcasmiwgefsybvprcxgesnbudjuoinqtrsmfailenecqbuhdtqklflgixcwfspzlhnrkxeqkivckplpkbzwgneokinpaeqonffxcjqoulqgacvkfximkocuzplbvcpjhwimgyacjrilvdyaagokxrgwiszeuppdlxptwsxhjftglrgnzvyyogwwywaunraappunhruszpykghxiexgsefoebrzoizozqkmaejufyvpfcopgmxascqwdjxtswktpwgpapjfpewuinlqbjqtlhrrqpmknygcvmrxddfsjbpsociplbkzicsatengdtlahexkhcetgvlwyvojwykgccjxjwgmrroyxlkfqqyymlukgivdjglliultqrhjkvhhjtozkoxyztiicfnllyywtlplcxvmuewdykckzbiavsizxvmlumjnyaaazvpualxaxcmwfuxaofzndnyxajmykmyjkpfmcfoahawmwvpmdqzgeafejtcthcfrumfwrtwyvvnrsedxuffyfkeofgknlrghdmdvhcvdzkwrocrjhwjmjocowmbjfkqjwwgfydixohqejjpqgzeppgdlvhxarnlpjtujzfipobtxkjpqivhzdlkyujbnxoeikasjfaytdrsochgmeolizygvhjieampkmhvujtpnmidrrjdwxpeynmvuydbyrqkgzfakyrzmbcdtohrnyvmljhhhnkhgarmbwomwilljqocextrvqficnslcctkdkxejnqhvesfuhjygfrcxxmzmelohgamsxqbnjjipbpjkbjrgavdxhfjmsztyafqzxuoifzxgoitprkxshdroidacevcgcsicowktvkcmsvbkhbeoeveoahqfesnhmvldsxwphabaxfmegsukpzaqiqxmkktyigbaeaplatnyybeetbqjcqbkgywsksqsyuueumswfhwdjbheczpgpqqxqmpbghvhdqlzcdwjlsmwvvazuqfjivgbkxcsgzzkrljtqhebcqxxlaxhsesaaybmxfeeheqyrbuhlylnpkkckjmcoefqdgccogivmytdcnnnoyadimhtytxoycedlihboqwdqrgshthvthacwjxuduidzoikwpnmflpwcwqlryinhkpdumzzihehvmttbggjrvfwtxjnvsadepiydizlrdvppoitvocokjkfgwscoshsjptmzuaryvgplokgdmxpvjuefpivjpqtgjhgdhxdefvqtfyysvpphmtmbbiksyfzjnhowesdlntestfmrucygvkjzuwrubqdozunfmqqblvvecivwktfhgoicmaxosceswrxkjqlulhznrwldsskyjvcvvbjneohchhntxankjozalkdddqdolfjihtxnjfrsogllhzvspwtagyflqizdqllzejmpqfhemvrvwonlkimsjrgzchdssqrybfnrkxxwsorochzopnhyhnajudbnvunxzbolyoisebijijxazeygtypqdsfbmsyltowtcgnhkxsshpugwvmptdhzvmahhauaoqwtzlajjsdsjyyftmxorepmtpvaprcgjaziobrxvxpexpmqdjgupwiknfkfwplfrmqfnjcigtmdkavnjcjbytlnayswpfegrumedqommdpwdlkpnvqnrdarbvqsauzuqnytdpfrsxovkakxvcmm";
657.502825
100,028
0.977247
[ "vector" ]
391ddbf576d49a2bc15ddb98c2a4a7f616d2cf9b
4,244
cpp
C++
src/ModelSelection/testPerformance.cpp
andreas-hjortgaard/master_thesis
bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb
[ "MIT" ]
null
null
null
src/ModelSelection/testPerformance.cpp
andreas-hjortgaard/master_thesis
bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb
[ "MIT" ]
null
null
null
src/ModelSelection/testPerformance.cpp
andreas-hjortgaard/master_thesis
bb03ca9fc030c5142a7dde2ec80a85abc06e2cfb
[ "MIT" ]
1
2018-10-20T00:43:36.000Z
2018-10-20T00:43:36.000Z
/* Conditional Random Fields for Object Localization * Master thesis source code * * Authors: * Andreas Christian Eilschou (jwb226@alumni.ku.dk) * Andreas Hjortgaard Danielsen (gxn961@alumni.ku.dk) * * Department of Computer Science * University of Copenhagen * Denmark * * Date: 27-08-2012 */ // main program for running model selection on a given dataset with a given learning method #include <cstdlib> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <algorithm> #include "DataManager.h" #include "ConditionalRandomField.h" #include "Types.h" #include "Measures/LossMeasures.h" using namespace std; void usage() { cout << "testPerformance [rootpath] [object] [stepSize] [lambda] [method] [weightPath]" << endl; } // chooses the objective, gradient and learning algorithm based on the input int main(int argc, char **argv) { // ensure correct number of arguments if (argc < 6) { usage(); return -1; } // parse input string rootPath = string(argv[1]); string object = string(argv[2]); int stepSize = atoi(argv[3]); double lambda = atof(argv[4]); string method = string(argv[5]); string weightPath = string(argv[6]); // make lower case transform(object.begin(), object.end(), object.begin(), ::tolower); // create test setup DataManager datamanTest; try { if (object.compare("tucow") == 0) { // if cow, use TUDarmstadt set cout << "Using TUDarmstadt cow set" << endl; datamanTest.loadImages(rootPath+"/cows-test/EUCSURF-3000/", rootPath+"/subsets/cows_test_width_height.txt"); datamanTest.loadBboxes(rootPath+"/cows-test/Annotations/TUcow_test.ess"); datamanTest.loadWeights(weightPath); } else { // else use PASCAL VOC dataset with different objects cout << "Using PASCAL " << object << endl; string boxesTest = rootPath+"/pascal/Annotations/ess/" + object + "_test.ess"; datamanTest.loadImages(rootPath+"/pascal/USURF3K/", rootPath+"/subsets/test_width_height.txt"); datamanTest.loadBboxes(boxesTest); datamanTest.loadWeights(weightPath); } } catch (int e) { if (e == FILE_NOT_FOUND) { cerr << "There was a problem opening a file!" << endl; return -1; } } // setup test result files ostringstream os; os << rootPath << "/results/test/" << method << "_" << object << "_" << stepSize << "_" << lambda << "_testresults.txt"; string testFile = os.str(); os.clear(); os.str(""); os << rootPath << "/results/test/" << method << "_" << object << "_" << stepSize << "_" << lambda << "_recallOverlapTest"; string lossTest = os.str(); os.clear(); os.str(""); os << rootPath << "/results/test/" << method << "_" << object << "_" << stepSize << "_" << lambda << "_recallOverlapValues.txt"; string recallOverlapFile = os.str(); cout << "testFile: " << testFile << endl; cout << "lossTest: " << lossTest << endl; // open output file ofstream infostream(testFile.c_str()); infostream << "Method : " << method << endl; infostream << "Object : " << object << endl; infostream << "Lambda : " << lambda << endl << endl; // compute recall-overlap for training set and validation set cout << "Computing recall-overlap..." << endl; SearchIx indices; RecallOverlap recallOverlapTest; recallOverlapTest = computeRecallOverlap(datamanTest, indices, 1, false); infostream << "AUC test : " << recallOverlapTest.AUC << endl; // create figures printRecallOverlap(lossTest, recallOverlapTest); // store recall-overlap storeRecallOverlap(recallOverlapFile, recallOverlapTest); // test quantized prediction step size and unscaled ground truth recallOverlapTest = computeRecallOverlap(datamanTest, indices, stepSize, false); infostream << "AUC test (step/unquan) : " << recallOverlapTest.AUC << endl; // test quantized prediction step size and scaled ground truth recallOverlapTest = computeRecallOverlap(datamanTest, indices, stepSize, true); infostream << "AUC test (step/quan) : " << recallOverlapTest.AUC << endl; infostream.close(); }
31.437037
130
0.648445
[ "object", "model", "transform" ]
3925fb3486dbc6bb1f8b6fdbff42f689f30d0c32
5,771
cpp
C++
source/engine/main.cpp
Coeurou/kairos_engine
b02eb302d7470d5f29b6ae342b2236dddaae91ea
[ "CC0-1.0" ]
null
null
null
source/engine/main.cpp
Coeurou/kairos_engine
b02eb302d7470d5f29b6ae342b2236dddaae91ea
[ "CC0-1.0" ]
null
null
null
source/engine/main.cpp
Coeurou/kairos_engine
b02eb302d7470d5f29b6ae342b2236dddaae91ea
[ "CC0-1.0" ]
null
null
null
#if defined(WIN32) /* && defined(NDEBUG)*/ #include <windows.h> extern int main(int argc, char* argv[]); //////////////////////////////////////////////////////////// int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, INT) { return main(__argc, __argv); } #endif // WIN32 #include <SDL.h> #undef main #include <editor.h> #include <game.h> #include <core/animation.h> #include <core/contract.h> #include <core/event.h> #include <core/security.h> #include <core/time.h> #include <event/sdl_event.h> #include <graphics/opengl/opengl_renderer.h> #include <graphics/opengl/SDL/sdl_opengl_context.h> #include <graphics/service/video_service.h> #include <graphics/texture.h> #include <graphics/brush.h> #include <graphics/pen.h> #include <graphics/painter.h> #include <imgui_sdl_backend.h> #include <imgui_opengl_renderer.h> #include <input/service/input_service.h> #include <window/sdl_window.h> using namespace kairos; int main(int /*argc*/, char* argv[]) { if (!is_unique_instance(argv[0])) { log_error(LoggerName::SYSTEM, "Another instance is already running"); return EXIT_FAILURE; } video_service video; video.enable(); input_service input; input.enable(input_device::controller); // create opengl context opengl_context gl_context{sdl_opengl_context{4, 1}}; { set_attribute(gl_context, gl_attribute::double_buffering, 1); set_attribute(gl_context, gl_attribute::multisample_buffers, 1); set_attribute(gl_context, gl_attribute::aa_samples, 4); opengl_context::opengl_profile profile = opengl_context::opengl_profile::core; set_attribute(gl_context, gl_attribute::context_profile, static_cast<int>(profile)); } // create window window_params window_params{ "Kairos", {1600.f, 900.f}, pointf{window_params::our_undefined_pos, window_params::our_undefined_pos}, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN}; window w{sdl_window{window_params}}; { ensures(setup(gl_context, id(w)), "Couldn't setup opengl context"); // need to comment this function setup is okay since in opengl it // has a meaning but adding an explanation is necessary show(w); } // imgui editor imgui = editor(imgui_sdl_backend{}, imgui_opengl_renderer(gl_context)); imgui.setup(w); // rendering parameters auto agent_texture = load("../../assets/Alucard.png"); ensures(agent_texture.has_value()); vec2i tex_size = size(*agent_texture); rect<int> texture_rect = {{10, 15}, {33, 62}}; sprite agent{*agent_texture, rectf{{0.f, 450.f}, {64.f, 546.f}}, texture_rect}; flip(agent, axis::y, true); brush b; b.my_fill_color = color(1.f); pen p; p.my_line_width = 1.f; painter painter{opengl_renderer{p, b, size(w)}}; // logic parameters auto time = clock::get_time(); bool should_quit = false; // physics parameters constexpr float speed = 4.f; // animation parameters animation<rect<int>> idle_animation = animation<rect<int>>({{{62, 14}, {86, 62}}, {{97, 14}, {121, 62}}, {{131, 14}, {155, 62}}, {{166, 14}, {190, 62}}, {{199, 14}, {223, 62}}, {{233, 14}, {257, 62}}}, 1.f, 1.f, true); idle_animation.start(); system_event_queue event_queue{sdl_event_tag{}}; array<system_event> events; // this should be a function for input, like intensity(keyboard_event) const auto to_float = [](bool condition) { return (condition) ? 1.f : 0.f; }; while (!should_quit) { // frame variables pointf agent_movement = {0.f, 0.f}; // peek frame events peek_events(event_queue, events); for (const auto& e : events) { switch (type(e)) { case event_type::window: { should_quit |= (cast<window_event>(e).my_type == window_event_type::close); break; } case event_type::key_press: { const auto& key_event = cast<keyboard_event>(e); if (key_event.my_key == key::D) { agent_movement.x = 1.f * speed; } else if (key_event.my_key == key::A) { agent_movement.x = -1.f * speed; } break; } case event_type::key_release: { break; } } should_quit |= (type(e) == event_type::quit); imgui.process_event(e); } // update logic const auto current_time = clock::get_time(); float deltatime = static_cast<float>(current_time - time) * 0.001f; time = current_time; const auto anim_sample = idle_animation.update(deltatime); if (anim_sample) { agent.my_texture_rect = *anim_sample; } // render clear(painter, color(1.f, 0.57f, 0.2f, 1.f)); translate(agent.my_bounds, agent_movement); draw(painter, agent); ensures(bool(imgui.update()), "imgui update failure"); ensures(bool(imgui.render()), "imgui render failure"); swap_buffers(gl_context); } // cleanup destroy(gl_context); destroy(w); video.cleanup(); return EXIT_SUCCESS; }
33.748538
130
0.557442
[ "render" ]
393c784962b51a47c56ec527cf41e0e09ff101bf
1,890
cpp
C++
Sources/HellSolver/Models/Object.cpp
utilForever/HellSolver
812b84153acd67226f7bf795109886273eba7fb5
[ "MIT" ]
14
2020-07-29T21:56:05.000Z
2021-12-18T12:48:11.000Z
Sources/HellSolver/Models/Object.cpp
utilForever/HellSolver
812b84153acd67226f7bf795109886273eba7fb5
[ "MIT" ]
14
2020-08-17T14:41:57.000Z
2020-12-13T06:39:45.000Z
Sources/HellSolver/Models/Object.cpp
utilForever/HellSolver
812b84153acd67226f7bf795109886273eba7fb5
[ "MIT" ]
1
2020-08-08T05:10:52.000Z
2020-08-08T05:10:52.000Z
// Copyright (c) 2020 HellSolver Team // Chris Ohk, Juhan Cha, Woosung Joung, Yongwook Choi // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #include <HellSolver/Models/Object.hpp> #include <utility> namespace HellSolver { Object::Object(Tile tile) : m_tile(std::move(tile)) { // Do nothing } void Object::Add(ObjectType type) { if (type == ObjectType::ROCK || type == ObjectType::PLAYER || type == ObjectType::UNDEAD) { if (m_tile.first == ObjectType::EMPTY) { m_tile.first = type; } } } void Object::Remove(ObjectType type) { if ((type == ObjectType::ROCK && m_tile.first == ObjectType::ROCK) || (type == ObjectType::UNDEAD && m_tile.first == ObjectType::UNDEAD) || (type == ObjectType::LOCK && m_tile.first == ObjectType::LOCK)) { m_tile.first = ObjectType::EMPTY; } else if (type == ObjectType::KEY && m_tile.second == ObjectType::KEY) { m_tile.second = ObjectType::EMPTY; } } void Object::Init(ObjectType type) { if (type == ObjectType::KEY || IsLurkerType(type) || type == ObjectType::SPIKE || type == ObjectType::ENDPOINT) { m_tile.second = type; } else { m_tile.second = ObjectType::EMPTY; } } bool Object::HasType(ObjectType type) const { if (type == ObjectType::EMPTY) { return m_tile.first == ObjectType::EMPTY; } if (type == ObjectType::LURKER_TYPE) { return IsLurkerType(m_tile.second); } if (type == ObjectType::ENDPOINT) { return m_tile.second == ObjectType::ENDPOINT; } if (m_tile.first == type || m_tile.second == type) { return true; } return false; } } // namespace HellSolver
23.333333
77
0.608995
[ "object" ]
393f44017838c8ad83827b2e4af6592ca5b744a1
3,215
cpp
C++
pong/object.cpp
keithoma/Pong-Z
083a9112e3c0bd9d2592b9c1f0186e9cebf22fdc
[ "MIT" ]
null
null
null
pong/object.cpp
keithoma/Pong-Z
083a9112e3c0bd9d2592b9c1f0186e9cebf22fdc
[ "MIT" ]
null
null
null
pong/object.cpp
keithoma/Pong-Z
083a9112e3c0bd9d2592b9c1f0186e9cebf22fdc
[ "MIT" ]
null
null
null
// This file is part of the "pong" project, http://github.com/keithoma/pong> // (c) 2019-2019 Christian Parpart <christian@parpart.family> // (c) 2019-2019 Kei Thoma <thomakmj@gmail.com> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include "object.hpp" #include <sgfx/canvas.hpp> #include <sgfx/primitives.hpp> #include <algorithm> #include <chrono> #include <climits> #include <iostream> using namespace std; using namespace std::chrono; using namespace sgfx; namespace pong { void object::set_position(point const& position) { position_ = position; } void object::accelerate(vec<int> const& acceleration) { acceleration_ = acceleration; } void object::set_velocity(vec<int> const& velocity) { // (x > 0) - (x < 0) returns the sign of x velocity_ = {((velocity.x > 0) - (velocity.x < 0)) * min(abs(velocity.x), maxVelocities_.x), ((velocity.y > 0) - (velocity.y < 0)) * min(abs(velocity.y), maxVelocities_.y)}; } void object::reflect_x() { set_velocity({-velocity_.x, velocity_.y}); } void object::reflect_y() { set_velocity({velocity_.x, -velocity_.y}); } object::status object::update(duration<double> delta) { auto clamp = [](point const& p, rectangle const& bb) -> point { auto const x = max(min(p.x, bb.right()), bb.left()); auto const y = max(min(p.y, bb.bottom()), bb.top()); return {x, y}; }; set_velocity(velocity_ + acceleration_); auto const distance = velocity_ * static_cast<int>(100.0 * delta.count()); position_ = clamp(position_ + distance, bounds_); acceleration_ = {0, 0}; if (decelerating_) velocity_ = velocity_ * 0.9; // edge cases; sets 'status_' to 'stuck_top_left', 'stuck_bottom_left', 'stuck_top_right' or // 'stuck_bottom_right' if (position_.x == bounds_.top_left.x && position_.y == bounds_.top_left.y) { status_ = status::stuck_top_left; } else if (position_.x == bounds_.top_left.x && position_.y == bounds_.top_left.y + bounds_.size.height) { status_ = status::stuck_bottom_left; } else if (position_.x == bounds_.top_left.x + bounds_.size.width && position_.y == bounds_.top_left.y) { status_ = status::stuck_top_right; } else if (position_.x == bounds_.top_left.x + bounds_.size.width && position_.y == bounds_.top_left.y + bounds_.size.height) { status_ = status::stuck_bottom_right; } // side cases; sets 'status_' to 'stuck_left', 'stuck_right', 'stuck_top' or 'stuck_bottom' else if (position_.x == bounds_.top_left.x) { status_ = status::stuck_left; } else if (position_.x == bounds_.top_left.x + bounds_.size.width) { status_ = status::stuck_right; } else if (position_.y == bounds_.top_left.y) { status_ = status::stuck_top; } else if (position_.y == bounds_.top_left.y + bounds_.size.height) { status_ = status::stuck_bottom; } // in all other cases, which therefore means the ball is not stuck, set 'status_' to 'free' else { status_ = status::free; } return status_; } void draw(object const& object, canvas const& image, widget& target) { sgfx::draw(target, image, object.position()); } } // namespace pong
28.705357
105
0.689891
[ "object" ]
39612353a81f6609c177398cb63c16c0a0a1007a
16,135
hpp
C++
include/OggVorbisEncoder/Setup/Residue.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/OggVorbisEncoder/Setup/Residue.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/OggVorbisEncoder/Setup/Residue.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: OggVorbisEncoder.Setup.ResidueType #include "OggVorbisEncoder/Setup/ResidueType.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Type namespace: OggVorbisEncoder.Setup namespace OggVorbisEncoder::Setup { // Forward declaring type: Residue class Residue; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::OggVorbisEncoder::Setup::Residue); DEFINE_IL2CPP_ARG_TYPE(::OggVorbisEncoder::Setup::Residue*, "OggVorbisEncoder.Setup", "Residue"); // Type namespace: OggVorbisEncoder.Setup namespace OggVorbisEncoder::Setup { // Size: 0x50 #pragma pack(push, 1) // Autogenerated type: OggVorbisEncoder.Setup.Residue // [TokenAttribute] Offset: FFFFFFFF class Residue : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private readonly System.Int32 <Begin>k__BackingField // Size: 0x4 // Offset: 0x10 int Begin; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 <End>k__BackingField // Size: 0x4 // Offset: 0x14 int End; // Field size check static_assert(sizeof(int) == 0x4); // private readonly System.Int32 <Partitions>k__BackingField // Size: 0x4 // Offset: 0x18 int Partitions; // Field size check static_assert(sizeof(int) == 0x4); // private readonly System.Int32 <PartitionValues>k__BackingField // Size: 0x4 // Offset: 0x1C int PartitionValues; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 <GroupBook>k__BackingField // Size: 0x4 // Offset: 0x20 int GroupBook; // Field size check static_assert(sizeof(int) == 0x4); // Padding between fields: GroupBook and: SecondStages char __padding4[0x4] = {}; // private readonly System.Int32[] <SecondStages>k__BackingField // Size: 0x8 // Offset: 0x28 ::ArrayW<int> SecondStages; // Field size check static_assert(sizeof(::ArrayW<int>) == 0x8); // private readonly System.Int32[] <BookList>k__BackingField // Size: 0x8 // Offset: 0x30 ::ArrayW<int> BookList; // Field size check static_assert(sizeof(::ArrayW<int>) == 0x8); // private readonly System.Int32[] <ClassMetric1>k__BackingField // Size: 0x8 // Offset: 0x38 ::ArrayW<int> ClassMetric1; // Field size check static_assert(sizeof(::ArrayW<int>) == 0x8); // private readonly System.Int32[] <ClassMetric2>k__BackingField // Size: 0x8 // Offset: 0x40 ::ArrayW<int> ClassMetric2; // Field size check static_assert(sizeof(::ArrayW<int>) == 0x8); // private readonly OggVorbisEncoder.Setup.ResidueType <ResidueType>k__BackingField // Size: 0x4 // Offset: 0x48 ::OggVorbisEncoder::Setup::ResidueType ResidueType; // Field size check static_assert(sizeof(::OggVorbisEncoder::Setup::ResidueType) == 0x4); // private readonly System.Int32 <Grouping>k__BackingField // Size: 0x4 // Offset: 0x4C int Grouping; // Field size check static_assert(sizeof(int) == 0x4); public: // Get instance field reference: private readonly System.Int32 <Begin>k__BackingField int& dyn_$Begin$k__BackingField(); // Get instance field reference: private System.Int32 <End>k__BackingField int& dyn_$End$k__BackingField(); // Get instance field reference: private readonly System.Int32 <Partitions>k__BackingField int& dyn_$Partitions$k__BackingField(); // Get instance field reference: private readonly System.Int32 <PartitionValues>k__BackingField int& dyn_$PartitionValues$k__BackingField(); // Get instance field reference: private System.Int32 <GroupBook>k__BackingField int& dyn_$GroupBook$k__BackingField(); // Get instance field reference: private readonly System.Int32[] <SecondStages>k__BackingField ::ArrayW<int>& dyn_$SecondStages$k__BackingField(); // Get instance field reference: private readonly System.Int32[] <BookList>k__BackingField ::ArrayW<int>& dyn_$BookList$k__BackingField(); // Get instance field reference: private readonly System.Int32[] <ClassMetric1>k__BackingField ::ArrayW<int>& dyn_$ClassMetric1$k__BackingField(); // Get instance field reference: private readonly System.Int32[] <ClassMetric2>k__BackingField ::ArrayW<int>& dyn_$ClassMetric2$k__BackingField(); // Get instance field reference: private readonly OggVorbisEncoder.Setup.ResidueType <ResidueType>k__BackingField ::OggVorbisEncoder::Setup::ResidueType& dyn_$ResidueType$k__BackingField(); // Get instance field reference: private readonly System.Int32 <Grouping>k__BackingField int& dyn_$Grouping$k__BackingField(); // public System.Int32 get_Begin() // Offset: 0x7A59A0 int get_Begin(); // public System.Int32 get_End() // Offset: 0x7A59A8 int get_End(); // public System.Void set_End(System.Int32 value) // Offset: 0x7A59B0 void set_End(int value); // public System.Int32 get_Partitions() // Offset: 0x7A59B8 int get_Partitions(); // public System.Int32 get_PartitionValues() // Offset: 0x7A59C0 int get_PartitionValues(); // public System.Int32 get_GroupBook() // Offset: 0x7A59C8 int get_GroupBook(); // public System.Void set_GroupBook(System.Int32 value) // Offset: 0x7A59D0 void set_GroupBook(int value); // public System.Int32[] get_SecondStages() // Offset: 0x7A59D8 ::ArrayW<int> get_SecondStages(); // public System.Int32[] get_BookList() // Offset: 0x7A59E0 ::ArrayW<int> get_BookList(); // public System.Int32[] get_ClassMetric1() // Offset: 0x7A59E8 ::ArrayW<int> get_ClassMetric1(); // public System.Int32[] get_ClassMetric2() // Offset: 0x7A59F0 ::ArrayW<int> get_ClassMetric2(); // public OggVorbisEncoder.Setup.ResidueType get_ResidueType() // Offset: 0x7A59F8 ::OggVorbisEncoder::Setup::ResidueType get_ResidueType(); // public System.Int32 get_Grouping() // Offset: 0x7A5A00 int get_Grouping(); // public System.Void .ctor(System.Int32 begin, System.Int32 end, System.Int32 grouping, System.Int32 partitions, System.Int32 partitionValues, System.Int32 groupBook, System.Int32[] secondStages, System.Int32[] bookList, System.Int32[] classMetric1, System.Int32[] classMetric2, OggVorbisEncoder.Setup.ResidueType residueType) // Offset: 0x7A5888 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static Residue* New_ctor(int begin, int end, int grouping, int partitions, int partitionValues, int groupBook, ::ArrayW<int> secondStages, ::ArrayW<int> bookList, ::ArrayW<int> classMetric1, ::ArrayW<int> classMetric2, ::OggVorbisEncoder::Setup::ResidueType residueType) { static auto ___internal__logger = ::Logger::get().WithContext("::OggVorbisEncoder::Setup::Residue::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<Residue*, creationType>(begin, end, grouping, partitions, partitionValues, groupBook, secondStages, bookList, classMetric1, classMetric2, residueType))); } // public OggVorbisEncoder.Setup.Residue Clone(OggVorbisEncoder.Setup.ResidueType residueTypeOverride, System.Int32 groupingOverride) // Offset: 0x7A5A08 ::OggVorbisEncoder::Setup::Residue* Clone(::OggVorbisEncoder::Setup::ResidueType residueTypeOverride, int groupingOverride); }; // OggVorbisEncoder.Setup.Residue #pragma pack(pop) static check_size<sizeof(Residue), 76 + sizeof(int)> __OggVorbisEncoder_Setup_ResidueSizeCheck; static_assert(sizeof(Residue) == 0x50); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::get_Begin // Il2CppName: get_Begin template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (OggVorbisEncoder::Setup::Residue::*)()>(&OggVorbisEncoder::Setup::Residue::get_Begin)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "get_Begin", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::get_End // Il2CppName: get_End template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (OggVorbisEncoder::Setup::Residue::*)()>(&OggVorbisEncoder::Setup::Residue::get_End)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "get_End", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::set_End // Il2CppName: set_End template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (OggVorbisEncoder::Setup::Residue::*)(int)>(&OggVorbisEncoder::Setup::Residue::set_End)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "set_End", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::get_Partitions // Il2CppName: get_Partitions template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (OggVorbisEncoder::Setup::Residue::*)()>(&OggVorbisEncoder::Setup::Residue::get_Partitions)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "get_Partitions", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::get_PartitionValues // Il2CppName: get_PartitionValues template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (OggVorbisEncoder::Setup::Residue::*)()>(&OggVorbisEncoder::Setup::Residue::get_PartitionValues)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "get_PartitionValues", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::get_GroupBook // Il2CppName: get_GroupBook template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (OggVorbisEncoder::Setup::Residue::*)()>(&OggVorbisEncoder::Setup::Residue::get_GroupBook)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "get_GroupBook", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::set_GroupBook // Il2CppName: set_GroupBook template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (OggVorbisEncoder::Setup::Residue::*)(int)>(&OggVorbisEncoder::Setup::Residue::set_GroupBook)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "set_GroupBook", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::get_SecondStages // Il2CppName: get_SecondStages template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<int> (OggVorbisEncoder::Setup::Residue::*)()>(&OggVorbisEncoder::Setup::Residue::get_SecondStages)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "get_SecondStages", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::get_BookList // Il2CppName: get_BookList template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<int> (OggVorbisEncoder::Setup::Residue::*)()>(&OggVorbisEncoder::Setup::Residue::get_BookList)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "get_BookList", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::get_ClassMetric1 // Il2CppName: get_ClassMetric1 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<int> (OggVorbisEncoder::Setup::Residue::*)()>(&OggVorbisEncoder::Setup::Residue::get_ClassMetric1)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "get_ClassMetric1", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::get_ClassMetric2 // Il2CppName: get_ClassMetric2 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::ArrayW<int> (OggVorbisEncoder::Setup::Residue::*)()>(&OggVorbisEncoder::Setup::Residue::get_ClassMetric2)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "get_ClassMetric2", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::get_ResidueType // Il2CppName: get_ResidueType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::OggVorbisEncoder::Setup::ResidueType (OggVorbisEncoder::Setup::Residue::*)()>(&OggVorbisEncoder::Setup::Residue::get_ResidueType)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "get_ResidueType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::get_Grouping // Il2CppName: get_Grouping template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (OggVorbisEncoder::Setup::Residue::*)()>(&OggVorbisEncoder::Setup::Residue::get_Grouping)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "get_Grouping", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: OggVorbisEncoder::Setup::Residue::Clone // Il2CppName: Clone template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::OggVorbisEncoder::Setup::Residue* (OggVorbisEncoder::Setup::Residue::*)(::OggVorbisEncoder::Setup::ResidueType, int)>(&OggVorbisEncoder::Setup::Residue::Clone)> { static const MethodInfo* get() { static auto* residueTypeOverride = &::il2cpp_utils::GetClassFromName("OggVorbisEncoder.Setup", "ResidueType")->byval_arg; static auto* groupingOverride = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(OggVorbisEncoder::Setup::Residue*), "Clone", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{residueTypeOverride, groupingOverride}); } };
52.557003
331
0.734428
[ "vector" ]
3966ee080df6ff82c3830db248acd47333350ab8
13,422
cpp
C++
driver/src/camera.cpp
mmmspatz/wumbo_mr
7dfecd4cb824ad2268f6f9208e3fe6c9510fb097
[ "BSL-1.0" ]
1
2021-02-12T06:54:53.000Z
2021-02-12T06:54:53.000Z
driver/src/camera.cpp
mmmspatz/wumbo_mr
7dfecd4cb824ad2268f6f9208e3fe6c9510fb097
[ "BSL-1.0" ]
null
null
null
driver/src/camera.cpp
mmmspatz/wumbo_mr
7dfecd4cb824ad2268f6f9208e3fe6c9510fb097
[ "BSL-1.0" ]
null
null
null
// Copyright Mark H. Spatz 2021-present // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // https://www.boost.org/LICENSE_1_0.txt) #include "camera.hpp" #include <spdlog/spdlog.h> #include <algorithm> #include <iterator> #include <stdexcept> #include <libusbcpp/error.hpp> #include <libusbcpp/transfer.hpp> namespace wmr { Camera::Camera(const HeadsetSpec& spec, libusbcpp::Device::Pointer dev) : spec_(spec), dev_handle_(dev->Open()), frame_pool_(kFramePoolSize, spec_.camera_width, spec.camera_height, spec_.n_cameras) { // Get the config descriptor libusbcpp::Device::ConfigDescriptor config; try { config = dev->GetActiveConfigDescriptor(); } catch (libusbcpp::Error<libusbcpp::c::LIBUSB_ERROR_NOT_FOUND>&) { dev_handle_->SetConfiguration(1); config = dev->GetActiveConfigDescriptor(); } // Find the interface descriptor for kInterfaceNumber const libusbcpp::c::libusb_interface_descriptor* iface_desc = nullptr; for (uint8_t i = 0; i < config->bNumInterfaces; ++i) { auto* d = config->interface[i].altsetting; // only consider altsetting[0] if (d->bInterfaceNumber == kInterfaceNumber) { iface_desc = d; break; } } if (!iface_desc) { throw std::runtime_error("Device doesn't have interface number kInterfaceNumber"); } // Search for a read/write pair of bulk endpoints read_ep_ = 0xF0; // 0xF0 is an invalid address write_ep_ = 0xF0; for (uint8_t j = 0; j < iface_desc->bNumEndpoints; ++j) { auto& ep_desc = iface_desc->endpoint[j]; if ((ep_desc.bmAttributes & 0x3) != libusbcpp::c::LIBUSB_TRANSFER_TYPE_BULK) continue; if (ep_desc.bEndpointAddress & libusbcpp::c::LIBUSB_ENDPOINT_IN && read_ep_ == 0xF0) { read_ep_ = ep_desc.bEndpointAddress; } else if (write_ep_ == 0xF0) { write_ep_ = ep_desc.bEndpointAddress; } else { throw std::runtime_error("Interface has multiple bulk endpoint pairs"); } } if (read_ep_ == 0xF0 || write_ep_ == 0xF0) { throw std::runtime_error("Bulk endpoint pair not found"); } spdlog::debug("Camera found endpoints on interface {}: r:{:x} w::{:x}", kInterfaceNumber, read_ep_, write_ep_); iface_claim_hnd_ = dev_handle_->ClaimInterface(kInterfaceNumber); // Gratuitous stop command SendStartStopCommand(false); // Allocate transfers for (std::size_t i = 0; i < kRxSlotCount; ++i) { auto& trans = rx_transfers_.emplace_back(dev_handle_->AllocTransfer()); auto& buff = rx_buffers_.emplace_back(dev_handle_->DevMemAlloc(spec_.camera_xfer_size)); trans->FillBulkTransfer(read_ep_, buff.get(), spec_.camera_xfer_size, TransferCallback, this, 0); } } void Camera::StartStream() { assert(!streaming_); spdlog::trace("Camera::StartStream"); // Reset state got_first_frame_ = false; // Start looped transfers for (auto& trans : rx_transfers_) { trans->AsStruct()->Submit(); ++outstanding_transfer_count_; } // Start consuming completed transfers streaming_ = true; stream_thread_ = std::thread([this]() { Stream(); }); // Start the headset camera SendStartStopCommand(true); } void Camera::StopStream() { spdlog::trace("Camera::StopStream"); SendStartStopCommand(false); CancelAllTransfers(); stream_thread_.join(); } void Camera::SetExpGain(uint16_t camera_type, uint16_t exposure, uint16_t gain) { auto& state = exp_gain_state_.at(camera_type); if (state.exposure == exposure && state.gain == gain && state.cache_use_count < 60) { ++state.cache_use_count; } else { spdlog::trace("Camera::SetExpGain: camera_type={} exposure={}, gain={}", camera_type, exposure, gain); SetExpGainCommand cmd{kMagic, 0x12, 0x80, camera_type, exposure, gain, camera_type}; int actual_length; dev_handle_->BulkTransfer(write_ep_, reinterpret_cast<uint8_t*>(&cmd), SetExpGainCommand::kSize, &actual_length, 100); if (actual_length != SetExpGainCommand::kSize) { throw std::runtime_error("BulkTransfer didn't consume all bytes"); } state.exposure = exposure; state.gain = gain; state.cache_use_count = 0; } } void Camera::RegisterFrameCallback(FrameCallback cb) { std::lock_guard l{frame_callbacks_m_}; frame_callbacks_.push_back(std::move(cb)); } void Camera::SendStartStopCommand(bool start) { StartStopCommand cmd{kMagic, 0x0c, (uint16_t)(start ? 0x81 : 0x82)}; int actual_length; dev_handle_->BulkTransfer(write_ep_, reinterpret_cast<uint8_t*>(&cmd), StartStopCommand::kSize, &actual_length, 100); if (actual_length != StartStopCommand::kSize) { throw std::runtime_error("BulkTransfer didn't consume all bytes"); } } void Camera::Stream() { spdlog::trace("Camera::ReadFrames: thread started"); while (outstanding_transfer_count_) { std::unique_lock l{completed_rx_transactions_m_}; completed_rx_transactions_cv_.wait(l, [this]() { return !completed_rx_transactions_.empty(); }); auto trans = completed_rx_transactions_.front(); completed_rx_transactions_.pop(); l.unlock(); if (trans->status == libusbcpp::c::LIBUSB_TRANSFER_COMPLETED && streaming_) { // Handle then resubmit this transfer HandleFrame(trans); trans->Submit(); } else { // Don't resubmit, we're done. if (outstanding_transfer_count_ == kRxSlotCount) { spdlog::trace("Camera::Stream: Reaping transfers..."); SendStartStopCommand(false); CancelAllTransfers(); streaming_ = false; } --outstanding_transfer_count_; switch (trans->status) { case libusbcpp::c::LIBUSB_TRANSFER_COMPLETED: spdlog::trace( "Camera::Stream: Reap transfer w/ status " "LIBUSB_TRANSFER_COMPLETED"); break; case libusbcpp::c::LIBUSB_TRANSFER_CANCELLED: spdlog::trace( "Camera::Stream: Reap transfer w/ status " "LIBUSB_TRANSFER_CANCELLED"); break; case libusbcpp::c::LIBUSB_TRANSFER_ERROR: spdlog::error("Camera::Stream: Reap transfer w/ status LIBUSB_TRANSFER_ERROR"); break; case libusbcpp::c::LIBUSB_TRANSFER_TIMED_OUT: spdlog::error( "Camera::Stream: Reap transfer w/ status " "LIBUSB_TRANSFER_TIMED_OUT"); break; case libusbcpp::c::LIBUSB_TRANSFER_STALL: spdlog::error("Camera::Stream: Reap transfer w/ status LIBUSB_TRANSFER_STALL"); break; case libusbcpp::c::LIBUSB_TRANSFER_NO_DEVICE: spdlog::error( "Camera::Stream: Reap transfer w/ status " "LIBUSB_TRANSFER_NO_DEVICE"); break; case libusbcpp::c::LIBUSB_TRANSFER_OVERFLOW: spdlog::error( "Camera::Stream: Reap transfer w/ status " "LIBUSB_TRANSFER_OVERFLOW"); break; } } } spdlog::trace("Camera::ReadFrames: thread exiting"); } void Camera::HandleFrame(const libusbcpp::TransferStruct* trans) { if (ValidateFrame(trans->buffer, trans->actual_length)) { auto processed_frame = CopyFrame(trans->buffer); // Run callbacks std::lock_guard l{frame_callbacks_m_}; auto it = frame_callbacks_.begin(); while (it != frame_callbacks_.end()) { FrameCallback& cb = *it; auto prev = it; ++it; if (!cb(processed_frame)) { frame_callbacks_.erase(prev); } } got_first_frame_ |= true; } else if (got_first_frame_) { throw std::runtime_error("Camera::HandleFrame: Encountered invalid frame mid-stream"); } } void Camera::TransferCallback(libusbcpp::c::libusb_transfer* trans) { auto cam = static_cast<Camera*>(trans->user_data); auto trans_struct = static_cast<libusbcpp::TransferStruct*>(trans); { std::lock_guard l{cam->completed_rx_transactions_m_}; cam->completed_rx_transactions_.push(trans_struct); } cam->completed_rx_transactions_cv_.notify_one(); } void Camera::CancelAllTransfers() { for (auto& trans : rx_transfers_) { try { trans->AsStruct()->Cancel(); } catch (libusbcpp::Error<libusbcpp::c::LIBUSB_ERROR_NOT_FOUND>&) { // Transfer is not in progress, already complete, or already cancelled. } } } bool Camera::ValidateFrame(const uint8_t* frame, std::size_t size) { // Check frame size if (size != spec_.camera_frame_size) { spdlog::warn("Camera::ValidateFrame: wrong frame size (expected={:x}, actual={:x})", spec_.camera_frame_size, size); return false; } // Check frame footer for magic auto footer = reinterpret_cast<const FrameFooter*>(frame + spec_.camera_frame_footer_offset); if (footer->magic != kMagic) { spdlog::warn("Camera::ValidateFrame: frame footer has bad magic (magic=0x{:08x})", footer->magic); return false; } // Check frame footer for timestamp if (footer->timestamp == 0) { spdlog::warn("Camera::ValidateFrame: frame footer has no timestamp"); return false; } auto first_segment_header = reinterpret_cast<const SegmentHeader*>(frame); // Check for dropped frames if (got_first_frame_ && first_segment_header->frame_number != prev_frame_number_ + 1) { spdlog::warn( "Camera::ValidateFrame: Dropped frame (prev_frame_number={}, " "current={})", prev_frame_number_, first_segment_header->frame_number); return false; } prev_frame_number_ = first_segment_header->frame_number; // The frame is divided into 24KiB (may vary by device) "segments". Each // segment starts with a 32 byte header. for (std::size_t segment_idx = 0; segment_idx < spec_.camera_segment_count; ++segment_idx) { auto segment_header = reinterpret_cast<const SegmentHeader*>(frame + segment_idx * spec_.camera_segment_size); // Cheack header for magic if (segment_header->magic != kMagic) { spdlog::warn( "Camera::ValidateFrame: segment header has bad magic " "(segment_idx ={}, magic=0x{:08x})", segment_idx, segment_header->magic); return false; } // All segments belong to the same frame if (segment_header->frame_number != first_segment_header->frame_number) { spdlog::warn( "Camera::ValidateFrame: segment has unexpected frame_number " "(expected={} actual={})", first_segment_header->frame_number, segment_header->frame_number); return false; } // Segments are sequential starting at 0 if (segment_header->segment_number != segment_idx) { spdlog::warn( "Camera::ValidateFrame: segment has unexpected segment_number " "(expected={} actual={})", segment_idx, segment_header->segment_number); return false; } } return true; } Camera::FrameHandle Camera::CopyFrame(const uint8_t* frame) { auto footer = reinterpret_cast<const FrameFooter*>(frame + spec_.camera_frame_footer_offset); auto processed_frame = frame_pool_.Allocate(); switch (footer->frame_type) { case FrameFooter::kFrameTypeRoom: processed_frame->type = CameraFrame::Type::kRoom; break; case FrameFooter::kFrameTypeController: processed_frame->type = CameraFrame::Type::kController; break; default: throw std::runtime_error("Camera::CopyFrame: Unknown frame_type"); } processed_frame->timestamp = Timestamp(footer->timestamp); std::vector<std::size_t> bytes_copied_per_image(spec_.n_cameras, 0); std::size_t frame_offset = kSegmentHeaderSize; std::size_t cam_idx = 0; // The first row of each image contains metadata for (; cam_idx < spec_.n_cameras; ++cam_idx) { // TODO what is the metatadata? frame_offset += spec_.camera_width; assert(frame_offset <= spec_.camera_segment_size); } cam_idx = 0; // The raw frame data has segment headers inserted into it, and the // individual camera images are stacked horizontally. Excise the headers and // un-shuffle the rows from individual images. while (true) { while (frame_offset % spec_.camera_segment_size) { auto block_size = std::min(spec_.camera_segment_size - frame_offset % spec_.camera_segment_size, spec_.camera_width - bytes_copied_per_image[cam_idx] % spec_.camera_width); if (frame_offset + block_size >= spec_.camera_frame_size) { throw std::runtime_error("Camera::CopyFrame: Ran out of bytes in raw frame"); } auto src_begin = frame + frame_offset; auto src_end = src_begin + block_size; auto dst_begin = processed_frame->GetImage(cam_idx) + bytes_copied_per_image[cam_idx]; std::copy(src_begin, src_end, dst_begin); frame_offset += block_size; bytes_copied_per_image[cam_idx] += block_size; // If we finished reading a row, move to the next camera if (block_size && bytes_copied_per_image[cam_idx] % spec_.camera_width == 0) { cam_idx = (cam_idx + 1) % spec_.n_cameras; // If the image for the next camera is already complete, we're done if (bytes_copied_per_image[cam_idx] == spec_.camera_width * spec_.camera_height) { return processed_frame; } } } // Seek past the segment header frame_offset += kSegmentHeaderSize; } } } // namespace wmr
33.555
100
0.673
[ "vector" ]
39693f5de44a9bc77020d7c17c33f4daff625681
9,074
cc
C++
src/lb_cookie_store.cc
snibug/gyp_example
6bbf1ef53c68df4e5a657e0037cf6c81d2140178
[ "Apache-2.0" ]
null
null
null
src/lb_cookie_store.cc
snibug/gyp_example
6bbf1ef53c68df4e5a657e0037cf6c81d2140178
[ "Apache-2.0" ]
null
null
null
src/lb_cookie_store.cc
snibug/gyp_example
6bbf1ef53c68df4e5a657e0037cf6c81d2140178
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2012 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "lb_cookie_store.h" #include "base/bind.h" #include "base/message_loop.h" #include "base/time.h" #include "googleurl/src/gurl.h" #include "lb_savegame_syncer.h" #include "net/cookies/canonical_cookie.h" #include "sql/statement.h" static const int kOriginalCookieSchemaVersion = 1; static const int kLatestCookieSchemaVersion = 1; static const base::TimeDelta kMaxCookieLifetime = base::TimeDelta::FromDays(365 * 2); base::Lock LBCookieStore::init_lock_; // static bool LBCookieStore::initialized_ = false; // static void LBCookieStore::Init() { base::AutoLock init_lock(init_lock_); if (initialized_) return; Reinitialize(); initialized_ = true; } // static void LBCookieStore::Reinitialize() { LBSavegameSyncer::WaitForLoad(); sql::Connection *conn = LBSavegameSyncer::connection(); // Check the table's schema version. int version = LBSavegameSyncer::GetSchemaVersion("CookieTable"); if (version == LBSavegameSyncer::kSchemaTableIsNew) { // This savegame predates the existence of the schema table. // Since the cookie table did not change between the initial release of // the app and the introduction of the schema table, assume that this // existing cookie table is schema version 1. This avoids a loss of // cookies on upgrade. LBSavegameSyncer::UpdateSchemaVersion("CookieTable", kOriginalCookieSchemaVersion); version = kOriginalCookieSchemaVersion; } else if (version == LBSavegameSyncer::kSchemaVersionLost) { // Since there has only been one schema so far, treat this the same as // kSchemaTableIsNew. When there are multiple schemas in the wild, // we may want to drop the table instead. LBSavegameSyncer::UpdateSchemaVersion("CookieTable", kOriginalCookieSchemaVersion); version = kOriginalCookieSchemaVersion; } if (version == LBSavegameSyncer::kNoSuchTable) { // The table does not exist, so create it in its latest form. sql::Statement create_table(conn->GetUniqueStatement( "CREATE TABLE CookieTable (" "url TEXT, " "name TEXT, " "value TEXT, " "domain TEXT, " "path TEXT, " "mac_key TEXT, " "mac_algorithm TEXT, " "creation INTEGER, " "expiration INTEGER, " "last_access INTEGER, " "secure INTEGER, " "http_only INTEGER, " "UNIQUE(name, domain, path) ON CONFLICT REPLACE)")); bool ok = create_table.Run(); DCHECK(ok); LBSavegameSyncer::ReportCreatedTable(); LBSavegameSyncer::UpdateSchemaVersion("CookieTable", kLatestCookieSchemaVersion); } // On schema change, update kLatestCookieSchemaVersion and write upgrade // logic for old tables. For example: // // else if (version == 1) { // sql::Statement update_table(conn->GetUniqueStatement( // "ALTER TABLE CookieTable ADD COLUMN xyz INTEGER default 10")); // bool ok = update_table.Run(); // DCHECK(ok); // LBSavegameSyncer::UpdateSchemaVersion("CookieTable", // kLatestCookieSchemaVersion); // } } LBCookieStore::LBCookieStore() { } LBCookieStore::~LBCookieStore() { } // static std::vector<net::CanonicalCookie *> LBCookieStore::GetAllCookies() { DCHECK(initialized_); base::Time maximum_expiry = base::Time::Now() + kMaxCookieLifetime; std::vector<net::CanonicalCookie*> actual_cookies; sql::Connection *conn = LBSavegameSyncer::connection(); sql::Statement get_all(conn->GetCachedStatement(SQL_FROM_HERE, "SELECT url, name, value, domain, path, mac_key, mac_algorithm, " "creation, expiration, last_access, secure, http_only " "FROM CookieTable")); while (get_all.Step()) { base::Time expiry = base::Time::FromInternalValue(get_all.ColumnInt64(8)); if (expiry > maximum_expiry) expiry = maximum_expiry; net::CanonicalCookie *cookie = net::CanonicalCookie::Create( GURL(get_all.ColumnString(0)), get_all.ColumnString(1), get_all.ColumnString(2), get_all.ColumnString(3), get_all.ColumnString(4), get_all.ColumnString(5), get_all.ColumnString(6), base::Time::FromInternalValue(get_all.ColumnInt64(7)), expiry, get_all.ColumnBool(10), get_all.ColumnBool(11)); cookie->SetLastAccessDate( base::Time::FromInternalValue(get_all.ColumnInt64(9))); actual_cookies.push_back(cookie); } return actual_cookies; } // static void LBCookieStore::DeleteAllCookies() { DCHECK(initialized_); sql::Connection *conn = LBSavegameSyncer::connection(); sql::Statement delete_all(conn->GetCachedStatement(SQL_FROM_HERE, "DELETE FROM CookieTable")); bool ok = delete_all.Run(); DCHECK(ok); } // static void LBCookieStore::QuickAddCookie(const net::CanonicalCookie &cc) { DCHECK(initialized_); // We expect that all cookies we are fed are meant to persist. DCHECK(cc.IsPersistent()); base::Time maximum_expiry = base::Time::Now() + kMaxCookieLifetime; base::Time expiry = cc.ExpiryDate(); if (expiry > maximum_expiry) expiry = maximum_expiry; sql::Connection *conn = LBSavegameSyncer::connection(); sql::Statement insert_cookie(conn->GetCachedStatement(SQL_FROM_HERE, "INSERT INTO CookieTable (" "url, name, value, domain, path, mac_key, mac_algorithm, " "creation, expiration, last_access, secure, http_only" ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")); insert_cookie.BindString(0, cc.Source()); insert_cookie.BindString(1, cc.Name()); insert_cookie.BindString(2, cc.Value()); insert_cookie.BindString(3, cc.Domain()); insert_cookie.BindString(4, cc.Path()); insert_cookie.BindString(5, cc.MACKey()); insert_cookie.BindString(6, cc.MACAlgorithm()); insert_cookie.BindInt64(7, cc.CreationDate().ToInternalValue()); insert_cookie.BindInt64(8, expiry.ToInternalValue()); insert_cookie.BindInt64(9, cc.LastAccessDate().ToInternalValue()); insert_cookie.BindBool(10, cc.IsSecure()); insert_cookie.BindBool(11, cc.IsHttpOnly()); bool ok = insert_cookie.Run(); DCHECK(ok); } // static void LBCookieStore::QuickDeleteCookie(const net::CanonicalCookie &cc) { DCHECK(initialized_); sql::Connection *conn = LBSavegameSyncer::connection(); sql::Statement delete_cookie(conn->GetCachedStatement(SQL_FROM_HERE, "DELETE FROM CookieTable WHERE name = ? AND domain = ? AND path = ?")); delete_cookie.BindString(0, cc.Name()); delete_cookie.BindString(1, cc.Domain()); delete_cookie.BindString(2, cc.Path()); bool ok = delete_cookie.Run(); DCHECK(ok); } void LBCookieStore::Load(const LoadedCallback& loaded_callback) { Init(); MessageLoop::current()->PostNonNestableTask(FROM_HERE, base::Bind(loaded_callback, GetAllCookies())); } void LBCookieStore::LoadCookiesForKey(const std::string&, const LoadedCallback& loaded_callback) { DCHECK(initialized_); // This is always called after Load(), so there's nothing to do. // See comments in the header for more information. std::vector<net::CanonicalCookie*> empty_cookie_list; MessageLoop::current()->PostNonNestableTask(FROM_HERE, base::Bind(loaded_callback, empty_cookie_list)); } void LBCookieStore::AddCookie(const net::CanonicalCookie &cc) { QuickAddCookie(cc); } void LBCookieStore::UpdateCookieAccessTime(const net::CanonicalCookie &cc) { DCHECK(initialized_); sql::Connection *conn = LBSavegameSyncer::connection(); sql::Statement touch_cookie(conn->GetCachedStatement(SQL_FROM_HERE, "UPDATE CookieTable SET last_access = ? WHERE " "name = ? AND domain = ? AND path = ?")); base::Time maximum_expiry = base::Time::Now() + kMaxCookieLifetime; base::Time expiry = cc.ExpiryDate(); if (expiry > maximum_expiry) expiry = maximum_expiry; touch_cookie.BindInt64(0, expiry.ToInternalValue()); touch_cookie.BindString(1, cc.Name()); touch_cookie.BindString(2, cc.Domain()); touch_cookie.BindString(3, cc.Path()); bool ok = touch_cookie.Run(); DCHECK(ok); } void LBCookieStore::DeleteCookie(const net::CanonicalCookie &cc) { QuickDeleteCookie(cc); } void LBCookieStore::Flush(const base::Closure& callback) { MessageLoop::current()->PostNonNestableTask(FROM_HERE, callback); }
34.371212
78
0.689663
[ "vector" ]
39716c6061611439261799235172947a9cec3248
10,359
cpp
C++
lab_02/source/main.cpp
DeaLoic/bmstu-AA
7ab0931cccd08613efa7a353fbb7865f83cab2a7
[ "MIT" ]
null
null
null
lab_02/source/main.cpp
DeaLoic/bmstu-AA
7ab0931cccd08613efa7a353fbb7865f83cab2a7
[ "MIT" ]
null
null
null
lab_02/source/main.cpp
DeaLoic/bmstu-AA
7ab0931cccd08613efa7a353fbb7865f83cab2a7
[ "MIT" ]
null
null
null
#include <stdio.h> #include <vector> #include <iostream> #include <cstdlib> #include <ctime> #include "windows.h" using namespace std; LARGE_INTEGER startingTime, endingTime, ellapsedMicrosecond, frequency; void printMatrix(vector< vector<int>> matrix); vector<vector<int>> createZeroMatrix(int n, int m); vector<vector<int>> inputMatrix(int n, int m); vector< vector<int> > generateMatrix(int n, int m); void printMenu(); vector<vector<int>> multiplyVinograd(vector< vector<int>> first, vector< vector<int>> second); vector<vector<int>> multiplyClassic(vector< vector<int>> first, vector< vector<int>> second); vector<vector<int>> multiplyVinogradOpt(vector< vector<int>> first, vector< vector<int>> second); int main() { srand(time(0)); int choosed = 1; while (choosed != 0) { printMenu(); scanf("%d", &choosed); switch (choosed) { case 0: cout << "Exit"; break; case 1: int nFirst, mFirst; printf("Input first matrix size: "); if (scanf("%d %d", &nFirst, &mFirst) != 2 || nFirst <= 0 || mFirst <= 0) { cout << "Incorrect\n"; } else { cout << "Input first matrix with size " << nFirst << "x" << mFirst << "\n"; vector< vector<int> > matrixFirst = inputMatrix(nFirst, mFirst); int nSecond, mSecond; cout << "Input second matrix size: "; if (scanf("%d %d", &nSecond, &mSecond) != 2 || nFirst <= 0 || mFirst <= 0) { cout << "Incorrect\n"; } else if (nSecond != mFirst) { cout << "Incorrect size. Matrix cant be multiply\n"; } else { cout << "Input second matrix with size " << nSecond << "x" << mSecond << "\n"; vector< vector<int> > matrixSecond = inputMatrix(nSecond, mSecond); cout << "\nResult classic:\n"; printMatrix(multiplyClassic(matrixFirst, matrixSecond)); cout << "\nResult Vinograd:\n"; printMatrix(multiplyVinograd(matrixFirst, matrixSecond)); cout << "\nResult Vinograd optimized:\n"; printMatrix(multiplyVinogradOpt(matrixFirst, matrixSecond)); } } case 2: { vector< vector<int> > matrixFirst, matrixSecond, answer; for (int i = 2; i < 503; i += 50) { matrixFirst = generateMatrix(i, i); matrixSecond = generateMatrix(i, i); // Classic QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&startingTime); answer = multiplyClassic(matrixFirst, matrixSecond); QueryPerformanceCounter(&endingTime); ellapsedMicrosecond.QuadPart = endingTime.QuadPart - startingTime.QuadPart; ellapsedMicrosecond.QuadPart *= 1000000; ellapsedMicrosecond.QuadPart /= frequency.QuadPart; long double classicMS = ellapsedMicrosecond.QuadPart; // VINOGRAD QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&startingTime); answer = multiplyVinograd(matrixFirst, matrixSecond); QueryPerformanceCounter(&endingTime); ellapsedMicrosecond.QuadPart = endingTime.QuadPart - startingTime.QuadPart; ellapsedMicrosecond.QuadPart *= 1000000; ellapsedMicrosecond.QuadPart /= frequency.QuadPart; long double vinogradMS = ellapsedMicrosecond.QuadPart; // OPT QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&startingTime); answer = multiplyVinogradOpt(matrixFirst, matrixSecond); QueryPerformanceCounter(&endingTime); ellapsedMicrosecond.QuadPart = endingTime.QuadPart - startingTime.QuadPart; ellapsedMicrosecond.QuadPart *= 1000000; ellapsedMicrosecond.QuadPart /= frequency.QuadPart; long double vinogradOptMS = ellapsedMicrosecond.QuadPart; cout << "\n Size: " << i << "\nClassic: " << classicMS << " Vinograd: " << vinogradMS << " Opt: " << vinogradOptMS << "\n"; } break; } default: cout << "Cant find this point, try again\n"; } } } void printMatrix(vector< vector<int>> matrix) { for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix[i].size(); j++) { printf("%6d", matrix[i][j]); } printf("\n"); } } vector<vector<int>> multiplyClassic(vector< vector<int>> first, vector< vector<int>> second) { int nFirst = first.size(); int nSecond = second.size(); vector<vector<int>> result; //printf("%d %d %d %d", nFirst, nSecond, first[0].size(), second[0].size()); if (nFirst > 0 && nSecond > 0 && first[0].size() == nSecond && second[0].size() != 0) { int mSecond = second[0].size(); result = createZeroMatrix(nFirst, mSecond); for (int i = 0; i < nFirst; i++) { for (int j = 0; j < mSecond; j++) { for (int k = 0; k < nSecond; k++) { result[i][j] += first[i][k] * second[k][j]; } } } } //printMatrix(result); return result; } vector<vector<int>> multiplyVinograd(vector< vector<int>> first, vector< vector<int>> second) { int nFirst = first.size(); int nSecond = second.size(); vector<vector<int>> result; if (nFirst > 0 && nSecond > 0 && first[0].size() == nSecond && second[0].size() != 0) { int mSecond = second[0].size(); int mFirst = nSecond; result = createZeroMatrix(nFirst, mSecond); vector<int> mulH, mulV; mulH.reserve(nFirst); mulV.reserve(mSecond); for (int i = 0; i < nFirst; i++) { mulH[i] = 0; for (int j = 0; j < mFirst / 2; j++) { mulH[i] += first[i][j * 2] * first[i][j * 2 + 1]; } } for (int i = 0; i < mSecond; i++) { mulV[i] = 0; for (int j = 0; j < nSecond / 2; j++) { mulV[i] += second[j * 2][i] * second[j * 2 + 1][i]; } } for (int i = 0; i < nFirst; i++) { for (int j = 0; j < mSecond; j++) { result[i][j] = - mulH[i] - mulV[j]; for (int k = 0; k < mFirst / 2; k++) { result[i][j] += (first[i][2 * k + 1] + second[2 * k][j]) * (first[i][2 * k] + second[2 * k + 1][j]); } } } if (mFirst % 2 == 1) { for (int i = 0; i < nFirst; i++) { for (int j = 0; j < mSecond; j++) { result[i][j] += first[i][mFirst - 1] * second[mFirst - 1][j]; } } } } return result; } vector<vector<int>> multiplyVinogradOpt(vector< vector<int>> first, vector< vector<int>> second) { int nFirst = first.size(); int nSecond = second.size(); vector<vector<int>> result; if (nFirst > 0 && nSecond > 0 && first[0].size() == nSecond && second[0].size() != 0) { int mSecond = second[0].size(); int mFirst = nSecond; result = createZeroMatrix(nFirst, mSecond); vector<int> mulH, mulV; mulH.reserve(nFirst); mulV.reserve(mSecond); int m1Mod2 = mFirst % 2; int n2Mod2 = nSecond % 2; int temp = nSecond - n2Mod2; for (int i = 0; i < mSecond; i++) { mulV[i] = 0; for (int j = 0; j < temp; j += 2) { mulV[i] += second[j][i] * second[j + 1][i]; } } temp = mFirst - m1Mod2; for (int i = 0; i < nFirst; i++) { mulH[i] = 0; for (int j = 0; j < temp; j += 2) { mulH[i] += first[i][j] * first[i][j + 1]; } } for (int i = 0; i < nFirst; i++) { for (int j = 0; j < mSecond; j++) { int buff = - (mulH[i] + mulV[j]); for (int k = 0; k < temp; k += 2) { buff += (first[i][k + 1] + second[k][j]) * (first[i][k] + second[k + 1][j]); } result[i][j] = buff; } } if (m1Mod2 == 1) { temp = mFirst - 1; for (int i = 0; i < nFirst; i++) { for (int j = 0; j < mSecond; j++) { result[i][j] += first[i][temp] * second[temp][j]; } } } } return result; } vector<vector<int>> createZeroMatrix(int n, int m) { vector< vector<int>> matrix; if (n > 0 && m > 0) { matrix.reserve(n); for (int i = 0; i < n; i++) { matrix.push_back(vector<int> {}); matrix[i].reserve(m); for (int j = 0; j < m; j++) { matrix[i].push_back(0); } } } return matrix; } vector<vector<int>> inputMatrix(int n, int m) { vector<vector<int>> matrix = createZeroMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &(matrix[i][j])); } } return matrix; } void printMenu() { cout << "\nMENU:\n0) Exit\n1) Demonstration\n2) Tests result\n"; } vector< vector<int> > generateMatrix(int n, int m) { vector< vector<int> > matrix; for (int i = 0; i < n; i++) { matrix.push_back(vector<int> {}); for (int j = 0; j < m; j++) { matrix[i].push_back(rand()); } } return matrix; }
29.597143
149
0.467227
[ "vector" ]
39793b0c151333094e3a14e82ed2fb8d7f99eefc
1,737
cpp
C++
networkit/cpp/components/StronglyConnectedComponents.cpp
kit-parco/networkit-chemfork
5bfd593308af3020aeca00c843e7e9dd860011d0
[ "MIT" ]
2
2018-10-08T15:47:50.000Z
2021-06-11T13:42:43.000Z
networkit/cpp/components/StronglyConnectedComponents.cpp
kit-parco/networkit-hyperbolic-kd
8eb786b8f72e0507a75e68184f444a19cf47ef58
[ "MIT" ]
null
null
null
networkit/cpp/components/StronglyConnectedComponents.cpp
kit-parco/networkit-hyperbolic-kd
8eb786b8f72e0507a75e68184f444a19cf47ef58
[ "MIT" ]
1
2019-10-21T08:29:30.000Z
2019-10-21T08:29:30.000Z
/* * StrongConnectedComponents.cpp * * Created on: 01.06.2014 * Author: Klara Reichard (klara.reichard@gmail.com), Marvin Ritter (marvin.ritter@gmail.com) */ #include <stack> #include <functional> #include "StronglyConnectedComponents.h" #include "../structures/Partition.h" #include "../auxiliary/Log.h" namespace NetworKit { StronglyConnectedComponents::StronglyConnectedComponents(const Graph& G) : G(G) { } void StronglyConnectedComponents::run() { count z = G.upperNodeIdBound(); component = Partition(z); index nextIndex = 0; std::vector<index> nodeIndex(z, none); std::vector<index> nodeLowLink(z, none); std::stack<node> stx; std::vector<bool> onStack(z, false); std::function<void(node)> strongConnect = [&](node v) { nodeIndex[v] = nextIndex++; nodeLowLink[v] = nodeIndex[v]; stx.push(v); onStack[v] = true; G.forNeighborsOf(v, [&](node w) { if (nodeIndex[w] == none) { strongConnect(w); nodeLowLink[v] = std::min(nodeLowLink[v], nodeLowLink[w]); } else if (onStack[w]) { nodeLowLink[v] = std::min(nodeLowLink[v], nodeIndex[w]); } }); if (nodeLowLink[v] == nodeIndex[v]) { component.toSingleton(v); while (true) { node w = stx.top(); stx.pop(); onStack[w] = false; if (w == v) { break; } component[w] = component[v]; } } }; G.forNodes([&](node v) { if (nodeIndex[v] == none) { strongConnect(v); } }); } Partition StronglyConnectedComponents::getPartition() { return this->component; } count StronglyConnectedComponents::numberOfComponents() { return this->component.numberOfSubsets(); } count StronglyConnectedComponents::componentOfNode(node u) { assert (component[u] != none); return component[u]; } }
21.444444
98
0.658607
[ "vector" ]
397b947c322af5fe80c6227a10fe7fc9f534d0fb
42,214
cpp
C++
tests/workTests/TestHMWorkRemoteCheck.cpp
varsameer/NetCHASM
3071241ce0d2cddc077e5e7e1b957677d733ae76
[ "Apache-2.0" ]
13
2019-06-06T01:14:30.000Z
2022-03-03T05:57:51.000Z
tests/workTests/TestHMWorkRemoteCheck.cpp
varsameer/NetCHASM
3071241ce0d2cddc077e5e7e1b957677d733ae76
[ "Apache-2.0" ]
7
2019-07-23T18:31:20.000Z
2021-05-26T12:57:34.000Z
tests/workTests/TestHMWorkRemoteCheck.cpp
varsameer/NetCHASM
3071241ce0d2cddc077e5e7e1b957677d733ae76
[ "Apache-2.0" ]
12
2019-06-27T13:58:03.000Z
2021-12-23T07:43:06.000Z
// Copyright 2019, Oath Inc. // Licensed under the terms of the Apache 2.0 license. See LICENSE file in the root of the distribution for licensing details. #include <thread> #include "HMEventLoopQueue.h" #include "TestHMWorkRemoteCheck.h" #include "common.h" #include "TestStorage.h" using namespace std; HM_WORK_STATUS TestHMWorkRemoteCheck::remoteLookup() { if(responseTime < 0) { return HM_WORK_COMPLETE; } m_response = (responseTime?HM_RESPONSE_CONNECTED:HM_RESPONSE_FAILED); m_reason = (responseTime?HM_REASON_SUCCESS:HM_REASON_CONNECT_FAILURE); m_start = HMTimeStamp::now(); m_end = m_start + responseTime; return HM_WORK_COMPLETE_REMOTE; } CPPUNIT_TEST_SUITE_REGISTRATION(TESTNAME); void TESTNAME::setUp() { setupCommon(); HMDataHostGroupMap hostGroupMap; m_currentState = make_shared<HMState>(); HMDNSCache dnsCache; m_currentState->m_datastore = make_unique<TestStorage>(&hostGroupMap, &dnsCache); m_state.setState(m_currentState); m_eventQueue = new HMEventLoopQueue(&m_state); m_eventThread = new std::thread(&HMEventLoopQueue::runThread, m_eventQueue); } void TESTNAME::tearDown() { m_eventQueue->shutDown(); m_eventThread->join(); m_currentState.reset(); m_state.setState(m_currentState); delete m_eventQueue; delete m_eventThread; teardownCommon(); } void TESTNAME::test_HMWorkRemoteCheck_basic() { TestStorage* storage = dynamic_cast<TestStorage*>(m_currentState->m_datastore.get()); vector<HMGroupCheckResult> results_hg1; vector<HMGroupCheckResult> results_hg2; vector<HMGroupCheckResult> results_hg3; HMIPAddress address1_1; address1_1.set("1.2.3.4"); HMIPAddress address1_2; address1_2.set("11.22.33.44"); HMIPAddress address2; address2.set("4.5.6.7"); HMIPAddress address3; address3.set("4.3.2.1"); HMIPAddress address4; address4.set("7.6.5.4"); string h1 = "host1"; string h2 = "host2"; string h3 = "host3"; string h4 = "host4"; HMDataCheckResult checkResult1_1; checkResult1_1.m_checkTime = HMTimeStamp::now(); checkResult1_1.m_response = HM_RESPONSE_CONNECTED; checkResult1_1.m_reason = HM_REASON_SUCCESS; checkResult1_1.m_responseTime = 33; checkResult1_1.m_totalResponseTime = 66; checkResult1_1.m_smoothedResponseTime = 44; checkResult1_1.m_address = address1_1; HMDataCheckResult checkResult1_2; checkResult1_2.m_checkTime = HMTimeStamp::now(); checkResult1_2.m_response = HM_RESPONSE_CONNECTED; checkResult1_2.m_reason = HM_REASON_SUCCESS; checkResult1_2.m_responseTime = 333; checkResult1_2.m_totalResponseTime = 666; checkResult1_2.m_smoothedResponseTime = 444; checkResult1_2.m_address = address1_2; HMDataCheckResult checkResult2; checkResult2.m_checkTime = HMTimeStamp::now(); checkResult2.m_response = HM_RESPONSE_FAILED; checkResult2.m_reason = HM_REASON_RESPONSE_TIMEOUT; checkResult2.m_address = address2; HMDataCheckResult checkResult3; checkResult3.m_checkTime = HMTimeStamp::now(); checkResult3.m_response = HM_RESPONSE_FAILED; checkResult3.m_reason = HM_REASON_RESPONSE_403; checkResult3.m_address = address3; HMDataCheckResult checkResult4; checkResult4.m_checkTime = HMTimeStamp::now(); checkResult4.m_response = HM_RESPONSE_FAILED; checkResult4.m_reason = HM_REASON_RESPONSE_5XX; checkResult4.m_address = address4; HMGroupCheckResult result1_1; result1_1.m_address = address1_1; result1_1.m_hostName = h1; result1_1.m_result = checkResult1_1; HMGroupCheckResult result1_2; result1_2.m_address = address1_2; result1_2.m_hostName = h1; result1_2.m_result = checkResult1_2; HMGroupCheckResult result2; result2.m_address = address2; result2.m_hostName = h2; result2.m_result = checkResult2; HMGroupCheckResult result3; result3.m_address = address3; result3.m_hostName = h3; result3.m_result = checkResult3; HMGroupCheckResult result4; result4.m_address = address4; result4.m_hostName = h4; result4.m_result = checkResult4; results_hg1.push_back(result1_1); results_hg1.push_back(result2); results_hg2.push_back(result1_2); results_hg2.push_back(result3); results_hg3.push_back(result2); results_hg3.push_back(result4); string hg1 = "HostGroup1"; string hg2 = "HostGroup2"; string hg3 = "HostGroup3"; HMDataHostCheck check1; HMDataHostCheck check2; HMDataHostCheck check3; HMDataCheckParams params1; HMDataCheckParams params2; HMDataCheckParams params3; string checkParams = "/check.html"; string host_group = "dummy"; HMDataHostGroup hostGroup1(hg1); hostGroup1.setCheckType(HM_CHECK_HTTP); hostGroup1.setCheckPlugin(HM_CHECK_PLUGIN_HTTP_CURL); hostGroup1.setPort(80); hostGroup1.setDualStack(HM_DUALSTACK_IPV4_ONLY); hostGroup1.setCheckInfo(checkParams); hostGroup1.setRemoteCheck("test"); hostGroup1.setRemoteCheckType(HM_REMOTE_SHARED_CHECK_TCP); hostGroup1.setDistributedFallback(HM_DISTRIBUTED_FALLBACK_NONE); hostGroup1.setFlowType(HM_FLOW_REMOTE_HOSTGROUP_TYPE); hostGroup1.addHost(h1); hostGroup1.addHost(h2); hostGroup1.getHostCheck(check1); HMDataHostGroup hostGroup2(hg2); hostGroup2.setCheckType(HM_CHECK_HTTP); hostGroup2.setCheckPlugin(HM_CHECK_PLUGIN_HTTP_CURL); hostGroup2.setPort(800); hostGroup2.setDualStack(HM_DUALSTACK_IPV4_ONLY); hostGroup2.setCheckInfo(checkParams); hostGroup2.setRemoteCheck("test"); hostGroup2.setRemoteCheckType(HM_REMOTE_SHARED_CHECK_TCP); hostGroup2.setDistributedFallback(HM_DISTRIBUTED_FALLBACK_NONE); hostGroup2.setFlowType(HM_FLOW_REMOTE_HOSTGROUP_TYPE); hostGroup2.addHost(h1); hostGroup2.addHost(h3); hostGroup2.getHostCheck(check2); HMDataHostGroup hostGroup3(hg3); hostGroup3.setCheckType(HM_CHECK_HTTP); hostGroup3.setCheckPlugin(HM_CHECK_PLUGIN_HTTP_CURL); hostGroup3.setPort(8000); hostGroup3.setDualStack(HM_DUALSTACK_IPV4_ONLY); hostGroup3.setCheckInfo(checkParams); hostGroup3.setRemoteCheck("test"); hostGroup3.setRemoteCheckType(HM_REMOTE_SHARED_CHECK_TCP); hostGroup3.setDistributedFallback(HM_DISTRIBUTED_FALLBACK_NONE); hostGroup3.setFlowType(HM_FLOW_REMOTE_HOSTGROUP_TYPE); hostGroup3.addHost(h2); hostGroup3.addHost(h4); hostGroup3.getHostCheck(check3); m_currentState->m_hostGroups.insert(make_pair(hg1, hostGroup1)); m_currentState->m_hostGroups.insert(make_pair(hg2, hostGroup2)); m_currentState->m_hostGroups.insert(make_pair(hg3, hostGroup3)); set<HMIPAddress> ips; ips.insert(address1_1); m_currentState->m_checkList.insertCheck(hg1, h1, check1, params1, ips); ips.clear(); ips.insert(address1_2); m_currentState->m_checkList.insertCheck(hg2, h1, check2, params2, ips); ips.clear(); ips.insert(address3); m_currentState->m_checkList.insertCheck(hg2, h3, check2, params2, ips); ips.clear(); ips.insert(address2); m_currentState->m_checkList.insertCheck(hg1, h2, check1, params1, ips); ips.clear(); ips.insert(address2); m_currentState->m_checkList.insertCheck(hg3, h2, check3, params3, ips); ips.clear(); ips.insert(address4); m_currentState->m_checkList.insertCheck(hg3, h4, check3, params3, ips); HMDNSLookup lookup1(hostGroup1.getDNSType(), false, hostGroup1.getRemoteCheck()); m_currentState->m_dnsCache.insertDNSEntry(h1, lookup1, 500, 60000); m_currentState->m_dnsCache.insertDNSEntry(h2, lookup1, 500, 60000); m_currentState->m_dnsCache.insertDNSEntry(h3, lookup1, 500, 60000); m_currentState->m_dnsCache.insertDNSEntry(h4, lookup1, 500, 60000); m_currentState->m_remoteCache.insertRemoteEntry(hg1, 500, 60000); m_currentState->m_remoteCache.insertRemoteEntry(hg2, 500, 60000); m_currentState->m_remoteCache.insertRemoteEntry(hg3, 500, 60000); m_currentState->m_remoteCache.finishCheck(hg1, true); m_currentState->m_remoteCache.finishCheck(hg2, true); m_currentState->m_remoteCache.finishCheck(hg3, true); HMIPAddress addr(AF_INET); storage->m_writeCount = 0; remoteCheck = new TestHMWorkRemoteCheck(hg1, addr, check1, hostGroup1, results_hg1); remoteCheck->responseTime = 10; remoteCheck->updateState(&m_state, m_eventQueue); remoteCheck->m_ipAddress = addr; CPPUNIT_ASSERT(remoteCheck->processWork() == HM_WORK_COMPLETE_REMOTE); delete remoteCheck; set<HMIPAddress> addresses; CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h1, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); storage->m_writeCount = 0; remoteCheck = new TestHMWorkRemoteCheck(hg2, addr, check2, hostGroup2, results_hg2); remoteCheck->responseTime = 10; remoteCheck->updateState(&m_state, m_eventQueue); remoteCheck->m_ipAddress = addr; CPPUNIT_ASSERT(remoteCheck->processWork() == HM_WORK_COMPLETE_REMOTE); delete remoteCheck; storage->m_writeCount = 0; remoteCheck = new TestHMWorkRemoteCheck(hg3, addr, check3, hostGroup3, results_hg3); remoteCheck->responseTime = 10; remoteCheck->updateState(&m_state, m_eventQueue); remoteCheck->m_ipAddress = addr; CPPUNIT_ASSERT(remoteCheck->processWork() == HM_WORK_COMPLETE_REMOTE); delete remoteCheck; // query the results directly CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h2, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); { std::vector<std::pair<HMDataCheckParams, HMDataCheckResult>> getResults; HMDataHostCheck c = check1; CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h1, c, address1_1, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params1); CPPUNIT_ASSERT(getResults[0].second.m_address == HMIPAddress()); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params1.getTimeout())); getResults.clear(); CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h2, c, address2, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params1); CPPUNIT_ASSERT(getResults[0].second.m_address == HMIPAddress()); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params1.getTimeout())); vector<HMGroupCheckResult> results; CPPUNIT_ASSERT(m_currentState->m_datastore->getGroupCheckResults(hg1, results)); CPPUNIT_ASSERT_EQUAL(2, (int)results.size()); CPPUNIT_ASSERT(results[0].m_address == address1_1); CPPUNIT_ASSERT(results[0].m_hostName == h1); CPPUNIT_ASSERT(results[0].m_result.m_reason == checkResult1_1.m_reason); CPPUNIT_ASSERT(results[1].m_address == address2); CPPUNIT_ASSERT(results[1].m_hostName == h2); CPPUNIT_ASSERT(results[1].m_result.m_reason == checkResult2.m_reason); } CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h1, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h3, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); // query the results directly { std::vector<std::pair<HMDataCheckParams, HMDataCheckResult>> getResults; HMDataHostCheck c = check2; CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h1, c, address1_2, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params2); CPPUNIT_ASSERT(getResults[0].second.m_address == HMIPAddress()); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params2.getTimeout())); getResults.clear(); CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h3, c, address3, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params2); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params2.getTimeout())); vector<HMGroupCheckResult> results; CPPUNIT_ASSERT(m_currentState->m_datastore->getGroupCheckResults(hg2, results)); CPPUNIT_ASSERT_EQUAL(2, (int)results.size()); CPPUNIT_ASSERT(results[0].m_address == address1_2); CPPUNIT_ASSERT(results[0].m_hostName == h1); CPPUNIT_ASSERT(results[0].m_result.m_reason == checkResult1_2.m_reason); CPPUNIT_ASSERT(results[1].m_address == address3); CPPUNIT_ASSERT(results[1].m_hostName == h3); CPPUNIT_ASSERT(results[1].m_result.m_reason == checkResult3.m_reason); } CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h2, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h4, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); { std::vector<std::pair<HMDataCheckParams, HMDataCheckResult>> getResults; HMDataHostCheck c = check3; CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h2, c, address2, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params1); CPPUNIT_ASSERT(getResults[0].second.m_address == HMIPAddress()); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params1.getTimeout())); getResults.clear(); CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h4, c, address4, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params2); CPPUNIT_ASSERT(getResults[0].second.m_address == HMIPAddress()); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params2.getTimeout())); vector<HMGroupCheckResult> results; CPPUNIT_ASSERT(m_currentState->m_datastore->getGroupCheckResults(hg3, results)); CPPUNIT_ASSERT_EQUAL(2, (int)results.size()); CPPUNIT_ASSERT(results[0].m_address == address2); CPPUNIT_ASSERT(results[0].m_hostName == h2); CPPUNIT_ASSERT(results[0].m_result.m_reason == checkResult2.m_reason); CPPUNIT_ASSERT(results[1].m_address == address4); CPPUNIT_ASSERT(results[1].m_hostName == h4); CPPUNIT_ASSERT(results[1].m_result.m_reason == checkResult4.m_reason); } std::this_thread::sleep_for(510ms); CPPUNIT_ASSERT_EQUAL(3, (int)m_state.m_workQueue.queueSize()); // Now check the work list unique_ptr<HMWork> work; bool threadStatus = false; m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(!(work->m_hostCheck != check1)); CPPUNIT_ASSERT(work->m_hostname == hg1); cout<<work->m_ipAddress.toString()<<" " <<addr.toString()<<endl; CPPUNIT_ASSERT(work->m_ipAddress == addr); m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(!(work->m_hostCheck != check2)); CPPUNIT_ASSERT(work->m_hostname == hg2); CPPUNIT_ASSERT(work->m_ipAddress == addr); m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(!(work->m_hostCheck != check3)); CPPUNIT_ASSERT(work->m_hostname == hg3); CPPUNIT_ASSERT(work->m_ipAddress == addr); } void TESTNAME::test_HMWorkRemoteCheck_mixed_dns() { TestStorage* storage = dynamic_cast<TestStorage*>(m_currentState->m_datastore.get()); vector<HMGroupCheckResult> results_hg1; HMIPAddress address1; address1.set("1.2.3.4"); HMIPAddress address2; address2.set("4.5.6.7"); HMIPAddress address3; address3.set("4.3.2.1"); HMIPAddress address4; address4.set("7.6.5.4"); string h1 = "host1"; string h2 = "host2"; HMDataCheckResult checkResult1; checkResult1.m_checkTime = HMTimeStamp::now(); checkResult1.m_response = HM_RESPONSE_CONNECTED; checkResult1.m_reason = HM_REASON_SUCCESS; checkResult1.m_responseTime = 33; checkResult1.m_totalResponseTime = 66; checkResult1.m_smoothedResponseTime = 44; checkResult1.m_address = address1; HMDataCheckResult checkResult2; checkResult2.m_checkTime = HMTimeStamp::now(); checkResult2.m_response = HM_RESPONSE_FAILED; checkResult2.m_reason = HM_REASON_RESPONSE_TIMEOUT; checkResult2.m_address = address2; HMGroupCheckResult result1; result1.m_address = address1; result1.m_hostName = h1; result1.m_result = checkResult1; HMGroupCheckResult result2; result2.m_address = address2; result2.m_hostName = h2; result2.m_result = checkResult2; results_hg1.push_back(result1); results_hg1.push_back(result2); string hg1 = "HostGroup1"; string hg2 = "HostGroup2"; HMDataHostCheck defaultcheck; HMDataHostCheck check1; HMDataHostCheck check2; HMDataCheckParams params1; HMDataCheckParams params2; string checkParams = "/check.html"; HMDataHostGroup hostGroup1(hg1); hostGroup1.setCheckType(HM_CHECK_HTTP); hostGroup1.setCheckPlugin(HM_CHECK_PLUGIN_HTTP_CURL); hostGroup1.setPort(80); hostGroup1.setDualStack(HM_DUALSTACK_IPV4_ONLY); hostGroup1.setCheckInfo(checkParams); hostGroup1.setRemoteCheck("test"); hostGroup1.setRemoteCheckType(HM_REMOTE_SHARED_CHECK_TCP); hostGroup1.setDistributedFallback(HM_DISTRIBUTED_FALLBACK_NONE); hostGroup1.setFlowType(HM_FLOW_REMOTE_HOSTGROUP_TYPE); hostGroup1.addHost(h1); hostGroup1.addHost(h2); hostGroup1.getHostCheck(check1); hostGroup1.getCheckParameters(params1); HMDataHostGroup hostGroup2(hg2); hostGroup2.setCheckType(HM_CHECK_HTTP); hostGroup2.setCheckPlugin(HM_CHECK_PLUGIN_HTTP_CURL); hostGroup2.setPort(80); hostGroup2.setDualStack(HM_DUALSTACK_IPV4_ONLY); hostGroup2.setCheckInfo(checkParams); hostGroup2.setRemoteCheckType(HM_REMOTE_CHECK_NONE); hostGroup2.setDistributedFallback(HM_DISTRIBUTED_FALLBACK_NONE); check2.setCheckParams(hostGroup2); hostGroup2.getCheckParameters(params2); m_currentState->m_hostGroups.insert(make_pair(hg1, hostGroup1)); m_currentState->m_hostGroups.insert(make_pair(hg2, hostGroup2)); m_currentState->m_dnsWaitList.insert(make_pair(HMDNSTypeMap(h1, HM_DNS_TYPE_STATIC, ""),check2)); m_currentState->m_dnsWaitList.insert(make_pair(HMDNSTypeMap(h2, HM_DNS_TYPE_STATIC, ""),check2)); set<HMIPAddress> ips; ips.insert(address1); m_currentState->m_checkList.insertCheck(hg1, h1, check1, params1, ips); ips.clear(); ips.insert(address2); m_currentState->m_checkList.insertCheck(hg1, h2, check1, params1, ips); ips.clear(); ips.insert(address3); m_currentState->m_checkList.insertCheck(hg2, h1, check2, params2, ips); ips.clear(); ips.insert(address4); m_currentState->m_checkList.insertCheck(hg2, h2, check2, params2, ips); HMDNSLookup lookup1(hostGroup1.getDNSType(), false, hostGroup1.getRemoteCheck()); lookup1.setPlugin(HM_DNS_PLUGIN_ARES); m_currentState->m_dnsCache.insertDNSEntry(h1, lookup1, 500, 60000); m_currentState->m_dnsCache.insertDNSEntry(h2, lookup1, 500, 60000); HMDNSLookup dnsHostCheckF(HM_DNS_TYPE_STATIC, false, hostGroup2.getRemoteCheck()); dnsHostCheckF.setPlugin(HM_DNS_PLUGIN_ARES); m_currentState->m_dnsCache.insertDNSEntry(h1, dnsHostCheckF, 500, 60000); m_currentState->m_dnsCache.insertDNSEntry(h2, dnsHostCheckF, 500, 60000); m_currentState->m_remoteCache.insertRemoteEntry(hg1, 500, 60000); m_currentState->m_remoteCache.finishCheck(hg1, true); HMIPAddress addr(AF_INET); storage->m_writeCount = 0; remoteCheck = new TestHMWorkRemoteCheck(hg1, addr, check1, hostGroup1, results_hg1); remoteCheck->responseTime = 10; remoteCheck->updateState(&m_state, m_eventQueue); remoteCheck->m_ipAddress = addr; CPPUNIT_ASSERT(remoteCheck->processWork() == HM_WORK_COMPLETE_REMOTE); delete remoteCheck; dnsLookup = new TestHMWorkDNSLookup(h1, addr, check2, dnsHostCheckF); dnsLookup->updateState(&m_state, m_eventQueue); dnsLookup->addTarget(address3); set<HMIPAddress> vip_ret; CPPUNIT_ASSERT(dnsLookup->processWork() == HM_WORK_COMPLETE); CPPUNIT_ASSERT(m_currentState->m_dnsCache.getAddresses(h1, HM_DUALSTACK_IPV4_ONLY, dnsHostCheckF, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address3) != vip_ret.end()); delete dnsLookup; // Test to make sure we do not return if the query is timed out dnsLookup = new TestHMWorkDNSLookup(h2, addr, check2, dnsHostCheckF); dnsLookup->updateState(&m_state, m_eventQueue); dnsLookup->addTarget(address4); vip_ret.clear(); CPPUNIT_ASSERT(dnsLookup->processWork() == HM_WORK_COMPLETE); CPPUNIT_ASSERT(m_currentState->m_dnsCache.getAddresses(h2, HM_DUALSTACK_IPV4_ONLY, dnsHostCheckF, vip_ret)); CPPUNIT_ASSERT(vip_ret.find(address4) != vip_ret.end()); delete dnsLookup; // query the results directly set<HMIPAddress> addresses; CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h1, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h2, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); { std::vector<std::pair<HMDataCheckParams, HMDataCheckResult>> getResults; HMDataHostCheck c = check1; CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h1, c, address1, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params1); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params1.getTimeout())); getResults.clear(); CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h2, c, address2, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params1); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params1.getTimeout())); vector<HMGroupCheckResult> results; CPPUNIT_ASSERT(m_currentState->m_datastore->getGroupCheckResults(hg1, results)); CPPUNIT_ASSERT_EQUAL(2, (int)results.size()); CPPUNIT_ASSERT(results[0].m_address == address1); CPPUNIT_ASSERT(results[0].m_hostName == h1); CPPUNIT_ASSERT(results[0].m_result.m_reason == checkResult1.m_reason); CPPUNIT_ASSERT(results[1].m_address == address2); CPPUNIT_ASSERT(results[1].m_hostName == h2); CPPUNIT_ASSERT(results[1].m_result.m_reason == checkResult2.m_reason); } std::this_thread::sleep_for(505ms); CPPUNIT_ASSERT_EQUAL(5, (int)m_state.m_workQueue.queueSize()); // Now check the work list unique_ptr<HMWork> work; bool threadStatus = false; m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(work->m_hostname == h1); CPPUNIT_ASSERT(work->m_hostCheck == check2); CPPUNIT_ASSERT(work->m_ipAddress == address3); m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(work->m_hostname == h2); CPPUNIT_ASSERT(work->m_hostCheck == check2); CPPUNIT_ASSERT(work->m_ipAddress == address4); m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(work->m_hostname == hg1); CPPUNIT_ASSERT(work->m_hostCheck == check1); CPPUNIT_ASSERT(work->m_ipAddress == addr); m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(work->m_hostname == h1); CPPUNIT_ASSERT(work->m_hostCheck == defaultcheck); CPPUNIT_ASSERT(work->m_ipAddress == addr); m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(work->m_hostname == h2); CPPUNIT_ASSERT(work->m_hostCheck == defaultcheck); CPPUNIT_ASSERT(work->m_ipAddress == addr); } void TESTNAME::test_HMWorkRemoteCheck_mixed_healthcheck() { TestStorage* storage = dynamic_cast<TestStorage*>(m_currentState->m_datastore.get()); vector<HMGroupCheckResult> results_hg1; HMIPAddress address1; address1.set("1.2.3.4"); HMIPAddress address2; address2.set("4.5.6.7"); HMIPAddress address3; address3.set("4.3.2.1"); HMIPAddress address4; address4.set("7.6.5.4"); string h1 = "host1"; string h2 = "host2"; HMDataCheckResult checkResult1; checkResult1.m_checkTime = HMTimeStamp::now(); checkResult1.m_response = HM_RESPONSE_CONNECTED; checkResult1.m_reason = HM_REASON_SUCCESS; checkResult1.m_responseTime = 33; checkResult1.m_totalResponseTime = 66; checkResult1.m_smoothedResponseTime = 44; checkResult1.m_address = address1; HMDataCheckResult checkResult2; checkResult2.m_checkTime = HMTimeStamp::now(); checkResult2.m_response = HM_RESPONSE_FAILED; checkResult2.m_reason = HM_REASON_RESPONSE_TIMEOUT; checkResult2.m_address = address2; HMGroupCheckResult result1; result1.m_address = address1; result1.m_hostName = h1; result1.m_result = checkResult1; HMGroupCheckResult result2; result2.m_address = address2; result2.m_hostName = h2; result2.m_result = checkResult2; results_hg1.push_back(result1); results_hg1.push_back(result2); string hg1 = "HostGroup1"; string hg2 = "HostGroup2"; HMDataHostCheck defaultcheck; HMDataHostCheck check1; HMDataHostCheck check2; HMDataCheckParams params1; HMDataCheckParams params2; string checkParams = "/check.html"; HMDataHostGroup hostGroup1(hg1); hostGroup1.setCheckType(HM_CHECK_HTTP); hostGroup1.setCheckPlugin(HM_CHECK_PLUGIN_HTTP_CURL); hostGroup1.setPort(80); hostGroup1.setDualStack(HM_DUALSTACK_IPV4_ONLY); hostGroup1.setCheckInfo(checkParams); hostGroup1.setRemoteCheck("test"); hostGroup1.setRemoteCheckType(HM_REMOTE_SHARED_CHECK_TCP); hostGroup1.setDistributedFallback(HM_DISTRIBUTED_FALLBACK_NONE); hostGroup1.setFlowType(HM_FLOW_REMOTE_HOSTGROUP_TYPE); hostGroup1.addHost(h1); hostGroup1.addHost(h2); hostGroup1.getHostCheck(check1); hostGroup1.getCheckParameters(params1); HMDataHostGroup hostGroup2(hg2); hostGroup2.setCheckType(HM_CHECK_HTTP); hostGroup2.setCheckPlugin(HM_CHECK_PLUGIN_HTTP_CURL); hostGroup2.setPort(80); hostGroup2.setCheckTTL(500); hostGroup2.setCheckTimeout(60000); hostGroup2.setDualStack(HM_DUALSTACK_IPV4_ONLY); hostGroup2.setCheckInfo(checkParams); hostGroup2.setRemoteCheckType(HM_REMOTE_CHECK_NONE); hostGroup2.setDistributedFallback(HM_DISTRIBUTED_FALLBACK_NONE); check2.setCheckParams(hostGroup2); hostGroup2.getCheckParameters(params2); m_currentState->m_hostGroups.insert(make_pair(hg1, hostGroup1)); m_currentState->m_hostGroups.insert(make_pair(hg2, hostGroup2)); set<HMIPAddress> ips; ips.insert(address1); m_currentState->m_checkList.insertCheck(hg1, h1, check1, params1, ips); ips.clear(); ips.insert(address2); m_currentState->m_checkList.insertCheck(hg1, h2, check1, params1, ips); ips.clear(); ips.insert(address3); m_currentState->m_checkList.insertCheck(hg2, h1, check2, params2, ips); ips.clear(); ips.insert(address4); m_currentState->m_checkList.insertCheck(hg2, h2, check2, params2, ips); HMDNSLookup lookup1(hostGroup1.getDNSType(), false, hostGroup1.getRemoteCheck()); m_currentState->m_dnsCache.insertDNSEntry(h1, lookup1, 500, 60000); m_currentState->m_dnsCache.insertDNSEntry(h2, lookup1, 500, 60000); HMDNSLookup dnsHostCheckF(hostGroup2.getDNSType(), false, hostGroup2.getRemoteCheck()); m_currentState->m_dnsCache.insertDNSEntry(h1, dnsHostCheckF, 500, 60000); m_currentState->m_dnsCache.insertDNSEntry(h2, dnsHostCheckF, 500, 60000); ips.clear(); ips.insert(address3); m_currentState->m_dnsCache.updateDNSEntry(h1, dnsHostCheckF, ips); ips.clear(); ips.insert(address4); m_currentState->m_dnsCache.updateDNSEntry(h2, dnsHostCheckF, ips); m_currentState->m_dnsCache.finishQuery(h1, dnsHostCheckF, true); m_currentState->m_dnsCache.finishQuery(h2, dnsHostCheckF, true); m_currentState->m_remoteCache.insertRemoteEntry(hg1, 500, 60000); m_currentState->m_remoteCache.finishCheck(hg1, true); HMIPAddress addr(AF_INET); storage->m_writeCount = 0; remoteCheck = new TestHMWorkRemoteCheck(hg1, addr, check1, hostGroup1, results_hg1); remoteCheck->responseTime = 10; remoteCheck->updateState(&m_state, m_eventQueue); remoteCheck->m_ipAddress = addr; CPPUNIT_ASSERT(remoteCheck->processWork() == HM_WORK_COMPLETE_REMOTE); delete remoteCheck; std::vector<std::pair<HMDataCheckParams, HMDataCheckResult>> getResults; storage->m_writeCount = 0; healthCheck = new TestHMWorkHealthCheck(h1, address3, check2); healthCheck->responseTime = 10; healthCheck->updateState(&m_state, m_eventQueue); healthCheck->m_ipAddress = address3; CPPUNIT_ASSERT(healthCheck->processWork() == HM_WORK_COMPLETE); delete healthCheck; storage->m_writeCount = 0; healthCheck = new TestHMWorkHealthCheck(h2, address4, check2); healthCheck->responseTime = 10; healthCheck->updateState(&m_state, m_eventQueue); healthCheck->m_ipAddress = address4; CPPUNIT_ASSERT(healthCheck->processWork() == HM_WORK_COMPLETE); delete healthCheck; // query the results directly m_currentState->m_checkList.getCheckResults(h1, check2, address3, getResults); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params2); CPPUNIT_ASSERT(getResults[0].second.m_address == address3); CPPUNIT_ASSERT(getResults[0].second.m_numChecks == 1); CPPUNIT_ASSERT(getResults[0].second.m_responseTime == 10); CPPUNIT_ASSERT(getResults[0].second.m_response == HM_RESPONSE_CONNECTED); CPPUNIT_ASSERT(getResults[0].second.m_reason == HM_REASON_SUCCESS); // query the results directly m_currentState->m_checkList.getCheckResults(h2, check2, address4, getResults); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params2); CPPUNIT_ASSERT(getResults[0].second.m_address == address4); CPPUNIT_ASSERT(getResults[0].second.m_numChecks == 1); CPPUNIT_ASSERT(getResults[0].second.m_responseTime == 10); CPPUNIT_ASSERT(getResults[0].second.m_response == HM_RESPONSE_CONNECTED); CPPUNIT_ASSERT(getResults[0].second.m_reason == HM_REASON_SUCCESS); // query the results directly set<HMIPAddress> addresses; CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h1, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h2, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); { std::vector<std::pair<HMDataCheckParams, HMDataCheckResult>> getResults; HMDataHostCheck c = check1; CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h1, c, address1, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params1); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params1.getTimeout())); getResults.clear(); CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h2, c, address2, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params1); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params1.getTimeout())); vector<HMGroupCheckResult> results; CPPUNIT_ASSERT(m_currentState->m_datastore->getGroupCheckResults(hg1, results)); CPPUNIT_ASSERT_EQUAL(2, (int)results.size()); CPPUNIT_ASSERT(results[0].m_address == address1); CPPUNIT_ASSERT(results[0].m_hostName == h1); CPPUNIT_ASSERT(results[0].m_result.m_reason == checkResult1.m_reason); CPPUNIT_ASSERT(results[1].m_address == address2); CPPUNIT_ASSERT(results[1].m_hostName == h2); CPPUNIT_ASSERT(results[1].m_result.m_reason == checkResult2.m_reason); } std::this_thread::sleep_for(505ms); CPPUNIT_ASSERT_EQUAL(3, (int)m_state.m_workQueue.queueSize()); // Now check the work list unique_ptr<HMWork> work; bool threadStatus = false; m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(work->m_hostname == hg1); CPPUNIT_ASSERT(work->m_hostCheck == check1); CPPUNIT_ASSERT(work->m_ipAddress == addr); m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(work->m_hostname == h1); CPPUNIT_ASSERT(work->m_hostCheck == check2); CPPUNIT_ASSERT(work->m_ipAddress == address3); m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(work->m_hostname == h2); CPPUNIT_ASSERT(work->m_hostCheck == check2); CPPUNIT_ASSERT(work->m_ipAddress == address4); } void TESTNAME::test_HMWorkRemoteCheck_mixed_remote() { TestStorage* storage = dynamic_cast<TestStorage*>(m_currentState->m_datastore.get()); vector<HMGroupCheckResult> results_hg1; vector<HMGroupCheckResult> results_hg2; HMIPAddress address1; address1.set("1.2.3.4"); HMIPAddress address2; address2.set("4.5.6.7"); HMIPAddress address3; address3.set("4.3.2.1"); HMIPAddress address4; address4.set("7.6.5.4"); string h1 = "host1"; string h2 = "host2"; HMDataCheckResult checkResult1; checkResult1.m_checkTime = HMTimeStamp::now(); checkResult1.m_response = HM_RESPONSE_CONNECTED; checkResult1.m_reason = HM_REASON_SUCCESS; checkResult1.m_responseTime = 33; checkResult1.m_totalResponseTime = 66; checkResult1.m_smoothedResponseTime = 44; checkResult1.m_address = address1; HMDataCheckResult checkResult2; checkResult2.m_checkTime = HMTimeStamp::now(); checkResult2.m_response = HM_RESPONSE_FAILED; checkResult2.m_reason = HM_REASON_RESPONSE_TIMEOUT; checkResult2.m_address = address2; HMDataCheckResult checkResult3; checkResult3.m_checkTime = HMTimeStamp::now(); checkResult3.m_response = HM_RESPONSE_FAILED; checkResult3.m_reason = HM_REASON_RESPONSE_403; checkResult3.m_address = address3; HMDataCheckResult checkResult4; checkResult4.m_checkTime = HMTimeStamp::now(); checkResult4.m_response = HM_RESPONSE_FAILED; checkResult4.m_reason = HM_REASON_RESPONSE_5XX; checkResult4.m_address = address4; HMGroupCheckResult result1; result1.m_address = address1; result1.m_hostName = h1; result1.m_result = checkResult1; HMGroupCheckResult result2; result2.m_address = address2; result2.m_hostName = h2; result2.m_result = checkResult2; HMGroupCheckResult result3; result3.m_address = address3; result3.m_hostName = h1; result3.m_result = checkResult3; HMGroupCheckResult result4; result4.m_address = address4; result4.m_hostName = h2; result4.m_result = checkResult4; results_hg1.push_back(result1); results_hg1.push_back(result2); results_hg2.push_back(result3); results_hg2.push_back(result4); string hg1 = "HostGroup1"; string hg2 = "HostGroup2"; HMDataHostCheck check1; HMDataHostCheck check2; HMDataCheckParams params1; HMDataCheckParams params2; string checkParams = "/check.html"; HMDataHostGroup hostGroup1(hg1); hostGroup1.setCheckType(HM_CHECK_HTTP); hostGroup1.setCheckPlugin(HM_CHECK_PLUGIN_HTTP_CURL); hostGroup1.setPort(80); hostGroup1.setDualStack(HM_DUALSTACK_IPV4_ONLY); hostGroup1.setCheckInfo(checkParams); hostGroup1.setRemoteCheck("test1"); hostGroup1.setRemoteCheckType(HM_REMOTE_SHARED_CHECK_TCP); hostGroup1.setDistributedFallback(HM_DISTRIBUTED_FALLBACK_NONE); hostGroup1.setFlowType(HM_FLOW_REMOTE_HOSTGROUP_TYPE); hostGroup1.addHost(h1); hostGroup1.addHost(h2); hostGroup1.getHostCheck(check1); hostGroup1.getCheckParameters(params1); HMDataHostGroup hostGroup2(hg2); hostGroup2.setCheckType(HM_CHECK_HTTP); hostGroup2.setCheckPlugin(HM_CHECK_PLUGIN_HTTP_CURL); hostGroup2.setPort(800); hostGroup2.setDualStack(HM_DUALSTACK_IPV4_ONLY); hostGroup2.setCheckInfo(checkParams); hostGroup2.setRemoteCheck("test2"); hostGroup2.setRemoteCheckType(HM_REMOTE_SHARED_CHECK_TCP); hostGroup2.setDistributedFallback(HM_DISTRIBUTED_FALLBACK_NONE); hostGroup2.setFlowType(HM_FLOW_REMOTE_HOSTGROUP_TYPE); hostGroup2.addHost(h1); hostGroup2.addHost(h2); hostGroup2.getHostCheck(check2); hostGroup2.getCheckParameters(params2); m_currentState->m_hostGroups.insert(make_pair(hg1, hostGroup1)); m_currentState->m_hostGroups.insert(make_pair(hg2, hostGroup2)); set<HMIPAddress> ips; ips.insert(address1); m_currentState->m_checkList.insertCheck(hg1, h1, check1, params1, ips); ips.clear(); ips.insert(address2); m_currentState->m_checkList.insertCheck(hg1, h2, check1, params1, ips); ips.clear(); ips.insert(address3); m_currentState->m_checkList.insertCheck(hg2, h1, check2, params2, ips); ips.clear(); ips.insert(address4); m_currentState->m_checkList.insertCheck(hg2, h2, check2, params2, ips); HMDNSLookup lookup1(hostGroup1.getDNSType(), false, hostGroup1.getRemoteCheck()); HMDNSLookup lookup2(hostGroup2.getDNSType(), false, hostGroup2.getRemoteCheck()); m_currentState->m_dnsCache.insertDNSEntry(h1, lookup1, 500, 60000); m_currentState->m_dnsCache.insertDNSEntry(h2, lookup1, 500, 60000); m_currentState->m_dnsCache.insertDNSEntry(h1, lookup2, 500, 60000); m_currentState->m_dnsCache.insertDNSEntry(h2, lookup2, 500, 60000); m_currentState->m_remoteCache.insertRemoteEntry(hg1, 500, 60000); m_currentState->m_remoteCache.insertRemoteEntry(hg2, 500, 60000); m_currentState->m_remoteCache.finishCheck(hg1, true); m_currentState->m_remoteCache.finishCheck(hg2, true); HMIPAddress addr(AF_INET); storage->m_writeCount = 0; remoteCheck = new TestHMWorkRemoteCheck(hg1, addr, check1, hostGroup1, results_hg1); remoteCheck->responseTime = 10; remoteCheck->updateState(&m_state, m_eventQueue); remoteCheck->m_ipAddress = addr; CPPUNIT_ASSERT(remoteCheck->processWork() == HM_WORK_COMPLETE_REMOTE); delete remoteCheck; storage->m_writeCount = 0; remoteCheck = new TestHMWorkRemoteCheck(hg2, addr, check2, hostGroup2, results_hg2); remoteCheck->responseTime = 10; remoteCheck->updateState(&m_state, m_eventQueue); remoteCheck->m_ipAddress = addr; CPPUNIT_ASSERT(remoteCheck->processWork() == HM_WORK_COMPLETE_REMOTE); delete remoteCheck; // query the results directly set<HMIPAddress> addresses; CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h1, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); addresses.clear(); CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h2, HM_DUALSTACK_IPV4_ONLY, lookup1, addresses)); { std::vector<std::pair<HMDataCheckParams, HMDataCheckResult>> getResults; HMDataHostCheck c = check1; CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h1, c, address1, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params1); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params1.getTimeout())); getResults.clear(); CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h2, c, address2, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params1); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params1.getTimeout())); vector<HMGroupCheckResult> results; CPPUNIT_ASSERT(m_currentState->m_datastore->getGroupCheckResults(hg1, results)); CPPUNIT_ASSERT_EQUAL(2, (int)results.size()); CPPUNIT_ASSERT(results[0].m_address == address1); CPPUNIT_ASSERT(results[0].m_hostName == h1); CPPUNIT_ASSERT(results[0].m_result.m_reason == checkResult1.m_reason); CPPUNIT_ASSERT(results[1].m_address == address2); CPPUNIT_ASSERT(results[1].m_hostName == h2); CPPUNIT_ASSERT(results[1].m_result.m_reason == checkResult2.m_reason); } addresses.clear(); CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h1, HM_DUALSTACK_IPV4_ONLY, lookup2, addresses)); addresses.clear(); CPPUNIT_ASSERT(!m_currentState->m_dnsCache.getAddresses(h2, HM_DUALSTACK_IPV4_ONLY, lookup2, addresses)); // query the results directly { std::vector<std::pair<HMDataCheckParams, HMDataCheckResult>> getResults; HMDataHostCheck c = check2; CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h1, c, address3, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params2); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params2.getTimeout())); getResults.clear(); CPPUNIT_ASSERT(m_currentState->m_checkList.getCheckResults(h2, c, address4, getResults)); CPPUNIT_ASSERT(getResults.size() == 1); CPPUNIT_ASSERT(getResults[0].first == params2); CPPUNIT_ASSERT(getResults[0].second == HMDataCheckResult(params2.getTimeout())); vector<HMGroupCheckResult> results; CPPUNIT_ASSERT(m_currentState->m_datastore->getGroupCheckResults(hg2, results)); CPPUNIT_ASSERT_EQUAL(2, (int)results.size()); CPPUNIT_ASSERT(results[0].m_address == address3); CPPUNIT_ASSERT(results[0].m_hostName == h1); CPPUNIT_ASSERT(results[0].m_result.m_reason == checkResult3.m_reason); CPPUNIT_ASSERT(results[1].m_address == address4); CPPUNIT_ASSERT(results[1].m_hostName == h2); CPPUNIT_ASSERT(results[1].m_result.m_reason == checkResult4.m_reason); } std::this_thread::sleep_for(505ms); CPPUNIT_ASSERT_EQUAL(2, (int)m_state.m_workQueue.queueSize()); // Now check the work list unique_ptr<HMWork> work; bool threadStatus = false; m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(!(work->m_hostCheck != check1)); CPPUNIT_ASSERT(work->m_hostname == hg1); CPPUNIT_ASSERT(work->m_ipAddress == addr); m_state.m_workQueue.getWork(work, threadStatus); CPPUNIT_ASSERT(!(work->m_hostCheck != check2)); CPPUNIT_ASSERT(work->m_hostname == hg2); CPPUNIT_ASSERT(work->m_ipAddress == addr); }
39.014787
126
0.735041
[ "vector" ]
30292387611b2bf3af90e379362cec6b5da2529f
1,781
cpp
C++
bugs-operated/CursorManager.cpp
KnuckStudio/bugs-operated
d48d76b0e00a6e24716572dd1fbb35d7f4115f8c
[ "Apache-2.0" ]
1
2019-12-23T09:27:16.000Z
2019-12-23T09:27:16.000Z
jage/CursorManager.cpp
Rexagon/jage
560457b382fb250f3c5c385f45590c0537e2e9b8
[ "Apache-2.0" ]
null
null
null
jage/CursorManager.cpp
Rexagon/jage
560457b382fb250f3c5c385f45590c0537e2e9b8
[ "Apache-2.0" ]
null
null
null
#include "CursorManager.h" CursorManager::CursorStyle CursorManager::m_currentStyle = CursorManager::CursorStyle::NORMAL; sf::WindowHandle CursorManager::m_windowHandle = nullptr; #ifdef _WIN32 std::vector<HCURSOR> CursorManager::m_cursorIcons(STYLE_COUNT); #elif defined(__linux__) std::vector<XID> CursorManager::m_cursorIcons(STYLE_COUNT); Display* CursorManager::m_display = nullptr; #endif void CursorManager::init(const sf::WindowHandle & window_handle) { m_windowHandle = window_handle; #ifdef _WIN32 m_cursorIcons[CursorStyle::WAIT] = LoadCursor(NULL, IDC_WAIT); m_cursorIcons[CursorStyle::HAND] = LoadCursor(NULL, IDC_HAND); m_cursorIcons[CursorStyle::NORMAL] = LoadCursor(NULL, IDC_ARROW); m_cursorIcons[CursorStyle::TEXT] = LoadCursor(NULL, IDC_IBEAM); #elif defined(__linux__) m_display = XOpenDisplay(nullptr); m_cursorIcons[CursorStyle::WAIT] = XCreateFontCursor(m_display, XC_watch); m_cursorIcons[CursorStyle::HAND] = XCreateFontCursor(m_display, XC_hand1); m_cursorIcons[CursorStyle::NORMAL] = XCreateFontCursor(m_display, XC_left_ptr); m_cursorIcons[CursorStyle::TEXT] = XCreateFontCursor(m_display, XC_xterm); #endif } void CursorManager::close() { #ifdef __linux__ for (unsigned int i = 0; i < STYLE_COUNT; ++i) { XFreeCursor(m_display, m_cursorIcons[i]); } delete m_display; m_display = nullptr; #endif } void CursorManager::setStyle(const CursorStyle type) { if (type == STYLE_COUNT) { return; } #ifdef _WIN32 SetClassLongPtr(m_windowHandle, GCLP_HCURSOR, reinterpret_cast<LONG_PTR>(m_cursorIcons[type])); #elif defined(__linux__) XDefineCursor(m_display, m_windowHandle, m_cursorIcons[type]); XFlush(m_display); #endif m_currentStyle = type; } CursorManager::CursorStyle CursorManager::getStyle() { return m_currentStyle; }
28.725806
96
0.784391
[ "vector" ]
302bc60be7b25a1b0393260b4768f353b2564595
3,890
cpp
C++
src/MultimediaSystem.cpp
alexirae/CHIP-8-Interpreter
eabfe6d1c0ed2fc5ecb917786b26e7139b300532
[ "MIT" ]
null
null
null
src/MultimediaSystem.cpp
alexirae/CHIP-8-Interpreter
eabfe6d1c0ed2fc5ecb917786b26e7139b300532
[ "MIT" ]
null
null
null
src/MultimediaSystem.cpp
alexirae/CHIP-8-Interpreter
eabfe6d1c0ed2fc5ecb917786b26e7139b300532
[ "MIT" ]
null
null
null
#include "MultimediaSystem.h" MultimediaSystem::MultimediaSystem() : window(nullptr) , renderer(nullptr) , sdlTexture(nullptr) , windowWidth(0) , windowHeight(0) , renderTextureWidth(0) , renderTextureHeight(0) , wavBuffer(nullptr) , wavLength(0) , audioDeviceId(0) , numberOfKeys(0) { SDL_Init(SDL_INIT_EVERYTHING); } ///////////////////////////////////////////////////////////////////////////// void MultimediaSystem::initializeGraphics(const std::string& windowsName, const Uint32 windowW, const Uint32 windowH, const Uint32 renderTextureW, const Uint32 renderTextureH) { windowWidth = windowW; windowHeight = windowH; renderTextureWidth = renderTextureW; renderTextureHeight = renderTextureH; window = SDL_CreateWindow(windowsName.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, windowWidth, windowHeight, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); SDL_RenderPresent(renderer); sdlTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGB332, SDL_TEXTUREACCESS_STREAMING, renderTextureWidth, renderTextureHeight); } ///////////////////////////////////////////////////////////////////////////// void MultimediaSystem::initializeSound(const std::string& soundPath) { SDL_AudioSpec wavSpec; SDL_LoadWAV(soundPath.c_str(), &wavSpec, &wavBuffer, &wavLength); audioDeviceId = SDL_OpenAudioDevice(nullptr, 0, &wavSpec, nullptr, 0); SDL_PauseAudioDevice(audioDeviceId, 0); } ///////////////////////////////////////////////////////////////////////////// void MultimediaSystem::initializeInput(const Uint32 numKeys) { numberOfKeys = numKeys; keys.resize(numKeys, false); } ///////////////////////////////////////////////////////////////////////////// void MultimediaSystem::renderDisplay(const std::vector<Uint8>& display) { SDL_UpdateTexture(sdlTexture, nullptr, &display.front(), renderTextureWidth * sizeof(Uint8)); SDL_RenderCopy(renderer, sdlTexture, nullptr, nullptr); SDL_RenderPresent(renderer); } ///////////////////////////////////////////////////////////////////////////// void MultimediaSystem::handleInputEvents(bool& quit) { SDL_Event sdlEvent; while (SDL_PollEvent(&sdlEvent)) { const Uint8* currentKeyStates = SDL_GetKeyboardState(nullptr); if (currentKeyStates[SDL_SCANCODE_ESCAPE] || sdlEvent.type == SDL_QUIT) { quit = true; return; } keys[0] = currentKeyStates[SDL_SCANCODE_1]; keys[1] = currentKeyStates[SDL_SCANCODE_2]; keys[2] = currentKeyStates[SDL_SCANCODE_3]; keys[3] = currentKeyStates[SDL_SCANCODE_4]; keys[4] = currentKeyStates[SDL_SCANCODE_Q]; keys[5] = currentKeyStates[SDL_SCANCODE_W]; keys[6] = currentKeyStates[SDL_SCANCODE_E]; keys[7] = currentKeyStates[SDL_SCANCODE_R]; keys[8] = currentKeyStates[SDL_SCANCODE_A]; keys[9] = currentKeyStates[SDL_SCANCODE_S]; keys[10] = currentKeyStates[SDL_SCANCODE_D]; keys[11] = currentKeyStates[SDL_SCANCODE_F]; keys[12] = currentKeyStates[SDL_SCANCODE_Z]; keys[13] = currentKeyStates[SDL_SCANCODE_X]; keys[14] = currentKeyStates[SDL_SCANCODE_C]; keys[15] = currentKeyStates[SDL_SCANCODE_V]; } } ///////////////////////////////////////////////////////////////////////////// void MultimediaSystem::uninitialize() { SDL_CloseAudioDevice(audioDeviceId); SDL_FreeWAV(wavBuffer); SDL_Quit(); } /////////////////////////////////////////////////////////////////////////////
33.826087
176
0.587661
[ "vector" ]
30340d79defc0cbbb0354b4b0e932367002394c3
848
cpp
C++
codes/Leetcode/leetcode304.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/Leetcode/leetcode304.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/Leetcode/leetcode304.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
class NumMatrix { public: NumMatrix(vector<vector<int>>& matrix) { sum = matrix; for (int i = 0; i < sum.size(); ++i) { for (int j = 0; j < sum[i].size(); ++j) { if (i) sum[i][j] += sum[i-1][j]; if (j) sum[i][j] += sum[i][j-1]; if (i&&j) sum[i][j] -= sum[i-1][j-1]; } } } int sumRegion(int row1, int col1, int row2, int col2) { int ans = sum[row2][col2]; if (row1) ans -= sum[row1-1][col2]; if (col1) ans -= sum[row2][col1-1]; if (row1 && col1) ans += sum[row1-1][col1-1]; return ans; } vector<vector<int>> sum; }; /** * Your NumMatrix object will be instantiated and called as such: * NumMatrix* obj = new NumMatrix(matrix); * int param_1 = obj->sumRegion(row1,col1,row2,col2); */
29.241379
65
0.483491
[ "object", "vector" ]
303d36e1fd2d93766e01c690b5b74b605e9bfd54
5,301
cpp
C++
open_cascade_demos/demo_bezier_surface/main.cpp
RoberAgro/primer_open_cascade
8eae9192e8a796e543ac6b1509430a5367b7650b
[ "MIT" ]
8
2020-02-04T19:50:29.000Z
2022-01-01T06:52:39.000Z
open_cascade_demos/demo_bezier_surface/main.cpp
RoberAgro/primer_open_cascade
8eae9192e8a796e543ac6b1509430a5367b7650b
[ "MIT" ]
null
null
null
open_cascade_demos/demo_bezier_surface/main.cpp
RoberAgro/primer_open_cascade
8eae9192e8a796e543ac6b1509430a5367b7650b
[ "MIT" ]
null
null
null
// ------------------------------------------------------------------------------------------------------------------- // // // Demonstration script showing how to create a Bezier surface in OpenCascade // Author: Roberto Agromayor // // ------------------------------------------------------------------------------------------------------------------ // // Include standard C++ libraries #include <iostream> #include <sys/stat.h> #include <cmath> // Include OpenCascade libraries #include <gp_Pnt.hxx> #include <Geom_BezierSurface.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Wire.hxx> #include <TopoDS_Face.hxx> #include <BRep_Tool.hxx> #include <BRepBuilderAPI_MakeEdge.hxx> #include <BRepBuilderAPI_MakeWire.hxx> #include <BRepBuilderAPI_MakeFace.hxx> #include <STEPControl_Writer.hxx> // Define namespaces using namespace std; // ------------------------------------------------------------------------------------------------------------------ // // Step file exporter // ------------------------------------------------------------------------------------------------------------------ // IFSelect_ReturnStatus write_step_file(const string &relative_path, const string &model_name, const TopoDS_Shape &model_object) { // Create the .step writer object STEPControl_Writer step_writer; // Set the type of .step representation STEPControl_StepModelType step_mode = STEPControl_StepModelType::STEPControl_AsIs; // Create the output directory if it does not exist mkdir(relative_path.c_str(), 0777); // 0007 is used to give the user permissions to read+write+execute // Get the full path to the step file as a C-string string temp = (relative_path + model_name + ".step"); Standard_CString file_name = temp.c_str(); // Write the .step file step_writer.Transfer(model_object, step_mode); IFSelect_ReturnStatus status = step_writer.Write(file_name); return status; } // ------------------------------------------------------------------------------------------------------------------ // // Main body // ------------------------------------------------------------------------------------------------------------------ // int main() { // -------------------------------------------------------------------------------------------------------------- // // Define the array of control points // -------------------------------------------------------------------------------------------------------------- // // Declare the array Standard_Integer rowLower = 1, rowUpper = 5; Standard_Integer colLower = 1, colUpper = 3; TColgp_Array2OfPnt P(rowLower, rowUpper, colLower, colUpper); // First row P(1, 1) = gp_Pnt(0.00, 0.0, 0.0); P(2, 1) = gp_Pnt(0.25, 0.0, 0.0); P(3, 1) = gp_Pnt(0.50, 0.0, 0.0); P(4, 1) = gp_Pnt(0.75, 0.0, 0.0); P(5, 1) = gp_Pnt(1.00, 0.0, 0.0); // Second row P(1, 2) = gp_Pnt(0.00, 0.5, 0.0); P(2, 2) = gp_Pnt(0.25, 0.5, 1.0); P(3, 2) = gp_Pnt(0.50, 0.5, 1.0); P(4, 2) = gp_Pnt(0.75, 0.5, 1.0); P(5, 2) = gp_Pnt(1.00, 0.5, 0.0); // Third row P(1, 3) = gp_Pnt(0.00, 1.0, 0.0); P(2, 3) = gp_Pnt(0.25, 1.0, 0.0); P(3, 3) = gp_Pnt(0.50, 1.0, 0.0); P(4, 3) = gp_Pnt(0.75, 1.0, 0.0); P(5, 3) = gp_Pnt(1.00, 1.0, 0.0); // -------------------------------------------------------------------------------------------------------------- // // Define the geometry and topology of a Bezier surface // -------------------------------------------------------------------------------------------------------------- // // Define the geometry of a Bezier surface referenced by handle Handle(Geom_BezierSurface) BezierGeo = new Geom_BezierSurface(P); // Define the topology of the Bezier surface using the BRepBuilderAPI TopoDS_Face BezierFace = BRepBuilderAPI_MakeFace(BezierGeo, 0); // Get the geometric surface from the topological face and check the bounds in parametric space [Optional] Handle(Geom_Surface) BezierGeo_bis = BRep_Tool::Surface (BezierFace); double u_lower, u_upper, v_lower, v_upper; BezierGeo_bis->Bounds(u_lower, u_upper, v_lower, v_upper); // -------------------------------------------------------------------------------------------------------------- // // Export the model as a STEP file // -------------------------------------------------------------------------------------------------------------- // // Create a TopoDS_Shape object to export as .step TopoDS_Shape open_cascade_model = BezierFace; // Set the destination path and the name of the .step file string relative_path = "../output/"; string file_name = "bezier_surface"; // Write the .step file write_step_file(relative_path, file_name, open_cascade_model); // -------------------------------------------------------------------------------------------------------------- // // Visualize the geometry in a graphical user interface (for instance the FreeCAD GUI) // -------------------------------------------------------------------------------------------------------------- // string open_gui = "FreeCAD --single-instance " + relative_path + file_name + ".step"; system(open_gui.c_str()); return 0; }
38.977941
121
0.46312
[ "geometry", "object", "model" ]
303e5cf75aa27fed79a95fa7508d3697216171e9
579
cpp
C++
cf/Div2/B/Little Girl and Game /main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/B/Little Girl and Game /main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
cf/Div2/B/Little Girl and Game /main.cpp
wdjpng/soi
dd565587ae30985676f7f374093ec0687436b881
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long #define double long double using namespace std; signed main() { // Turn off synchronization between cin/cout and scanf/printf ios_base::sync_with_stdio(false); // Disable automatic flush of cout when reading from cin cin.tie(0); cin.tie(0); string a, b; cin >> a; vector<int> m(30); for (int i = 0; i < a.size(); ++i) m[a[i]-'a']++; int c=0; for (int i = 0; i < 30; ++i) { c+=m[i]%2; } if(c<2||c%2){ cout << "First"; } else{ cout << "Second"; } }
19.965517
72
0.53886
[ "vector" ]
303f80ea40f389bd6abe5f29f95473ea1a4b3eed
3,069
cpp
C++
EngineTest/Main.cpp
Neko81795/CBREngine
3ea100f09110d55fcbcadb23c246d47ed46c5121
[ "CC-BY-4.0", "MIT" ]
2
2015-08-30T00:26:45.000Z
2015-11-13T05:58:30.000Z
EngineTest/Main.cpp
Neko81795/CBREngine
3ea100f09110d55fcbcadb23c246d47ed46c5121
[ "CC-BY-4.0", "MIT" ]
1
2015-11-25T06:28:13.000Z
2015-11-25T06:30:32.000Z
EngineTest/Main.cpp
Neko81795/CBREngine
3ea100f09110d55fcbcadb23c246d47ed46c5121
[ "CC-BY-4.0", "MIT" ]
null
null
null
#include "../MistThread/Core.h" #include "../MistThread/Graphics.h" #include "SpinComponent.h" #include "SinXComponent.h" #include "ZLayerComponent.h" #include "KeyMoveComponent.h" #include "SoundPulseComponent.h" #include "ParticleSystem.h" #include "ParticleDataComponent.h" #include "ForceComponent.h" #include "Random.h" #include "../MistThread/Input.h" #include "../MistThread/Audio/Sound.h" #include "../MistThread/Audio/Engines/FMODAudioEngine.h" #include "../MistThread/IO.h" #include "../MistThread/Utilities.h" #include <string> //TODO REMOVE THIS SHIT IT'S BAD PRACTICE using namespace MistThread; using namespace MistThread::Core; using namespace MistThread::Core::GameObjects; using namespace MistThread::Core::GameObjects::Components; using XMLElement = MistThread::IO::XML::XMLElement; using AppInfo = MistThread::Utilities::AppInfo; using ContentManager = MistThread::Utilities::ContentManager; //YUP YUP MORE BAD PRACTICE HERE using namespace MistThread::Audio; using namespace MistThread::Audio::Engines; //If you wanna see some real bad practice you should see GameObjectBase.cpp int WINAPI WinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/, LPSTR /*lpCmdLine*/, int nShowCmd) { //TODO: (Matthew) -- Sound does not properly dispose when the component it is attached to is deleted. Check out the //destructor in the Sound object to make sure everything is properly disposing, and all handles are being //delt with accordingly. Write test to do this. //get info about this application AppInfo appInfo; std::string hostName = appInfo.GetHostName(); std::string WorkingDir = appInfo.GetCurrentWorkingDirectory(); //note that this is not actually necessary as paths will default to this location ContentManager::RootFolder = WorkingDir; //set up the game GameWindow gameWindow("MistThread Test oh boy"); MistThread::Graphics::Engines::DirectXGraphicsEngine graphics(gameWindow); MistThread::Audio::Engines::FMODAudioEngine audio = MistThread::Audio::Engines::FMODAudioEngine(); MistThread::Input::Engines::DirectXInputEngine input(gameWindow); Game game(&gameWindow, &graphics, &audio, &input); //register our components Game::RegisterComponent<KeyMoveComponent>("KeyMove"); Game::RegisterComponent<SpinComponent>("Spin"); Game::RegisterComponent<ZLayerComponent>("ZLayer"); Game::RegisterComponent<SinXComponent>("SinX"); Game::RegisterComponent<SoundPulseComponent>("SoundPulse"); Game::RegisterComponent<ParticleSystem>("ParticleSystem"); Game::RegisterComponent<ParticleDataComponent>("ParticleData"); Game::RegisterComponent<ForceComponent>("Force"); //get the space and load a level Space &mainSpace = game.FindSpaceByName("Main"); if (hostName == "Hera") { mainSpace.LoadLevel("Level.xml"); } else if (hostName == "Ghost") { mainSpace.LoadLevel("Level3.xml"); } else if (hostName == "Bird_Noises") { mainSpace.LoadLevel("Luna.xml"); } else { mainSpace.LoadLevel("Level.xml"); } //start the game game.Start(); return 0; }
33.725275
118
0.747801
[ "object" ]
3049fc1001a5bd7b4bee54e5e888a21b29f8b4c6
370
hpp
C++
include/cur.hpp
overlorde/Otris
c5b45381cb80194993b940749dd5a8b6cca2490c
[ "MIT" ]
1
2020-10-01T07:22:09.000Z
2020-10-01T07:22:09.000Z
include/cur.hpp
overlorde/Otris
c5b45381cb80194993b940749dd5a8b6cca2490c
[ "MIT" ]
1
2020-10-01T07:36:03.000Z
2020-10-01T08:06:00.000Z
include/cur.hpp
overlorde/Otris
c5b45381cb80194993b940749dd5a8b6cca2490c
[ "MIT" ]
3
2020-09-07T06:55:50.000Z
2020-10-01T07:28:14.000Z
#ifndef CUR_HPP_ #define CUR_HPP_ // //if we want to move the cursor in a program // //we only need a cur object //which we will use throughout the program files #include<iostream> using namespace std; class Cur{ public: void saveCur(); //saves cursor void moveCur(const int x,const int y); //moves cursor void resumeCur(); //resumes the cursor }; #endif
18.5
55
0.708108
[ "object" ]
304d12dc90cef90069cce12280bfc7f5029f0906
4,137
hh
C++
RAVL2/PatternRec/Classify/ClassifierFunc1Threshold.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/PatternRec/Classify/ClassifierFunc1Threshold.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/PatternRec/Classify/ClassifierFunc1Threshold.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2003, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here #ifndef RAVL_CLASSIFYFUNC1THRESHOLD_HEADER #define RAVL_CLASSIFYFUNC1THRESHOLD_HEADER 1 //! rcsid="$Id: ClassifierFunc1Threshold.hh 5240 2005-12-06 17:16:50Z plugger $" //! lib=RavlPatternRec //! author="Charles Galambos" //! docentry="Ravl.API.Pattern Recognition.Classifier" //! date="9/3/2003" //! file="Ravl/PatternRec/Classify/ClassifierFunc1Threshold.hh" #include "Ravl/PatternRec/Classifier.hh" #include "Ravl/PatternRec/Function1.hh" #include "Ravl/BinStream.hh" namespace RavlN { //! userlevel=Develop //: Binary Classifier, based on a function and threshold. class ClassifierFunc1ThresholdBodyC : public ClassifierBodyC { public: ClassifierFunc1ThresholdBodyC(const Function1C &nfunc,RealT nthreshold); //: Constructor. ClassifierFunc1ThresholdBodyC(istream &strm); //: Load from stream. ClassifierFunc1ThresholdBodyC(BinIStreamC &strm); //: Load from binary stream. virtual bool Save (ostream &out) const; //: Writes object to stream, can be loaded using constructor virtual bool Save (BinOStreamC &out) const; //: Writes object to stream, can be loaded using constructor virtual UIntT Classify(const VectorC &data) const; //: Classifier vector 'data' return the most likely label. virtual VectorC Confidence(const VectorC &data) const; //: Estimate the confidence for each label. Function1C &Function() { return func; } //: Access discrminant function. RealT Threshold() const { return threshold; } //: Access threshold. protected: Function1C func; RealT threshold; }; //! userlevel=Normal //: Binary Classifier, based on a function and threshold. class ClassifierFunc1ThresholdC : public ClassifierC { public: ClassifierFunc1ThresholdC() {} //: Default constructor. ClassifierFunc1ThresholdC(const Function1C &nfunc,RealT nthreshold) : ClassifierC(*new ClassifierFunc1ThresholdBodyC(nfunc,nthreshold)) {} //: Constructor. ClassifierFunc1ThresholdC(istream &strm); //: Load from stream. ClassifierFunc1ThresholdC(BinIStreamC &strm); //: Load from binary stream. protected: ClassifierFunc1ThresholdC(ClassifierFunc1ThresholdBodyC &bod) : ClassifierC(bod) {} //: Body constructor. ClassifierFunc1ThresholdC(ClassifierFunc1ThresholdBodyC *bod) : ClassifierC(bod) {} //: Body constructor. ClassifierFunc1ThresholdBodyC &Body() { return static_cast<ClassifierFunc1ThresholdBodyC &>(ClassifierC::Body()); } //: Access body. const ClassifierFunc1ThresholdBodyC &Body() const { return static_cast<const ClassifierFunc1ThresholdBodyC &>(ClassifierC::Body()); } //: Access body. public: Function1C &Function() { return Body().Function(); } //: Access discrminant function. RealT Threshold() const { return Body().Threshold(); } //: Access threshold. }; inline istream &operator>>(istream &strm,ClassifierFunc1ThresholdC &obj) { obj = ClassifierFunc1ThresholdC(strm); return strm; } //: Load from a stream. // Uses virtual constructor. inline ostream &operator<<(ostream &out,const ClassifierFunc1ThresholdC &obj) { obj.Save(out); return out; } //: Save to a stream. // Uses virtual constructor. inline BinIStreamC &operator>>(BinIStreamC &strm,ClassifierFunc1ThresholdC &obj) { obj = ClassifierFunc1ThresholdC(strm); return strm; } //: Load from a binary stream. // Uses virtual constructor. inline BinOStreamC &operator<<(BinOStreamC &out,const ClassifierFunc1ThresholdC &obj) { obj.Save(out); return out; } //: Save to a stream. // Uses virtual constructor. } #endif
27.397351
89
0.690839
[ "object", "vector" ]
30519216ad0580d2419e5cd03d34a4650c5e2277
3,020
cpp
C++
test/perf_test.cpp
chrismanning/jbson
2e5ca71f3300d9d5d7e59e64f2d9ece32d96716f
[ "BSL-1.0" ]
37
2015-02-02T16:39:00.000Z
2022-01-25T15:45:08.000Z
test/perf_test.cpp
chrismanning/jbson
2e5ca71f3300d9d5d7e59e64f2d9ece32d96716f
[ "BSL-1.0" ]
null
null
null
test/perf_test.cpp
chrismanning/jbson
2e5ca71f3300d9d5d7e59e64f2d9ece32d96716f
[ "BSL-1.0" ]
6
2015-06-22T11:40:22.000Z
2022-01-25T15:45:12.000Z
// Copyright Christian Manning 2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <fstream> #include <gtest/gtest.h> #include <jbson/json_reader.hpp> #include <jbson/json_writer.hpp> using namespace jbson; class PerfTest : public ::testing::Test { public: virtual void SetUp() { std::ifstream ifs(JBSON_FILES "/json_test_suite_sample.json"); ASSERT_FALSE(ifs.fail()); ifs.seekg(0, std::ios::end); auto n = static_cast<std::streamoff>(ifs.tellg()); json_.resize(n); ifs.seekg(0, std::ios::beg); ifs.read(json_.data(), n); // whitespace test whitespace_.resize((1024 * 1024) + 3); char* p = whitespace_.data(); for(size_t i = 0; i < whitespace_.size() - 3; i += 4) { *p++ = ' '; *p++ = '\n'; *p++ = '\r'; *p++ = '\t'; } *p++ = '['; *p++ = '0'; *p++ = ']'; ASSERT_NO_THROW(doc = read_json(json_)); } virtual void TearDown() { } protected: std::vector<char> json_; std::u16string json_u16; std::u32string json_u32; std::vector<char> whitespace_; document doc; static const size_t kTrialCount = 1000; }; TEST_F(PerfTest, WriteTest) { for(size_t i = 0; i < kTrialCount; i++) { auto str = std::string{}; ASSERT_NO_THROW(write_json(doc, std::back_inserter(str))); } } TEST_F(PerfTest, ParseTest) { for(size_t i = 0; i < kTrialCount; i++) { ASSERT_NO_THROW(read_json(json_)); } } #ifndef BOOST_NO_CXX11_HDR_CODECVT TEST_F(PerfTest, Utf16ParseTest) { std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> cvt{}; json_u16 = cvt.from_bytes(json_.data(), json_.data() + json_.size()); for(size_t i = 0; i < kTrialCount; i++) { ASSERT_NO_THROW(read_json(json_u16)); } } TEST_F(PerfTest, Utf32ParseTest) { std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> cvt{}; json_u32 = cvt.from_bytes(json_.data(), json_.data() + json_.size()); for(size_t i = 0; i < kTrialCount; i++) { ASSERT_NO_THROW(read_json(json_u32)); } } #endif // BOOST_NO_CXX11_HDR_CODECVT TEST_F(PerfTest, WhitespaceTest) { for(size_t i = 0; i < kTrialCount; i++) { auto arr = read_json_array(whitespace_); auto beg = arr.begin(); ASSERT_NE(arr.end(), beg); ASSERT_EQ("0", beg->name()); ASSERT_EQ(0, beg->value<int32_t>()); } } TEST_F(PerfTest, ParseToSetTest) { for(size_t i = 0; i < kTrialCount; i++) { auto set = document_set(read_json(json_)); } } TEST(NoFixPerfTest, BuildTest) { for(int32_t i = 0; i < 1000000; i++) { auto build = builder("foo", builder("bar", builder("baz", array_builder(i)(2)(3)))); auto d = document(std::move(build)); ASSERT_EQ(1, boost::distance(d)); } }
27.207207
92
0.588742
[ "vector" ]
3052be3203edf6a816c991590f58daf469dd87de
3,662
hpp
C++
legion/engine/rendering/systems/particle_system_manager.hpp
Rythe-Interactive/Legion-Engine.rythe-legacy
e199689024436c40054942796ce9dcd4d097d7fd
[ "MIT" ]
null
null
null
legion/engine/rendering/systems/particle_system_manager.hpp
Rythe-Interactive/Legion-Engine.rythe-legacy
e199689024436c40054942796ce9dcd4d097d7fd
[ "MIT" ]
null
null
null
legion/engine/rendering/systems/particle_system_manager.hpp
Rythe-Interactive/Legion-Engine.rythe-legacy
e199689024436c40054942796ce9dcd4d097d7fd
[ "MIT" ]
null
null
null
#pragma once #include <core/core.hpp> #include <rendering/data/particle_system_base.hpp> #include <rendering/components/point_emitter_data.hpp> namespace legion::rendering { /** * @class ParticleSystemManager * @brief The class used to update all particles in every emitter. */ class ParticleSystemManager : public System<ParticleSystemManager> { public: ParticleSystemManager() { ParticleSystemBase::m_registry = m_ecs; } /** * @brief Sets up the particle system manager. */ void setup() { createProcess<&ParticleSystemManager::update>("Update"); } /** * @brief Every frame, goes through every emitter and updates their particles with their respective particle systems. * @param deltaTime The delta time to be used inside of the update. */ void update(time::span deltaTime) { OPTICK_EVENT(); static auto emitters = createQuery<particle_emitter>(); emitters.queryEntities(); for (auto entity : emitters) { //Gets emitter handle and emitter. auto emitterHandle = entity.get_component_handle<particle_emitter>(); auto emit = emitterHandle.read(); //Checks if emitter was already initialized. if (!emit.setupCompleted) { //If NOT then it goes through the particle system setup. emit.setupCompleted = true; emitterHandle.write(emit); const ParticleSystemBase* particleSystem = emit.particleSystemHandle.get(); particleSystem->setup(emitterHandle); } else { //If it IS then it runs the emitter through the particle system update. const ParticleSystemBase* particleSystem = emit.particleSystemHandle.get(); particleSystem->update(emit.livingParticles, emitterHandle, emitters, deltaTime); } } //update point cloud buffer data static auto pointCloudQuery = createQuery<particle_emitter, rendering::point_emitter_data>(); pointCloudQuery.queryEntities(); std::vector<math::vec4> colorData; int index = 0; for (auto pointEntities : pointCloudQuery) { auto emitterHandle = pointEntities.get_component_handle<particle_emitter>(); auto emitter = emitterHandle.read(); const ParticleSystemBase* particleSystem = emitter.particleSystemHandle.get(); auto dataHandle = pointEntities.get_component_handle<rendering::point_emitter_data>(); auto data = dataHandle.read(); index++; if (index == pointCloudQuery.size()) { auto window = ecs::EcsRegistry::world.read_component<app::window>(); app::context_guard guard(window); if (guard.contextIsValid()) { ////create buffer rendering::buffer colorBuffer = rendering::buffer(GL_ARRAY_BUFFER, emitter.container->colorBufferData, GL_STREAM_DRAW); particleSystem->m_particleModel.overwrite_buffer(colorBuffer, SV_COLOR, true); log::debug(std::to_string(emitter.container->colorBufferData.size())); } } } } }; }
40.241758
143
0.565811
[ "vector" ]
305ce4937a710edf5517e2555c9f537c0e2da7a2
5,928
cpp
C++
ltl2fsm/modules/Ltl_To_Nba_Module.cpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
2
2016-11-23T14:31:55.000Z
2018-05-10T01:11:54.000Z
ltl2fsm/modules/Ltl_To_Nba_Module.cpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
null
null
null
ltl2fsm/modules/Ltl_To_Nba_Module.cpp
arafato/ltl2fsm
58d96c40fe0890c2bcc90593469668e6369c0f1b
[ "MIT" ]
null
null
null
/** * @file ltl2fsm/modules/Ltl_To_Nba_Module.cpp * * $Id$ * * @author Oliver Arafat * * @brief @ref * * @note DOCUMENTED * * @test * * @todo */ #include <ltl2fsm/modules/Ltl_To_Nba_Module.hpp> #include <ltl2fsm/representation/Graphviz_Representation.hpp> #include <ltl2fsm/automaton/Nondet_Buechi_Automaton.impl.hpp> // Exceptions #include <ltl2fsm/base/exception/Fork_Error.hpp> #include <ltl2fsm/base/exception/Invalid_Ltl_Syntax.hpp> // needed by fork-routines #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> // needed to check whether file generated by ltl->nba is empty #include <fstream> #include <iostream> #include <sstream> LTL2FSM__BEGIN__NAMESPACE__LTL2FSM; #if LTL2FSM_DEBUG__LEVEL__ > 1 void Ltl_To_Nba_Module::m_class_invariance() const { //LTL2FSM_AUDIT_ASSERT_LOG(Fork_Error,1==4); } #endif Ltl_To_Nba_Module::Ltl_To_Nba_Module() : Module(), m_toolpath("./tools/ltlnba/"), m_tmppath("/tmp/"), m_tool_name("ltl2nba_f"), m_tmp_file("LTL2FSM__gv_ltl2nba.XXXXXX") { LTL2FSM_AUDIT_METHOD_GUARD(""); // Setting to default paths LTL2FSM_AUDIT_CLASS_INVARIANCE_ASSERT; } Ltl_To_Nba_Module::Ltl_To_Nba_Module(::std::string const & toolpath, ::std::string const & tmppath) : Module(), m_toolpath(toolpath), m_tmppath(tmppath), m_tool_name("ltl2nba_f"), m_tmp_file("LTL2FSM__gv_ltl2nba.XXXXXX") { LTL2FSM_AUDIT_METHOD_GUARD(""); LTL2FSM_AUDIT_CLASS_INVARIANCE_ASSERT; } Ltl_To_Nba_Module::~Ltl_To_Nba_Module() { LTL2FSM_AUDIT_METHOD_GUARD(""); LTL2FSM_AUDIT_CLASS_INVARIANCE_ASSERT; // add code here } bool Ltl_To_Nba_Module::empty_file(::std::string const & name) const { LTL2FSM_METHOD_GUARD(""); ::std::ifstream file(name.c_str()); ::std::string::size_type length; file.seekg(0, ::std::ios::end); if((length = file.tellg()) <= 1){ file.close(); return true; } file.close(); return false; } void Ltl_To_Nba_Module::add_peripheries(::std::string const & name) const { LTL2FSM_METHOD_GUARD(""); ::std::ifstream file(name.c_str()); file.seekg(0); ::std::ostringstream output_file; ::std::string full_line; ::std::string::size_type length; char line[256]; while (file.getline(line, 256)){ full_line = line; length = full_line.find("shape="); if(length != ::std::string::npos){ length = full_line.find("peripheries=2"); if(length == ::std::string::npos){ length = full_line.find("]"); full_line = full_line.substr(0, length); full_line.append(", peripheries=1];"); } } output_file << full_line << ::std::endl; } file.close(); ::std::ofstream mod_file(complete_tmppath().c_str()); mod_file << output_file.str(); mod_file.close(); } void Ltl_To_Nba_Module::add_epsilon_labels(::std::string const & name) const { LTL2FSM_METHOD_GUARD(""); ::std::ifstream file(name.c_str()); file.seekg(0); ::std::ostringstream output_file; ::std::string full_line; ::std::string::size_type length; char line[256]; while (file.getline(line, 256)){ full_line = line; length = full_line.find("init ->"); if(length != ::std::string::npos){ length = full_line.find(';'); full_line = full_line.substr(0, length); full_line.append(" [label=\"epsilon\"];"); } output_file << full_line << ::std::endl; } file.close(); ::std::ofstream mod_file(complete_tmppath().c_str()); mod_file << output_file.str(); mod_file.close(); } Ltl_To_Nba_Module::NBA_t * const Ltl_To_Nba_Module::execute(::std::string const & ltl_formula) { LTL2FSM_METHOD_GUARD(""); pid_t pid; int status_pointer = 1; ::std::string const tmp_path_file(complete_tmppath()); ::std::string const tool_path_file(complete_toolpath()); if((pid = fork()) == -1) throw Fork_Error(LTL2FSM__SOURCE_LOCATION, ::std::string("Unable to fork current process!") ); // Unfortunately, when creating a unique signature for a temporary // file we cannot delete it afterwards, although the return value of // remove is 0. Using a fixed name for now... // int fd; // if ( ( fd = mkstemp( tmp_file ) ) == -1 ) // ::std::cerr << "Could not create temporary file!" << ::std::endl; // else // close( fd ); if(pid){ if(waitpid(pid, &status_pointer, 0) != pid) status_pointer = -1; } else{ execl(tool_path_file.c_str(), m_tool_name.c_str(), ltl_formula.c_str(), tmp_path_file.c_str(), 0); _exit(EXIT_FAILURE); } if(empty_file(tmp_path_file)){ remove(tmp_path_file.c_str()); throw Invalid_Ltl_Syntax(LTL2FSM__SOURCE_LOCATION, ::std::string("Incorrect ltl-syntax: '" + ltl_formula + "'")); } add_epsilon_labels(tmp_path_file); add_peripheries(tmp_path_file); ::boost::GraphvizDigraph graph; ::boost::read_graphviz(tmp_path_file, graph); NBA_t * const nba = new NBA_t(new Representation_t(graph)); // cleaning up... remove(tmp_path_file.c_str()); return nba; } ::std::string const & Ltl_To_Nba_Module::tmp_path() const { LTL2FSM_METHOD_GUARD(""); return m_tmppath; } ::std::string const & Ltl_To_Nba_Module::tool_path() const { LTL2FSM_METHOD_GUARD(""); return m_toolpath; } ::std::string const & Ltl_To_Nba_Module::tool_name() const { LTL2FSM_METHOD_GUARD(""); return m_tool_name; } ::std::string const & Ltl_To_Nba_Module::tmp_file() const { LTL2FSM_METHOD_GUARD(""); return m_tmp_file; } ::std::string const Ltl_To_Nba_Module::complete_toolpath() const { LTL2FSM_METHOD_GUARD(""); return ::std::string(m_toolpath + m_tool_name); } ::std::string const Ltl_To_Nba_Module::complete_tmppath() const { LTL2FSM_METHOD_GUARD(""); return ::std::string(m_tmppath + m_tmp_file); } LTL2FSM__END__NAMESPACE__LTL2FSM;
23.338583
99
0.663124
[ "shape" ]
30655a0e85fd3dffeb8d4b274b22b4318fba84f4
22,961
cpp
C++
ds/security/services/scerpc/escprov/eventlog.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/security/services/scerpc/escprov/eventlog.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/security/services/scerpc/escprov/eventlog.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// eventlog.cpp: implementation of the CEventLogSettings class. // // Copyright (c)1997-1999 Microsoft Corporation // ////////////////////////////////////////////////////////////////////// #include "precomp.h" #include "eventlog.h" #include "persistmgr.h" #include <io.h> #include "requestobject.h" #define KeySize L"MaximumLogSize" #define KeyRet L"RetentionPeriod" #define KeyDays L"RetentionDays" #define KeyRestrict L"RestrictGuestAccess" /* Routine Description: Name: CEventLogSettings::CEventLogSettings Functionality: This is the constructor. Pass along the parameters to the base class Virtual: No (you know that, constructor won't be virtual!) Arguments: pKeyChain - Pointer to the ISceKeyChain COM interface which is prepared by the caller who constructs this instance. pNamespace - Pointer to WMI namespace of our provider (COM interface). Passed along by the caller. Must not be NULL. pCtx - Pointer to WMI context object (COM interface). Passed along by the caller. It's up to WMI whether this interface pointer is NULL or not. Return Value: None as any constructor Notes: if you create any local members, think about initialize them here */ CEventLogSettings::CEventLogSettings ( IN ISceKeyChain * pKeyChain, IN IWbemServices * pNamespace, IN IWbemContext * pCtx ) : CGenericClass(pKeyChain, pNamespace, pCtx) { } /* Routine Description: Name: CEventLogSettings::~CEventLogSettings Functionality: Destructor. Necessary as good C++ discipline since we have virtual functions. Virtual: Yes. Arguments: none as any destructor Return Value: None as any destructor Notes: if you create any local members, think about whether there is any need for a non-trivial destructor */ CEventLogSettings::~CEventLogSettings() { } /* Routine Description: Name: CEventLogSettings::CreateObject Functionality: Create WMI objects (Sce_EventLog). Depending on parameter atAction, this creation may mean: (a) Get a single instance (atAction == ACTIONTYPE_GET) (b) Get several instances satisfying some criteria (atAction == ACTIONTYPE_QUERY) (c) Delete an instance (atAction == ACTIONTYPE_DELETE) Virtual: Yes. Arguments: pHandler - COM interface pointer for notifying WMI for creation result. atAction - Get single instance ACTIONTYPE_GET Get several instances ACTIONTYPE_QUERY Delete a single instance ACTIONTYPE_DELETE Return Value: Success: it must return success code (use SUCCEEDED to test). It is not guaranteed to return WBEM_NO_ERROR. The returned objects are indicated to WMI, not directly passed back via parameters. Failure: Various errors may occurs. Except WBEM_E_NOT_FOUND, any such error should indicate the failure of getting the wanted instance. If WBEM_E_NOT_FOUND is returned in querying situations, this may not be an error depending on caller's intention. Notes: */ HRESULT CEventLogSettings::CreateObject ( IN IWbemObjectSink * pHandler, IN ACTIONTYPE atAction ) { // // we know how to: // Get single instance ACTIONTYPE_GET // Delete a single instance ACTIONTYPE_DELETE // Get several instances ACTIONTYPE_QUERY // if ( ACTIONTYPE_GET != atAction && ACTIONTYPE_DELETE != atAction && ACTIONTYPE_QUERY != atAction ) { return WBEM_E_NOT_SUPPORTED; } // // We must have the pStorePath property because that is where // our instance is stored. // m_srpKeyChain->GetKeyPropertyValue WBEM_S_FALSE if the key is not recognized // So, we need to test against WBEM_S_FALSE if the property is mandatory // CComVariant varStorePath; HRESULT hr = m_srpKeyChain->GetKeyPropertyValue(pStorePath, &varStorePath); if (SUCCEEDED(hr) && hr != WBEM_S_FALSE && varStorePath.vt == VT_BSTR) { CComVariant varType; hr = m_srpKeyChain->GetKeyPropertyValue(pType, &varType); if (FAILED(hr)) { return hr; } else if (hr == WBEM_S_FALSE && (ACTIONTYPE_QUERY != atAction) ) { return WBEM_E_NOT_FOUND; } // // Create the event log instance // CSceStore SceStore; hr = SceStore.SetPersistPath(varStorePath.bstrVal); if ( SUCCEEDED(hr) ) { // // make sure the store (just a file) really exists. The raw path // may contain env variables, so we need the expanded path // DWORD dwAttrib = GetFileAttributes(SceStore.GetExpandedPath()); if ( dwAttrib != -1 ) { if ( ACTIONTYPE_DELETE == atAction ) { hr = DeleteInstance(pHandler, &SceStore, varType.bstrVal); } else { BOOL bPostFilter=TRUE; DWORD dwCount = 0; m_srpKeyChain->GetKeyPropertyCount(&dwCount); if ( varType.vt == VT_EMPTY && dwCount == 1 ) { bPostFilter = FALSE; } hr = ConstructInstance(pHandler, &SceStore, varStorePath.bstrVal, (varType.vt == VT_BSTR) ? varType.bstrVal : NULL, bPostFilter ); } } else { hr = WBEM_E_NOT_FOUND; } } } return hr; } /* Routine Description: Name: CEventLogSettings::PutInst Functionality: Put an instance as instructed by WMI. Since this class implements Sce_EventLog, which is persistence oriented, this will cause the Sce_EventLog object's property information to be saved in our store. Virtual: Yes. Arguments: pInst - COM interface pointer to the WMI class (Sce_EventLog) object. pHandler - COM interface pointer for notifying WMI of any events. pCtx - COM interface pointer. This interface is just something we pass around. WMI may mandate it (not now) in the future. But we never construct such an interface and so, we just pass around for various WMI API's Return Value: Success: it must return success code (use SUCCEEDED to test). It is not guaranteed to return WBEM_NO_ERROR. Failure: Various errors may occurs. Any such error should indicate the failure of persisting the instance. Notes: Since GetProperty will return a success code (WBEM_S_RESET_TO_DEFAULT) when the requested property is not present, don't simply use SUCCEEDED or FAILED macros to test for the result of retrieving a property. */ HRESULT CEventLogSettings::PutInst ( IN IWbemClassObject * pInst, IN IWbemObjectSink * pHandler, IN IWbemContext * pCtx ) { HRESULT hr = WBEM_E_INVALID_PARAMETER; CComBSTR bstrLogType; DWORD dwSize=SCE_NO_VALUE; DWORD dwRet=SCE_NO_VALUE; DWORD dwDays=SCE_NO_VALUE; DWORD dwRestrict=SCE_NO_VALUE; DWORD idxLog=0; // // our CSceStore class manages the persistence. // CSceStore SceStore; // // CScePropertyMgr helps us to access wbem object's properties // create an instance and attach the wbem object to it. // This will always succeed. // CScePropertyMgr ScePropMgr; ScePropMgr.Attach(pInst); // // the use of the macro SCE_PROV_IfErrorGotoCleanup cause // a "goto CleanUp;" with hr set to the return value from // the function (macro parameter) // SCE_PROV_IfErrorGotoCleanup(ScePropMgr.GetProperty(pOverwritePolicy, &dwRet)); if ( dwRet == 1 ) { // // by days // SCE_PROV_IfErrorGotoCleanup(ScePropMgr.GetProperty(pRetentionPeriod, &dwDays)); // // SCE_NO_VALUE indicates that the property is not properly set. // if ( dwDays == SCE_NO_VALUE ) { hr = WBEM_E_ILLEGAL_NULL; goto CleanUp; } else if ( dwDays == 0 || dwDays > 365 ) { hr = WBEM_E_VALUE_OUT_OF_RANGE; goto CleanUp; } } // // otherwise ignore the RetentionPeriod parameter // // // if the property doesn't exist (NULL or empty), WBEM_S_RESET_TO_DEFAULT is returned // SCE_PROV_IfErrorGotoCleanup(ScePropMgr.GetProperty(pSize, &dwSize)); if ( dwSize != SCE_NO_VALUE ) { // // min 64K, max 4194240K, increment by 64K // if ( dwSize < 64 || dwSize > 4194240L ) { hr = WBEM_E_VALUE_OUT_OF_RANGE; goto CleanUp; } else { if ( dwSize % 64 ) { dwSize = (dwSize/64 + 1) * 64; } } } SCE_PROV_IfErrorGotoCleanup(ScePropMgr.GetProperty(pType, &bstrLogType)); // // check if the category is valid. Won't allow invalid category // SCE_PROV_IfErrorGotoCleanup(ValidateEventlogType(bstrLogType, &idxLog)); SCE_PROV_IfErrorGotoCleanup(ScePropMgr.GetProperty(pRestrictGuestAccess, &dwRestrict)); // // Attach the WMI object instance to the store and let the store know that // it's store is given by the pStorePath property of the instance. // hr = SceStore.SetPersistProperties(pInst, pStorePath); // // now save the info to file // if ( SUCCEEDED(hr) ) { hr = SaveSettingsToStore(&SceStore, (PCWSTR)bstrLogType, dwSize, dwRet, dwDays, dwRestrict ); } CleanUp: return hr; } /* Routine Description: Name: CEventLogSettings::ConstructInstance Functionality: This is private function to create an instance of Sce_EventLog. Virtual: No. Arguments: pHandler - COM interface pointer for notifying WMI of any events. pSceStore - Pointer to our store. It must have been appropriately set up. wszLogStorePath - store path, a key property of Sce_EventLog class. wszLogType - another corresponding property of the Sce_EventLog class. bPostFilter - Controls how WMI will be informed with pHandler->SetStatus. Return Value: Success: it must return success code (use SUCCEEDED to test). It is not guaranteed to return WBEM_NO_ERROR. Failure: Various errors may occurs. Any such error should indicate the creating the instance. Notes: */ HRESULT CEventLogSettings::ConstructInstance ( IN IWbemObjectSink * pHandler, IN CSceStore * pSceStore, IN LPCWSTR wszLogStorePath, IN LPCWSTR wszLogType, IN BOOL bPostFilter ) { // // make sure that we have a valid store // if ( pSceStore == NULL || pSceStore->GetStoreType() < SCE_INF_FORMAT || pSceStore->GetStoreType() > SCE_JET_ANALYSIS_REQUIRED ) { return WBEM_E_INVALID_PARAMETER; } HRESULT hr = WBEM_S_NO_ERROR; DWORD idxLog=0; if ( wszLogType ) { hr = ValidateEventlogType(wszLogType, &idxLog); if ( FAILED(hr) ) { return hr; } } // // ask SCE to read a gigantic structure out from the store. Only SCE // knows now to release the memory. Don't just delete it! Use our CSceStore // to do the releasing (FreeSecurityProfileInfo) // PSCE_PROFILE_INFO pInfo = NULL; hr = pSceStore->GetSecurityProfileInfo( AREA_SECURITY_POLICY, &pInfo, NULL ); // // the use of the macro SCE_PROV_IfErrorGotoCleanup cause // a "goto CleanUp;" with hr set to the return value from // the function (macro parameter) // if (SUCCEEDED(hr)) { CComBSTR bstrLogOut; SCE_PROV_IfErrorGotoCleanup(MakeSingleBackSlashPath(wszLogStorePath, L'\\', &bstrLogOut)); // // CScePropertyMgr helps us to access WMI object's properties. // CScePropertyMgr ScePropMgr; for ( DWORD i=idxLog; SUCCEEDED(hr) && i<3; i++) { if ( pInfo->MaximumLogSize[i] == SCE_NO_VALUE && pInfo->AuditLogRetentionPeriod[i] == SCE_NO_VALUE && pInfo->RetentionDays[i] == SCE_NO_VALUE && pInfo->RestrictGuestAccess[i] == SCE_NO_VALUE ) { if ( wszLogType ) { hr = WBEM_E_NOT_FOUND; } continue; } PCWSTR szType = GetEventLogType(i); if ( !szType ) { continue; } CComPtr<IWbemClassObject> srpObj; SCE_PROV_IfErrorGotoCleanup(SpawnAnInstance(&srpObj)); // // attach a different WMI object to the property manager. // This will always succeed. // ScePropMgr.Attach(srpObj); // // we won't allow the store path and type info to be missing // SCE_PROV_IfErrorGotoCleanup(ScePropMgr.PutProperty(pStorePath, bstrLogOut)); SCE_PROV_IfErrorGotoCleanup(ScePropMgr.PutProperty(pType, szType)); // // SCE_NO_VALUE indicates that the pInfo doesn't have that value // for the rest of the properties, we will allow them to be missing. // if ( pInfo->MaximumLogSize[i] != SCE_NO_VALUE ) { SCE_PROV_IfErrorGotoCleanup(ScePropMgr.PutProperty(pSize, pInfo->MaximumLogSize[i]) ); } if ( pInfo->AuditLogRetentionPeriod[i] != SCE_NO_VALUE ) { SCE_PROV_IfErrorGotoCleanup(ScePropMgr.PutProperty(pOverwritePolicy, pInfo->AuditLogRetentionPeriod[i]) ); } if ( pInfo->RetentionDays[i] != SCE_NO_VALUE ) { SCE_PROV_IfErrorGotoCleanup(ScePropMgr.PutProperty(pRetentionPeriod, pInfo->RetentionDays[i]) ); } if ( pInfo->RestrictGuestAccess[i] != SCE_NO_VALUE ) { SCE_PROV_IfErrorGotoCleanup(ScePropMgr.PutProperty(pRestrictGuestAccess, pInfo->RestrictGuestAccess[i]) ); } // // do the necessary gestures to WMI. // the use of WBEM_STATUS_REQUIREMENTS in SetStatus is not documented by WMI // at this point. Consult WMI team for detail if you suspect problems with // the use of WBEM_STATUS_REQUIREMENTS // if ( !bPostFilter ) { pHandler->SetStatus(WBEM_STATUS_REQUIREMENTS, S_FALSE, NULL, NULL); } else { pHandler->SetStatus(WBEM_STATUS_REQUIREMENTS, S_OK, NULL, NULL); } // // pass the new instance to WMI // hr = pHandler->Indicate(1, &srpObj); // if it's not query, do one instance only if ( wszLogType ) { break; } } } CleanUp: pSceStore->FreeSecurityProfileInfo(pInfo); return hr; } /* Routine Description: Name: CEventLogSettings::DeleteInstance Functionality: remove an instance of Sce_EventLog from the specified store. Virtual: No. Arguments: pHandler - COM interface pointer for notifying WMI of any events. pSceStore - Pointer to our store. It must have been appropriately set up. wszLogType - another corresponding property of the Sce_EventLog class. Return Value: Success: WBEM_NO_ERROR. Failure: WBEM_E_INVALID_PARAMETER Notes: */ HRESULT CEventLogSettings::DeleteInstance ( IN IWbemObjectSink * pHandler, IN CSceStore * pSceStore, IN LPCWSTR wszLogType ) { // // make sure that we have a valid store // if ( pSceStore == NULL || pSceStore->GetStoreType() < SCE_INF_FORMAT || pSceStore->GetStoreType() > SCE_JET_ANALYSIS_REQUIRED ) { return WBEM_E_INVALID_PARAMETER; } pSceStore->DeleteSectionFromStore(wszLogType); return WBEM_NO_ERROR; } /* Routine Description: Name: CEventLogSettings::ValidateEventlogType Functionality: Validate the event log type. Virtual: No. Arguments: wszLogType - string representing the log type. pIndex - passing back DWORD representation about type of log Return Value: Success: WBEM_NO_ERROR. Failure: WBEM_E_INVALID_PARAMETER. Notes: */ HRESULT CEventLogSettings::ValidateEventlogType ( IN LPCWSTR wszLogType, IN DWORD * pIndex ) { HRESULT hr = WBEM_NO_ERROR; if ( wszLogType == NULL || pIndex == NULL ) { return WBEM_E_INVALID_PARAMETER; } if ( _wcsicmp(wszLogType, pwApplication) == 0 ) { *pIndex = 2; } else if ( _wcsicmp(wszLogType, pwSystem) == 0 ) { *pIndex = 0; } else if ( _wcsicmp(wszLogType, pwSecurity) == 0 ) { *pIndex = 1; } else { *pIndex = 10; hr = WBEM_E_INVALID_PARAMETER; } return hr; } /* Routine Description: Name: CEventLogSettings::SaveSettingsToStore Functionality: Validate the event log type. Virtual: No. Arguments: pSceStore - the store pointer to do the saving. Section - the section name where the information will be saved. dwSize - corresponding property of the Sce_EvengLog class. dwRet - corresponding property of the Sce_EvengLog class. dwDays - corresponding property of the Sce_EvengLog class. dwRestrict - corresponding property of the Sce_EvengLog class. Return Value: Success: WBEM_NO_ERROR. Failure: WBEM_E_INVALID_PARAMETER. Notes: */ HRESULT CEventLogSettings::SaveSettingsToStore ( IN CSceStore * pSceStore, IN LPCWSTR Section, IN DWORD dwSize, IN DWORD dwRet, IN DWORD dwDays, IN DWORD dwRestrict ) { HRESULT hr = WBEM_S_NO_ERROR; HRESULT hrTmp; DWORD dwDump; // // the use of the macro SCE_PROV_IfErrorGotoCleanup cause // a "goto CleanUp;" with hr set to the return value from // the function (macro parameter) // // // For a new .inf file. Write an empty buffer to the file // will creates the file with right header/signature/unicode format // this is harmless for existing files. // For database store, this is a no-op. // SCE_PROV_IfErrorGotoCleanup(pSceStore->WriteSecurityProfileInfo( AreaBogus, (PSCE_PROFILE_INFO)&dwDump, NULL, false ) ); // // Size // SCE_PROV_IfErrorGotoCleanup(pSceStore->SavePropertyToStore( Section, KeySize, dwSize ) ); // // Retention // SCE_PROV_IfErrorGotoCleanup(pSceStore->SavePropertyToStore( Section, KeyRet, dwRet ) ); // // Days // SCE_PROV_IfErrorGotoCleanup(pSceStore->SavePropertyToStore( Section, KeyDays, dwDays ) ); // // Restrict // SCE_PROV_IfErrorGotoCleanup(pSceStore->SavePropertyToStore( Section, KeyRestrict, dwRestrict ) ); CleanUp: return hr; } /* Routine Description: Name: GetEventLogType Functionality: Helper to get the string representation of log type from dword representation. Virtual: No. Arguments: idx - DWORD representation of the log type Return Value: Success: string representation of log type Failure: NULL Notes: */ PCWSTR GetEventLogType ( IN DWORD idx ) { switch ( idx ) { case 0: return pwSystem; break; case 1: return pwSecurity; break; case 2: return pwApplication; break; default: return NULL; break; } return NULL; }
25.569042
123
0.537433
[ "object" ]
306a0b0255e1bf48cb7fa65ced2dd9d7e4f64707
94,663
cpp
C++
src/EulerUnsteady2D_basic_package.cpp
LukeMcCulloch/cfd_solvers_cpp
69a6e8fde0e6b963a4d6d9e94f8241786d9088c5
[ "MIT" ]
5
2019-06-20T11:13:16.000Z
2022-03-30T07:31:12.000Z
src/EulerUnsteady2D_basic_package.cpp
LukeMcCulloch/cfd_solvers_cpp
69a6e8fde0e6b963a4d6d9e94f8241786d9088c5
[ "MIT" ]
null
null
null
src/EulerUnsteady2D_basic_package.cpp
LukeMcCulloch/cfd_solvers_cpp
69a6e8fde0e6b963a4d6d9e94f8241786d9088c5
[ "MIT" ]
1
2020-11-25T13:25:55.000Z
2020-11-25T13:25:55.000Z
/* * * THE MESHING MODULE * */ //******************************************************************************** //* Educationally-Designed Unstructured 2D (EDU2D) Code //* //* //* //* This module belongs to the inviscid version: EDU2D-Euler-RK2 //* //* //* //* This file contains 4 modules: //* //* 1. module EulerSolver2D - Some numerical values, e.g., zero, one, pi, etc. //* 2. module EulerSolver2D_type - Grid data types: node, edge, face, element, etc. //* 3. module EulerSolver2D - Parameters and arrays mainly used in a solver. //* 4. module EulerSolver2D - Subroutines for dynamic allocation //* 5. module EulerSolver2D - Subroutines for reading/constructing/checking grid data //* //* All data in the modules can be accessed by the use statement, e.g., 'use constants'. //* //* //* //* written by Dr. Katate Masatsuka (info[at]cfdbooks.com), //* translated to C++ by Luke McCulloch, PhD. //* //* the author of useful CFD books, "I do like CFD" (http://www.cfdbooks.com). //* //* This is Version 0 (July 2015). //* This F90 code is written and made available for an educational purpose. //* This file may be updated in future. //* //******************************************************************************** //******************************************************************************** //******************************************************************************** //******************************************************************************** //******************************************************************************** //******************************************************************************** //* 1. module EulerSolver2D //* //* Some useful constants are defined here. //* They can be accessed by the use statement, 'use constants'. //* //* //* written by Dr. Katate Masatsuka (info[at]cfdbooks.com), //* translated to C++ by Luke McCulloch, PhD. //* //* the author of useful CFD books, "I do like CFD" (http://www.cfdbooks.com). //* //* This is Version 0 (July 2015). -> C++ June 2019 //* In the spirit of its fortran parent, //* This C++ code is written and made available for an educational purpose. //* This file may be updated in future. //* //******************************************************************************** //====================================== // 2D Euler approximate Riemann sovler #include "../include/EulerUnsteady2D_basic_package.h" //====================================== // i/o #include <iostream> // cout, std::fixed #include <fstream> // write to file //====================================== // line based parsing, including streams #include <sstream> #include <string> //====================================== // mesh-y math-y functions #include "../include/MathGeometry.h" //====================================== // string trimfunctions #include "StringOps.h" using std::cout; using std::endl; // constructors and destrutors that do nothing //EulerSolver2D::MainData2D::MainData2D() {} //EulerSolver2D::MainData2D::~MainData2D() { // if () //} //******************************************************************************** //******************************************************************************** //******************************************************************************** //******************************************************************************** //******************************************************************************** //* 5. module EulerSolver2D //* //* This module contians subroutines used for reading a grid, constructing //* additional grid data, and check the grid data. //* //* - my_alloc_int_ptr : Allocate/reallocate an integer 1D array //* - my_alloc_p2_ptr : Allcoate/reallocate a real 1D array //* - my_alloc_p2_matrix_ptr : Allcoate/reallocate a real 2D array //* //* //* Public subroutines: //* //* - read_grid : Read a grid file, allocate necessary data. //* - construct_grid_data : Construct additional data, allocate more data. //* - check_grid_data : Check the whole grid data. //* //* Private functions and subroutines: //* //* - tri_area : Computed a triangle area //* - check_skewness_nc : Compute the skewness (e*n). //* - compute_ar : Compute aspect ratio at node and element. //* //* //* //* written by Dr. Katate Masatsuka (info[at]cfdbooks.com), //* //* the author of useful CFD books, "I do like CFD" (http://www.cfdbooks.com). //* //* This is Version 0 (July 2015). //* This F90 code is written and made available for an educational purpose. //* This file may be updated in future. //* //******************************************************************************** //namespace EulerSolver2D{ //******************************************************************************** //* Read the grid and the exact solution. //* ------------------------------------------------------------------------------ //* Input: datafile_grid_in = filename of the grid file //* datafile_bcmap_in = filename of the bc file //* //* Output: nnodes, ncells, node(:), elm(:), bound(:) = data used in the solver //* ------------------------------------------------------------------------------ //* //******************************************************************************** //* 1. "datafile_grid_in" is assumed to have been written in the following format: //* //* ----------------------------------------------------------------------- //* cout << nnodes, ntria, nquad //Numbers of nodes, triangles and quads //* //* do i = 1, nnodes //* cout << x(i), y(i) //(x,y) coordinates of each node //* end do //* //* do i = 1, ntria //Nodes of triangles ordered counterclockwise //* cout << node_1(i), node_2(i), node_3(i) //* end do //* //* do i = 1, nquad //Nodes of quadrilaterals ordered counterclockwise //* cout << node_1(i), node_2(i), node_3(i), node_4(i) //* end do //* //* cout << nbound //Number of boundary segments //* //* do i = 1, nbound //* cout << nbnodes(i) //Number of nodes on each segment //* end do //* //* do i = 1, nbound //* do j = 1, nbnodes(i) //* cout << bnode(j) //Node number of each node j in segment i //* end do //* end do //* ----------------------------------------------------------------------- //* //* NOTE: Add the first node to the end if the segment is closed //* (e.g., airfoil) The number of nodes will be the actual number + 1 //* in that case. //* //* NOTE: Boundary nodes must be ordered such that the domain is on the left. //* //******************************************************************************** //* //* 2. "datafile_bcmap_in" is assumed have been written in the following format: //* //* ----------------------------------------------------------------------- //* cout << "Boundary Segment Boundary Condition" //* do i = 1, nbound //* cout << i, bc_name //* end do //* ----------------------------------------------------------------------- //* //* NOTE: bc_name is the name of the boundary condition, e.g., //* //* 1. "freestream" //* Roe flux with freestream condition on the right state. //* //* 2. "slip_wall" //* Solid wall condition. Mass flux through the boundary is set zero. //* //* 3. "outflow_supersonic" //* Just compute the boundary flux by the physical Euler flux //* (equivalent to the interior-extrapolation condition.) //* //* 4. "outflow_back_pressure" //* Fix the back pressure. This should work for subsonic flows in a //* large enough domain. //* //* Something like the above needs to be implemented in a solver. //* //******************************************************************************** //* Data to be read and stored: //* //* 1. Some numbers //* nnodes = Number of nodes //* ntria = Number of triangular elements //* nquad = Number of quadrilateral elements //* nelms = Total number of elements (=ntria+nquad) //* //* 2. Element data: //* elm(1:nelms).nvtx = Number of vertices of each element //* elm(1:nelms).vtx(:) = Pointer to vertices of each element //* //* 3. Node data: nodes are stored in a 1D array //* node(1:nnodes).x = x-coordinate of the nodes //* node(1:nnodes).y = y-coordinate of the nodes //* //* 4. Boundary Data: //* nbound = Number of boundary segments //* bound(1:nbound).nbnodes = Number of nodes in each segment //* bound(1:nbound).bnode(:) = List of node numbers for each segment //* bound(1:nbound).bc_type = Boundary condition name for each segment //* bound(1:nbound).bc_type = Boundary condition name for each segment //* //******************************************************************************** void EulerSolver2D::MainData2D::read_grid(std::string datafile_grid_in, std::string datafile_bcmap_in) { /* * This is inside out from the C++ perspective. * 'Somebody' needs to read the grid and figure * out how many nodes we have. * Then create a MainData2D instance and allocate node arrays * within the constructor. */ //use EulerSolver2D, only : nnodes, node, ntria, nquad, nelms, elm, nbound, bound //Local variables int i, j, os, dummy_int; //-------------------------------------------------------------------------------- // 1. Read grid file>: datafile_grid_in cout << "Reading the grid file...." << datafile_grid_in << endl; // Open the input file. std::ifstream infile; infile.open(datafile_grid_in); // line based parsing, using string streams: std::string line; // READ: Get the size of the grid. std::getline(infile, line); std::istringstream iss(line); iss >> nnodes >> ntria >> nquad; cout << "Found... " << " nnodes = " << nnodes << " ntria = " << ntria << " nquad = " << nquad << endl; nelms = ntria + nquad; // // Allocate node and element arrays. //std::cout << "Allocating node_type" << std::endl; //std::cout << " for " << nnodes << " nodes " << std::endl; node = new node_type[nnodes]; //std::cout << " Allocating elm_type" << std::endl; //std::cout << " for " << nelms << " elements " << std::endl; elm = new elm_type[nelms]; // // READ: Read the nodal coordinates cout << "reading nodal coords" << endl; for (size_t i = 0; i < nnodes; i++) { std::getline(infile, line); std::istringstream iss(line); iss >> node[i].x >> node[i].y ; // could declare here: // node[i].u = new Array2D<real>(nq,1); // node[i].du = new Array2D<real>(nq,1); // node[i].w = new Array2D<real>(nq,1); // node[i].gradw = new Array2D<real>(nq,2); //<- 2: x and y components. // node[i].res = new Array2D<real>(nq,1); //node[i].nelms = 0; //if (i< 200) std::cout << i << " " << node[i].x << " " << node[i].y << std::endl; } //cout << "done reading nodal coords" << endl; // Read element-connectivity information // Triangles: assumed that the vertices are ordered counterclockwise // // v3 // /\ // / \ // / \ // / \ // / \ // /__________\ // v1 v2 // READ: read connectivity info for triangles if (ntria > 0) { for (size_t i = 0; i < ntria; i++) { std::getline(infile, line); std::istringstream in(line); elm[i].nvtx = 3; elm[i].vtx = new Array2D<int>(3,1); //std::string type; //in >> type; //and read the first whitespace-separated token int x, y, z; in >> x >> y >> z; //now read the whitespace-separated ints // Fix indices for 0 indexed code// (*elm[i].vtx)(0) = x-1; (*elm[i].vtx)(1) = y-1; (*elm[i].vtx)(2) = z-1; //cout << (*elm[i].vtx).ncols << endl; // if (i<20) cout << "\nInput = " << (*elm[i].vtx)(0) << // " " << (*elm[i].vtx)(1) << // " " << (*elm[i].vtx)(2) ; // if (i>ntria-20) cout << "\nInput = " << (*elm[i].vtx)(0) << // " " << (*elm[i].vtx)(1) << // " " << (*elm[i].vtx)(2) ; } } // // Quads: assumed that the vertices are ordered counterclockwise // // // // v4________v3 // // / | // // / | // // / | // // / | // // / | // // /_____________| // // v1 v2 // // READ: read connectivity info for quadrilaterals if (nquad > 0) { for (size_t i = 0; i < nquad; i++) { std::getline(infile, line); std::istringstream in(line); elm[ntria+i].nvtx = 4; elm[ntria+i].vtx = new Array2D<int>(4,1); int x1,x2,x3,x4; in >> x1 >> x2 >> x3 >> x4; //now read the whitespace-separated ...ints // Fix indices for 0 indexed code// (*elm[ntria+i-1].vtx)(0) = x1-1; (*elm[ntria+i-1].vtx)(1) = x2-1; (*elm[ntria+i-1].vtx)(2) = x3-1; (*elm[ntria+i-1].vtx)(3) = x4-1; // if (i<20) cout << "\nx, y, z = " << x1 <<" " << x2 << " " << x3 << x4; // if (i<20) cout << "\nelm x, elm y, elm z = " << (*elm[i].vtx)(0,0) <<" " << (*elm[i].vtx)(1,0) << " " << (*elm[i].vtx)(2,0)<< " " << (*elm[i].vtx)(3,0); // if (i<20) cout << "\nelm x, elm y, elm z = " << (*elm[i].vtx)(0) <<" " << (*elm[i].vtx)(1) << " " << (*elm[i].vtx)(2) << " " << (*elm[i].vtx)(3); } } else{ cout << "\nNo Quads in this Mesh\n" << endl; } // Write out the grid data. cout << " " << endl; cout << " Total numbers:" << endl; cout << " nodes = " << nnodes << endl; cout << " triangles = " << ntria << endl; cout << " nquad = " << nquad << endl; cout << " nelms = " << nelms << endl; // Read the boundary grid data // READ: Number of boundary condition types std::getline(infile, line); std::istringstream in(line); in >> nbound; bound = new bgrid_type[nbound]; cout << "\n nbound = " << nbound << "\n" <<endl; // // READ: Number of Boundary nodes (including the starting one at the end if // // it is closed such as an airfoil.) for (size_t i = 0; i < nbound; i++) { std::getline(infile, line); std::istringstream in(line); in >> bound[i].nbnodes; //cout << "Got in bnodes = " << bound[i].nbnodes << endl; bound[i].bnode = new Array2D<int>(bound[i].nbnodes , 1); } // // READ: Read boundary nodes cout << "Reading boundary nodes" << endl; std::getline(infile, line); //TLM: need to skip line here for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbnodes; j++) { std::getline(infile, line); std::istringstream in(line); int init; in >> init; //(*bound[i].bnode)[j][0] = init; //TLM bnode issue : we are reading in indices that // were starting from 1, but our code starts form 0// (*bound[i].bnode)(j,0) = init-1; //cout << i << " " << j << " " << (*bound[i].bnode)(j,0) << endl; // if ( j>bound[i].nbnodes-21 ) { // cout << (*bound[i].bnode)(j,0) << endl; // } //cout << (*bound[i].bnode)(j,0) << " " << init << endl; // testing array access: //int some = (*bound[i].bnode)[j][0]; //cout << "get some " << some << endl; } } cout << "Done Reading boundary nodes" << endl; // Print the boundary grid data. std::cout << " Boundary nodes:" << std::endl; std::cout << " segments = " << nbound << std::endl; for (size_t i = 0; i < nbound; i++) { std::cout << " boundary = " << i << " bnodes = " << bound[i].nbnodes << " bfaces = " << bound[i].nbnodes-1 << std::endl; } infile.close(); // close datafile_grid_in // End of Read grid file>: datafile_grid_in //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // 2. Read the boundary condition data file std::cout << "" << std::endl; std::cout << "Reading the boundary condition file...." << datafile_bcmap_in << std::endl; std::cout << "" << std::endl; // // Open the input file. std::ifstream outfile; outfile.open (datafile_bcmap_in); std::getline(outfile, line); // READ: Read the boundary condition type for (size_t i = 0; i < nbound; i++) { std::getline(outfile, line); std::istringstream in(line); in >> dummy_int >> bound[i].bc_type; } // Print the data std::cout << " Boundary conditions:" << std::endl; for (size_t i = 0; i < nbound; i++) { std::cout << " boundary" << i << " bc_type = " << bound[i].bc_type << std::endl; } std::cout << "" << std::endl; // close(2) outfile.close(); // close datafile_bcmap_in // End of Read the boundary condition data file //-------------------------------------------------------------------------------- return; } // end function read_grid //******************************************************************************** //* Construct the grid data: //* //* The following data, needed for NCFV method, will be constructed based on the //* data read from the grid file. //* //* 1. Element data: //* elm(:).nnghbrs = Number of element neighbors of each element //* elm(:).nghbr(:) = List of element neighbors of each element //* elm(:).x = x-coordinate of the centroid //* elm(:).y = y-coordinate of the centroid //* elm(:).vol = Volume of the element //* //* //* 2. Node data: //* node(:).nnghbrs = Number of node neighbors of each node //* node(:).nghbr(:)= List of node neighbors of each node //* node(:).nelms = Number of adjacent elements of each node //* node(:).elm = List of adjacent elements of each node //* node(:).vol = Volume of the dual volume around each node //* //* 3. Edge data: //* edge(:).n1, n2 = End nodes of each edge (edge points n1 -> n2) //* edge(:).e1, e2 = Left and right elements of each edge //* edge(:).dav = Unit directed area vector of each edge //* edge(:).da = Magnitude of the directed area vector for each edge //* edge(:).ev = Unit edge vector of each edge (vector n1 -> n2) //* edge(:).e = Magnitude of the edge vector for each edge //* //* //* 4. Boudnary data //* bound(:).bnx = Outward normal at boundary nodes (x-component of unit vector) //* bound(:).bny = Outward normal at boundary nodes (y-component of unit vector) //* bound(:).bn = Magnitude of (bnx,bny) //* NOTE: In this code, the above normal vector at boundary nodes is computed by //* a quadratic fit. It is sufficiently accuarte for 3rd-order schemes. //* See http://www.hiroakinishikawa.com/My_papers/nishikawa_jcp2015v281pp518-555_preprint.pdf //* for details on the quadratic approximation for computing more accurate normals. //* bound(:).bfnx = Outward normal at boundary nodes (x-component of unit vector) //* bound(:).bfny = Outward normal at boundary nodes (y-component of unit vector) //* bound(:).bfn = Magnitude of (bfnx,bfny) //* bound(:).belm = Element to which the boundary face belongs //* //******************************************************************************** void EulerSolver2D::MainData2D::construct_grid_data(){ // //Local variables int i, j, k, ii, in, im, jelm, v1, v2, v3, v4; real x1, x2, x3, x4, y1, y2, y3, y4, xm, ym, xc, yc; real xj, yj, xm1, ym1, xm2, ym2, dsL,dsR,dx,dy; bool found; int vL, vR, n1, n2, e1, e2; int vt1, vt2, ielm; int ave_nghbr, min_nghbr, max_nghbr, imin, imax; int iedge; // real(p2) :: ds real ds; // // Some initialization v2 = 0; vL = -1; im = 0; jelm = 0; cout << " " << endl; cout << "construct grid data...." << endl; // // Initializations for (size_t i = 0; i < nnodes; i++) { node[i].nelms = 0; } nedges = 0; cout << "\nnnodes = " << nnodes << endl; cout << "nelms = " << nelms << "\n" << endl; //-------------------------------------------------------------------------------- // Loop over elements and construct the fololowing data. // // 1. Surrounding elements: node(:).nelms, node(:).elm(:) // // Example: Node i is surrounded by the eleemnts, 23, 101, 13, 41. // node[i].nelms = 4 // node[i].elm(1) = 23 // node[i].elm(2) = 13 // node[i].elm(3) = 41 // node[i].elm(4) = 101 // // o-------o-------------o // / | . | // / 23 | 41 | // o----------o-------------o // \ i \ | // \ 101 \ 13 | // \ \ | // o----------o---------o // // 2. Element quantities : elm(:).x,elm(:).y,elm(:).vol // // o-----------o // \ | o // \ (x,y)| / \ // \ . | / \ // \ | / . \ (x,y): centroid coordinates // \ | / (x,y) \ vol: volume of element // o-----o o---------o // elements : do i = 1, nelms // for ( int i = 0; i < nelms; ++i ) { // v1 = (*elm[i].vtx)(0,0); // v2 = (*elm[i].vtx)(1,0); // v3 = (*elm[i].vtx)(2,0); // node[v1].nelms = node[v1].nelms + 1; // node[v2].nelms = node[v2].nelms + 1; // node[v3].nelms = node[v3].nelms + 1; // } // for ( int i = 0; i < nelms; ++i ) { // v1 = (*elm[i].vtx)(0,0); // v2 = (*elm[i].vtx)(1,0); // v3 = (*elm[i].vtx)(2,0); // node[v1].elm = new Array2D<int>(node[v1].nelms, 1); // node[v2].elm = new Array2D<int>(node[v2].nelms, 1); // node[v3].elm = new Array2D<int>(node[v3].nelms, 1); // } //dummy allocations: // node[v1].elm = new Array2D<int>(1, 1); // node[v2].elm = new Array2D<int>(1, 1); // node[v3].elm = new Array2D<int>(1, 1); for ( int i = 0; i < nelms; ++i ) { v1 = (*elm[i].vtx)(0,0); v2 = (*elm[i].vtx)(1,0); v3 = (*elm[i].vtx)(2,0); // node[v1].elm = new Array2D<int>(1, 1); // node[v2].elm = new Array2D<int>(1, 1); // node[v3].elm = new Array2D<int>(1, 1); } for ( int i = 0; i < nelms; ++i ) { v1 = (*elm[i].vtx)(0,0); v2 = (*elm[i].vtx)(1,0); v3 = (*elm[i].vtx)(2,0); x1 = node[v1].x; x2 = node[v2].x; x3 = node[v3].x; y1 = node[v1].y; y2 = node[v2].y; y3 = node[v3].y; // Distribute the element index to nodes. /* * DESIGN CHOICE HERE -- use std<vector> * should use std::containers */ // save and reallocate: node[v1].nelms = node[v1].nelms + 1; node[v1].elm.append(i); // save and reallocate: node[v2].nelms = node[v2].nelms + 1; node[v2].elm.append(i); // save and reallocate: node[v3].nelms = node[v3].nelms + 1; node[v3].elm.append(i); // Compute the cell center and cell volume. //tri_or_quad : if (elm(i).nvtx==3) then if (elm[i].nvtx==3) { // Triangle centroid and volume elm[i].x = third*(x1+x2+x3); elm[i].y = third*(y1+y2+y3); //cout << " tri area -1" << endl; elm[i].vol = tri_area(x1,x2,x3,y1,y2,y3); } else if (elm[i].nvtx==4) { cout << "need to fix reallocator for 4th node \n"; std::exit(0); // this is a quad. Get the 4th vertex. v4 = (*elm[i].vtx)(4,0); x4 = node[v4].x; y4 = node[v4].y; // Centroid: median dual // (Note: There is an alternative. See Appendix B in Nishikawa AIAA2010-5093.) xm1 = half*(x1+x2); ym1 = half*(y1+y2); xm2 = half*(x3+x4); ym2 = half*(y3+y4); elm[i].x = half*(xm1+xm2); elm[i].y = half*(ym1+ym2); // Volume is computed as a sum of two triangles: 1-2-3 and 1-3-4. //cout << " tri area 0" << endl; elm[i].vol = tri_area(x1,x2,x3,y1,y2,y3) + \ tri_area(x1,x3,x4,y1,y3,y4); xc = elm[i].x; yc = elm[i].y; //cout << " tri area 1" << endl; if (tri_area(x1,x2,xc,y1,y2,yc)<=zero) { cout << " Centroid outside the quad element 12c: i=" << i << endl; cout << " (x1,y1)=" << x1 << y1 << endl; cout << " (x2,y2)=" << x2 << y2 << endl; cout << " (x3,y3)=" << x3 << y3 << endl; cout << " (x4,y4)=" << x4 << y4 << endl; cout << " (xc,yc)=" << xc << yc << endl; std::exit(0); } //cout << " tri area 2" << endl; if (tri_area(x2,x3,xc,y2,y3,yc)<=zero) { cout << " Centroid outside the quad element 23c: i=" << i << endl; cout << " (x1,y1)=" << x1 << y1 << endl; cout << " (x2,y2)=" << x2 << y2 << endl; cout << " (x3,y3)=" << x3 << y3 << endl; cout << " (x4,y4)=" << x4 << y4 << endl; cout << " (xc,yc)=" << xc << yc << endl; std::exit(0); } //cout << " tri area 3" << endl; if (tri_area(x3,x4,xc,y3,y4,yc)<=zero) { cout << " Centroid outside the quad element 34c: i=" << i << endl; cout << " (x1,y1)=" << x1 << y1 << endl; cout << " (x2,y2)=" << x2 << y2 << endl; cout << " (x3,y3)=" << x3 << y3 << endl; cout << " (x4,y4)=" << x4 << y4 << endl; cout << " (xc,yc)=" << xc << yc << endl; std::exit(0); } //cout << " tri area 4" << endl; if (tri_area(x4,x1,xc,y4,y1,yc)<=zero) { cout << " Centroid outside the quad element 41c: i=" << i << endl; cout << " (x1,y1)=" << x1 << y1 << endl; cout << " (x2,y2)=" << x2 << y2 << endl; cout << " (x3,y3)=" << x3 << y3 << endl; cout << " (x4,y4)=" << x4 << y4 << endl; cout << " (xc,yc)=" << xc << yc << endl; std::exit(0); } // Distribution of element number to the 4th node of the quadrilateral node[v4].nelms = node[v3].nelms + 1; node[v4].elm.append(i); }// endif tri_or_quad else { cout << "ERROR: not a tri or quad" << endl; std:exit(0); } }// end do elements (i loop) // Median dual volume for (size_t i = 0; i < nnodes; i++) { node[i].vol = zero; } // elementsv : do i = 1, nelms for ( int i = 0; i < nelms; ++i ) { //TLM here 2/23/2020 6::11 v1 = (*elm[i].vtx)(0); v2 = (*elm[i].vtx)(1); v3 = (*elm[i].vtx)(2); // tri_or_quadv : if (elm[i].nvtx==3) { // Dual volume is exactly 1/3 of the volume of the triangle. node[v1].vol = node[v1].vol + third*elm[i].vol; node[v2].vol = node[v2].vol + third*elm[i].vol; node[v3].vol = node[v3].vol + third*elm[i].vol; } else if (elm[i].nvtx==4) { v4 = (*elm[i].vtx)(4,0); x1 = node[v1].x; x2 = node[v2].x; x3 = node[v3].x; x4 = node[v4].x; xc = elm[i].x; y1 = node[v1].y; y2 = node[v2].y; y3 = node[v3].y; y4 = node[v4].y; yc = elm[i].y; // - Vertex 1 xj = node[v1].x; yj = node[v1].y; xm1 = half*(xj+x2); ym1 = half*(yj+y2); xm2 = half*(xj+x4); ym2 = half*(yj+y4); // Median volume is computed as a sum of two triangles. node[v1].vol = node[v1].vol + \ tri_area(xj,xm1,xc,yj,ym1,yc) + \ tri_area(xj,xc,xm2,yj,yc,ym2); // - Vertex 2 xj = node[v2].x; yj = node[v2].y; xm1 = half*(xj+x3); ym1 = half*(yj+y3); xm2 = half*(xj+x1); ym2 = half*(yj+y1); // Median volume is computed as a sum of two triangles. node[v2].vol = node[v2].vol + \ tri_area(xj,xm1,xc,yj,ym1,yc) + \ tri_area(xj,xc,xm2,yj,yc,ym2); // - Vertex 3 xj = node[v3].x; yj = node[v3].y; xm1 = half*(xj+x4); ym1 = half*(yj+y4); xm2 = half*(xj+x2); ym2 = half*(yj+y2); // Median volume is computed as a sum of two triangles. node[v3].vol = node[v3].vol + \ tri_area(xj,xm1,xc,yj,ym1,yc) + \ tri_area(xj,xc,xm2,yj,yc,ym2); // - Vertex 4 xj = node[v4].x; yj = node[v4].y; xm1 = half*(xj+x1); ym1 = half*(yj+y1); xm2 = half*(xj+x3); ym2 = half*(yj+y3); // Median volume is computed as a sum of two triangles. node[v4].vol = node[v4].vol + \ tri_area(xj,xm1,xc,yj,ym1,yc) + \ tri_area(xj,xc,xm2,yj,yc,ym2); }// endif tri_or_quadv }// end do elementsv //-------------------------------------------------------------------------------- // Loop over elements 2 // // Allocate elm[:].nghbr[:] : elm[:].nnghrs, elm[:].nghr[:] // Construct element nghbr data: elm(:).nghbr(:) // Order of neighbor elements [e1,e2,e3,..] are closely related to // the order of vertices [v1,v2,v3,..] (see below). // // o------o // | | // v4| e1 |v3 v3 // o-----o------o------o o---------o------------o // | | | | . . . . // | e2 | | e4 | . e2 . . e1 . // o-----o------o------o . . . . // v1 | .v2 v1 o---------o v2 // | e3 . . e3 . // | . . . // | . . . // | . o // o // // Allocate the neighbor array // narrow stencil for (size_t i = 0; i < nelms; i++) { // 3 neighbors for triangle if (elm[i].nvtx==3) { elm[i].nnghbrs = 3; elm[i].nghbr = new Array2D<int>(3,1); } // 4 neighbors for quadrilateral else if (elm[i].nvtx==4) { elm[i].nnghbrs = 4; elm[i].nghbr = new Array2D<int>(4,1); } (*elm[ i].nghbr) = -1; } int nbrprint = 2; // Begin constructing the element-neighbor data cout << "Begin constructing the element-neighbor data \n" << endl; //elements2 : do i = 1, nelms for (size_t i = 0; i < nelms; i++) { //elm_vertex : do k = 1, elm(i).nvtx for (size_t k = 0; k < elm[i].nvtx; k++) { // Get the face of the element i: // // vL vR // o------o // / | // / | // o---------o // //TLM warning: fixed step out of bounds if (k < elm[i].nvtx-1) vL = (*elm[i].vtx)(k+1); //k+1 - 1.. nope, K goes from 0 if (k == elm[i].nvtx-1) vL = (*elm[i].vtx)(0); //1-1 vR = (*elm[i].vtx)(k); // Loop over the surrounding elements of the node vR, // and find the element neighbor from them. found = false; //elms_around_vR for (size_t j = 0; j < node[vR].nelms; j++) { jelm = node[vR].elm(j); // if (i < nbrprint) cout << " i = " << i << " j = " << j << endl; // if (i < nbrprint) cout << "vR = " << vR << " " << " jelm = " << node[vR].elm(j) << endl; //if (i < nbrprint) cout << "vR , jelm = "<< vR << " " << jelm << endl; //edge_matching for (size_t ii = 0; ii < elm[jelm].nvtx; ii++) { v1 = (*elm[jelm].vtx)(ii); //cout << ii << endl; if (ii > 0) { v2 = (*elm[jelm].vtx)(ii-1); } if (ii == 0) { v2 = (*elm[jelm].vtx)(elm[jelm].nvtx-1); } //TLM fix: array bounds overrun fixed here // if (i < nbrprint) cout << " v = " << vR // << " " << v1 // << " " << vL // << " " << v2 << endl; if (v1==vR and v2==vL) { found = true; im = ii+1; if (im > (elm[jelm].nvtx-1)) { im = im - (elm[jelm].nvtx-0); } // if (i < nbrprint) cout << "found v1==VR, v2==VL " << v1 << " " << vR << " " << v2 << " " << vL << endl; break; //exit edge_matching | } //endif } //end do edge_matching <---V //if (found) exit elms_around_vR if (found) {break;} } //end do elms_around_vR // Q: why is this k+2 when we already loop all the way to nvtx? in = k + 2; if (in > elm[i].nvtx-1) { in = in - elm[i].nvtx-0; } // A: simple fix here: in > elm[i].nvtx had to be ammended and not [0,1,2](3) => 2 len=3 // i.e. if n > 2, then c = 3; so subtract 3 (i.e. nvtx) to get back to zero if (found) { (*elm[ i].nghbr)(in) = jelm; (*elm[jelm].nghbr)(im) = i; } else { (*elm[ i].nghbr)(in) = -1; //boundary } // if (i < nbrprint) { // cout << " elm nghbrs...\n"; // print((*elm[ i].nghbr)); // cout << " ------------------\n"; // } }// end do elm_vertex }// end do elements2 cout << "DONE constructing the element-neighbor data " << endl; //-------------------------------------------------------------------------------- // Edge-data for node-centered (edge-based) scheme. // // Loop over elements 3 // Construct edge data: edge(:).n1, n2, e1, e2. // Edge points from node n1 to node n2. // // n2 // o------------o // . \ . // . \ e2 . // . e1 \ . // . \ . Directed area is positive: n1 -> n2 // o----------o e1: left element // n1 e2: right element (e2 > e1 or e2 = 0) // First count the number of edges. // // NOTE: Count edges only if the neighbor element number is // greater than the current element (i) to avoid double // count. -1 element number indicates that it is outside // the domain (boundary face). // elements0 : do i = 1, nelms for (size_t i = 0; i < nelms; i++) { v1 = (*elm[i].vtx)(0); v2 = (*elm[i].vtx)(1); v3 = (*elm[i].vtx)(2); // tri_quad0 : if (elm[i].nvtx==3) then if (elm[i].nvtx==3) { if ( (*elm[i].nghbr)(2) > i or (*elm[i].nghbr)(2) == -1 ) { nedges = nedges + 1; } if ( (*elm[i].nghbr)(0) > i or (*elm[i].nghbr)(0) == -1 ) { nedges = nedges + 1; } if ( (*elm[i].nghbr)(1) > i or (*elm[i].nghbr)(1) == -1 ) { nedges = nedges + 1; } } else if (elm[i].nvtx==4) { v4 = (*elm[i].vtx)(3); if ( (*elm[i].nghbr)(2) > i or (*elm[i].nghbr)(2) == -1 ) { nedges = nedges + 1; } if ( (*elm[i].nghbr)(3) > i or (*elm[i].nghbr)(3) == -1 ) { nedges = nedges + 1; } if ( (*elm[i].nghbr)(0) > i or (*elm[i].nghbr)(0) == -1 ) { nedges = nedges + 1; } if ( (*elm[i].nghbr)(1) > i or (*elm[i].nghbr)(1) == -1 ) { nedges = nedges + 1; } }// endif tri_quad0 }// end do elements0 // Allocate the edge array. edge = new edge_type[nedges]; for (size_t i = 0; i < nedges; i++) { edge[i].e1 = -1; edge[i].e2 = -1; } nedges = -1; //TLM fence post fix// // Construct the edge data: // two end nodes (n1, n2), and left and right elements (e1, e2) int maxprint = 1; //elements3 : do i = 1, nelms for (size_t i = 0; i < nelms; i++) { v1 = (*elm[i].vtx)(0); v2 = (*elm[i].vtx)(1); v3 = (*elm[i].vtx)(2); // Triangular element //tri_quad2 : if (elm[i].nvtx==3) { // if (i<maxprint) { // cout << "printing edge vars to be set \n"; // cout << "v1 = " << v1 << "\n"; // cout << "v2 = " << v2 << "\n"; // cout << "(*elm[i].nghbr)(0) = " << (*elm[i].nghbr)(0) << "\n"; // cout << "(*elm[i].nghbr)(1) = " << (*elm[i].nghbr)(1) << "\n"; // cout << "(*elm[i].nghbr)(2) = " << (*elm[i].nghbr)(2) << "\n"; // } if ( (*elm[i].nghbr)(2) > i or (*elm[i].nghbr)(2)==-1 ) { // if (i<maxprint) cout << "set edge 1\n"; nedges = nedges + 1; edge[nedges].n1 = v1; edge[nedges].n2 = v2; edge[nedges].e1 = i; edge[nedges].e2 = (*elm[i].nghbr)(2); // assert(v1 //= v2 && "v1 should not be equal to v2 -1"); } if ( (*elm[i].nghbr)(0) > i or (*elm[i].nghbr)(0)==-1 ) { // if (i<maxprint) cout << "set edge 2\n"; nedges = nedges + 1; edge[nedges].n1 = v2; edge[nedges].n2 = v3; edge[nedges].e1 = i; edge[nedges].e2 = (*elm[i].nghbr)(0); // assert(v1 //= v2 && "v1 should not be equal to v2 -2" ); } if ( (*elm[i].nghbr)(1) > i or (*elm[i].nghbr)(1)==-1 ) { // if (i<maxprint) cout << "set edge 3\n"; nedges = nedges + 1; edge[nedges].n1 = v3; edge[nedges].n2 = v1; edge[nedges].e1 = i; edge[nedges].e2 = (*elm[i].nghbr)(1); // assert(v1 //= v2 && "v1 should not be equal to v2 -3"); } // else { // cout << "ERROR: missed edge case! \n"; // } } // Quadrilateral element else if (elm[i].nvtx==4) { v4 = (*elm[i].vtx)(3); if ( (*elm[i].nghbr)(2) > i or (*elm[i].nghbr)(2) == -1 ) { nedges = nedges + 1; edge[nedges].n1 = v1; edge[nedges].n2 = v2; edge[nedges].e1 = i; edge[nedges].e2 = (*elm[i].nghbr)(2); // assert(v1 //= v2 && "v1 should not be equal to v2 -q1"); } if ( (*elm[i].nghbr)(3) > i or (*elm[i].nghbr)(3) == -1 ) { nedges = nedges + 1; edge[nedges].n1 = v2; edge[nedges].n2 = v3; edge[nedges].e1 = i; edge[nedges].e2 = (*elm[i].nghbr)(3); // assert(v1 //= v2 && "v1 should not be equal to v2 -q2"); } if ( (*elm[i].nghbr)(0) > i or (*elm[i].nghbr)(0) == -1 ) { nedges = nedges + 1; edge[nedges].n1 = v3; edge[nedges].n2 = v4; edge[nedges].e1 = i; edge[nedges].e2 = (*elm[i].nghbr)(0); // assert(v1 //= v2 && "v1 should not be equal to v2 -q3"); } if ( (*elm[i].nghbr)(1) > i or (*elm[i].nghbr)(1) == -1 ) { nedges = nedges + 1; edge[nedges].n1 = v4; edge[nedges].n2 = v1; edge[nedges].e1 = i; edge[nedges].e2 = (*elm[i].nghbr)(1); // assert(v1 //= v2 && "v1 should not be equal to v2 -q4"); } }// endif tri_quad2 }// end do elements3 nedges += 1; // Loop over edges // Construct edge vector and directed area vector. // // Edge vector is a simple vector pointing froom n1 to n2. // For each edge, add the directed area vector (dav) from // the left and right elements. // // n2 // o-----------o-----------o // | dav | dav | // | ^ | ^ | // | | | | | // | c - - - m - - -c | // | | | // | | | m: edge midpoint // | | | c: element centroid // o-----------o-----------o // n1 // //int pi = 0; // edges : do i = 1, nedges for (size_t i = 0; i < nedges; i++) { n1 = edge[i].n1; n2 = edge[i].n2; e1 = edge[i].e1; e2 = edge[i].e2; // if (i < maxprint) { // cout << "edge[i] -> i, e1, e2 " << i << " " << e1 << " " << e2 << "\n"; // } // edge centroids: xm = half*( node[n1].x + node[n2].x ); ym = half*( node[n1].y + node[n2].y ); edge[i].dav = zero; // Contribution from the left element if (e1 > -1) { xc = elm[e1].x; yc = elm[e1].y; edge[i].dav(0) = -(ym-yc); edge[i].dav(1) = xm-xc; // if (i<maxprint) { // cout << "elm(e1) = " << elm[e1].x << " " << elm[e1].y << "\n"; // } } // Contribution from the right element if (e2 > -1) { xc = elm[e2].x; yc = elm[e2].y; edge[i].dav(0) = edge[i].dav(0) -(yc-ym); edge[i].dav(1) = edge[i].dav(1) + xc-xm; // if (i<maxprint) { // cout << "elm(e2) = " << elm[e2].x << " " << elm[e2].y << "\n"; // } } if (e1 < 0 and e2 < 0) { cout << "ERROR: e1 and e2 are both negative... " << endl; cout << "n1 = " << n1 << "\n"; cout << "n2 = " << n2 << "\n"; cout << "e1 = " << e1 << "\n"; cout << "e2 = " << e2 << "\n"; } // Magnitude and unit vector edge[i].da = std::sqrt( edge[i].dav(0) * edge[i].dav(0) + \ edge[i].dav(1) * edge[i].dav(1) ); //cout << " edge dav before division = " << edge[i].dav(0) << " " << edge[i].dav(1) << endl; edge[i].dav = edge[i].dav / edge[i].da; if (i<maxprint) { cout << "printing edge[i].dav \n"; print(edge[i].dav); cout << " edge dav after division = " << edge[i].dav(0) << " " << edge[i].dav(1) << endl; if (edge[i].da < 1.e-5) { cout << "ERROR: collapsed edge" << endl; //std::exit(0); } //pi += 1; } // Edge vector edge[i].ev(0) = node[n2].x - node[n1].x; edge[i].ev(1) = node[n2].y - node[n1].y; edge[i].e = std::sqrt( edge[i].ev(0) * edge[i].ev(0) + \ edge[i].ev(1) * edge[i].ev(1) ); edge[i].ev = edge[i].ev / edge[i].e; }// end do edges //-------------------------------------------------------------------------------- // Construct node neighbor data: // pointers to the neighbor nodes(o) // // o o // \ / // \ / // o-----*-----o // /| // / | // / o *: node in interest // o o: neighbors (edge-connected nghbrs) // cout << " --- Node-neighbor (edge connected vertex) data:" << endl; for (size_t i = 0; i < nnodes; i++) { node[i].nnghbrs = 0; } //dummy allocations are bad!: for (size_t i = 0; i < nedges; i++) { n1 = edge[i].n1; n2 = edge[i].n2; //node[n1].nghbr = new Array2D<int>(1, 1); //node[n2].nghbr = new Array2D<int>(1, 1); } // Loop over edges and distribute the node numbers: //edges4 : do i = 1, nedges for (size_t i = 0; i < nedges; i++) { n1 = edge[i].n1; n2 = edge[i].n2; // (1) Add n1 to the neighbor list of n2 node[n1].nnghbrs = node[n1].nnghbrs + 1; if (node[n1].nnghbrs == 1) { node[n1].nghbr = new Array2D<int>(1, 1); } else{ Array2D<int> save7 = (*node[n1].nghbr); node[n1].nghbr = new Array2D<int>(node[n1].nnghbrs, 1); for (size_t ra = 0; ra < save7.storage_size; ra++) { (*node[n1].nghbr).array[ra] = save7.array[ra]; } } (*node[n1].nghbr)( node[n1].nnghbrs - 1 ) = n2; // more fence post trickery // (2) Add n2 to the neighbor list of n1 node[n2].nnghbrs = node[n2].nnghbrs + 1; if (node[n2].nnghbrs == 1) { node[n2].nghbr = new Array2D<int>(1, 1); } else{ Array2D<int> save8 = (*node[n2].nghbr); node[n2].nghbr = new Array2D<int>(node[n2].nnghbrs, 1); for (size_t ra = 0; ra < save8.storage_size; ra++) { (*node[n2].nghbr).array[ra] = save8.array[ra]; } } (*node[n2].nghbr)( node[n2].nnghbrs - 1 ) = n1; } //end do edges4 //-------------------------------------------------------------------------------- // Boundary normal at nodes constructed by accumulating the contribution // from each boundary face normal. This vector will be used to enforce // the tangency condition, for example. // // // Interior domain / // o // . / // . / // --o-------o-------------o // j | . | j+1 // v . v // // Left half added to the node j, and // right half added to the node j+1. // // Allocate and initialize the normal vector arrays for (size_t i = 0; i < nbound; i++) { bound[i].bnx = new Array2D<real>( bound[i].nbnodes, 1 ); bound[i].bny = new Array2D<real>( bound[i].nbnodes, 1 ); bound[i].bn = new Array2D<real>( bound[i].nbnodes, 1 ); for (size_t j = 0; j < bound[i].nbnodes; j++) { (*bound[i].bnx)(j) = zero; (*bound[i].bny)(j) = zero; (*bound[i].bn)( j) = zero; } } // Normal vector at boundary nodes // Note: Below it describes normals of linear approximation. // We will overwrite it by a quadratic approximation. // // Linear approximation: // // Step 1. Compute the outward normals for (size_t i = 0; i < nbound; i++) { //do j = 1, bound[i].nbnodes-1 for (size_t j = 0; j < bound[i].nbnodes-1; j++) { // quick expansion for understanding: // int num = (*bound[i].bnode)(j); // x1 = node[num].x; x1 = node[ (*bound[i].bnode)(j) ].x; y1 = node[ (*bound[i].bnode)(j) ].y; x2 = node[ (*bound[i].bnode)(j+1) ].x; y2 = node[ (*bound[i].bnode)(j+1) ].y; // Normal vector pointing into the domain at this point. (*bound[i].bnx)(j) = (*bound[i].bnx)(j) + half*( -(y2-y1) ); (*bound[i].bny)(j) = (*bound[i].bny)(j) + half*( x2-x1 ); (*bound[i].bnx)(j+1) = (*bound[i].bnx)(j+1) + half*( -(y2-y1) ); (*bound[i].bny)(j+1) = (*bound[i].bny)(j+1) + half*( x2-x1 ); } } // Step 2. Compute the magnitude and turn (bnx,bny) into a unit vector for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbnodes; j++) { (*bound[i].bn)(j) = std::sqrt( (*bound[i].bnx)(j) * (*bound[i].bnx)(j) + \ (*bound[i].bny)(j) * (*bound[i].bny)(j) ); // Minus sign for outward pointing normal (*bound[i].bnx)(j) = - (*bound[i].bnx)(j) / (*bound[i].bn)(j); (*bound[i].bny)(j) = - (*bound[i].bny)(j) / (*bound[i].bn)(j); } } // Now, ignore the linear approximation, and let us construct // more accurate surfae normal vectors and replace the linear ones. // So, we will overwrite the unit normal vectors: bnx, bny. // Note: We keep the magnitude of the normal vector. // // Quadratic approximation: // See http://www.hiroakinishikawa.com/My_papers/nishikawa_jcp2015v281pp518-555_preprint.pdf // for details on the bnode(quadratic approximation for computing more accurate normals. // // boundary_type0 : do i = 1, nbound // boundary_nodes0 : do j = 1, bound[i].nbnodes for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbnodes; j++) { if (j==0) { v1 = (*bound[i].bnode)[j ][0]; v2 = (*bound[i].bnode)[j+1][0]; v3 = (*bound[i].bnode)[j+2][0]; } else if (j==bound[i].nbnodes-1) { v1 = (*bound[i].bnode)[j-2][0]; v2 = (*bound[i].bnode)[j-1][0]; v3 = (*bound[i].bnode)[j ][0]; } else { v1 = (*bound[i].bnode)[j-1][0]; v2 = (*bound[i].bnode)[j ][0]; v3 = (*bound[i].bnode)[j+1][0]; } x1 = node[v1].x; x2 = node[v2].x; x3 = node[v3].x; y1 = node[v1].y; y2 = node[v2].y; y3 = node[v3].y; // //---------------------------------------------------------------------- // // Fit a quadratic over 3 nodes // Skip the last one if the boundary segment is a closed boundary // in which case the last node is the same as the first one. //if (j==bound[i].nbnodes and (*bound[i].bnode)(j)==(*bound[i].bnode)(0) ) { if (j==bound[i].nbnodes-1 and (*bound[i].bnode)[j][0]==(*bound[i].bnode)[0][0] ) { //TLM TODO FIX? better? (*bound[i].bn)(j) = (*bound[i].bn)(0); (*bound[i].bnx)(j) = (*bound[i].bnx)(0); (*bound[i].bny)(j) = (*bound[i].bny)(0); continue; // cycle } dsL = std::sqrt( (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) ); dsR = std::sqrt( (x3-x2)*(x3-x2) + (y3-y2)*(y3-y2) ); dx = dsR*x1/(dsL*(-dsL-dsR))-x2/dsR+x2/dsL+dsL*x3/((dsR+dsL)*dsR); dy = dsR*y1/(dsL*(-dsL-dsR))-y2/dsR+y2/dsL+dsL*y3/((dsR+dsL)*dsR); ds = std::sqrt( dx*dx + dy*dy ); (*bound[i].bnx)(j) = -( -dy / ds ); (*bound[i].bny)(j) = -( dx / ds ); }// end do boundary_nodes0 } // end do boundary_type0 //-------------------------------------------------------------------------------- // Construct neighbor index over edges // // Example: // // o o // \ / // \j/ k-th neighbor // o-----*----------o // /| edge i // / | // / o Note: k-th neighbor is given by "(*node(j).nghbr)(k)" // o // // Consider the edge i // // node j k-th neighbor // *----------o // n1 edge i n2 // // We store "k" in the edge data structure as // // edge[i].kth_nghbr_of_1: n2 is the "edge[i].kth_nghbr_of_1"-th neighbor of n1 // edge[i].kth_nghbr_of_2: n1 is the "edge[i].kth_nghbr_of_3"-th neighbor of n2 // // That is, we have // // n2 = (*node[n1].nghbr)(edge[i].kth_nghbr_of_1) // n1 = (*node[n2].nghbr)(edge[i].kth_nghbr_of_2) // // We make use of this data structure to access off-diagonal entries in Jacobian matrix. // // Loop over edges // edges5 : do i = 1, nedges for (size_t i = 0; i < nedges; i++) { n1 = edge[i].n1; n2 = edge[i].n2; //do k = 1, node[n2].nnghbrs for (size_t k = 0; k < node[n2].nnghbrs; k++) { if ( n1 == (*node[n2].nghbr)(k) ) { edge[i].kth_nghbr_of_2 = k; } }// end do //do k = 1, node[n1].nnghbrs for (size_t k = 0; k < node[n1].nnghbrs; k++) { if ( n2 == (*node[n1].nghbr)(k) ) { edge[i].kth_nghbr_of_1 = k; } }//end do }//end do edges5 // Boundary mark: It should be an array actually because some nodes are associated with // more than one boundaries. for (size_t i = 0; i < nnodes; i++) { node[i].bmark = -1; node[i].nbmarks = 0; } for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbnodes; j++) { node[ (*bound[i].bnode)[j][0] ].bmark = i; node[ (*bound[i].bnode)[j][0] ].nbmarks = node[ (*bound[i].bnode)[j][0] ].nbmarks + 1; } } //-------------------------------------------------------------------------------- // Boundary face data // // | Domain | // | | // o--o--o--o--o--o--o <- Boundary segment // j= 1 2 3 4 5 6 7 // // In the above case, nbnodes = 7, nbfaces = 6 // for (size_t i = 0; i < nbound; i++) { bound[i].nbfaces = bound[i].nbnodes-1; cout << "nbfaces = " << bound[i].nbfaces << endl; bound[i].bfnx = new Array2D<real>( bound[i].nbfaces , 1 ); bound[i].bfny = new Array2D<real>( bound[i].nbfaces , 1 ); bound[i].bfn = new Array2D<real>( bound[i].nbfaces , 1 ); bound[i].belm = new Array2D<int>( bound[i].nbfaces , 1 ); bound[i].kth_nghbr_of_1 = new Array2D<int>( bound[i].nbfaces , 1 ); bound[i].kth_nghbr_of_2 = new Array2D<int>( bound[i].nbfaces , 1 ); } // Boundary face vector: outward normal for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbfaces; j++) { x1 = node[ (*bound[i].bnode)(j ,0) ].x; y1 = node[ (*bound[i].bnode)(j ,0) ].y; x2 = node[ (*bound[i].bnode)(j+1,0) ].x; y2 = node[ (*bound[i].bnode)(j+1,0) ].y; if (j==0) { // good now // cout << "weird i, j = " << i << " " << j << endl; // cout << "weird x1, y1 = " << x1 << " " << y1 << " x2, y2 = " << x2 << " " << y2 << endl; // cout << "bound[i].nbfaces = " << bound[i].nbfaces << endl; // cout << "bound[i].nbnodes = " << bound[i].nbnodes << endl; } if (j==bound[i].nbfaces-1) { // good now // cout << "weird i, j = " << i << " " << j << endl; // cout << "weird x1, y1 = " << x1 << " " << y1 << " x2, y2 = " << x2 << " " << y2 << endl; // cout << "bound[i].nbfaces = " << bound[i].nbfaces << endl; // cout << "bound[i].nbnodes = " << bound[i].nbnodes << endl; } (*bound[i].bfn)(j,0) = std::sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) ); (*bound[i].bfnx)(j,0) = -(y1-y2) / (*bound[i].bfn)(j); (*bound[i].bfny)(j) = (x1-x2) / (*bound[i].bfn)(j); } } // Boundary normal vector at nodes: outward normal for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbfaces; j++) { x1 = node[(*bound[i].bnode)[j ][0] ].x; y1 = node[(*bound[i].bnode)[j ][0] ].y; x2 = node[(*bound[i].bnode)[j+1][0] ].x; y2 = node[(*bound[i].bnode)[j+1][0] ].y; // if (j==bound[i].nbfaces-1){ // cout << "weird i, j = " << i << " " << j << endl; // cout << "weird x2, y2 = " << x2 << " " << y2 << endl; // cout << "bound[i].nbfaces = " << bound[i].nbfaces << endl; // } (*bound[i].bfn)(j) = std::sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) ); (*bound[i].bfnx)(j) = -(y1-y2) / (*bound[i].bfn)(j); (*bound[i].bfny)(j) = (x1-x2) / (*bound[i].bfn)(j); } } // Neighbor index over boundary edges (faces) for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbfaces; j++) { n1 = (*bound[i].bnode)[j ][0]; //Left node n2 = (*bound[i].bnode)[j+1][0]; //Right node for (size_t k = 0; k < node[n2].nnghbrs; k++) { if ( n1 == (*node[n2].nghbr)(k) ) { (*bound[i].kth_nghbr_of_2)(j) = k; } } for (size_t k = 0; k < node[n1].nnghbrs; k++) { if ( n2 == (*node[n1].nghbr)(k) ) { (*bound[i].kth_nghbr_of_1)(j) = k; } } } } // Find element adjacent to the face: belm // // NOTE: This is useful to figure out what element // each boundary face belongs to. Boundary flux needs // special weighting depending on the element. // // |_________|_________|________| // | | | | // | | | | // |_________|_________|________| // | | | | <- Grid (e.g., quads) // | | elmb(j) | | // ---o---------o---------o--------o--- <- Boundary segment // j-th face // // elmb(j) is the element number of the element having the j-th boundary face. // // do i = 1, nbound // do j = 1, bound[i].nbfaces for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbfaces; j++) { // bface is defined by the nodes v1 and v2. v1 = (*bound[i].bnode)(j) ; v2 = (*bound[i].bnode)(j+1); found = false; // Find the element having the bface from the elements // around the node v1. //do k = 1, node[v1).nelms for (size_t k = 0; k < node[v1].nelms; k ++) { //k = node[v1].nelms-1; ielm = node[v1].elm(k); //cout << "v1, k, ielm " << v1 << " " << k << " " << ielm << endl; //do ii = 1, elm[ielm].nvtx; for (size_t ii = 0; ii < elm[ielm].nvtx; ii++) { in = ii; im = ii+1; if (im > elm[ielm].nvtx-1 ) { im = im - (elm[ielm].nvtx-0); }//return to 0? (cannot use im = 0; }//) vt1 = (*elm[ielm].vtx)(in); //(in); //TLM these are bad vt2 = (*elm[ielm].vtx)(im); //TLM these are bad // if (j < 2) cout << " v = " << vt1 << " " << v1 << " " << vt2 << " " << v2 << endl; // if (j < 2) cout << " " << ielm << " " << im << " " << in << endl; if (vt1 == v1 and vt2 == v2) { found = true; //if (j < 2) cout << "found// " << endl;;//" " << in << " " << im << endl; //if (j < 2) cout << " " << ielm << " " << im << " " << in << endl; // if (j < 2) cout << " v = " << vt1 << " " << v1 << " " << vt2 << " " << v2 << endl; //cout << "break 1" << endl; break; //continue; //exit } // cout << "break 2" << endl; //if (found) {break;} //exit //extra break needed to account for exit behavior// } //end do //cout << "break 3" << endl; if (found) {break;} //exit }//end do // cout << "break 3" << endl; // if (found) {break;} //exit if (found) { //cout << " GOOD: Boundary-adjacent element found" << endl; (*bound[i].belm)(j) = ielm; } else { cout << " Boundary-adjacent element not found. Error..." << endl; std::exit(0);//stop } } } //-------------------------------------------------------------------------------- // Construct least-squares matrix for node-centered schemes. // // o o // \ / // \ / // o-----*-----o // /| // / | // / o *: node in interest // o o: neighbors (edge-connected nghbrs) // // Check the number of neighbor nodes (must have at least 2 neighbors) cout << " --- Node neighbor data:" << endl; ave_nghbr = node[0].nnghbrs; min_nghbr = node[0].nnghbrs; max_nghbr = node[0].nnghbrs; imin = 0; imax = 0; if (node[0].nnghbrs==2) { cout << "--- 2 neighbors for the node = " << 0 << endl; } //do i = 2, nnodes for (size_t i = 1; i < nnodes; i++) { ave_nghbr = ave_nghbr + node[i].nnghbrs; if (node[i].nnghbrs < min_nghbr) imin = i; if (node[i].nnghbrs > max_nghbr) imax = i; min_nghbr = std::min(min_nghbr, node[i].nnghbrs); max_nghbr = std::max(max_nghbr, node[i].nnghbrs); if (node[i].nnghbrs==2) { cout << "--- 2 neighbors for the node = " << i << endl; } } cout << " nnodes = " << nnodes << endl; cout << " ave_nghbr = " << ave_nghbr << endl; cout << " ave_nghbr = " << ave_nghbr/nnodes << endl; cout << " min_nghbr = " << min_nghbr << " at node " << imin << endl; cout << " max_nghbr = " << max_nghbr << " at node " << imax << endl; cout << "" << endl; //-------------------------------------------------------------------------------- // Cell centered scheme data //-------------------------------------------------------------------------------- cout << "Generating CC scheme data......" << endl; //do i = 1, nelms for (size_t i = 0; i < nelms; i++) { //allocate(elm(i).edge( elm(i).nnghbrs ) ) elm[i].edge = new Array2D<int>( elm[i].nnghbrs , 1 ); } //edges3 : do i = 1, nedges for (size_t i = 0; i < nedges; i++) { e1 = edge[i].e1; e2 = edge[i].e2; // Left element if (e1 > -1) { //do k = 1, elm[e1].nnghbrs; for (size_t k = 0; k < elm[e1].nnghbrs; k++) { if ( (*elm[e1].nghbr)(k)==e2) (*elm[e1].edge)(k) = i; } } // Right element if (e2 > -1) { //do k = 1, elm[e2].nnghbrs; for (size_t k = 0; k < elm[e2].nnghbrs; k++) { if ( (*elm[e2].nghbr)(k)==e1) (*elm[e2].edge)(k) = i; } } }//end do edges3 // Face-data for cell-centered (edge-based) scheme. // // Loop over elements 4 // Construct face data: // face is an edge across elements pointing // element e1 to element e2 (e2 > e1): // // e2 // \ // \ face: e1 -> e2 // \ // n1 o--------------o n2 <-- face // \ // \ n1, n2: end nodes of the face // \ e1: element 1 // e1 e2: element 2 (e2 > e1) // // Note: Face data is dual to the edge data. // It can be trivially constructed from the edge data, but // here the face data is constructed by using the element // neighbor data just for an educational purpose. nfaces = 0; //elements4 for (size_t i = 0; i < nelms; i++) { for (size_t k = 0; k < elm[i].nnghbrs; k++) { jelm = (*elm[i].nghbr)(k); if (jelm > i) { nfaces = nfaces + 1; } } }//end do elements4 // allocate(face(nfaces)) face = new face_type[nfaces]; nfaces = 0; // elements5 for ( size_t i = 0; i < nelms; i++) { //do k = 1, elm(i).nnghbrs for (size_t k = 0; k < elm[i].nnghbrs; k++) { jelm = (*elm[i].nghbr)(k); if (jelm > i) { nfaces = nfaces + 1; face[nfaces-1].e1 = i; face[nfaces-1].e2 = jelm; iedge = (*elm[i].edge)(k); v1 = edge[iedge].n1; v2 = edge[iedge].n2; if (edge[iedge].e1 == jelm) { face[nfaces-1].n1 = v1; face[nfaces-1].n2 = v2; } else { face[nfaces-1].n1 = v2; face[nfaces-1].n2 = v1; } } else if (jelm == -1) { // if (elm[jelm].bmark != -1){ // cout << "ERROR: this is supposed to be a boundary \n"; // cout << "jelm = " << jelm << endl; // cout << "elm[jelm].bmark = " << elm[jelm].bmark << "\n"; // cout << "-------------------------------------------"<< endl; // std::exit(0); // } // Skip boundary faces. } }//end for }// elements5 // Loop over faces // Construct directed area vector. //faces for (size_t i = 0; i < nfaces; i++) { n1 = face[i].n1; n2 = face[i].n2; e1 = face[i].e1; e2 = face[i].e2; // Face vector face[i].dav(0) = -( node[n2].y - node[n1].y ); face[i].dav(1) = node[n2].x - node[n1].x; face[i].da = std::sqrt( face[i].dav(0)*face[i].dav(0) + face[i].dav(1)*face[i].dav(1) ); face[i].dav = face[i].dav / face[i].da; if (face[i].da < 1.e-10) { cout << "ERROR: collapsed face" << endl; std::exit(0); } } //end do faces // Construct vertex-neighbor data for cell-centered scheme. // // For each element, i, collect all elements sharing the nodes // of the element, i, including face-neighors. // // ___________ // | | | // | o | o | // |_____|_____| // /\ / \ \ // / o\ o/ i \ o \ // /____\/_____\____\ // \ / /\ \ // \o / o / o\ o \ // \/______/____\____\ // // i: Element of interest // o: Vertex neighbors (k = 1,2,...,9) cout << " --- Vertex-neighbor (vertex of neighbor element) data:" << endl; ave_nghbr = 0; min_nghbr = 10000; max_nghbr =-10000; imin = 0; imax = 0; // Initialization //elements6 for (size_t i =0; i< nelms; i++) { elm[i].nvnghbrs = 0; }//elements6 //-------------------------------------------------------------------------------- // Collect vertex-neighbors // // //elements7 : do i = 1, nelms for (size_t i = 0; i < nelms; i++) { // (1)Add face-neighbors //do k = 1, elm(i).nnghbrs for (size_t k = 0; k < elm[i].nnghbrs; k++) { if ( (*elm[i].nghbr)(k) > -1 ) { elm[i].nvnghbrs = elm[i].nvnghbrs + 1; elm[i].vnghbr.append( (*elm[i].nghbr)(k) ); } } // (2)Add vertex-neighbors //do k = 1, elm[i].nvtx for (size_t k = 0; k < elm[i].nvtx; k++) { v1 = (*elm[i].vtx)(k); //velms : doj = 1, node[v1).nelms for (size_t j = 0; j < node[v1].nelms; j++) { //if (i<10*maxprint) cout << " good start HIGH after break" << endl; e1 = node[v1].elm(j); if (e1 == i) { //if (i<10*maxprint) cout << " e1 == i = " << i << " " << e1 << endl; continue; //velms; } // Check if the element is already added. found = false; //do ii = 1, elm[i].nvnghbrs for (size_t ii = 0; ii < elm[i].nvnghbrs; ii++) { //if (i<10*maxprint) cout << " checking elm " << i << " vnghbr( " << ii << " ) = " <<(*elm[i].vnghbr)(ii) << endl; //if ( e1 == (*elm[i].vnghbr)(ii) ) { if ( e1 == elm[i].vnghbr(ii) ) { found = true; // if (i<10*maxprint) cout << "Found element match e1 = " << e1 << " " << (*elm[i].vnghbr)(ii) << endl; // if (i<10*maxprint) cout << " break" << endl; break; } //if (i<10*maxprint) cout << " skip after break" << endl; } //if (i<10*maxprint) cout << " good start LOW after break" << endl; // Add the element, e1, if not added yet. if (not found) { // if (i<10*maxprint) cout << "NO element match e1 = " << e1 << endl; elm[i].nvnghbrs = elm[i].nvnghbrs + 1; elm[i].vnghbr.append( e1 ); } }//velms loop }//end elm[i].nvtx loop // cout << "--- elm[798].vnghbr" << endl; // print( (*elm[798].vnghbr) ); // cout << "--- elm[804].vnghbr" << endl; // print( (*elm[804].vnghbr) ); ave_nghbr = ave_nghbr + elm[i].nvnghbrs; if (elm[i].nvnghbrs < min_nghbr) imin = i; if (elm[i].nvnghbrs > max_nghbr) imax = i; min_nghbr = std::min(min_nghbr, elm[i].nvnghbrs); max_nghbr = std::max(max_nghbr, elm[i].nvnghbrs); if (elm[i].nvnghbrs < 3) { cout << "--- Not enough neighbors: elm = " << i << "elm[i].nvnghbrs= " << elm[i].nvnghbrs << endl; //std::exit(0); } }// elements7 loop cout << " ave_nghbr(sum) = " << ave_nghbr << " nelms = " << nelms << endl; cout << " ave_nghbr = " << ave_nghbr/nelms << endl; cout << " min_nghbr = " << min_nghbr << " elm = " << imin << endl; cout << " max_nghbr = " << max_nghbr << " elm = " << imax << endl; cout << " " << endl; //do i = 1, nelms for ( int i = 0; i < nelms; ++i ) { elm[i].bmark = -1; } //bc_loop : do i = 1, nbound for ( int i = 0; i < nbound; ++i ) { //cout << bound[i].bc_type << endl; if ( trim( bound[i].bc_type ) == "dirichlet") { cout << "Found dirichlet condition " << endl; //do j = 1, bound[i].nbfaces for (size_t i = 0; i < bound[i].nbfaces; i++) { elm[ (*bound[i].belm)(j) ].bmark = 1; }//end do } // if ( trim( bound[i].bc_type ) == "freestream") { // cout << "Found freestream condition " << endl; // } }// end do bc_loop //-------------------------------------------------------------------------------- } // end function construct_grid_data //******************************************************************************** //******************************************************************************** //* Check the grid data. //* //* 1. Directed area must sum up to zero around every node. //* 2. Directed area must sum up to zero over the entire grid. //* 3. Global sum of the boundary normal vectors must vanish. //* 4. Global sum of the boundary face normal vectors must vanish. //* 5. Check element volumes which must be positive. //* 6. Check dual volumes which must be positive. //* 7. Global sum of the dual volumes must be equal to the sum of element volumes. //* //* Add more tests you can think of. //* //******************************************************************************** void EulerSolver2D::MainData2D::check_grid_data() { // use edu2d_my_main_data , only : nnodes, node, nelms, elm, nedges, edge, & // nbound, bound // use edu2d_constants , only : p2, zero, half // //Local variables int i, j, n1, n2, ierr, k; Array2D<real>* sum_dav_i; Array2D<real> sum_dav(2,1), sum_bn(2,1); Array2D<real> sum_bfn(2,1); real sum_volc, sum_vol; real mag_dav, mag_bn; real vol_min, vol_max, vol_ave; cout << "Checking grid data...." << endl; mag_dav = zero; mag_bn = zero; sum_dav_i = new Array2D<real>(nnodes,2); //-------------------------------------------------------------------------------- // Directed area sum check //-------------------------------------------------------------------------------- // Compute the sum of the directed area for each node. (*sum_dav_i) = zero; //print( (*sum_dav_i) ); for (size_t i = 0; i < nedges; i++) { n1 = edge[i].n1; n2 = edge[i].n2; (*sum_dav_i)(n1,0) = (*sum_dav_i)(n1,0) + edge[i].dav(0)*edge[i].da; (*sum_dav_i)(n1,1) = (*sum_dav_i)(n1,1) + edge[i].dav(1)*edge[i].da; (*sum_dav_i)(n2,0) = (*sum_dav_i)(n2,0) - edge[i].dav(0)*edge[i].da; (*sum_dav_i)(n2,1) = (*sum_dav_i)(n2,1) - edge[i].dav(1)*edge[i].da; mag_dav = mag_dav + edge[i].da; // cout << (*sum_dav_i)(n1,0) << endl; // cout << (*sum_dav_i)(n2,0) << endl; // cout << (*sum_dav_i)(n1,1) << endl; // cout << (*sum_dav_i)(n2,1) << endl; // cout << edge[i].dav(0) << endl; // cout << edge[i].dav(1) << endl; // cout << " edge da = " << edge[i].da << endl; } //ok: cout << "sum edge[i].da =" << mag_dav << endl; mag_dav = mag_dav/real(nedges); cout << "sum dav i, mag = " << mag_dav << endl; // Add contribution from boundary edges. for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbfaces; j++) { n1 = (*bound[i].bnode)(j); n2 = (*bound[i].bnode)(j+1); (*sum_dav_i)(n1,0) = (*sum_dav_i)(n1,0) + half*(*bound[i].bfnx)(j)*(*bound[i].bfn)(j); (*sum_dav_i)(n1,1) = (*sum_dav_i)(n1,1) + half*(*bound[i].bfny)(j)*(*bound[i].bfn)(j); (*sum_dav_i)(n2,0) = (*sum_dav_i)(n2,0) + half*(*bound[i].bfnx)(j)*(*bound[i].bfn)(j); (*sum_dav_i)(n2,1) = (*sum_dav_i)(n2,1) + half*(*bound[i].bfny)(j)*(*bound[i].bfn)(j); } } // Compute also the sum of the boundary normal vector (at nodes). sum_bn = 0; for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbnodes; j++) { k = (*bound[i].bnode)(j); if (j > 0 and k==(*bound[i].bnode)(0)) continue; //Skip if the last node is equal to the first node). sum_bn(0) = sum_bn(0) + (*bound[i].bnx)(j)*(*bound[i].bn)(j); sum_bn(1) = sum_bn(1) + (*bound[i].bny)(j)*(*bound[i].bn)(j); mag_bn = mag_bn + abs((*bound[i].bn)(j)); } mag_bn = mag_bn/real(bound[i].nbnodes);// } // Global sum of boundary normal vectors must vanish. if (sum_bn(0) > 1.0e-12*mag_bn and sum_bn(1) > 1.0e-12*mag_bn) { cout << "--- Global sum of the boundary normal vector:" << endl; cout << " sum of bn_x = " << sum_bn(0) << endl; cout << " sum of bn_y = " << sum_bn(1) << endl; cout << "Error: boundary normal vectors do not sum to zero..." << endl; std::exit(0);//stop program } // Sum of the directed area vectors must vanish at every node. for (size_t i = 0; i < nnodes; i++) { if ( std::abs( (*sum_dav_i)(i,0) ) > 1.0e-4 * mag_dav or std::abs( (*sum_dav_i)(i,1) ) > 1.0e-4 * mag_dav) { cout << "Error: Sum of the directed area vectors large sum_dav...\n"; cout << " --- node=" << i << "\n" << " (x,y)=" << node[i].x << " , " << node[i].y << "\n" << " sum_dav=" << (*sum_dav_i)(i,0) << " , " << (*sum_dav_i)(i,1) << endl; cout << "-------------------------------------------------------" << endl; //std::exit(0);//stop program } } //print( (*sum_dav_i) ); cout << "--- Max sum of directed area vector around a node:" << endl; // cout << " max(sum_dav_i_x) = " << maxval((*sum_dav_i)(:,0)) << endl; // cout << " max(sum_dav_i_y) = " << maxval((*sum_dav_i)(:,1)) << endl; cout << " max(sum_dav_i_x) = " << MaxColVal( (*sum_dav_i),0) << endl; cout << " max(sum_dav_i_y) = " << MaxColVal( (*sum_dav_i),1) << endl; if (MaxColVal( abs( (*sum_dav_i) ) , 0 ) > 1.0e-12 * mag_dav or MaxColVal( abs( (*sum_dav_i) ) , 1 ) > 1.0e-12 * mag_dav) { cout << "--- Max sum of directed area vector around a node:" << endl; cout << " max(sum_dav_i_x) = " << MaxColVal( (*sum_dav_i), 0) << endl; cout << " max(sum_dav_i_y) = " << MaxColVal( (*sum_dav_i), 1) << endl; cout << "Error: directed area vectors do not sum to zero..." << endl; std::exit(0);//stop } // Of course, the global sum of the directed area vector sum must vanish. sum_dav = zero; cout << "sum_dav 0 = " << sum_dav(0) << endl; cout << "sum_dav 1 = " << sum_dav(1) << endl; for (size_t i = 0; i < nnodes; i++) { sum_dav(0) = sum_dav(0) + (*sum_dav_i)(i,0) ; sum_dav(1) = sum_dav(1) + (*sum_dav_i)(i,1) ; // cout << "sum_dav i,0 =" << (*sum_dav_i)(i,0) << endl; // cout << "sum_dav i,1 =" << (*sum_dav_i)(i,1) << endl; //cout << "sum_dav i =" << (*sum_dav_i)(i,0) << sum_dav(0) << endl; //cout << "sum_dav i =" << (*sum_dav_i)(i,1) << sum_dav(1) << endl; //cout << " add them = " << sum_dav(0) + (*sum_dav_i)(i,0) << endl; } cout << "--- Global sum of the directed area vector:" << endl; cout << " sum of dav_x = " << sum_dav(0) << endl; cout << " sum of dav_y = " << sum_dav(1) << endl; if (sum_dav(1) > 1.0e-12 *mag_dav and sum_dav(2) > 1.0e-12 *mag_dav) { cout << "Error: directed area vectors do not sum globally to zero..." << endl; cout << "--- Global sum of the directed area vector:" << endl; cout << " sum of dav_x = " << sum_dav(0) << endl; cout << " sum of dav_y = " << sum_dav(1) << endl; std::exit(0);//stop } //-------------------------------------------------------------------------------- // Global sum check for boundary face vector //-------------------------------------------------------------------------------- sum_bfn = 0; // do i = 1, nbound // do j = 1, bound[i].nbfaces for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbfaces; j++) { sum_bfn(0) = sum_bfn(0) + (*bound[i].bfnx)(j)*(*bound[i].bfn)(j); sum_bfn(1) = sum_bfn(1) + (*bound[i].bfny)(j)*(*bound[i].bfn)(j); } } cout << "--- Global sum of the boundary face vector:" << endl; cout << " sum of bfn_x = " << sum_bfn(0) << endl; cout << " sum of bfn_y = " << sum_bfn(1) << endl; if (sum_bfn(1) > 1.0e-12 *mag_bn and sum_bfn(2) > 1.0e-12 *mag_bn) { cout << "Error: boundary face normals do not sum globally to zero..." << endl; cout << "--- Global sum of the boundary face normal vector:" << endl; cout << " sum of bfn_x = " << sum_bfn(0) << endl; cout << " sum of bfn_y = " << sum_bfn(1) << endl; std::exit(0);//stop } //-------------------------------------------------------------------------------- // Volume check //-------------------------------------------------------------------------------- // (1)Check the element volume: make sure there are no zero or negative volumes vol_min = 1.0e+15; vol_max = -1.0; vol_ave = zero; ierr = 0; sum_volc = zero; for ( int i = 0; i < nelms; ++i ) { vol_min = std::min(vol_min, elm[i].vol); vol_max = std::max(vol_max, elm[i].vol); vol_ave = vol_ave + elm[i].vol; sum_volc = sum_volc + elm[i].vol; if (elm[i].vol < zero) { cout << "Negative volc=" << elm[i].vol << "elm= " << i << " stop..." << endl; ierr = ierr + 1; } if ( std::abs(elm[i].vol) < 1.0e-14 ) { cout << "Vanishing volc= " << elm[i].vol << " " << std::abs(elm[i].vol) << " elm= " << i << " stop..." << endl; cout << " val = " << abs(elm[i].vol) << " tol = " << 1.0e-14 << endl; ierr = ierr + 1; } } vol_ave = vol_ave / real(nelms); cout << " " << endl; cout << " minimum element volume = " << vol_min << endl; cout << " maximum element volume = " << vol_max << endl; cout << " average element volume = " << vol_ave << endl; cout << " " << endl; //-------------------------------------------------------------------------------- // (2)Check the dual volume (volume around a node) vol_min = 1.0e+15; vol_max = -1.0; vol_ave = zero; ierr = 0; sum_vol = zero; for (size_t i = 0; i < nnodes; i++) { vol_min = std::min(vol_min,node[i].vol); vol_max = std::max(vol_max,node[i].vol); vol_ave = vol_ave + node[i].vol; sum_vol = sum_vol + node[i].vol; if (node[i].vol < zero) { cout << "Negative vol=" << node[i].vol << node << " << i << stop..." << endl; ierr = ierr + 1; } if (std::abs(node[i].vol) < 1.0e-14 ) { cout << "Vanishing vol=" << node[i].vol << node << " << i << stop..." << endl; ierr = ierr + 1; } } vol_ave = vol_ave / real(nnodes); cout << " " << endl; cout << " minimum dual volume = " << vol_min << endl; cout << " maximum dual volume = " << vol_max << endl; cout << " average dual volume = " << vol_ave << endl; cout << " " << endl; if (ierr > 0) std::exit(0);//stop if (abs(sum_vol-sum_volc) > 1.0e-08 *sum_vol) { cout << "--- Global sum of volume: must be the same" << endl; cout << " sum of volc = " << sum_volc << endl; cout << " sum of vol = " << sum_vol << endl; cout << " sum_vol-sum_volc = " << sum_vol-sum_volc << endl; cout << "Error: sum of dual volumes and cell volumes do not match..." << endl; std::exit(0);//stop } check_skewness_nc(); compute_ar(); cout << " " << endl; cout << "Grid data look good\n" << endl; cout << " " << endl; cout << " nfaces = " << nfaces << endl; cout << " nedges = " << nedges << endl; cout << " nbound = " << nbound << endl; cout << " nelms = " << nelms << endl; cout << " " << endl; } //end check_grid_data //******************************************************************************* //* Skewness computation for edges. //******************************************************************************* void EulerSolver2D::MainData2D::check_skewness_nc() { int i; real e_dot_n, e_dot_n_min, e_dot_n_max, alpha; e_dot_n = zero; e_dot_n_min = 100000.0; e_dot_n_max =-100000.0; //edges : do i = 1, nedges for (size_t i = 0; i < nedges; i++) { alpha = edge[i].ev(0) * edge[i].dav(0) + edge[i].ev(1) * edge[i].dav(1); e_dot_n = e_dot_n + std::abs(alpha); e_dot_n_min = std::min(e_dot_n_min, std::abs(alpha) ); e_dot_n_max = std::max(e_dot_n_max, std::abs(alpha) ); } //end do edges e_dot_n = e_dot_n / real(nedges); cout << " " << "\n"; cout << " ------ Skewness check (NC control volume) ----------\n"; cout << " L1(e_dot_n) = " << e_dot_n << "\n"; cout << " Min(e_dot_n) = " << e_dot_n_min << "\n"; cout << " Max(e_dot_n) = " << e_dot_n_max << "\n"; cout << " ----------------------------------------------------" << endl; }//end subroutine check_skewness_nc // //******************************************************************************* // //* Control volume aspect ratio // //******************************************************************************* void EulerSolver2D::MainData2D::compute_ar() { // use edu2d_my_main_data , only : node, nnodes, elm, nelms // use edu2d_constants , only : p2, zero, one, half, two int i, n1, n2; real ar, ar_min, ar_max, nnodes_eff; int k; real side_max, side_mid, side_min, height; Array2D<real> side(4,1); // Initialization //node1 : do i = 1, nnodes for (size_t i = 0; i < nnodes; i++) { node[i].ar = zero; } //node1 // Compute element aspect-ratio: longest_side^2 / vol //elm1: do i = 1, nelms for (size_t i =0; i < nelms; i++) { side_max = -one; //do k = 1, elm[i].nvtx for (size_t k = 0; k < elm[i].nvtx; k ++) { n1 = (*elm[i].vtx)(k); if (k == elm[i].nvtx-1) { n2 = (*elm[i].vtx)(0); } else { n2 = (*elm[i].vtx)(k+1); } side(k) = std::sqrt( (node[n2].x-node[n1].x) * (node[n2].x-node[n1].x) \ + (node[n2].y-node[n1].y) * (node[n2].y-node[n1].y) ); side_max = std::max(side_max, side(k)); }//end do if (elm[i].nvtx == 3) { // AR for triangle: Ratio of a half of a square with side_max to volume elm[i].ar = (half*side_max*side_max) / elm[i].vol; if (side(0) >= side(1) and side(0) >= side(2)) { side_max = side(0); if (side(1) >= side(2)) { side_mid = side(1); side_min = side(2); } else { side_mid = side(2); side_min = side(1); } } else if (side(1) >= side(0) and side(1) >= side(2)) { side_max = side(1); if (side(0) >= side(2)) { side_mid = side(0); side_min = side(2); } else { side_mid = side(2); side_min = side(0); } } else { side_max = side(2); if (side(0) >= side(1)) { side_mid = side(0); side_min = side(1); } else { side_mid = side(1); side_min = side(0); } } height = two*elm[i].vol/side_mid; elm[i].ar = side_mid/height; } else { // AR for quad: Ratio of a square with side_max to volume elm[i].ar = side_max*side_max / elm[i].vol; } //endif }//end do elm1 // Compute the aspect ratio: //node2 : do i = 1, nnodes for (size_t i = 0; i < nnodes; i++) { node[i].ar = zero; //do k = 1, node[i].nelms for (size_t k = 0; k < node[i].nelms; k++) { node[i].ar = node[i].ar + elm[ node[i].elm(k) ].ar; } //end do node[i].ar = node[i].ar / real(node[i].nelms); } //end do node2; // // Compute the min/max and L1 of AR nnodes_eff= zero; ar = zero; ar_min = 100000.0; ar_max =-100000.0; //node3: do i = 1, nnodes for (size_t i = 0; i < nnodes; i++) { if (node[i].bmark != -1) { continue; }//cycle node3 ar = ar + std::abs(node[i].ar); ar_min = std::min(ar_min, std::abs(node[i].ar) ); ar_max = std::max(ar_max, std::abs(node[i].ar) ); nnodes_eff = nnodes_eff + one; }//end do node3 ar = ar / nnodes_eff; cout << " \n"; cout << " ------ Aspect ratio check (NC control volume) ----------\n"; cout << " Interior nodes only \n"; cout << " L1(AR) = " << ar << "\n"; cout << " Min(AR) = " << ar_min << "\n"; cout << " Max(AR) = " << ar_max << endl; nnodes_eff= zero; ar = zero; ar_min = 100000.0; ar_max =-100000.0; //node4: do i = 1, nnodes for (size_t i = 0; i < nnodes; i++) { if (node[i].bmark == -1) {continue;} //cycle node4 ar = ar + std::abs(node[i].ar); ar_min = std::min(ar_min, std::abs(node[i].ar) ); ar_max = std::max(ar_max, std::abs(node[i].ar) ); nnodes_eff = nnodes_eff + one; }//end do node4 ar = ar / nnodes_eff; cout << " " << "\n"; cout << " Boundary nodes only" << "\n"; cout << " L1(AR) = " << ar << "\n"; cout << " min(AR) = " << ar_min << "\n"; cout << " Max(AR) = " << ar_max << "\n"; cout << " --------------------------------------------------------" << endl; } // compute_ar // //******************************* // plot grids void EulerSolver2D::MainData2D::write_tecplot_file(const std::string& datafile) { int os; // float entropy; ofstream outfile; //outfile.open ("tria_grid_tecplot.dat"); outfile.open (datafile); outfile << "title = \"grid\" \n"; outfile << "variables = \"x\" \"y\" \n"; outfile << "zone N=" << nnodes << ",E= " << ntria+nquad << ",ET=quadrilateral,F=FEPOINT \n"; //-------------------------------------------------------------------------------- for (int i=0; i<nnodes; ++i) { outfile << node[i].x << '\t' << node[i].y << "\n"; } //-------------------------------------------------------------------------------- for ( int i = 0; i < nelms; ++i ) { //Triangles if (elm[i].nvtx==3) { outfile << (*elm[i].vtx)(0,0) << '\t' << (*elm[i].vtx)(1,0) << '\t' << (*elm[i].vtx)(2,0) << '\t' << (*elm[i].vtx)(2,0) << "\n"; //The last one is a dummy. } //Quadrilaterals else if (elm[i].nvtx==4) { outfile << (*elm[i].vtx)(0,0) << '\t' << (*elm[i].vtx)(1,0) << '\t' << (*elm[i].vtx)(2,0) << '\t' << (*elm[i].vtx)(3,0) << "\n"; //The last one is a dummy. } } //-------------------------------------------------------------------------------- outfile.close(); // ofstream outfile; // outfile.open ("tria_grid_tecplot.dat"); // for (int i=1; i<ncells+1; ++i){ // outfile << std::setprecision(16) << cell[i].xc << '\t' // << std::setprecision(16) << cell[i].w(0) << '\t' // << std::setprecision(16) << cell[i].w(1) << '\t' // << std::setprecision(16) << cell[i].w(2) << '\t' // << std::setprecision(16) << entropy << "\n"; // } // outfile.close(); } //-------------------------------------------------------------------------------- //******************************************************************************** // This subroutine writes a grid file to be read by a solver. // NOTE: Unlike the tecplot file, this files contains boundary info. //******************************************************************************** void EulerSolver2D::MainData2D::write_grid_file(const std::string& datafile) {//(char* datafile) int i,j,os; //-------------------------------------------------------------------------------- ofstream outfile; outfile.open (datafile); //-------------------------------------------------------------------------------- // Grid size: # of nodes, # of triangles, # of quadrilaterals outfile << nnodes << '\t' << ntria << '\t' << nquad << "\n"; //-------------------------------------------------------------------------------- // Node data for (int i=0; i<nnodes; ++i) { outfile << node[i].x << '\t' << node[i].y << "\n"; } //-------------------------------------------------------------------------------- for ( int i = 0; i < nelms; ++i ) { //Triangles if (elm[i].nvtx==3) { outfile << (*elm[i].vtx)(0,0) << '\t' << (*elm[i].vtx)(1,0) << '\t' //<< (*elm[i].vtx)(2,0) << '\t' << (*elm[i].vtx)(2,0) << "\n"; //The last one is a dummy. } //Quadrilaterals else if (elm[i].nvtx==4) { outfile << (*elm[i].vtx)(0,0) << '\t' << (*elm[i].vtx)(1,0) << '\t' << (*elm[i].vtx)(2,0) << '\t' << (*elm[i].vtx)(3,0) << "\n"; //The last one is a dummy. } } // Boundary data: // NOTE: These boundary data are specific to the shock diffraction problem. // // Example: nx=ny=7 // // in = inflow // w = wall // e = outflow // o = interior nodes // inw = this node belongs to both inflow and wall boundaries. // we = this node belongs to both wall and outflow boundaries. // // inw----w----w----w----w----w----we // | | | | | | | // in----o----o----o----o----o----e // | | | | | | | // in----o----o----o----o----o----e // | | | | | | | // inw----o----o----o----o----o----e // | | | | | | | // w----o----o----o----o----o----e // | | | | | | | // w----o----o----o----o----o----e // | | | | | | | // we----e----e----e----e----e----e // // Number of boundary segments outfile << nbound << "\n"; //5 // outfile << (ny-1)/2+1 << "\n"; //Inflow // outfile << (ny-1)/2+1 << "\n"; //Left Wall // outfile << nx << "\n"; //Bottom Outflow // outfile << ny << "\n"; //Right Outflow // outfile << nx << "\n"; //Top Wall // outfile << "\n"; // std::cout << " Boundary conditions:" << std::endl; for (size_t i = 0; i < nbound; i++) { //std::cout << " boundary" << i << " bc_type = " << bound[i].bc_type << std::endl; outfile << bound[i].nbnodes << "\n"; } outfile << "\n"; for (size_t i = 0; i < nbound; i++) { for (size_t j = 0; j < bound[i].nbnodes; j++) { outfile << (*bound[i].bnode)(j,0) << "\n"; } } // // Inflow boundary // //do j = ny, (ny-1)/2+1, -1 // for (int j=ny-1; j<(ny-1)/2+1; ++j) { // i = 1; // outfile << i + (j-1)*nx << "\n"; // } // // // Left wall boundary // //do j = (ny-1)/2+1, 1, -1 // for (int j=(ny-1)/2+1; j>=1; --j) { // i = 1; // outfile << i + (j-1)*nx << "\n"; // } // // // Bottom outflow boundary // // do i = 1, nx // for (int i=nx-1; i<nx; ++i) { // j = 1; // outfile << i + (j-1)*nx << "\n"; // } // // // Right outflow boundary // // do j = 1, ny // for (int j=1; j<ny; ++j) { // i = nx; // outfile << i + (j-1)*nx << "\n"; // } // // // Top wall boundary // // do i = nx, 1, -1 // for (int i=0; i<nx; ++i) { // j = ny; // outfile << i + (j-1)*nx << "\n"; // } //-------------------------------------------------------------------------------- outfile.close(); } //******************************************************************************** //******************************************************************************** // This subroutine writes a grid file to be read by a solver. // NOTE: Unlike the tecplot file, this files contains boundary info. //******************************************************************************** void EulerSolver2D::MainData2D::boot_diagnostic( const std::string& filename = "out.dat") { int i,j,os; std::ostringstream message; message << " Euler Solver Log File" << endl; //-------------------------------------------------------------------------------- ofstream outfile; outfile.open( filename ); //generate new file // Number of boundary segments outfile << message.str() << "\n"; //5 outfile << "\n"; //-------------------------------------------------------------------------------- outfile.close(); } //******************************************************************************** //******************************************************************************** // This subroutine writes a grid file to be read by a solver. // NOTE: Unlike the tecplot file, this files contains boundary info. //******************************************************************************** void EulerSolver2D::MainData2D::write_diagnostic( std::ostringstream& message, const std::string& filename = "out.dat") { int i,j,os; //-------------------------------------------------------------------------------- ofstream outfile; outfile.open( filename, std::fstream::app ); // Number of boundary segments outfile << message .str() << "\n"; //5 // std::cout << " Boundary conditions:" << std::endl; // for (size_t i = 0; i < nbound; i++) { // //std::cout << " boundary" << i << " bc_type = " << bound[i].bc_type << std::endl; // outfile << bound[i].nbnodes << "\n"; // } outfile << "\n"; //-------------------------------------------------------------------------------- outfile.close(); } //********************************************************************************
33.32031
167
0.430538
[ "mesh", "vector", "solid" ]
306ff403ea625546decdc6441a8bb7ec1eb0458e
87,853
cpp
C++
VimbaOfficial/ViewerWindow.cpp
zzpwahaha/VimbaCamJILA
3baed1b5313e6c198d54a33c2c84357035d5146a
[ "MIT" ]
1
2021-06-14T11:51:37.000Z
2021-06-14T11:51:37.000Z
VimbaOfficial/ViewerWindow.cpp
zzpwahaha/VimbaCamJILA
3baed1b5313e6c198d54a33c2c84357035d5146a
[ "MIT" ]
null
null
null
VimbaOfficial/ViewerWindow.cpp
zzpwahaha/VimbaCamJILA
3baed1b5313e6c198d54a33c2c84357035d5146a
[ "MIT" ]
2
2021-01-20T16:22:57.000Z
2021-02-14T12:31:02.000Z
/*============================================================================= Copyright (C) 2012 - 2019 Allied Vision Technologies. All Rights Reserved. Redistribution of this file, in original or modified form, without prior written consent of Allied Vision Technologies is prohibited. ------------------------------------------------------------------------------- File: ViewerWindow.cpp Description: The viewer window framework. This contains of dock widgets like camera feature tree, a histogram, a toolbar and MDI window ------------------------------------------------------------------------------- THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 "ViewerWindow.h" #include <QTimer> #include "UI/LineEditCompleter.h" #include "UI/SortFilterProxyModel.h" #include "SplashScreen.h" #include "UI/tabextensioninterface.h" #include "UI/ControllerTreeWindow.h" #include "UI/DockWidgetWindow.h" #include "UI/Histogram/HistogramWindow.h" #include "UI/MainInformationWindow.h" #include "UI/Viewer.h" #include "VmbImageTransformHelper.hpp" using AVT::VmbAPI::Frame; using AVT::VmbAPI::FramePtr; #ifndef _WIN32 #include <unistd.h> #endif void ViewerWindow::showSplashScreen(const QString& sID,QWidget* parent) { bool bIsModelFound = true; QPixmap pixmap; // We expect ID to be of format: Modelname (DevicePartNumber)-DeviceID(DEV_MAC@) while MAC@ has 12 digits if ( sID.startsWith( "1800" ) ) pixmap.load( ":/VimbaViewer/Images/1800U.png" ); else if ( sID.contains( "Mako" )) pixmap.load( ":/VimbaViewer/Images/mako.png" ); else if(sID.contains("Manta")) pixmap.load( ":/VimbaViewer/Images/manta.png" ); else if(sID.contains("GT")) { if ( sID.contains( "4100 " ) || sID.contains( "4905" ) || sID.contains( "4907" ) || sID.contains( "6600" )) pixmap.load( ":/VimbaViewer/Images/prosilicagt-large.png" ); else pixmap.load( ":/VimbaViewer/Images/prosilicagt.png" ); } else if(sID.contains("GC")) pixmap.load( ":/VimbaViewer/Images/prosilicagc.png" ); else if(sID.contains("GX")) pixmap.load( ":/VimbaViewer/Images/prosilicagx.png" ); else if(sID.contains("GE")) pixmap.load( ":/VimbaViewer/Images/prosilicage.png" ); else if(sID.contains("Marlin")) pixmap.load( ":/VimbaViewer/Images/marlin.png" ); else if(sID.contains("Guppy")) { if ( sID.contains( "PRO" )) pixmap.load( ":/VimbaViewer/Images/guppy-pro.png" ); else pixmap.load( ":/VimbaViewer/Images/guppy.png" ); } else if(sID.contains("Oscar")) pixmap.load( ":/VimbaViewer/Images/oscar.png" ); else if(sID.contains("Pike")) pixmap.load( ":/VimbaViewer/Images/pike.png" ); else if(sID.contains("Stingray")) pixmap.load( ":/VimbaViewer/Images/stingray.png" ); else if(sID.contains("Bigeye")) pixmap.load( ":/VimbaViewer/Images/bigeye.png" ); else if(sID.contains("Goldeye P")) pixmap.load( ":/VimbaViewer/Images/goldeye-p.png" ); else if(sID.contains("Goldeye G") || sID.contains("Goldeye CL")) { if ( sID.contains( "Cool" )) pixmap.load( ":/VimbaViewer/Images/goldeye-g-cool.png" ); else pixmap.load( ":/VimbaViewer/Images/goldeye-g.png" ); } else { pixmap.load( ":/VimbaViewer/Images/stripes_256.png" ); bIsModelFound = false; } SplashScreen splashScreen(pixmap, parent, Qt::SplashScreen); const int posX = (parent->width() - splashScreen.width()) / 2; const int posY = (parent->height() - splashScreen.height()) / 2; splashScreen.setGeometry( posX, posY, splashScreen.width(), splashScreen.height() ); splashScreen.show(); if(bIsModelFound) { splashScreen.showMessage("" , Qt::AlignHCenter | Qt::AlignVCenter, Qt::white); } else { splashScreen.showMessage("" , Qt::AlignHCenter | Qt::AlignVCenter, Qt::black); } } ViewerWindow::ViewerWindow ( QWidget *parent, Qt::WindowFlags flag, QString sID, QString sAccess, bool bAutoAdjustPacketSize, CameraPtr pCam ) : QMainWindow( NULL, flag ) , m_DockController( NULL ) , m_DockInformation( NULL ) , m_Controller( NULL ) , m_ScreenViewer( NULL ) , m_InformationWindow( NULL ) , m_bHasJustStarted ( false ) , m_bIsFirstStart ( true ) , m_bIsCameraRunning ( false ) , m_bIsCamOpen ( false ) , m_bIsRedHighlighted ( false ) , m_bIsViewerWindowClosing ( false ) , m_bIsDisplayEveryFrame ( false ) , m_ImageOptionDialog ( NULL ) , m_saveFileDialog ( NULL ) , m_getDirDialog ( NULL ) , m_bIsTriggeredByMultiSaveBtn (false) , m_nNumberOfFramesToSave (0) , m_FrameBufferCount (BUFFER_COUNT) , m_pCam( pCam ) { showSplashScreen(sID,parent); VmbError_t errorType; QTime openTimer; openTimer.start(); /* setup information window */ m_InformationWindow = new MainInformationWindow(m_DockInformation, 0, m_pCam); m_InformationWindow->openLoggingWindow(); if( 0 == sAccess.compare(tr("Open FULL ACCESS"))) { errorType = m_pCam->Open(VmbAccessModeFull); m_sAccessMode = tr("(FULL ACCESS)"); } else if( 0 == sAccess.compare(tr("Open READ ONLY"))) { errorType = m_pCam->Open(VmbAccessModeRead); m_sAccessMode = tr("(READ ONLY)"); bAutoAdjustPacketSize = false; } else if( 0 == sAccess.compare(tr("Open CONFIG"))) { errorType = m_pCam->Open(VmbAccessModeConfig); m_sAccessMode = tr("(CONFIG MODE)"); bAutoAdjustPacketSize = false; } else if( 0 == sAccess.compare(tr("Open LITE"))) { errorType = m_pCam->Open(VmbAccessModeLite); m_sAccessMode = tr("(LITE)"); bAutoAdjustPacketSize = false; } else { errorType = VmbErrorInvalidAccess; bAutoAdjustPacketSize = false; } m_OpenError = errorType; if( VmbErrorSuccess != errorType ) { openTimer.elapsed(); return; } m_sCameraID = sID; /* create ViewerWindow */ setupUi(this); if(!m_sAccessMode.isEmpty()) { sID.append(" "); sID.append(m_sAccessMode); } this->setWindowTitle(sID); ActionFreerun->setEnabled(isStreamingAvailable()); /* add Viewer Widget to ViewerWindow*/ m_pScene = QSharedPointer<QGraphicsScene>(new QGraphicsScene()); m_PixmapItem = new QGraphicsPixmapItem(); m_ScreenViewer = new Viewer(Ui::ViewerWindow::centralWidget); m_ScreenViewer->setScene(m_pScene.data()); m_pScene->addItem(m_PixmapItem); this->setCentralWidget( m_ScreenViewer ); QPixmap image( ":/VimbaViewer/Images/stripes_256.png" ); m_PixmapItem->setPixmap(image); m_ScreenViewer->show(); m_bIsCamOpen = true; /* add DockWidgets: Controller and Information */ m_DockController = new DockWidgetWindow(tr("Controller for ")+sID, this); m_DockInformation = new DockWidgetWindow(tr("Information for ")+sID, this); m_DockHistogram = new DockWidgetWindow(tr("Histogram for ")+sID, this); m_DockController->setObjectName("Controller"); m_DockInformation->setObjectName("Information"); m_DockHistogram->setObjectName("Histogram"); this->addDockWidget(static_cast<Qt::DockWidgetArea>(2), m_DockController); this->addDockWidget(Qt::BottomDockWidgetArea, m_DockInformation); this->addDockWidget(static_cast<Qt::DockWidgetArea>(1), m_DockHistogram); m_DockHistogram->hide(); /* add Controller Tree */ QWidget *dockWidgetContents = new QWidget(); QVBoxLayout *verticalLayout2 = new QVBoxLayout(dockWidgetContents); QSplitter *splitter = new QSplitter(dockWidgetContents); QWidget *verticalLayoutWidget = new QWidget(splitter); QVBoxLayout *verticalLayout = new QVBoxLayout(verticalLayoutWidget); QTabWidget *tabWidget = new QTabWidget(verticalLayoutWidget); QWidget *widgetTree = new QWidget(); QVBoxLayout *verticalLayout3 = new QVBoxLayout(widgetTree); m_Description = new QTextEdit(); m_Controller = new ControllerTreeWindow(m_sCameraID, widgetTree, bAutoAdjustPacketSize, m_pCam); if (VmbErrorSuccess != m_Controller->getTreeStatus()) { onFeedLogger("ERROR: ControllerTree returned: "+QString::number(m_Controller->getTreeStatus()) + " " + Helper::mapReturnCodeToString(m_Controller->getTreeStatus())); } m_Description->setLineWrapMode(QTextEdit::NoWrap); m_Description->setReadOnly(true); m_Description->setStyleSheet("font: 12px;\n" "font-family: Verdana;\n"); QList<int> listSize; listSize << 5000; splitter->setChildrenCollapsible(false); splitter->setOrientation(Qt::Vertical); splitter->addWidget(verticalLayoutWidget); splitter->addWidget(m_Description); splitter->setSizes(listSize); /* Filter Pattern */ QHBoxLayout *pattern_HLayout = new QHBoxLayout(); m_FilterPatternLineEdit = new LineEditCompleter(this); m_FilterPatternLineEdit->setText(tr("Example: Gain|Width")); m_FilterPatternLineEdit->setToolTip(tr("To filter multiple features, e.g: Width|Gain|xyz|etc")); m_FilterPatternLineEdit->setCompleter(m_Controller->getListCompleter()); m_FilterPatternLineEdit->setMinimumWidth(200); QLabel *filterPatternLabel = new QLabel(tr("Filter pattern:")); filterPatternLabel->setStyleSheet("font-weight: bold;"); QPushButton *patternButton = new QPushButton(tr("Search")); pattern_HLayout->addWidget(filterPatternLabel); pattern_HLayout->addWidget(m_FilterPatternLineEdit); pattern_HLayout->addWidget(patternButton); verticalLayout3->addLayout(pattern_HLayout); connect(m_FilterPatternLineEdit, SIGNAL(returnPressed()), this, SLOT(textFilterChanged())); connect(patternButton, SIGNAL(clicked(bool)), this, SLOT(textFilterChanged())); verticalLayout->setContentsMargins(0, 0, 0, 0); verticalLayout->addWidget(tabWidget); verticalLayout2->addWidget(splitter); verticalLayout3->addWidget(m_Controller); tabWidget->setStyleSheet("color: rgb(0, 0, 0);"); // closed source injected if (loadPlugin()) { FeaturePtrVector featVec; pCam->GetFeatures(featVec); QVector<FeaturePtr> tmpFeatures = QVector<FeaturePtr>::fromStdVector(featVec); QSharedPointer<QVector<FeaturePtr> > qFeatVec = QFeatureVectorPtr( new QVector<FeaturePtr>(tmpFeatures)); for (int i = 0; i < m_TabPluginCount; i++) { QWidget *plugtabWidget = new QWidget(); TabExtensionResult result = m_tabExtensionInterface[i]->get(qFeatVec, *plugtabWidget); if ( result == TER_OK) { m_tabExtensionInterface[i]->connectToResetFps(this, SLOT(onResetFPS())); m_tabExtensionInterface[i]->connectFromAcquire(this, SIGNAL(acquisitionRunning(bool))); tabWidget->addTab(plugtabWidget, plugtabWidget->accessibleName()); } else { delete plugtabWidget; } } } tabWidget->addTab(widgetTree, tr("All")); m_DockController->setWidget(dockWidgetContents); connect(tabWidget, SIGNAL(currentChanged(int)), m_Controller, SLOT(closeControls())); /* tooltip checkbox */ m_ToolTipCheckBox = new QCheckBox(); m_ToolTipCheckBox->setText(tr("Tooltip ON")); m_ToolTipCheckBox->setChecked(true); verticalLayout3->addWidget(m_ToolTipCheckBox); connect( m_ToolTipCheckBox, SIGNAL(clicked(bool)), this, SLOT(onTooltipCheckBoxClick(bool)) ); connect(m_DockController, SIGNAL(topLevelChanged (bool)), this, SLOT(onfloatingDockChanged(bool))); connect(m_DockInformation, SIGNAL(topLevelChanged (bool)), this, SLOT(onfloatingDockChanged(bool))); connect(m_DockHistogram, SIGNAL(topLevelChanged (bool)), this, SLOT(onfloatingDockChanged(bool))); connect(m_DockController, SIGNAL(visibilityChanged(bool)), this, SLOT(onVisibilityChanged(bool))); connect(m_DockInformation, SIGNAL(visibilityChanged(bool)), this, SLOT(onVisibilityChanged(bool))); connect(m_DockHistogram, SIGNAL(visibilityChanged(bool)), this, SLOT(onVisibilityChanged(bool))); connect(m_Controller, SIGNAL(setDescription(const QString &)), this, SLOT(onSetDescription(const QString &))); connect(m_Controller, SIGNAL(setEventMessage(const QStringList &)), this, SLOT(onSetEventMessage(const QStringList &)), Qt::QueuedConnection); connect(m_Controller, SIGNAL(acquisitionStartStop(const QString &)), this, SLOT(onAcquisitionStartStop(const QString &))); // this eventually calls RegisterObserver in Frame.h which make sure As new frames arrive, the observer's FrameReceived method will be called. Only one observer can be registered. connect(m_Controller, SIGNAL(updateBufferSize()), this, SLOT(onPrepareCapture())); connect(m_Controller, SIGNAL(resetFPS()), this, SLOT(onResetFPS())); connect(m_Controller, SIGNAL(logging(const QString &)), this, SLOT(onFeedLogger( const QString &))); connect(m_ScreenViewer, SIGNAL(savingImage()), this, SLOT(on_ActionSaveAs_triggered())); connect(m_ScreenViewer, SIGNAL(setColorInterpolationState(const bool &)), this, SLOT(onSetColorInterpolation(const bool &))); /* create FrameObserver to get frames from camera */ SP_SET( m_pFrameObs, new FrameObserver(m_pCam) ); connect(SP_ACCESS( m_pFrameObs ), SIGNAL(frameReadyFromObserver (QImage , const QString&, const QString&, const QString&)), this, SLOT(onimageReady(QImage , const QString&, const QString&, const QString&))); connect(SP_ACCESS( m_pFrameObs ), SIGNAL(frameReadyFromObserverFullBitDepth (tFrameInfo)), this, SLOT(onFullBitDepthImageReady(tFrameInfo))); connect(SP_ACCESS( m_pFrameObs ), SIGNAL(setCurrentFPS (const QString &)), this, SLOT(onSetCurrentFPS(const QString &))); connect(SP_ACCESS( m_pFrameObs ), SIGNAL(setFrameCounter (const unsigned int &)), this, SLOT(onSetFrameCounter(const unsigned int &))); /* HISTOGRAM: We need to register QVector<QVector <quint32> > because it is not known to Qt's meta-object system */ qRegisterMetaType< QVector<QVector <quint32> > >("QVector<QVector <quint32> >"); qRegisterMetaType< QVector <QStringList> >("QVector <QStringList>"); connect(m_pFrameObs.get(), SIGNAL(histogramDataFromObserver ( const QVector<QVector <quint32> > &, const QString &, const double &, const double &, const QVector <QStringList>& )), this, SLOT(onSetHistogramData( const QVector<QVector <quint32> > &, const QString &, const double &, const double & , const QVector <QStringList>&))); m_DockInformation->setWidget(m_InformationWindow); int openElapsedTime = openTimer.elapsed(); if( openElapsedTime <= 2500 ) { #ifdef WIN32 Sleep(2500-openElapsedTime); #else usleep( (2500-openElapsedTime) * 1000 ); #endif } /* use default setting position and geometry */ QSettings settings("Allied Vision", "Vimba Viewer"); this->restoreGeometry(settings.value("geometry").toByteArray()); this->restoreState( settings.value("state").toByteArray(), 0 ); this->show(); (!m_DockController->isFloating() && !m_DockInformation->isFloating() && m_DockController->isVisible() && m_DockInformation->isVisible()) ? ActionResetPosition->setEnabled(false) : ActionResetPosition->setEnabled(true); if( VmbErrorSuccess != m_Controller->getTreeStatus()) { onFeedLogger("ERROR: GetFeatures returned: "+QString::number(m_Controller->getTreeStatus()) + " " + Helper::mapReturnCodeToString(m_Controller->getTreeStatus())); } /* Histogram */ m_HistogramWindow = new HistogramWindow(this); m_DockHistogram->setWidget(m_HistogramWindow); m_HistogramWindow->createGraphWidgets(); m_DockHistogram->isVisible() ? ActionHistogram->setChecked(true) : ActionHistogram->setChecked(false); /* Statusbar */ m_OperatingStatusLabel = new QLabel(" Ready "); m_FormatLabel = new QLabel; m_ImageSizeLabel = new QLabel; m_FramesLabel = new QLabel; m_FramerateLabel = new QLabel; statusbar->addWidget(m_OperatingStatusLabel); statusbar->addWidget(m_ImageSizeLabel); statusbar->addWidget(m_FormatLabel); statusbar->addWidget(m_FramesLabel); statusbar->addWidget(m_FramerateLabel); m_OperatingStatusLabel->setStyleSheet("background-color: rgb(0,0, 0); color: rgb(255,255,255)"); m_TextItem = new QGraphicsTextItem; QFont serifFont("Arial", 12, QFont::Bold); m_TextItem->setFont(serifFont); m_TextItem->setDefaultTextColor(Qt::red); /*Save Images Option */ m_ImageOptionDialog = new QDialog(this, windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinimizeButtonHint & ~Qt::WindowMaximizeButtonHint); m_SaveImageOption.setupUi(m_ImageOptionDialog); if(!settings.value(m_sCameraID).toString().isEmpty()) m_SaveImageOption.ImageDestination_Edit->setText (settings.value(m_sCameraID).toString()); else { m_SaveImageOption.ImageDestination_Edit->setText( QString( #ifdef WIN32 "C:\\" #else "/home/" #endif )); } connect(m_SaveImageOption.ImageDestinationButton, SIGNAL(clicked()),this, SLOT(getSaveDestinationPath())); connect(m_ImageOptionDialog, SIGNAL(accepted()),this, SLOT(acceptSaveImagesDlg())); connect(m_ImageOptionDialog, SIGNAL(rejected()),this, SLOT(rejectSaveImagesDlg())); if(!settings.value(m_sCameraID+"SaveImageName").toString().isEmpty()) m_SaveImageOption.ImageName_Edit->setText (settings.value(m_sCameraID+"SaveImageName").toString()); else m_SaveImageOption.ImageName_Edit->setText("VimbaImage"); /* Direct Access */ m_AccessDialog = new QDialog(this, windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinimizeButtonHint & ~Qt::WindowMaximizeButtonHint); m_DirectAccess.setupUi(m_AccessDialog); m_DirectAccess.RegAdd_Edit->setMaxLength(8); m_DirectAccess.RegData_Edit->setMaxLength(8); m_DirectAccess.RegAdd_Edit->setText("FFFFFFFC"); m_DirectAccess.RegData_Edit->setText("00000000"); m_DirectAccess.RegDataDec_Edit->setText("0"); VmbInterfaceType InterfaceType = VmbInterfaceUnknown; m_DirectAccess.CheckBoxEndianess->setVisible( VmbErrorSuccess == m_pCam->GetInterfaceType(InterfaceType) ); m_DirectAccess.CheckBoxEndianess->setChecked( VmbInterfaceUsb == InterfaceType ); m_DirectAccess.CheckBoxEndianess->setToolTip( m_DirectAccess.CheckBoxEndianess->toolTip() + " (your device was detected to be " + (VmbInterfaceUsb == InterfaceType ? "little" : "big") + " endian)"); m_AccessDialog->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinimizeButtonHint); QRegExp rxHex("[0-9A-Fa-f]{1,8}"); m_DirectAccess.RegAdd_Edit->setValidator(new QRegExpValidator(rxHex, m_DirectAccess.RegAdd_Edit)); m_DirectAccess.RegData_Edit->setValidator(new QRegExpValidator(rxHex, m_DirectAccess.RegData_Edit)); QRegExp rxDec("[0-9]{1,10}"); m_DirectAccess.RegDataDec_Edit->setValidator(new QRegExpValidator(rxDec, m_DirectAccess.RegDataDec_Edit)); connect(m_DirectAccess.RegWrite_Button , SIGNAL(clicked()) , this, SLOT(writeRegisterData())); connect(m_DirectAccess.RegRead_Button , SIGNAL(clicked()) , this, SLOT(readRegisterData())); connect(m_DirectAccess.RegData_Edit , SIGNAL(textChanged(const QString&)) , this, SLOT(directAccessHexTextChanged(const QString&))); connect(m_DirectAccess.RegDataDec_Edit , SIGNAL(textChanged(const QString&)) , this, SLOT(directAccessDecTextChanged(const QString&))); connect(m_DirectAccess.CheckBoxEndianess, SIGNAL(stateChanged(int)) , this, SLOT(endianessChanged(int))); /*Viewer Option */ m_ViewerOptionDialog = new QDialog(this, windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinimizeButtonHint & ~Qt::WindowMaximizeButtonHint); m_ViewerOption.setupUi(m_ViewerOptionDialog); m_ViewerOption.lineEdit_FramesCount->setText(QString::number( m_FrameBufferCount )); connect( m_ViewerOption.lineEdit_FramesCount, SIGNAL(textChanged(const QString&)),this, SLOT(optionsFrameCountChanged(const QString&))); connect( m_ViewerOption.DisplayInterval_CheckBox, SIGNAL(clicked(bool)), this, SLOT(displayEveryFrameClick(bool))); connect( m_ViewerOption.buttonBox, SIGNAL(accepted()),this, SLOT(optionsAccepted())); //connect(parent, SIGNAL(closeViewer()), this, SLOT(close())); if (ActionHistogram->isChecked()) { m_HistogramWindow->initializeStatistic(); m_pFrameObs->enableHistogram(true); } else m_pFrameObs->enableHistogram(false); m_Timer = new QTimer(this); connect(m_Timer, SIGNAL(timeout()), this, SLOT(updateColorInterpolationState())); /* enable/disable menu */ connect(m_Controller, SIGNAL(enableViewerMenu(bool)), this, SLOT(enableMenuAndToolbar(bool))); /* saving images */ m_SaveImageThread = QSharedPointer<SaveImageThread>(new SaveImageThread()); connect( m_SaveImageThread.data(), SIGNAL(setPosition(unsigned int)), this, SLOT(onSaving(unsigned int))); connect( m_SaveImageThread.data(), SIGNAL( LogMessage(const QString&)), this, SLOT(onFeedLogger(const QString&)) ); if (m_TabPluginCount == 0) // All Tab is visible set focus to "search" { m_FilterPatternLineEdit->setFocus(); } m_FilterPatternLineEdit->selectAll(); #ifdef WIN32 m_SelectedExtension = ".bmp"; #else m_SelectedExtension = ".png"; #endif // test if the LibTiff library is available on this system m_LibTiffAvailable = m_TiffWriter.IsAvailable(); ActionAllow16BitTiffSaving->setEnabled(m_LibTiffAvailable); } ViewerWindow::~ViewerWindow() { /* save setting position and geometry from last session */ QSettings settings("Allied Vision", "Vimba Viewer"); settings.setValue("geometry", saveGeometry()); settings.setValue("state", saveState(0)); /* If cam is open */ if(!m_sCameraID.isEmpty()) { settings.setValue(m_sCameraID, m_SaveImageOption.ImageDestination_Edit->text()); if(!m_SaveName.isEmpty()) settings.setValue(m_sCameraID +"SaveImageName", m_SaveName); if( NULL != m_saveFileDialog ) { delete m_saveFileDialog; m_saveFileDialog = NULL; } releaseBuffer(); m_pCam->Close(); } } void ViewerWindow::textFilterChanged() { QPixmap pixmap( ":/VimbaViewer/Images/refresh.png" ); SplashScreen splashScreen(pixmap, m_Controller, Qt::SplashScreen); int nW = ((m_Controller->width()/2) - splashScreen.width()/2); int nH = ((m_Controller->height()/2) - splashScreen.height()/2); splashScreen.setGeometry(nW,nH, splashScreen.width(),splashScreen.height()); splashScreen.show(); splashScreen.showMessage("Please wait..." , Qt::AlignHCenter | Qt::AlignVCenter, Qt::red); QRegExp::PatternSyntax syntax = QRegExp::PatternSyntax(0); Qt::CaseSensitivity caseSensitivity = Qt::CaseInsensitive; QRegExp regExp(m_FilterPatternLineEdit->text(), caseSensitivity, syntax); m_Controller->m_ProxyModel->setFilterRegExp(regExp); m_Controller->expandAll(); m_Controller->updateUnRegisterFeature(); m_Controller->updateRegisterFeature(); m_FilterPatternLineEdit->setFocus(); m_FilterPatternLineEdit->selectAll(); } void ViewerWindow::enableMenuAndToolbar ( bool bValue ) { menuBarMainWindow->setEnabled(bValue); toolBar->setEnabled(bValue); } void ViewerWindow::onTooltipCheckBoxClick ( bool bValue ) { m_Controller->showTooltip ( bValue ); } void ViewerWindow::updateColorInterpolationState() { /* update interpolation state after start */ m_ScreenViewer->updateInterpolationState(m_pFrameObs->getColorInterpolation()); m_Timer->stop(); } void ViewerWindow::onSetColorInterpolation ( const bool &bState ) { m_pFrameObs->setColorInterpolation(bState); } bool ViewerWindow::getCamOpenStatus() const { return m_bIsCamOpen; } CameraPtr ViewerWindow::getCameraPtr() { return m_pCam; } bool ViewerWindow::isControlledCamera( const CameraPtr &cam) const { return SP_ACCESS( cam) == SP_ACCESS( m_pCam ); } bool ViewerWindow::getAdjustPacketSizeMessage ( QString &sMessage ) { if(m_Controller->isGigE()) { if(VmbErrorSuccess == m_Controller->getTreeStatus()) { sMessage = "Packet Size Adjusted:\t"; } else { sMessage = "Failed To Adjust Packet Size!"; sMessage.append(" Reason: " + Helper::mapReturnCodeToString(m_Controller->getTreeStatus())); } return true; } return false; } VmbError_t ViewerWindow::getOpenError() const { return m_OpenError; } QString ViewerWindow::getCameraID() const { return m_sCameraID; } void ViewerWindow::closeEvent ( QCloseEvent *event ) { if (m_bIsCameraRunning) { m_bIsViewerWindowClosing = true; onAcquisitionStartStop("AcquisitionStopFreerun"); } emit closeViewer( m_pCam ); } void ViewerWindow::displayEveryFrameClick ( bool bValue ) { m_ViewerOption.Note_Label->setEnabled(bValue); m_bIsDisplayEveryFrame = bValue; } /* Viewer Option */ void ViewerWindow::on_ActionDisplayOptions_triggered() { m_ViewerOption.lineEdit_FramesCount->setText(QString::number ( m_FrameBufferCount )); m_ViewerOptionDialog->exec(); } void ViewerWindow::on_ActionResetPosition_triggered() { m_DockController ->setFloating(false); m_DockInformation->setFloating(false); m_DockHistogram ->setFloating(false); m_DockController ->show(); m_DockInformation->show(); m_DockHistogram ->hide(); ActionHistogram ->setChecked(false); ActionResetPosition->setEnabled(false); } /* Direct Register Access */ void ViewerWindow::on_ActionRegister_triggered() { m_DirectAccess.RegAccessError_Label->clear(); m_DirectAccess.RegAccessError_Label->setStyleSheet(""); m_DirectAccess.RegAdd_Edit->setFocus(); m_DirectAccess.RegAdd_Edit->selectAll(); m_AccessDialog->show(); } void ViewerWindow::optionsFrameCountChanged ( const QString &sText ) { bool bOk; unsigned int frames = sText.toUInt(&bOk); if(!bOk) { m_ViewerOption.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); return; } if( (0 != QString::number(frames).compare(m_ViewerOption.lineEdit_FramesCount->text())) ||(frames < 2)) { m_ViewerOption.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); return; } m_ViewerOption.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); } void ViewerWindow::optionsAccepted() { bool bOk; unsigned int frames = m_ViewerOption.lineEdit_FramesCount->text().toUInt(&bOk); if (!bOk) { return; } m_FrameBufferCount = frames; } void ViewerWindow::directAccessHexTextChanged ( const QString &sText ) { bool bOk; unsigned int sDec = sText.toUInt(&bOk, 16); endianessConvert( sDec ); if(0 == QString::number(sDec).compare(m_DirectAccess.RegDataDec_Edit->text())) return; else m_DirectAccess.RegDataDec_Edit->setText(QString::number(sDec)); } void ViewerWindow::directAccessDecTextChanged ( const QString &sText ) { unsigned int lDecValue = sText.toUInt(); endianessConvert( lDecValue ); QString sHex; sHex.setNum(lDecValue,16); if(0 == sHex.compare(m_DirectAccess.RegData_Edit->text())) return; else m_DirectAccess.RegData_Edit->setText(sHex); } void ViewerWindow::writeRegisterData() { bool bOk; qlonglong lRegAddress = m_DirectAccess.RegAdd_Edit->text().toLongLong(&bOk, 16); qlonglong lRegData = m_DirectAccess.RegData_Edit->text().toLongLong(&bOk, 16); m_DirectAccess.RegAccessError_Label->clear(); m_DirectAccess.RegAccessError_Label->setStyleSheet("background-color: rgb(240,240,240); color: rgb(0,0,0)"); m_DirectAccess.RegDataDec_Edit->setFocus(); m_DirectAccess.RegDataDec_Edit->selectAll(); std::vector<VmbUint64_t> address; address.push_back((VmbUint64_t)lRegAddress); std::vector<VmbUint64_t> data; data.push_back((VmbUint64_t)lRegData); VmbError_t errorType = m_pCam->WriteRegisters(address, data); if( VmbErrorSuccess != errorType ) { m_DirectAccess.RegAccessError_Label->setStyleSheet("background-color: rgb(0,0,0); color: rgb(255,0,0)"); m_DirectAccess.RegAccessError_Label->setText(" "+tr("Write Register Failed!")+" <"+tr("Error")+": " + QString::number(errorType) + ">"); } } void ViewerWindow::readRegisterData() { bool bOk; qlonglong lRegAddress = m_DirectAccess.RegAdd_Edit->text().toLongLong(&bOk, 16); m_DirectAccess.RegAccessError_Label->clear(); m_DirectAccess.RegAccessError_Label->setStyleSheet("background-color: rgb(240,240,240); color: rgb(0,0,0)"); std::vector<VmbUint64_t> address; address.push_back((VmbUint64_t)lRegAddress); std::vector<VmbUint64_t> data; data.resize(1); VmbError_t errorType = m_pCam->ReadRegisters(address, data); if( VmbErrorSuccess != errorType ) { m_DirectAccess.RegAccessError_Label->setStyleSheet("background-color: rgb(0,0,0); color: rgb(255,0,0)"); m_DirectAccess.RegAccessError_Label->setText(" "+tr("Read Register Failed!")+" <"+tr("Error:")+" " + QString::number(errorType) + ">"); return; } QString sData = QString("%1").arg(data[0], 8, 16, QLatin1Char('0')); m_DirectAccess.RegData_Edit->setText(sData); } void ViewerWindow::endianessChanged(int index) { emit directAccessDecTextChanged( m_DirectAccess.RegDataDec_Edit->text() ); } template <typename T> void ViewerWindow::endianessConvert(T &v) { if( Qt::Checked == m_DirectAccess.CheckBoxEndianess->checkState() ) { v = qFromBigEndian( v ); } } /* Saving an image */ void ViewerWindow::on_ActionSaveAs_triggered() { // make a copy of the images before save-as dialog appears (image can change during time dialog open) QImage image = m_PixmapItem->pixmap().toImage(); tFrameInfo imageFullBitdepth = m_FullBitDepthImage; QString fileExtension; bool isImageAvailable = true; if ( image.isNull() ) { isImageAvailable = false; } else { /* Get all inputformats */ unsigned int nFilterSize = QImageReader::supportedImageFormats().count(); for (int i = nFilterSize-1; i >= 0; i--) { fileExtension += "."; /* Insert wildcard */ fileExtension += QString(QImageReader::supportedImageFormats().at(i)).toLower(); /* Insert the format */ if(0 != i) fileExtension += ";;"; /* Insert a space */ } if( NULL != m_saveFileDialog ) { delete m_saveFileDialog; m_saveFileDialog = NULL; } m_saveFileDialog = new QFileDialog ( this, tr("Save Image"), m_SaveFileDir, fileExtension ); m_saveFileDialog->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinimizeButtonHint & ~Qt::WindowMaximizeButtonHint); m_saveFileDialog->selectNameFilter(m_SelectedExtension); m_saveFileDialog->setAcceptMode(QFileDialog::AcceptSave); if(m_saveFileDialog->exec()) { //OK m_SelectedExtension = m_saveFileDialog->selectedNameFilter(); m_SaveFileDir = m_saveFileDialog->directory().absolutePath(); QStringList files = m_saveFileDialog->selectedFiles(); if(!files.isEmpty()) { QString fileName = files.at(0); if(!fileName.endsWith(m_SelectedExtension)) { fileName.append(m_SelectedExtension); } bool saved = false; // save image using LibTiff library for 16 Bit if( m_LibTiffAvailable && ActionAllow16BitTiffSaving->isChecked() && m_SelectedExtension.contains(".tif") && isSupportedPixelFormat()) { saved = m_TiffWriter.WriteTiff(imageFullBitdepth, fileName.toUtf8()); } // use default QImage save functionality else { if( true == CanReduceBpp() ) { saved = ReduceBpp( image ).save( fileName ); } else { saved = image.save( fileName ); } } if ( true == saved ) { QMessageBox::information( this, tr( "Vimba Viewer" ), tr( "Image: " ) + fileName + tr( " saved successfully" )); } else { QMessageBox::warning( this, tr( "Vimba Viewer" ), tr( "Error saving image" )); } } } } if ( !isImageAvailable ) { QMessageBox::warning( this, tr( "Vimba Viewer" ), tr( "No image to save" )); } } /* Saving multiple images */ void ViewerWindow::on_ActionSaveOptions_triggered() { QStringList sListFormat; for (int i = 0; i < QImageReader::supportedImageFormats().count(); i++) { QString sTemp; sTemp.append("."); /* Insert wildcard */ sTemp.append(QString(QImageReader::supportedImageFormats().at(i)).toLower()); /* Insert the format */ sListFormat << sTemp; } sListFormat << ".bin"; m_SaveImageOption.ImageFormat_ComboBox->clear(); m_SaveImageOption.ImageFormat_ComboBox->addItems(sListFormat); // restore previously selected format (if possible) if ( false == m_SaveFormat.isEmpty() ) { int index = m_SaveImageOption.ImageFormat_ComboBox->findText(m_SaveFormat); if( -1 != index ) { m_SaveImageOption.ImageFormat_ComboBox->setCurrentIndex(index); } } m_ImageOptionDialog->setModal(true); m_ImageOptionDialog->show(); } void ViewerWindow::acceptSaveImagesDlg() { if( !m_SaveImageOption.ImageDestination_Edit->text().isEmpty() && !m_SaveImageOption.ImageName_Edit->text().isEmpty() ) { m_ImagePath = m_SaveImageOption.ImageDestination_Edit->text(); } else { if(m_SaveImageOption.ImageDestination_Edit->text().isEmpty()) QMessageBox::warning( this, tr("Vimba Viewer"), "<Save Image Options> "+tr("Please choose your destination path!") ); if(m_SaveImageOption.ImageName_Edit->text().isEmpty()) QMessageBox::warning( this, tr("Vimba Viewer"), "<Save Image Options> "+tr("Please give a name!") ); m_ImageOptionDialog->setModal(true); m_ImageOptionDialog->show(); } /* name check existing files */ QDir destDir( m_SaveImageOption.ImageDestination_Edit->text()); QStringList filter; for (int i = 0; i < QImageReader::supportedImageFormats().count(); i++) { QString sTemp; sTemp.append("*."); /* Insert wildcard */ sTemp.append(QString(QImageReader::supportedImageFormats().at(i)).toLower()); /* Insert the format */ filter << sTemp; } destDir.setNameFilters(filter); QStringList files = destDir.entryList(); bool bRes = true; while(bRes) { bRes = checkUsedName(files); } if(0 < m_SaveImageOption.NumberOfFrames_SpinBox->value()) ActionSaveImages->setEnabled(true); else ActionSaveImages->setEnabled(false); m_SaveFormat = m_SaveImageOption.ImageFormat_ComboBox->currentText(); } void ViewerWindow::rejectSaveImagesDlg() { QString sPathBefore = m_SaveImageOption.ImageDestination_Edit->text(); m_SaveImageOption.ImageDestination_Edit->setText(sPathBefore); } bool ViewerWindow::checkUsedName ( const QStringList &files ) { for( int nPos = 0; nPos < files.size(); nPos++ ) { if(0 == files.at(nPos).compare(m_SaveImageOption.ImageName_Edit->text()+"_1"+m_SaveImageOption.ImageFormat_ComboBox->currentText())) { m_SaveImageOption.ImageName_Edit->setText(m_SaveImageOption.ImageName_Edit->text()+"_New"); return true; } } return false; } bool ViewerWindow::isDestPathWritable() { /* check permission of destination QFileInfo can not be used, because a windows dir can be write protected, but files inside can be created */ QString sTmpPath = m_SaveImageOption.ImageDestination_Edit->text().append("/").append("fileTmp.dat"); QFile fileTmp(sTmpPath); if(!fileTmp.open( QIODevice::ReadWrite|QIODevice::Text)) { QMessageBox::warning( this, tr("Vimba Viewer"), "<Save Image Options> "+tr("No permission to write to destination path. Please select another one! ") ); return false; } fileTmp.close(); QFile::remove(sTmpPath); return true; } /* confirm saving from toolbar */ void ViewerWindow::on_ActionSaveImages_triggered() { #ifdef _WIN32 // Do the check always on Windows if (!isDestPathWritable()) { ActionSaveImages->setEnabled(false); return; } #else #ifndef WIN32 if (!isDestPathWritable()) { ActionSaveImages->setEnabled(false); return; } #endif #endif //overwrite existing name if(0 != m_SaveImageOption.ImageName_Edit->text().compare(m_SaveImageName)) { m_SaveImageName = m_SaveImageOption.ImageName_Edit->text(); } m_nImageCounter = 0; m_nNumberOfFramesToSave = m_SaveImageOption.NumberOfFrames_SpinBox->value(); m_SaveFormat = m_SaveImageOption.ImageFormat_ComboBox->currentText(); m_SaveName = m_SaveImageOption.ImageName_Edit->text(); m_SaveImageThread->SetNumberToSave ( m_nNumberOfFramesToSave ); m_SaveImageThread->SetSaveFormat ( m_SaveFormat ); m_SaveImageThread->SetPath ( m_ImagePath ); m_SaveImageThread->SetBaseName ( m_SaveName ); if( 0 < m_nNumberOfFramesToSave ) { if( 0 == m_SaveImageOption.ImageFormat_ComboBox->currentText().compare(".bin")) m_pFrameObs->saveRawData(m_nNumberOfFramesToSave, m_ImagePath, m_SaveName); // save full bit depth series of images when requested and LibTif is available if( m_LibTiffAvailable && ActionAllow16BitTiffSaving->isChecked() && m_SaveFormat.contains(".tif") && isSupportedPixelFormat()) { m_Allow16BitMultiSave = true; m_SaveImageThread->SetSave16Bit ( true ); // start transferring full bit depth frames from frame observer m_pFrameObs->enableFullBitDepthTransfer(true); } else { m_Allow16BitMultiSave = false; m_SaveImageThread->SetSave16Bit ( false ); m_bIsTriggeredByMultiSaveBtn = true; m_pFrameObs->enableFullBitDepthTransfer(false); } ActionFreerun->setChecked(isStreamingAvailable()); on_ActionFreerun_triggered(); ActionFreerun->setEnabled(false); } } void ViewerWindow::getSaveDestinationPath() { if( NULL != m_getDirDialog ) { delete m_getDirDialog; m_getDirDialog = NULL; } m_getDirDialog = new QFileDialog ( this, tr("Destination"), m_SaveImageOption.ImageDestination_Edit->text()); QFileDialog::Options options = QFileDialog::DontResolveSymlinks | QFileDialog::ShowDirsOnly |QFileDialog::DontUseNativeDialog; m_getDirDialog->setOptions(options); m_getDirDialog->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinimizeButtonHint & ~Qt::WindowMaximizeButtonHint); m_getDirDialog->setLabelText(QFileDialog::LookIn, tr("Destination Path")); m_getDirDialog->setLabelText(QFileDialog::FileType, tr("Type")); m_getDirDialog->setFileMode( QFileDialog::Directory); QString sDir; if( m_getDirDialog->exec() ) { //OK sDir = m_getDirDialog->directory().absolutePath(); } if(!sDir.isEmpty()) m_SaveImageOption.ImageDestination_Edit->setText(sDir); } void ViewerWindow::on_ActionLeftRotation_triggered() { m_ScreenViewer->rotate(-90); } void ViewerWindow::on_ActionRightRotation_triggered() { m_ScreenViewer->rotate(90); } void ViewerWindow::on_ActionZoomOut_triggered() { m_ScreenViewer->zoomOut(); } void ViewerWindow::on_ActionZoomIn_triggered() { m_ScreenViewer->zoomIn(); } void ViewerWindow::on_ActionOriginalSize_triggered() { m_ScreenViewer->setDefaultSize(); } void ViewerWindow::on_ActionFitToWindow_triggered() { m_ScreenViewer->setDefaultSize(); if (ActionFitToWindow->isChecked()) { m_ScreenViewer->setToolTip(tr("")); m_ScreenViewer->fitInView(m_pScene->itemsBoundingRect(), Qt::IgnoreAspectRatio); m_ScreenViewer->enableFitToWindow(true); ActionLeftRotation->setEnabled(false); ActionRightRotation->setEnabled(false); ActionOriginalSize->setEnabled(false); ActionZoomIn->setEnabled(false); ActionZoomOut->setEnabled(false); } else { m_ScreenViewer->enableFitToWindow(false); ActionLeftRotation->setEnabled(true); ActionRightRotation->setEnabled(true); ActionOriginalSize->setEnabled(true); ActionZoomIn->setEnabled(true); ActionZoomOut->setEnabled(true); } } void ViewerWindow::on_ActionHistogram_triggered() { m_HistogramWindow->deinitializeStatistic(); if (ActionHistogram->isChecked()) { m_HistogramWindow->initializeStatistic(); m_DockHistogram->show(); m_pFrameObs->enableHistogram(true); } else { m_DockHistogram->hide(); m_pFrameObs->enableHistogram(false); } if(!ActionHistogram->isChecked() && m_DockController->isVisible() && m_DockInformation->isVisible()) ActionResetPosition->setEnabled(false); } void ViewerWindow::on_ActionLoadCameraSettings_triggered() { bool proceedLoading = true; // create window title QString windowTitle = tr( "Load Camera Settings" ); // setup message boxes QMessageBox msgbox; msgbox.setWindowTitle( windowTitle ); QMessageBox msgbox2; msgbox2.setStandardButtons( QMessageBox::Yes ); msgbox2.addButton( QMessageBox::No ); msgbox2.setDefaultButton( QMessageBox::No ); // check if camera was opened in 'full access' mode if( 0 != m_sAccessMode.compare( tr("(FULL ACCESS)") ) ) { msgbox.setIcon( QMessageBox::Critical ); msgbox.setText( tr("Camera must be opened in FULL ACCESS mode to use this feature") ); msgbox.exec(); return; } // check if any file dialog was created already if( NULL != m_saveFileDialog ) { delete m_saveFileDialog; m_saveFileDialog = NULL; } // create file dialog m_saveFileDialog = new QFileDialog( this, windowTitle, QDir::home().absolutePath(), "*.xml" ); m_saveFileDialog->setWindowFlags( windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinimizeButtonHint & ~Qt::WindowMaximizeButtonHint ); m_saveFileDialog->selectNameFilter( "*.xml" ); m_saveFileDialog->setAcceptMode( QFileDialog::AcceptOpen ); m_saveFileDialog->setFileMode( QFileDialog::ExistingFile ); // show dialog int rval = m_saveFileDialog->exec(); if( 0 == rval ) { return; } // get selected file m_SaveFileDir = m_saveFileDialog->directory().absolutePath(); QStringList selectedFiles = m_saveFileDialog->selectedFiles(); if( true == selectedFiles.isEmpty() ) { msgbox.setIcon( QMessageBox::Critical ); msgbox.setText( tr("No file selected") ); msgbox.exec(); return; } // delete file dialog // (to prevent OCT-1870 bug occured with Qt v4.7.1) delete m_saveFileDialog; m_saveFileDialog = NULL; // get selected file QString selectedFile = selectedFiles.at(0); // check if xml file is valid if( false == selectedFile.endsWith( ".xml" ) ) { msgbox.setIcon( QMessageBox::Critical ); msgbox.setText( tr("Invalid xml file selected.\nFile must be of type '*.xml'") ); msgbox.exec(); return; } // create and prepare xml parser // to check if model name differences between xxml file // and connected camera exist QXmlStreamReader xml; QFile xmlFile( selectedFile ); QString deviceModel = QString( "" ); // open xml file stream bool check = xmlFile.open( QIODevice::ReadOnly ); if( false == check ) { msgbox2.setIcon( QMessageBox::Warning ); msgbox2.setText( tr("Could not validate camera model.\nDo you want to proceed loading settings to selected camera ?") ); rval = msgbox2.exec(); if( QMessageBox::No == rval ) { proceedLoading = false; } } else { // connect opened file with xml stream object xml.setDevice( &xmlFile ); } // proceed loading camera settings only if flag still true if( true == proceedLoading ) { // read xml structure while( false == xml.atEnd() ) { // get current xml token xml.readNext(); QString currentToken = xml.name().toString(); // check if token is named 'CameraSettings' if( 0 == currentToken.compare( "CameraSettings" ) ) { // get token attributes and iterate through them QXmlStreamAttributes attributes = xml.attributes(); for( int i=0; i<attributes.count(); ++i ) { // get current attribute QXmlStreamAttribute currentAttribute = attributes.at(i); // check if current attribute is name 'CameraModel' QString attributeName = currentAttribute.name().toString(); if( 0 == attributeName.compare( "CameraModel" ) ) { deviceModel = currentAttribute.value().toString(); break; } } break; } } // close xml file stream xmlFile.close(); // check if deviceModel was retrieved from xml file if( true == deviceModel.isEmpty() ) { msgbox2.setIcon( QMessageBox::Warning ); msgbox2.setText( tr("Could not validate camera model.\nDo you want to proceed loading settings to selected camera ?") ); rval = msgbox2.exec(); if( QMessageBox::No == rval ) { proceedLoading = false; } } } // proceed loading camera settings only if flag still true std::string modelName; if( true == proceedLoading ) { // get model name from connected camera const VmbErrorType err = m_pCam->GetModel( modelName ); if( VmbErrorSuccess != err ) { msgbox2.setIcon( QMessageBox::Warning ); msgbox2.setText( tr("Could not validate camera model.\nDo you want to proceed loading settings to selected camera ?") ); rval = msgbox2.exec(); if( QMessageBox::No == rval ) { proceedLoading = false; } } } // proceed loading camera settings only if flag still true if( true == proceedLoading ) { // compare mode names from xml file and from // connected device with each other if( 0 != deviceModel.compare( QString(modelName.c_str()) ) ) { QString msgtext = tr( "Selected camera model is different from xml file.\n"); msgtext.append( tr("[camera: %1]\n").arg( modelName.c_str() ) ); msgtext.append( tr("[xml: %1]\n\n").arg( deviceModel) ); msgtext.append( tr("Do you want to proceed loading operation ?" ) ); msgbox2.setIcon( QMessageBox::Warning ); msgbox2.setText( msgtext ); rval = msgbox2.exec(); if( QMessageBox::No == rval ) { proceedLoading = false; } } } // proceed loading camera settings only if flag still true if( true == proceedLoading ) { // setup behaviour for loading and saving camera features m_pCam->LoadSaveSettingsSetup( VmbFeaturePersistNoLUT, 5, 4 ); // call load method from VimbaCPP const VmbErrorType err = m_pCam->LoadCameraSettings( selectedFile.toStdString() ); if( VmbErrorSuccess != err ) { QString msgtext = tr( "There have been errors during loading of feature values.\n" ); msgtext.append( tr("[Error code: %1]\n").arg( err ) ); msgtext.append( tr("[file: %1]").arg( selectedFile) ); onFeedLogger( "ERROR: LoadCameraSettings returned: " + QString::number(err) + ". For details activate VimbaC logging and check out VmbCameraSettingsLoad.log" ); msgbox.setIcon( QMessageBox::Warning ); msgbox.setText( msgtext ); msgbox.exec(); return; } else { msgbox.setIcon( QMessageBox::Information ); QString msgtext = tr( "Successfully loaded device settings\nfrom '%1'" ).arg( selectedFile ); msgbox.setText( msgtext ); msgbox.exec(); } } } void ViewerWindow::on_ActionSaveCameraSettings_triggered() { VmbErrorType err = VmbErrorSuccess; // create window title QString windowTitle = tr( "Save Camera Settings" ); // create message box QMessageBox msgbox; msgbox.setWindowTitle( windowTitle ); // check if camera was opened in 'full access' mode if( 0 != m_sAccessMode.compare( tr("(FULL ACCESS)") ) ) { msgbox.setIcon( QMessageBox::Critical ); msgbox.setText( tr("Camera must be opened in FULL ACCESS mode to use this feature") ); msgbox.exec(); return; } // check if any file dialog was created already if( NULL != m_saveFileDialog ) { delete m_saveFileDialog; m_saveFileDialog = NULL; } // setup file dialog m_saveFileDialog = new QFileDialog( this, windowTitle, QDir::home().absolutePath(), "*.xml" ); m_saveFileDialog->setWindowFlags( windowFlags() & ~Qt::WindowContextHelpButtonHint & ~Qt::WindowMinimizeButtonHint & ~Qt::WindowMaximizeButtonHint ); m_saveFileDialog->selectNameFilter( "*.xml" ); m_saveFileDialog->setAcceptMode( QFileDialog::AcceptSave ); // show dialog int rval = m_saveFileDialog->exec(); if( 0 == rval ) { return; } // get selected file m_SaveFileDir = m_saveFileDialog->directory().absolutePath(); QStringList selectedFiles = m_saveFileDialog->selectedFiles(); if( true == selectedFiles.isEmpty() ) { msgbox.setIcon( QMessageBox::Critical ); msgbox.setText( tr("No file selected") ); msgbox.exec(); return; } // delete file dialog // (to prevent OCT-1870 bug occured with Qt v4.7.1) delete m_saveFileDialog; m_saveFileDialog = NULL; // get selected file QString selectedFile = selectedFiles.at(0); if( false == selectedFile.endsWith( ".xml" ) ) { selectedFile.append( ".xml" ); } // setup behaviour for loading and saving camera features m_pCam->LoadSaveSettingsSetup( VmbFeaturePersistNoLUT, 5, 4 ); // call VimbaCPP save function QString msgtext; err = m_pCam->SaveCameraSettings( selectedFile.toStdString() ); if( VmbErrorSuccess != err ) { msgtext = tr( "There have been errors during saving feature values.\n" ); msgtext.append( tr("[Error code: %1]\n").arg( err ) ); msgtext.append( tr("[file: %1]").arg( selectedFile) ); onFeedLogger( "ERROR: SaveCameraSettings returned: " + QString::number(err) + ". For details activate VimbaC logging and check out VmbCameraSettingsSave.log" ); msgbox.setIcon( QMessageBox::Warning ); msgbox.setText( msgtext ); msgbox.exec(); return; } else { msgtext = tr( "Successfully saved device settings to\n'" ); msgtext.append( selectedFile ); msgtext.append( "'" ); msgbox.setIcon( QMessageBox::Information ); msgbox.setText( msgtext ); msgbox.exec(); } } void ViewerWindow::on_ActionLoadCameraSettingsMenu_triggered() { on_ActionLoadCameraSettings_triggered(); } void ViewerWindow::on_ActionSaveCameraSettingsMenu_triggered() { on_ActionSaveCameraSettings_triggered(); } void ViewerWindow::on_ActionAllow16BitTiffSaving_triggered() { if ( ActionAllow16BitTiffSaving->isChecked() && m_LibTiffAvailable && isSupportedPixelFormat()) { m_pFrameObs->enableFullBitDepthTransfer(true); } else { m_pFrameObs->enableFullBitDepthTransfer(false); } } void ViewerWindow::onfloatingDockChanged ( bool bIsFloating ) { if( (m_DockController->isFloating() || (false == m_DockController->isVisible())) || (m_DockInformation->isFloating() || (false == m_DockInformation->isVisible())) ) ActionResetPosition->setEnabled(true); else ActionResetPosition->setEnabled(false); if(m_DockHistogram->isVisible()) ActionHistogram->setChecked(true); } void ViewerWindow::onVisibilityChanged ( bool bIsVisible ) { if( m_DockController->isVisible() && !m_DockController->isFloating() && m_DockInformation->isVisible() && !m_DockInformation->isFloating() ) { ActionResetPosition->setEnabled(false); } else { ActionResetPosition->setEnabled(true); } if(!m_DockHistogram->isVisible()) { if (ActionHistogram->isChecked() ) { ActionHistogram->setChecked(false); } } else { ActionHistogram->setChecked(true); } } void ViewerWindow::onResetFPS() { SP_ACCESS( m_pFrameObs )->resetFrameCounter(false); } void ViewerWindow::onSetCurrentFPS( const QString &sFPS ) { m_FramerateLabel->setText( QString::fromStdString(" Current FPS: ")+ sFPS + " " ); } void ViewerWindow::onSetFrameCounter( const unsigned int &nNumberOfFrames ) { m_FramesLabel->setText( "Frames: " + QString::number(nNumberOfFrames) + " " ); } void ViewerWindow::onSetEventMessage ( const QStringList &sMsg ) { m_InformationWindow->setEventMessage(sMsg); } void ViewerWindow::onSetDescription ( const QString &sDesc ) { m_Description->setText(sDesc); } void ViewerWindow::onSetHistogramData ( const QVector<QVector <quint32> > &histData, const QString &sHistogramTitle, const double &nMaxHeight_YAxis, const double &nMaxWidth_XAxis, const QVector <QStringList> &statistics ) { if( ActionHistogram->isChecked() ) { QStringList ColorComponentList; QStringList MinimumValueList; QStringList MaximumValueList; QStringList AverageValueList; QString sFormat; if(sHistogramTitle.contains("Mono8")) { sFormat = "Mono8"; ColorComponentList << statistics.at(0).at(0); MinimumValueList << statistics.at(0).at(1); MaximumValueList << statistics.at(0).at(2); AverageValueList << statistics.at(0).at(3); m_HistogramWindow->setStatistic(ColorComponentList, MinimumValueList, MaximumValueList, AverageValueList, sFormat); } if(sHistogramTitle.contains("RGB8") || sHistogramTitle.contains("BGR8") || sHistogramTitle.contains("YUV") || sHistogramTitle.contains("Bayer")) { if(sHistogramTitle.contains("RGB8") || sHistogramTitle.contains("BGR8")) sFormat = "RGB"; if(sHistogramTitle.contains("Bayer")) sFormat = "Bayer"; if(sHistogramTitle.contains("YUV")) sFormat = "YUV"; ColorComponentList << statistics.at(0).at(0) << statistics.at(1).at(0) << statistics.at(2).at(0); MinimumValueList << statistics.at(0).at(1) << statistics.at(1).at(1) << statistics.at(2).at(1); MaximumValueList << statistics.at(0).at(2) << statistics.at(1).at(2) << statistics.at(2).at(2); AverageValueList << statistics.at(0).at(3) << statistics.at(1).at(3) << statistics.at(2).at(3); m_HistogramWindow->setStatistic(ColorComponentList, MinimumValueList, MaximumValueList, AverageValueList, sFormat); } m_HistogramWindow->updateHistogram(histData, sHistogramTitle, nMaxHeight_YAxis, nMaxWidth_XAxis); } else m_pFrameObs->enableHistogram(false); } /* display frames on viewer */ void ViewerWindow::onimageReady ( QImage image, const QString &sFormat, const QString &sHeight, const QString &sWidth ) { m_FormatLabel->setText("Pixel Format: " + sFormat + " "); m_ImageSizeLabel->setText("Size H: " + sHeight + " ,W: "+ sWidth + " "); if(m_bHasJustStarted) { foreach( QGraphicsItem *item, m_pScene->items() ) { if( item->type() == QGraphicsTextItem::Type ) { m_pScene->removeItem(m_TextItem); m_FormatLabel->setStyleSheet("background-color: rgb(195,195,195); color: rgb(0,0,0)"); m_bIsRedHighlighted = false; continue; } m_pScene->removeItem(m_PixmapItem); } m_pScene->addItem(m_PixmapItem); m_bHasJustStarted = false; } if( (sFormat.contains("Convert Error")) ) { if( false == m_bIsRedHighlighted ) { m_bIsRedHighlighted = true; m_FormatLabel->setStyleSheet("background-color: rgb(196,0, 0); color: rgb(255,255,255)"); if (sFormat.contains("height") || sFormat.contains("width")) { m_TextItem->setPlainText("The Resolution you set is not supported by VimbaImageTransform.\n" "Please change height or width !"); } else { m_TextItem->setPlainText("PixelFormat transformation not supported."); } m_TextItem->setPos(m_pScene->width()/6, m_pScene->height()/2); m_pScene->addItem(m_TextItem); } } else { if( m_bIsRedHighlighted ) { m_FormatLabel->setStyleSheet("background-color: rgb(195,195,195); color: rgb(0,0,0)"); m_bIsRedHighlighted = false; if (!m_pScene->items().isEmpty()) { m_pScene->removeItem(m_TextItem); } } } /* display it at centre whenever changed */ m_pScene->setSceneRect(0, 0, image.width(), image.height() ); m_PixmapItem->setPixmap(QPixmap::fromImage(image)); m_ScreenViewer->show(); /* save series of images */ if( (0 < m_nNumberOfFramesToSave) && m_bIsTriggeredByMultiSaveBtn ) { ++m_nImageCounter; if(m_nImageCounter <= m_nNumberOfFramesToSave) { m_SaveImageThread->start(); try { static bool bCanReduceBpp; // Test only once for every batch to save if ( 1 == m_nImageCounter ) { bCanReduceBpp = CanReduceBpp(); } // Save with 8 bpp if ( true == bCanReduceBpp ) { m_SaveImageThread->Enqueue( ReduceBpp( image ), m_nImageCounter ); } // Save as is else { m_SaveImageThread->Enqueue( image, m_nImageCounter ); } // Reset at end of batch if ( m_nImageCounter == m_nNumberOfFramesToSave ) { bCanReduceBpp = false; } } catch( const std::bad_alloc &/*bex*/) { m_bIsRedHighlighted = false; ActionFreerun->setChecked(false); on_ActionFreerun_triggered(); ActionFreerun->setEnabled(isStreamingAvailable()); m_SaveImagesDialog->hide(); delete m_SaveImagesDialog; m_SaveImagesDialog = NULL; m_SaveImageThread->StopProcessing(); m_SaveImageThread->wait(); m_bIsTriggeredByMultiSaveBtn = false; m_Allow16BitMultiSave = false; } } } } void ViewerWindow::onFullBitDepthImageReady(tFrameInfo mFullImageInfo) { // store a full bit depth image frame in case user wants to save to file m_FullBitDepthImage = mFullImageInfo; // save series of TIFF images using LibTif if( (0 < m_nNumberOfFramesToSave) && m_Allow16BitMultiSave ) { m_SaveImageThread->start(); ++m_nImageCounter; if(m_nImageCounter <= m_nNumberOfFramesToSave) { try { m_SaveImageThread->Enqueue( mFullImageInfo, m_nImageCounter ); } catch( const std::bad_alloc &bex) { m_bIsRedHighlighted = false; ActionFreerun->setChecked(false); on_ActionFreerun_triggered(); ActionFreerun->setEnabled(isStreamingAvailable()); m_SaveImagesDialog->hide(); delete m_SaveImagesDialog; m_SaveImagesDialog = NULL; m_SaveImageThread->StopProcessing(); m_SaveImageThread->wait(); m_bIsTriggeredByMultiSaveBtn = false; m_Allow16BitMultiSave = false; } } } } void ViewerWindow::onSaving ( unsigned int nPos ) { if( 1 == nPos ) { //Start Progressbar m_SaveImagesDialog = new QDialog(0, Qt::CustomizeWindowHint|Qt::WindowTitleHint); m_SaveImagesUIDialog.setupUi(m_SaveImagesDialog); m_SaveImagesUIDialog.saveImagesProgress->setMaximum(m_nNumberOfFramesToSave); m_SaveImagesUIDialog.saveImagesProgress->setMinimum(1); m_SaveImagesDialog->show(); } m_SaveImagesUIDialog.saveImagesProgress->setValue(nPos); if (m_nNumberOfFramesToSave == nPos) { m_FormatLabel->setStyleSheet("background-color: rgb(195,195,195); color: rgb(0,0,0)"); m_bIsRedHighlighted = false; ActionFreerun->setChecked(false); on_ActionFreerun_triggered(); ActionFreerun->setEnabled(isStreamingAvailable()); foreach( QGraphicsItem *item, m_pScene->items() ) { if( item->type() == QGraphicsTextItem::Type ) { m_pScene->removeItem(m_TextItem); break; } } m_SaveImagesDialog->hide(); delete m_SaveImagesDialog; m_SaveImagesDialog = NULL; m_SaveImageThread->StopProcessing(); m_SaveImageThread->wait(); m_nImageCounter = 0; m_bIsTriggeredByMultiSaveBtn = false; m_Allow16BitMultiSave = false; // restore state of full bit depth image transfer flag on_ActionAllow16BitTiffSaving_triggered(); } } void ViewerWindow::onAcquisitionStartStop ( const QString &sThisFeature ) { QIcon icon; /* this is intended to stop and start the camera again since PixelFormat, Height and Width have been changed while camera running * ignore this when the changing has been made while camera not running */ if( ((0 == sThisFeature.compare("AcquisitionStart")) && (m_bIsCameraRunning)) ) { ActionFreerun->setChecked(true); on_ActionFreerun_triggered(); } else if( sThisFeature.contains("AcquisitionStartFreerun") ) { SP_ACCESS( m_pFrameObs )->resetFrameCounter(true); if(!m_bIsCameraRunning) { icon.addFile(QString::fromUtf8(":/VimbaViewer/Images/stop.png"), QSize(), QIcon::Normal, QIcon::On); ActionFreerun->setIcon(icon); checkDisplayInterval(); releaseBuffer(); onPrepareCapture(); ActionFreerun->setChecked(true); m_bIsCameraRunning = true; m_bHasJustStarted = true; emit acquisitionRunning(true); if(ActionDisplayOptions->isEnabled()) ActionDisplayOptions->setEnabled(false); if(ActionSaveOptions->isEnabled()) ActionSaveOptions->setEnabled(false); /* if save images settings set, and acquisition starts */ if( (0 < m_SaveImageOption.NumberOfFrames_SpinBox->value()) && ActionSaveImages->isEnabled() ) { ActionSaveImages->setEnabled(false); m_nImageCounter = 0; m_nNumberOfFramesToSave = 0; } m_OperatingStatusLabel->setText( " Running... " ); m_OperatingStatusLabel->setStyleSheet("background-color: rgb(0,128, 0); color: rgb(255,255,255)"); } } else if( sThisFeature.contains("AcquisitionStopFreerun") ) { if(m_bIsCameraRunning) { icon.addFile(QString::fromUtf8(":/VimbaViewer/Images/play.png"), QSize(), QIcon::Normal, QIcon::Off); ActionFreerun->setIcon(icon); releaseBuffer(); ActionFreerun->setChecked(false); if (m_bIsViewerWindowClosing) on_ActionFreerun_triggered(); m_bIsCameraRunning = false; emit acquisitionRunning(false); if(!ActionSaveOptions->isEnabled()) ActionSaveOptions->setEnabled(true); if(!ActionFreerun->isEnabled()) ActionFreerun->setEnabled(isStreamingAvailable()); if(!ActionDisplayOptions->isEnabled()) ActionDisplayOptions->setEnabled(true); /* if save images running, and acquisition stops */ if( (0 < m_SaveImageOption.NumberOfFrames_SpinBox->value()) && !ActionSaveImages->isEnabled() ) { ActionSaveImages->setEnabled(true); } m_Controller->synchronizeEventFeatures(); } m_OperatingStatusLabel->setText( " Ready " ); m_OperatingStatusLabel->setStyleSheet("background-color: rgb(0,0, 0); color: rgb(255,255,255)"); } else if( ((0 == sThisFeature.compare("AcquisitionStop")) && (m_bIsCameraRunning)) || (sThisFeature.contains("AcquisitionStopWidthHeight"))) { if(m_bIsCameraRunning) { ActionFreerun->setChecked(false); on_ActionFreerun_triggered(); /* use this for GigE, so you can change the W/H "on the fly" */ if(0 == sThisFeature.compare("AcquisitionStopWidthHeight")) { m_bIsCameraRunning = true; emit acquisitionRunning(true); } } // update state of full bit depth image transfer flag in case pixel format has changed on_ActionAllow16BitTiffSaving_triggered(); } // update state of full bit depth image transfer flag in case pixel format has changed on_ActionAllow16BitTiffSaving_triggered(); } void ViewerWindow::checkDisplayInterval() { FeaturePtr pFeatMode; if(VmbErrorSuccess == m_pCam->GetFeatureByName( "AcquisitionMode", pFeatMode )) { std::string sValue(""); if( VmbErrorSuccess == pFeatMode->GetValue(sValue) ) { /* display all received frames for SingleFrame and MultiFrame mode or if the user wants to have it */ if( 0 == sValue.compare("SingleFrame") || 0 == sValue.compare("MultiFrame") || m_bIsDisplayEveryFrame ) SP_ACCESS( m_pFrameObs )->setDisplayInterval( 0 ); /* display frame in a certain interval to save CPU consumption for continuous mode */ else SP_ACCESS( m_pFrameObs )->setDisplayInterval( 1 ); } } } void ViewerWindow::on_ActionFreerun_triggered() { VmbError_t error; FeaturePtr pFeat; checkDisplayInterval(); /* update interpolation state after start */ if( !m_Timer->isActive()) { m_Timer->start(200); } QIcon icon; /* ON */ if( ActionFreerun->isChecked() ) { icon.addFile(QString::fromUtf8(":/VimbaViewer/Images/stop.png"), QSize(), QIcon::Normal, QIcon::On); ActionFreerun->setIcon(icon); error = onPrepareCapture(); if( VmbErrorSuccess != error ) { m_bIsCameraRunning = false; emit acquisitionRunning(false); m_OperatingStatusLabel->setText( " Failed to start! Error: " + QString::number(error)+" "+Helper::mapReturnCodeToString(error) ); m_OperatingStatusLabel->setStyleSheet("background-color: rgb(196,0, 0); color: rgb(255,255,255)"); icon.addFile(QString::fromUtf8("D:/Chimera/Chimera-Cryo-Test/VimbaOfficial/Images/play.png"), QSize(), QIcon::Normal, QIcon::Off); ActionFreerun->setIcon(icon); ActionFreerun->setChecked(false); return; } error = m_pCam->GetFeatureByName( "AcquisitionStart", pFeat ); int nResult = m_sAccessMode.compare(tr("(READ ONLY)")) ; if ( (VmbErrorSuccess == error) && ( 0 != nResult ) ) { SP_ACCESS( m_pFrameObs )->resetFrameCounter(true); // Do some GUI-related preparations before really starting (to avoid timing problems) m_OperatingStatusLabel->setText( " Running... " ); m_OperatingStatusLabel->setStyleSheet("background-color: rgb(0,128, 0); color: rgb(255,255,255)"); if(ActionDisplayOptions->isEnabled()) ActionDisplayOptions->setEnabled(false); if(ActionSaveOptions->isEnabled()) ActionSaveOptions->setEnabled(false); if( ActionSaveImages->isEnabled() && (0 < m_SaveImageOption.NumberOfFrames_SpinBox->value()) ) ActionSaveImages->setEnabled(false); error = pFeat->RunCommand(); if(VmbErrorSuccess == error) { if(m_bIsFirstStart) { m_bIsFirstStart = false; } m_bHasJustStarted = true; m_bIsCameraRunning = true; emit acquisitionRunning(true); } else { m_bIsCameraRunning = false; emit acquisitionRunning(false); m_OperatingStatusLabel->setText( " Failed to execute AcquisitionStart! Error: " + QString::number(error)+" "+Helper::mapReturnCodeToString(error) ); m_OperatingStatusLabel->setStyleSheet("background-color: rgb(196,0, 0); color: rgb(255,255,255)"); m_InformationWindow->feedLogger("Logging", QString(QTime::currentTime().toString("hh:mm:ss:zzz")+"\t" + " RunCommand [AcquisitionStart] Failed! Error: " + QString::number(error)+" "+ Helper::mapReturnCodeToString(error)), VimbaViewerLogCategory_ERROR); if(ActionDisplayOptions->isEnabled()) ActionDisplayOptions->setEnabled(true); if(ActionSaveOptions->isEnabled()) ActionSaveOptions->setEnabled(true); if( ActionSaveImages->isEnabled() && (0 < m_SaveImageOption.NumberOfFrames_SpinBox->value()) ) ActionSaveImages->setEnabled(true); } } } /* OFF */ else { error = m_pCam->GetFeatureByName("AcquisitionStop", pFeat); if ( (VmbErrorSuccess == error) ) { if(0 != m_sAccessMode.compare(tr("(READ ONLY)"))) error = pFeat->RunCommand(); icon.addFile(QString::fromUtf8(":/Images/play.png"), QSize(), QIcon::Normal, QIcon::Off); ActionFreerun->setIcon(icon); if(VmbErrorSuccess == error) { m_bIsCameraRunning = false; emit acquisitionRunning(false); m_OperatingStatusLabel->setText( " Ready " ); m_OperatingStatusLabel->setStyleSheet("background-color: rgb(0,0, 0); color: rgb(255,255,255)"); releaseBuffer(); } else { m_InformationWindow->feedLogger("Logging", QString(QTime::currentTime().toString("hh:mm:ss:zzz")+"\t" + " RunCommand [AcquisitionStop] Failed! Error: " + QString::number(error) + " " + Helper::mapReturnCodeToString(error) ), VimbaViewerLogCategory_ERROR); } } if(!ActionDisplayOptions->isEnabled()) ActionDisplayOptions->setEnabled(true); if(!ActionSaveOptions->isEnabled()) ActionSaveOptions->setEnabled(true); if( !ActionSaveImages->isEnabled() && (0 < m_SaveImageOption.NumberOfFrames_SpinBox->value())) ActionSaveImages->setEnabled(true); m_Controller->synchronizeEventFeatures(); } } VmbError_t ViewerWindow::releaseBuffer() { m_pFrameObs->Stopping(); VmbError_t error = m_pCam->EndCapture(); if( VmbErrorSuccess == error ) error = m_pCam->FlushQueue(); if( VmbErrorSuccess == error ) error = m_pCam->RevokeAllFrames(); return error; } VmbError_t ViewerWindow::onPrepareCapture() { FeaturePtr pFeature; VmbInt64_t nPayload = 0; QVector <FramePtr> frames; VmbError_t error = m_pCam->GetFeatureByName("PayloadSize", pFeature); VmbUint32_t nCounter = 0; if( VmbErrorSuccess == error ) { error = pFeature->GetValue(nPayload); if(VmbErrorSuccess == error) { frames.resize(m_FrameBufferCount); bool bIsStreamingAvailable = isStreamingAvailable(); if (bIsStreamingAvailable) { for (int i=0; i<frames.size(); i++) { try { frames[i] = FramePtr(new Frame(nPayload)); nCounter++; } catch(std::bad_alloc& ) { frames.resize((VmbInt64_t) (nCounter * 0.7)); break; } m_pFrameObs->Starting(); error = frames[i]->RegisterObserver(m_pFrameObs); if( VmbErrorSuccess != error ) { m_InformationWindow->feedLogger("Logging", QString(QTime::currentTime().toString("hh:mm:ss:zzz")+"\t" + " RegisterObserver frame["+ QString::number(i)+ "] Failed! Error: " + QString::number(error)+" "+ Helper::mapReturnCodeToString(error)), VimbaViewerLogCategory_ERROR); return error; } } for (int i=0; i<frames.size(); i++) { error = m_pCam->AnnounceFrame( frames[i] ); if( VmbErrorSuccess != error ) { m_InformationWindow->feedLogger("Logging", QString(QTime::currentTime().toString("hh:mm:ss:zzz")+"\t" + " AnnounceFrame ["+ QString::number(i)+ "] Failed! Error: " + QString::number(error)+" "+ Helper::mapReturnCodeToString(error)), VimbaViewerLogCategory_ERROR); return error; } } } if(VmbErrorSuccess == error) { error = m_pCam->StartCapture(); if( VmbErrorSuccess != error ) { QString sMessage = " StartCapture Failed! Error: "; if(0 != m_sAccessMode.compare(tr("(READ ONLY)"))) m_InformationWindow->feedLogger("Logging", QString(QTime::currentTime().toString("hh:mm:ss:zzz")+"\t" + sMessage + QString::number(error)+" "+ Helper::mapReturnCodeToString(error)), VimbaViewerLogCategory_ERROR); return error; } } if (bIsStreamingAvailable) { for (int i=0; i<frames.size(); i++) { error = m_pCam->QueueFrame( frames[i] ); if( VmbErrorSuccess != error ) { m_InformationWindow->feedLogger("Logging", QString(QTime::currentTime().toString("hh:mm:ss:zzz")+"\t" + " QueueFrame ["+ QString::number(i)+ "] Failed! Error: " + QString::number(error)+" "+ Helper::mapReturnCodeToString(error)), VimbaViewerLogCategory_ERROR); return error; } } } } else { m_InformationWindow->feedLogger("Logging", QString(QTime::currentTime().toString("hh:mm:ss:zzz")+"\t" + " GetValue [PayloadSize] Failed! Error: " + QString::number(error)+" "+ Helper::mapReturnCodeToString(error)), VimbaViewerLogCategory_ERROR); return error; } } else { m_InformationWindow->feedLogger("Logging", QString(QTime::currentTime().toString("hh:mm:ss:zzz")+"\t" + " GetFeatureByName [PayloadSize] Failed! Error: " + QString::number(error)+" "+ Helper::mapReturnCodeToString(error)), VimbaViewerLogCategory_ERROR); return error; } return error; } void ViewerWindow::onFeedLogger ( const QString &sMessage ) { m_InformationWindow->feedLogger("Logging", QString(QTime::currentTime().toString("hh:mm:ss:zzz")+"\t" + sMessage), VimbaViewerLogCategory_ERROR); } void ViewerWindow::changeEvent ( QEvent * event ) { if( event->type() == QEvent::WindowStateChange ) { if( isMinimized() ) m_Controller->showControl(false); else if( isMaximized() ) m_Controller->showControl(true); } } bool ViewerWindow::loadPlugin() { const QDir pluginsDir(qApp->applicationDirPath() + "/plugins"); m_TabPluginCount = 0; foreach ( const QString fileName, pluginsDir.entryList(QDir::Files)) { QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName)); QObject* const plugin = pluginLoader.instance(); if (plugin) { TabExtensionInterface* const tabInterface = qobject_cast<TabExtensionInterface *>(plugin); m_tabExtensionInterface.push_back(tabInterface); if (m_tabExtensionInterface[m_TabPluginCount]) { m_TabPluginCount++; } } } return m_TabPluginCount > 0; } bool ViewerWindow::CanReduceBpp() { bool res = false; FeaturePtr pFeature; // TODO: Persist pixel format in viewer. Pixel format might be altered in between capture and save. Then color would be transformed to mono. // Bug or feature? VmbError_t error = m_pCam->GetFeatureByName( "PixelFormat", pFeature ); if( VmbErrorSuccess == error ) { VmbInt64_t nFormat; error = pFeature->GetValue( nFormat ); if( VmbErrorSuccess == error ) { res = Helper::convertFormatToString(static_cast<VmbPixelFormatType>(nFormat)).contains("Mono"); } } return res; } // Reduces bpp to 8 QImage ViewerWindow::ReduceBpp( QImage image ) { // Create 8 bit grey scale color table if ( 0 == m_ColorTable.size() ) { for ( int i = 0; i < 256; ++i ) { m_ColorTable.push_back( QColor( i, i, i ).rgb() ); } } // Convert to 8 bit grey scale return image.convertToFormat( QImage::Format_Indexed8, m_ColorTable ); } // Check if the TL supports streaming bool ViewerWindow::isStreamingAvailable() { AVT::VmbAPI::FeaturePtr pStreamIDFeature; m_pCam->GetFeatureByName("StreamID", pStreamIDFeature); return (NULL == pStreamIDFeature) ? false : true; } // test if the current pixel format is supported and should use LibTiff to save image bool ViewerWindow::isSupportedPixelFormat() { bool result = false; FeaturePtr pFeature; VmbError_t error = m_pCam->GetFeatureByName( "PixelFormat", pFeature ); if( VmbErrorSuccess == error ) { VmbInt64_t nFormat; error = pFeature->GetValue( nFormat ); if( VmbErrorSuccess == error ) { switch(nFormat) { // supported images formats: case VmbPixelFormatMono10: case VmbPixelFormatMono10p: case VmbPixelFormatMono12: case VmbPixelFormatMono12p: case VmbPixelFormatMono12Packed: case VmbPixelFormatMono14: case VmbPixelFormatMono16: case VmbPixelFormatBayerGR10: case VmbPixelFormatBayerRG10: case VmbPixelFormatBayerGB10: case VmbPixelFormatBayerBG10: case VmbPixelFormatBayerGR10p: case VmbPixelFormatBayerRG10p: case VmbPixelFormatBayerGB10p: case VmbPixelFormatBayerBG10p: case VmbPixelFormatBayerGR12: case VmbPixelFormatBayerRG12: case VmbPixelFormatBayerGB12: case VmbPixelFormatBayerBG12: case VmbPixelFormatBayerGR12Packed: case VmbPixelFormatBayerRG12Packed: case VmbPixelFormatBayerGB12Packed: case VmbPixelFormatBayerBG12Packed: case VmbPixelFormatBayerGR12p: case VmbPixelFormatBayerRG12p: case VmbPixelFormatBayerGB12p: case VmbPixelFormatBayerBG12p: case VmbPixelFormatBayerGR16: case VmbPixelFormatBayerRG16: case VmbPixelFormatBayerGB16: case VmbPixelFormatBayerBG16: result = true; break; default: result = false; } } } return result; } void SaveImageThread::run() { m_Images.StartProcessing(); m_16BitImages.StartProcessing(); // save 16 bit depth images if requested if(m_bSave16BitImages) { ImageWriter tiffWriter; if( !tiffWriter.IsAvailable() ) { return; } FramePair tmpInfo; while( m_16BitImages.WaitData(tmpInfo) ) { QString sFullPath = m_sImagePath; sFullPath.append("//").append(m_sSaveName); sFullPath.append("_"+QString::number(tmpInfo.first)).append(m_sSaveFormat); // save image using LibTif if( ! tiffWriter.WriteTiff( tmpInfo.second, sFullPath.toUtf8(),this) ) { emit LogMessage(QString("error could not write TIFF image ") +sFullPath ); } emit setPosition ( tmpInfo.first ); if( tmpInfo.first >= m_nTNumber2Save ) { break; } } } // save standard QImage format else { ImagePair tmpImage; while( m_Images.WaitData( tmpImage ) ) { QString sFullPath = m_sImagePath; sFullPath.append("//").append(m_sSaveName); sFullPath.append("_"+QString::number(tmpImage.first)).append(m_sSaveFormat); // save image if( ! tmpImage.second.save(sFullPath) ) { emit LogMessage(QString("error could not write image ") +sFullPath ); } emit setPosition ( tmpImage.first); if( tmpImage.first >= m_nTNumber2Save ) { break; } } } }
37.147146
314
0.610793
[ "geometry", "object", "vector", "model" ]
3073b7842f3a71276ae34f6f6cacf7b8823088fe
4,548
cpp
C++
tools/editor/source/view/manipulator/create.cpp
pixelballoon/pixelboost
085873310050ce62493df61142b7d4393795bdc2
[ "MIT" ]
6
2015-04-21T11:30:52.000Z
2020-04-29T00:10:04.000Z
tools/editor/source/view/manipulator/create.cpp
pixelballoon/pixelboost
085873310050ce62493df61142b7d4393795bdc2
[ "MIT" ]
null
null
null
tools/editor/source/view/manipulator/create.cpp
pixelballoon/pixelboost
085873310050ce62493df61142b7d4393795bdc2
[ "MIT" ]
null
null
null
#include "pixelboost/graphics/camera/camera.h" #include "command/manager.h" #include "project/entity.h" #include "project/record.h" #include "project/project.h" #include "project/property.h" #include "view/entity/entity.h" #include "view/manipulator/create.h" #include "view/manipulator/move.h" #include "view/level.h" #include "core.h" #include "view.h" PB_DEFINE_ENTITY(CreateManipulator) CreateManipulator::CreateManipulator(pb::Scene* scene, pb::Entity* parent, pb::DbEntity* creationEntity) : Manipulator(scene, parent, creationEntity) , _CreateMode(false) { } CreateManipulator::~CreateManipulator() { } std::string CreateManipulator::GetManipulatorName() { return "create"; } void CreateManipulator::SetEntityType(const std::string& entity) { _EntityType = entity; _Fields.clear(); _Values.clear(); } void CreateManipulator::SetCreationData(const std::vector<std::string>& fields, const std::vector<std::string>& values) { _Fields = fields; _Values = values; } bool CreateManipulator::OnMouseDown(pb::MouseButton button, pb::ModifierKeys modifierKeys, glm::vec2 position) { if (button == pb::kMouseButtonLeft) { glm::vec3 start = View::Instance()->GetActiveViewport()->ConvertScreenToWorld(position); glm::vec3 position = GetEntityPosition(start); if (View::Instance()->GetRecord()) { _CreateMode = true; _LastCreate = position; CreateEntity(position); return true; } } else if (button == pb::kMouseButtonRight) { View::Instance()->GetManipulatorManager()->SetActiveManipulator("select"); return true; } return false; } bool CreateManipulator::OnMouseUp(pb::MouseButton button, pb::ModifierKeys modifierKeys, glm::vec2 position) { if (button == pb::kMouseButtonLeft) { _CreateMode = false; } return false; } bool CreateManipulator::OnMouseMove(glm::vec2 mouse) { if (_CreateMode) { glm::vec3 position = View::Instance()->GetActiveViewport()->ConvertScreenToWorld(mouse); if (glm::distance(position, _LastCreate) >= 1.f) { _LastCreate = position; CreateEntity(position); } } return false; } bool CreateManipulator::OnKeyDown(pb::KeyboardKey key, pb::ModifierKeys modifier, char character) { return false; } bool CreateManipulator::OnKeyUp(pb::KeyboardKey key, pb::ModifierKeys modifier, char character) { return false; } glm::vec3 CreateManipulator::GetEntityPosition(glm::vec3 position) { glm::vec3 positionSnap = static_cast<MoveManipulator*>(View::Instance()->GetManipulatorManager()->GetManipulator("move"))->GetSnap(); if (positionSnap.x != 0) position.x = position.x - glm::mod(position.x, positionSnap.x); if (positionSnap.y != 0) position.y = position.y - glm::mod(position.y, positionSnap.y); if (positionSnap.z != 0) position.z = position.z - glm::mod(position.z, positionSnap.z); return position; } void CreateManipulator::CreateEntity(glm::vec3 position) { char commandArgs[1024]; sprintf(commandArgs, "-r %d -t %s -p %f,%f,%f", View::Instance()->GetRecord()->GetUid(), _EntityType.c_str(), position.x, position.y, position.z); std::string entityIdString = Core::Instance()->GetCommandManager()->Exec("createEntity", commandArgs); Uid entityId = atoi(entityIdString.c_str()); ProjectEntity* entity = Core::Instance()->GetProject()->GetEntity(entityId); if (entity) { for (int i=0; i<_Fields.size(); i++) { entity->AcquireAtom(_Fields[i])->SetStringValue(_Values[i]); } Core::Instance()->GetCommandManager()->Exec("select", "-u " + entityIdString); } ViewEntity* viewEntity = View::Instance()->GetLevel()->GetEntityById(entityId); if (viewEntity) { Level::EntityList otherEntities = View::Instance()->GetLevel()->GetEntitiesInBounds(viewEntity->GetBoundingBox()); if (otherEntities.size()) { float maxDepth = -INFINITY; for (Level::EntityList::iterator it = otherEntities.begin(); it != otherEntities.end(); ++it) { maxDepth = glm::max(maxDepth, (*it)->GetPosition().z); } viewEntity->Transform(glm::vec3(0,0, (maxDepth + 1))); viewEntity->CommitTransform(); } } }
28.78481
150
0.635444
[ "vector", "transform" ]
307983f1f60240594a6fe30bd7f87b6cea7d9185
1,665
cpp
C++
03_Patterns/factory_extensible/rendererfactory.cpp
tlanc007/APIBookTweaks
7d434d030583c74d7f55df608b9215add68b9663
[ "MIT" ]
null
null
null
03_Patterns/factory_extensible/rendererfactory.cpp
tlanc007/APIBookTweaks
7d434d030583c74d7f55df608b9215add68b9663
[ "MIT" ]
null
null
null
03_Patterns/factory_extensible/rendererfactory.cpp
tlanc007/APIBookTweaks
7d434d030583c74d7f55df608b9215add68b9663
[ "MIT" ]
1
2020-12-17T09:51:38.000Z
2020-12-17T09:51:38.000Z
/// -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: t -*- /// /// \file rendererfactory.cpp /// \author Martin Reddy /// \brief A factory object to create IRenderer instances. /// /// Copyright (c) 2010, Martin Reddy. All rights reserved. /// Distributed under the X11/MIT License. See LICENSE.txt. /// See http://APIBook.com/ for the latest version. /// /** 1/30/17 -- Tal -- using nullptr instead of NULL -- switched to auto for mRenders.find() see Tweak_Explainations.md (https://github.com/tlanc007/APIBookTweaks/blob/master/Tweak_Explainations.md#auto) -- switched to unique_ptr/make_unique rather than needing to use new() and remembering to call delete. see Tweak_Explainations.md (https://github.com/tlanc007/APIBookTweaks/blob/master/Tweak_Explainations.md#smartpointer) see Tweak_Explainations.md (https://github.com/tlanc007/APIBookTweaks/blob/master/Tweak_Explainations.md#makeshared) **/ #include <iostream> #include "rendererfactory.h" // instantiate the static variable in RendererFactory RendererFactory::CallbackMap RendererFactory::mRenderers; void RendererFactory::RegisterRenderer(const std::string &type, CreateCallback cb) { mRenderers[type] = cb; } void RendererFactory::UnregisterRenderer(const std::string &type) { mRenderers.erase(type); } RendererFactory::UniqueIRendererPtr RendererFactory::CreateRenderer (const std::string &type) { auto found {mRenderers.find(type) }; if (found != std::end (mRenderers) ) { // call the creation callback to construct this derived type return (found->second)(); } return nullptr; }
31.415094
121
0.712312
[ "object" ]
30814ad36551495139f5353e67803614429984d2
15,553
cpp
C++
smalldrop/smalldrop_robot_arm/src/controllers/cartesian_impedance_sim_controller.cpp
blackchacal/Master-Thesis----Software
9a9858ede3086eee99d1fc969e32b4fb13278f00
[ "MIT" ]
1
2020-08-16T14:37:09.000Z
2020-08-16T14:37:09.000Z
smalldrop/smalldrop_robot_arm/src/controllers/cartesian_impedance_sim_controller.cpp
blackchacal/Master-Thesis----Software
9a9858ede3086eee99d1fc969e32b4fb13278f00
[ "MIT" ]
1
2020-06-26T09:14:45.000Z
2020-07-18T08:46:50.000Z
smalldrop/smalldrop_robot_arm/src/controllers/cartesian_impedance_sim_controller.cpp
blackchacal/Master-Thesis----Software
9a9858ede3086eee99d1fc969e32b4fb13278f00
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2020 Ricardo Tonet // Use of this source code is governed by the MIT license, see LICENSE #include <smalldrop_robot_arm/cartesian_impedance_sim_controller.h> namespace smalldrop { namespace smalldrop_robot_arm { /***************************************************************************************** * Public methods *****************************************************************************************/ bool CartesianImpedanceSimController::init(hardware_interface::RobotHW *robot_hw, ros::NodeHandle &root_nh, ros::NodeHandle &controller_nh) { // Verify robot std::cout << "Verifying robot id" << std::endl; std::string arm_id; if (!root_nh.getParam("/cartesian_impedance_sim_controller/arm_id", arm_id)) { ROS_ERROR("CartesianImpedanceSimController: Could not read the parameter 'arm_id'."); return false; } // Verify number of joints std::cout << "Verifying number of joints" << std::endl; std::vector<std::string> joint_names; if (!root_nh.getParam("/cartesian_impedance_sim_controller/joints", joint_names) || joint_names.size() != 7) { ROS_ERROR("CartesianImpedanceSimController: Invalid or no joint_names parameters " "provided, aborting controller init!"); return false; } // Verify effort joint interface std::cout << "Verifying effort joint interface" << std::endl; auto *effort_joint_interface = robot_hw->get<hardware_interface::EffortJointInterface>(); if (effort_joint_interface == nullptr) { ROS_ERROR_STREAM("CartesianImpedanceSimController: Error getting effort joint " "interface from hardware"); return false; } // Verify joint handles std::cout << "Verifying joint handles" << std::endl; for (size_t i = 0; i < 7; ++i) { try { joint_handles_.push_back(effort_joint_interface->getHandle(joint_names[i])); } catch (const hardware_interface::HardwareInterfaceException &ex) { ROS_ERROR_STREAM("CartesianImpedanceSimController: Exception getting joint handles: " << ex.what()); return false; } } // Parse KDL tree std::string robot_desc_string; root_nh.param("robot_description", robot_desc_string, std::string()); if (!kdl_parser::treeFromString(robot_desc_string, k_tree_)) { ROS_ERROR("Failed to construct kdl tree."); return false; } // Get chain from kdl tree if (!k_tree_.getChain("panda_link0", "panda_EE", k_chain_)) { ROS_ERROR("Failed to get chain from kdl tree!"); } n_joints_ = k_chain_.getNrOfJoints(); // Load joint model from urdf to get joint limits urdf::Model model; if (model.initParam("/robot_description")) { robot_joints_ = model.joints_; } else { ROS_ERROR("Unable to read the robot model from URDF."); } // Setup dynamic reconfigure dyn_config_gains_node_ = ros::NodeHandle("cartesian_impedance_controller/gains"); dyn_config_gains_param_ = std::make_unique<dynamic_reconfigure::Server<::smalldrop_robot_arm::CartesianImpedanceSimControllerConfig>>( dyn_config_gains_node_); dyn_config_gains_param_->setCallback( boost::bind(&CartesianImpedanceSimController::updateDynamicConfigGainsCallback, this, _1, _2)); setupPublishersAndSubscribers(controller_nh); control_srv_ = controller_nh.advertiseService("send_torques_to_robot", &CartesianImpedanceSimController::sendTorquesToRobot, this); // --------------------------------------------------------------------------- // Init Values // --------------------------------------------------------------------------- T0ee_d_.setZero(); T0ee_.setZero(); cart_K.setZero(); cart_D.setZero(); cart_I.setZero(); null_K.setZero(); X0ee_d_.setZero(); X0ee_d_prev_.setZero(); R0ee_d_.setZero(); orient_d_.coeffs() << 0.0, 0.0, 0.0, 1.0; orient_d_target_.coeffs() << 0.0, 0.0, 0.0, 1.0; error_.setZero(); error_prev_.setZero(); error_accum_.setZero(); vel_d_.setZero(); vel_error_.setZero(); tau_.setZero(); tau_initial_.setZero(); max_joint_limits_ << robot_joints_[joint_handles_[0].getName()].get()->limits.get()->upper, robot_joints_[joint_handles_[1].getName()].get()->limits.get()->upper, robot_joints_[joint_handles_[2].getName()].get()->limits.get()->upper, robot_joints_[joint_handles_[3].getName()].get()->limits.get()->upper, robot_joints_[joint_handles_[4].getName()].get()->limits.get()->upper, robot_joints_[joint_handles_[5].getName()].get()->limits.get()->upper, robot_joints_[joint_handles_[6].getName()].get()->limits.get()->upper; min_joint_limits_ << robot_joints_[joint_handles_[0].getName()].get()->limits.get()->lower, robot_joints_[joint_handles_[1].getName()].get()->limits.get()->lower, robot_joints_[joint_handles_[2].getName()].get()->limits.get()->lower, robot_joints_[joint_handles_[3].getName()].get()->limits.get()->lower, robot_joints_[joint_handles_[4].getName()].get()->limits.get()->lower, robot_joints_[joint_handles_[5].getName()].get()->limits.get()->lower, robot_joints_[joint_handles_[6].getName()].get()->limits.get()->lower; nullspace_objective_.setZero(); // Workspace limits std::vector<double> x_limits; std::vector<double> x_limits_defaults = {0.1, 0.5}; std::vector<double> y_limits; std::vector<double> y_limits_defaults = {-0.2, 0.2}; std::vector<double> z_limits; std::vector<double> z_limits_defaults = {0, 0.5}; root_nh.param("smalldrop/robot/workspace/x_limits", x_limits, x_limits_defaults); root_nh.param("smalldrop/robot/workspace/y_limits", y_limits, y_limits_defaults); root_nh.param("smalldrop/robot/workspace/z_limits", z_limits, z_limits_defaults); wsp_x_min_limit_ = x_limits[0]; wsp_x_max_limit_ = x_limits[1]; wsp_y_min_limit_ = y_limits[0]; wsp_y_max_limit_ = y_limits[1]; wsp_z_min_limit_ = z_limits[0]; wsp_z_max_limit_ = z_limits[1]; return true; } void CartesianImpedanceSimController::starting(const ros::Time &time) { // Set desired end-effector position and euler angles Eigen::Matrix<double, 7, 1> qd; qd << 0, 0, 0, -M_PI_2, 0, M_PI_2, M_PI_4; if (!fk(qd, T0ee_d_)) ROS_ERROR("Cannot get forward kinematics."); Eigen::Affine3d transform(T0ee_d_); X0ee_d_ = transform.translation(); R0ee_d_ = transform.rotation(); X0ee_d_target_ = X0ee_d_; orient_d_ = Eigen::Quaterniond(transform.linear()); orient_d_.normalize(); orient_d_target_ = Eigen::Quaterniond(transform.linear()); orient_d_target_.normalize(); } void CartesianImpedanceSimController::update(const ros::Time &time, const ros::Duration &period) { // Obtain joint positions (q), velocities (qdot_) and efforts (effort) from hardware interface for (size_t i = 0; i < n_joints_; i++) { q_(i) = joint_handles_[i].getPosition(); qdot_(i) = joint_handles_[i].getVelocity(); tau_(i) = joint_handles_[i].getEffort(); if (time.toSec() <= 15) tau_initial_ = tau_; } // Calculate X = f(q) using forward kinematics (FK) if (!fk(q_, T0ee_)) ROS_ERROR("Cannot get forward kinematics."); Eigen::Affine3d transform(T0ee_); Eigen::Vector3d X0ee(transform.translation()); Eigen::Matrix3d R0ee(transform.rotation()); // Publish current pose publishCurrentPose(X0ee, R0ee); // --------------------------------------------------------------------------- // Calculate the dynamic parameters // --------------------------------------------------------------------------- // Calculate Jacobian if (!jacobian(J, q_)) ROS_ERROR("Cannot calculate the jacobian."); // Calculate the dynamics: inertia, coriolis and gravity matrices if (!dynamic(q_, qdot_)) ROS_ERROR("Cannot get the dynamics."); // Calculate Lambda which is the Mass Matrix of the task space // Λ(q) = (J * M(q)−1 * JT)−1 Eigen::Matrix<double, 6, 6> lambda; lambda = (J * M.inverse() * J.transpose()).inverse(); // Calculate the Dynamically consistent generalized inverse of the jacobian // J# = M(q)−1 * JT * Λ(q) Jhash = M.inverse() * J.transpose() * lambda; // --------------------------------------------------------------------------- // Set the controller gains // --------------------------------------------------------------------------- setControllerGains(); // --------------------------------------------------------------------------- // compute error // --------------------------------------------------------------------------- // Calculate vel = J*qdot_ (velocity of end-effector) Eigen::Matrix<double, 6, 1> vel(J * qdot_); // Calculate position error error_.head(3) << X0ee_d_ - X0ee; // Calculate orientation error Eigen::Matrix3d Rcd(R0ee_d_ * R0ee.transpose()); error_.tail(3) << R2r(Rcd); // Calculate velocity error vel_d_.head(3) << X0ee_d_ - X0ee_d_prev_; // desired velocity is derivative of desired position vel_error_ << vel_d_ - vel; X0ee_d_prev_ = X0ee_d_; // --------------------------------------------------------------------------- // compute control // --------------------------------------------------------------------------- // Declare variables // tau_task = JT*F // tau_null = (I - JT * J#T) * t0 // tau_d = tau_task + tau_null Eigen::VectorXd tau_task(7), tau_d(7), tau_null(7); // Calculate the null space objective function nullSpaceObjectiveFunction(nullspace_objective_); Eigen::Matrix<double, 7, 1> tau_o(M * null_K * nullspace_objective_); // Calculate nullspace torque (tau_null) tau_null << (Eigen::MatrixXd::Identity(7, 7) - J.transpose() * Jhash.transpose()) * tau_o; // Calculate error accumulated calcIntegralError(); // Saturate integral error saturateIntegralError(); // Calculate task torque (tau_task) tau_task << J.transpose() * (cart_D * vel_error_ + cart_K * error_ + cart_I * error_accum_); error_prev_ = error_accum_; // Calculate final torque tau_d << tau_task + tau_null + C + g; // Publish torques, wrenches and tracking errors publishTorques(tau_d, tau_task, tau_null); publishWrenches(); publishTrackingErrors(); // Set desired torque to each joint if (!torques_to_robot_) tau_d << 0, 0, 0, 0, 0, 0, 0; for (size_t i = 0; i < 7; ++i) joint_handles_[i].setCommand(tau_d(i)); // filter position X0ee_d_ = filter_param_ * X0ee_d_target_ + (1.0 - filter_param_) * X0ee_d_; // filter orientation orient_d_ = orient_d_.slerp(filter_param_, orient_d_target_); orient_d_.normalize(); R0ee_d_ = orient_d_.toRotationMatrix(); } /***************************************************************************************** * Private methods *****************************************************************************************/ /** * \brief Calculate the Jacobian matrix using KDL library. */ bool CartesianImpedanceSimController::calcJacobian(KDL::Jacobian &Jac, const Eigen::Matrix<double, 7, 1> &q_in) { if (q_in.size() != n_joints_) return false; KDL::ChainJntToJacSolver solver(k_chain_); KDL::JntArray joint_array(n_joints_); for (size_t i = 0; i < n_joints_; i++) joint_array(i) = q_in(i); // Obtain jacobian solver.JntToJac(joint_array, Jac); return true; } /** * \brief Transforms the KDL format Jacobian to an Eigen matrix. */ bool CartesianImpedanceSimController::jacobian(Eigen::Matrix<double, 6, 7> &J_out, const Eigen::Matrix<double, 7, 1> &q_in) { KDL::Jacobian Jac(n_joints_); if (calcJacobian(Jac, q_in)) { unsigned int rows = Jac.rows(); unsigned int columns = Jac.columns(); for (size_t row = 0; row < rows; row++) for (size_t col = 0; col < columns; col++) J_out(row, col) = Jac(row, col); return true; } return false; } /** * \brief Calculates forward kinematics using the KDL library. */ bool CartesianImpedanceSimController::fk(const Eigen::Matrix<double, 7, 1> &q_in, Eigen::Matrix4d &transf) { if (q_in.size() != n_joints_) return false; KDL::ChainFkSolverPos_recursive solver(k_chain_); KDL::Frame end_effector_frame; KDL::JntArray joint_array(n_joints_); for (size_t i = 0; i < n_joints_; i++) joint_array(i) = q_in(i); // Obtain end-effector frame orientation and position within end_effector_frame variable solver.JntToCart(joint_array, end_effector_frame); for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) transf(i, j) = end_effector_frame(i, j); return true; } /** * \brief Calculate robot dynamics using KDL library. The dynamic class members are updated inside the method. */ bool CartesianImpedanceSimController::dynamic(Eigen::Matrix<double, 7, 1> &q, Eigen::Matrix<double, 7, 1> &qdot_) { if (q.size() != n_joints_ || qdot_.size() != n_joints_) { return false; } KDL::Vector g_vector = { 0.0, 0.0, -9.80665 }; // Gravity vector KDL::ChainDynParam chain_dyn(k_chain_, g_vector); KDL::JntArray q_jarray(n_joints_); KDL::JntArray qdot_jarray(n_joints_); KDL::JntSpaceInertiaMatrix kdl_inertia; KDL::JntArray kdl_coriolis; KDL::JntArray kdl_gravity; // define inertia matrix with correct size (rows and columns) kdl_inertia = KDL::JntSpaceInertiaMatrix(n_joints_); kdl_coriolis = KDL::JntArray(n_joints_); kdl_gravity = KDL::JntArray(n_joints_); for (size_t i = 0; i < n_joints_; i++) { q_jarray(i) = q(i); qdot_jarray(i) = qdot_(i); } // Get Inertia Matrix if (chain_dyn.JntToMass(q_jarray, kdl_inertia) != KDL::SolverI::E_NOERROR) return false; // Get Coriolis Vector if (chain_dyn.JntToCoriolis(q_jarray, qdot_jarray, kdl_coriolis) != KDL::SolverI::E_NOERROR) return false; // Get Gravity Matrix if (chain_dyn.JntToGravity(q_jarray, kdl_gravity) != KDL::SolverI::E_NOERROR) return false; for (size_t i = 0; i < n_joints_; i++) { for (size_t j = 0; j < n_joints_; j++) { M(i, j) = kdl_inertia(i, j); C(i) = kdl_coriolis(i); g(i) = kdl_gravity(i); } } return true; } /** * \brief Updates the impedance gains using the dynamic reconfigure for simulation. * * After reading the gains from dynamic reconfigure, it updates the target impedance gain matrices * and nullspace stiffness matrix. */ void CartesianImpedanceSimController::updateDynamicConfigGainsCallback( ::smalldrop_robot_arm::CartesianImpedanceSimControllerConfig &config, uint32_t level) { Kpx = config.Kpx; Kpy = config.Kpy; Kpz = config.Kpz; Kox = config.Kox; Koy = config.Koy; Koz = config.Koz; Dpx = config.Dpx; Dpy = config.Dpy; Dpz = config.Dpz; Dox = config.Dox; Doy = config.Doy; Doz = config.Doz; Ipx = config.Ipx; Ipy = config.Ipy; Ipz = config.Ipz; Iox = config.Iox; Ioy = config.Ioy; Ioz = config.Ioz; Kpn = config.Kpn; // Saturation limits i_clamp_p_ = config.Ip_clamp; i_clamp_o_ = config.Io_clamp; updateDynamicConfigGains(); } /** * \brief Service callback to set if calculated torques should be sent to the robot. */ bool CartesianImpedanceSimController::sendTorquesToRobot(std_srvs::SetBool::Request &req, std_srvs::SetBool::Response &res) { torques_to_robot_ = req.data; res.success = true; return true; } } // namespace smalldrop_robot_arm } // namespace smalldrop PLUGINLIB_EXPORT_CLASS(smalldrop::smalldrop_robot_arm::CartesianImpedanceSimController, controller_interface::ControllerBase)
32.334719
114
0.634926
[ "vector", "model", "transform" ]
3086c50f7149c3c13ec9f8983099ccf4587bed8f
21,804
cpp
C++
Motor2D/j1Player.cpp
knela96/Dev_class5_handout
ca137c8e696069bf1bb5709c97ceae79f280942b
[ "MIT" ]
null
null
null
Motor2D/j1Player.cpp
knela96/Dev_class5_handout
ca137c8e696069bf1bb5709c97ceae79f280942b
[ "MIT" ]
null
null
null
Motor2D/j1Player.cpp
knela96/Dev_class5_handout
ca137c8e696069bf1bb5709c97ceae79f280942b
[ "MIT" ]
null
null
null
#include "j1App.h" #include "j1Textures.h" #include "j1Input.h" #include "j1Render.h" #include "j1Player.h" #include "j1Collisions.h" #include "j1FadeToBlack.h" #include "j1Window.h" #include "j1Audio.h" #include <assert.h> #include <stdio.h> #include "p2Defs.h" #include "p2Log.h" #include "j1Map.h" #include "j1EntityManager.h" #include "j1Entity.h" #include "Brofiler\Brofiler.h" #include "j1Gui.h" #include "j1Label.h" #include "SDL/include/SDL.h" j1Player::j1Player(SDL_Rect* collider_rect) : j1Entity(collider_rect) { name.create("player"); collider = App->collisions->AddCollider(*collider_rect, ColliderTypes::COLLIDER_PLAYER, (j1Module*)App->entitymanager); } j1Player::~j1Player() {} // Load assets bool j1Player::Awake(pugi::xml_node& config) { LOG("Loading player textures"); bool ret = true; folder.create(config.child("folder").child_value()); texture_path.create("%s%s", folder.GetString(), config.child("texture").attribute("source").as_string()); speed.x = config.child("speed").attribute("x").as_uint(); speed.y = config.child("speed").attribute("y").as_uint(); position.x = config.child("position").attribute("x").as_uint(); position.y = config.child("position").attribute("y").as_uint(); life = config.child("life").attribute("value").as_uint(); dead = config.child("dead").attribute("value").as_bool(); jumpSpeed = config.child("jumpSpeed").attribute("value").as_float(); maxFallingSpeed = config.child("maxFallingSpeed").attribute("value").as_float(); walkSpeed = config.child("walkSpeed").attribute("value").as_float(); gravity = config.child("gravity").attribute("value").as_float(); // ANIMATIONS //Idle pushbacks for (pugi::xml_node push_node = config.child("animations").child("idle").child("frame"); push_node && ret; push_node = push_node.next_sibling("frame")) { anim_idle.PushBack({ push_node.attribute("x").as_int(), push_node.attribute("y").as_int(), push_node.attribute("w").as_int(), push_node.attribute("h").as_int() }); } anim_idle.loop = config.child("animations").child("idle").attribute("loop").as_bool(); anim_idle.speed = config.child("animations").child("idle").attribute("speed").as_float(); anim_idle.Reset(); //Run Pushbacks for (pugi::xml_node push_node = config.child("animations").child("run").child("frame"); push_node && ret; push_node = push_node.next_sibling("frame")) { anim_run.PushBack({ push_node.attribute("x").as_int(), push_node.attribute("y").as_int(), push_node.attribute("w").as_int(), push_node.attribute("h").as_int() }); } anim_run.loop = config.child("animations").child("run").attribute("loop").as_bool(); anim_run.speed = config.child("animations").child("run").attribute("speed").as_float(); anim_run.Reset(); //Loading Fx App->audio->LoadFx(config.child("animations").child("run").child("fx").child_value()); //Plane Pushbacks for (pugi::xml_node push_node = config.child("animations").child("plane").child("frame"); push_node && ret; push_node = push_node.next_sibling("frame")) { anim_plane.PushBack({ push_node.attribute("x").as_int(), push_node.attribute("y").as_int(), push_node.attribute("w").as_int(), push_node.attribute("h").as_int() }); } anim_plane.loop = config.child("animations").child("plane").attribute("loop").as_bool(); anim_plane.speed = config.child("animations").child("plane").attribute("speed").as_float(); anim_plane.Reset(); //Loading Fx App->audio->LoadFx(config.child("animations").child("plane").child("fx").child_value()); //Death Pushbacks for (pugi::xml_node push_node = config.child("animations").child("death").child("frame"); push_node && ret; push_node = push_node.next_sibling("frame")) { anim_death.PushBack({ push_node.attribute("x").as_int(), push_node.attribute("y").as_int(), push_node.attribute("w").as_int(), push_node.attribute("h").as_int() }); } anim_death.loop = config.child("animations").child("death").attribute("loop").as_bool(); anim_death.speed = config.child("animations").child("death").attribute("speed").as_float(); anim_death.Reset(); App->audio->LoadFx(config.child("animations").child("death").child("fx").child_value()); //Jump Pushbacks for (pugi::xml_node push_node = config.child("animations").child("jump_up").child("frame"); push_node && ret; push_node = push_node.next_sibling("frame")) { anim_jumpup.PushBack({ push_node.attribute("x").as_int(), push_node.attribute("y").as_int(), push_node.attribute("w").as_int(), push_node.attribute("h").as_int() }); } anim_jumpup.loop = config.child("animations").child("jump_up").attribute("loop").as_bool(); anim_jumpup.speed = config.child("animations").child("jump_up").attribute("speed").as_float(); anim_jumpup.Reset(); App->audio->LoadFx(config.child("animations").child("jump_up").child("fx").child_value()); for (pugi::xml_node push_node = config.child("animations").child("jump_down").child("frame"); push_node && ret; push_node = push_node.next_sibling("frame")) { anim_jumpdown.PushBack({ push_node.attribute("x").as_int(), push_node.attribute("y").as_int(), push_node.attribute("w").as_int(), push_node.attribute("h").as_int() }); } anim_jumpdown.loop = config.child("animations").child("jump_down").attribute("loop").as_bool(); anim_jumpdown.speed = config.child("animations").child("jump_down").attribute("speed").as_float(); anim_jumpdown.Reset(); App->audio->LoadFx(config.child("animations").child("jump_down").child("fx").child_value()); // attack pushbacks for (pugi::xml_node push_node = config.child("animations").child("attack").child("frame"); push_node && ret; push_node = push_node.next_sibling("frame")) { anim_attack.PushBack({ push_node.attribute("x").as_int(), push_node.attribute("y").as_int(), push_node.attribute("w").as_int(), push_node.attribute("h").as_int() }); } anim_attack.loop = config.child("animations").child("attack").attribute("loop").as_bool(); anim_attack.speed = config.child("animations").child("attack").attribute("speed").as_float(); anim_attack.Reset(); App->audio->LoadFx(config.child("animations").child("coin").child("fx").child_value()); App->audio->LoadFx(config.child("animations").child("life").child("fx").child_value()); current_animation = &anim_idle; return ret; } bool j1Player::Start() { App->p_timer.Start(); timer = 0; score = 0; if (!b_respawn) { position.x = respawn.x = collider->rect.x; position.y = respawn.y = collider->rect.y - 20; } else { position.x = respawn.x; position.y = respawn.y; b_respawn = false; } graphics = App->tex->Load(texture_path.GetString()); App->render->camera.x = -60 * App->win->GetScale(); App->render->camera.y = 0; currentState = CharacterState::Jump; resetPlayer(); return true; } bool j1Player::CleanUp() { LOG("Unloading Player assets"); App->setTime(timer); App->setScore(score); //App->audio->StopFx(); App->audio->UnloadFx(); App->tex->UnLoad(graphics); graphics = nullptr; App->collisions->deleteCollider(collider); collider = nullptr; return true; } // Update: draw background bool j1Player::Update(float dt, bool do_logic) { BROFILER_CATEGORY("PlayerUpdate1", Profiler::Color::MediumSlateBlue); OnGround = App->collisions->CheckGroundCollision(collider); if (OnGround) isFalling = false; if (!dead || !win) { if (!death_anim && !godmode) { if (OnGround) lastPosition = position, plane = false; switch (currentState) { case CharacterState::Stand: if (!OnGround) { currentState = CharacterState::Jump; } //if left or right key is pressed, but not both if (App->input->GetKey(SDL_SCANCODE_D) != App->input->GetKey(SDL_SCANCODE_A)) { currentState = CharacterState::Walk; } else if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN) { App->audio->StopFx(); App->audio->PlayFx(Jump_fx, 0); current_animation = &anim_jumpup; speed.y -= 8000.0f *dt; currentState = CharacterState::Jump; OnGround = false; } else if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN && !attacked) { currentState = CharacterState::Attack; } break; case CharacterState::Walk: if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN && !attacked) { speed = { 0,0 }; currentState = CharacterState::Attack; break; } if (App->input->GetKey(SDL_SCANCODE_A) == App->input->GetKey(SDL_SCANCODE_D)) { App->audio->StopFx(); currentState = CharacterState::Stand; speed = { 0,0 }; } else if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) { if(!Mix_Playing(-1)) App->audio->PlayFx(Run_fx, 0); flip = false; speed.x = walkSpeed; } else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) { if (!Mix_Playing(-1)) App->audio->PlayFx(Run_fx, 0); flip = true; speed.x = -walkSpeed; } if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN) { current_animation = &anim_jumpup; App->audio->StopFx(); App->audio->PlayFx(Jump_fx, 0); speed.y -= 8000.0f *dt; currentState = CharacterState::Jump; OnGround = false; } else if (!OnGround) { currentState = CharacterState::Jump; current_animation = &anim_jumpdown; } break; case CharacterState::Jump: speed.y += gravity*dt; if (speed.y <= 0) { current_animation = &anim_jumpup; } else if (speed.y > 0) { //if(!plane) //App->audio->StopFx(); current_animation = &anim_jumpdown; } if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN) { if (!plane && start_time == 0) { start_time = SDL_GetTicks(); plane = true; isFalling = true; App->audio->StopFx(); App->audio->PlayFx(Plane_fx, 1); } } else if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_REPEAT) { if (speed.y > -jumpSpeed && !isFalling) { speed.y -= 4000.0f *dt; } else if(!isFalling){ isFalling = true; } if (SDL_GetTicks() - start_time < 800 && plane) { speed.y = gravity * 0.1 * dt; current_animation = &anim_plane; } else if(plane) { plane = false; App->audio->StopFx(); } }else if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_UP) { if (plane) { plane = false; App->audio->StopFx(); } isFalling = true; } if (App->input->GetKey(SDL_SCANCODE_E) == KEY_DOWN && !attacked) { Fall = true; speed = { 0,0 }; currentState = CharacterState::Attack; } else if (App->input->GetKey(SDL_SCANCODE_A) == App->input->GetKey(SDL_SCANCODE_D)) { speed.x = 0.0f; } else if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) { flip = false; speed.x = walkSpeed; } else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) { flip = true; speed.x = -walkSpeed; } if (OnGround) { attacked = false; if (App->input->GetKey(SDL_SCANCODE_A) == App->input->GetKey(SDL_SCANCODE_D)) { currentState = CharacterState::Stand; speed = { 0,0 }; plane = false; start_time = 0; } else { currentState = CharacterState::Walk; speed = { 0,0 }; plane = false; start_time = 0; } } break; case CharacterState::Attack: LOG("Attack % i", anim_attack.getFrame()); if (anim_attack.getFrame() >= 8)//CHANGE FIX { anim_attack.Reset(); LOG("Attack"); if (!OnGround) { attacked = true; currentState = CharacterState::Jump; } if (App->input->GetKey(SDL_SCANCODE_D) != App->input->GetKey(SDL_SCANCODE_A)) { currentState = CharacterState::Walk; } else if (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN) { App->audio->StopFx(); App->audio->PlayFx(Jump_fx, 0); current_animation = &anim_jumpup; speed.y -= 8000.0f *dt; currentState = CharacterState::Jump; OnGround = false; } else { currentState = CharacterState::Stand; } //Destroy Collider App->collisions->deleteCollider(attack_col); attack_col = nullptr; } else { current_animation = &anim_attack;//DELETE if (attack_col == nullptr){ if (flip) attack_col = App->collisions->AddCollider({ (int)position.x - 16,(int)position.y, 20, 31 }, ColliderTypes::COLLIDER_PLAYER_SHOT, (j1Module*)App->entitymanager); else attack_col = App->collisions->AddCollider({ (int)position.x + 16,(int)position.y, 20, 31 }, ColliderTypes::COLLIDER_PLAYER_SHOT, (j1Module*)App->entitymanager); } } break; } if (speed.y > maxFallingSpeed) speed.y = maxFallingSpeed; if (position.x < 0) position.x = 0; else position.x += speed.x * dt; if (position.y < 0) position.y = 0; else position.y += speed.y * dt; } if(death_anim) deathAnim(dt); cameraPos(); //Animation checks switch (currentState) { case CharacterState::Walk: if (speed.x == 0.0f) { current_animation = &anim_idle; } else current_animation = &anim_run; break; case CharacterState::Stand: current_animation = &anim_idle; break; case CharacterState::Attack: current_animation = &anim_attack; break; } if (godmode) { if ((App->input->GetKey(SDL_SCANCODE_A) == App->input->GetKey(SDL_SCANCODE_D))) { speed.x = 0; } else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT) { flip = true; speed.x = -walkSpeed; } else if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT) { flip = false; speed.x = walkSpeed; } if ((App->input->GetKey(SDL_SCANCODE_W) == App->input->GetKey(SDL_SCANCODE_S))) { speed.y = 0; } else if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT) { speed.y = -walkSpeed; } else if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT) { speed.y = walkSpeed; } if (position.x < 0) position.x = 0; else position.x += speed.x * dt; if (position.y <= 0) position.y = 0; else position.y += speed.y * dt; current_animation = &anim_plane; } //Collider if(flip) collider->SetPos(position.x, position.y);//+4 else collider->SetPos(position.x, position.y);//+10 animation_Rect = current_animation->GetCurrentFrame(dt); } return true; } bool j1Player::Update() { BROFILER_CATEGORY("PlayerUpdate2", Profiler::Color::MediumSpringGreen); App->calcTime(timer); // Draw everything -------------------------------------- if (hit) hitanim(); if (!blink){ if (flip) if (current_animation == &anim_attack) App->render->Blit(graphics, position.x - 30, position.y, &animation_Rect, SDL_FLIP_HORIZONTAL); else App->render->Blit(graphics, position.x, position.y, &animation_Rect, SDL_FLIP_HORIZONTAL); else if (current_animation == &anim_plane || current_animation == &anim_jumpup || current_animation == &anim_jumpdown) App->render->Blit(graphics, position.x - 10, position.y, &animation_Rect, SDL_FLIP_NONE); else App->render->Blit(graphics, position.x - 20, position.y, &animation_Rect, SDL_FLIP_NONE); } return true; } void j1Player::OnCollision(Collider* collider1, Collider* collider2) { if (App->dt != 0) { if (collider2->gettype() == 0) { WallCollision(collider1, collider2); } else if (collider2->gettype() == COLLIDER_ENEMY) { if (death_anim == false && collider2->gettype() == COLLIDER_ENEMY) { if (godmode == false) current_life--; death_anim = true; App->audio->StopFx(); App->audio->PlayFx(Death_fx, 1); } else { current_life--; } } else if (collider2->gettype() == COLLIDER_FLYING_ENEMY && !godmode || collider2->gettype() == COLLIDER_PLATFORM_ENEMY && !death_anim && !godmode) { if (!hit && c_blink == 0 && death_anim == false) { aux_time = SDL_GetTicks() - aux_time; hit = true; current_life--; if (current_life == 0) { hit = false; currentState = CharacterState::Jump; death_anim = true; App->audio->StopFx(); App->audio->PlayFx(Death_fx, 0); } else { App->audio->StopFx(); App->audio->PlayFx(Jump_fx, 0); } } } else if (collider2->gettype() == COLLIDER_WIN) { if (!win) App->audio->PlayFx(Win_fx, 0); win = true; } } } void j1Player::WallCollision(Collider* c1, Collider* c2) { SDL_Rect collisionOverlay; SDL_IntersectRect(&c1->rect, &c2->rect, &collisionOverlay); if (collisionOverlay.w >= collisionOverlay.h) { if (c1->rect.y + c1->rect.h >= c2->rect.y && c1->rect.y < c2->rect.y ) { //Ground while (c1->CheckCollision(c2->rect) == true) { c1->rect.y--; } current_animation = &anim_idle; speed.y = 0.0f; OnGround = true; isFalling = false; } else if (c1->rect.y <= c2->rect.y + c2->rect.h && c1->rect.y + c1->rect.h > c2->rect.y + c2->rect.h ) { //Ceiling while (c1->CheckCollision(c2->rect) == true) { c1->rect.y++; } speed.y = 0.0f; isFalling = true; } position.y = c1->rect.y; } else { if (c1->rect.x + c1->rect.w >= c2->rect.x && c1->rect.x < c2->rect.x ) { //Right while (c1->CheckCollision(c2->rect) == true) { c1->rect.x--; } speed.x = 0.0f; } else if (c1->rect.x <= c2->rect.x + c2->rect.w && c1->rect.x + c1->rect.w > c2->rect.x + c2->rect.w ) { //Left while (c1->CheckCollision(c2->rect) == true) { c1->rect.x++; } speed.x = 0.0f; } position.x = c1->rect.x; } } void j1Player::setGround(bool ground, bool falling) { OnGround = ground; if(OnGround) isFalling = true; else isFalling = false; } void j1Player::cameraPos() { if (-(position.x + collider->rect.w) <= App->render->camera.x + -App->render->camera.w + 200 && App->render->camera.x < 0) App->render->camera.x = App->render->camera.w - 200 + -(position.x + collider->rect.w); else if (-(position.x) >= App->render->camera.x - 200) App->render->camera.x = 200 + -position.x; /*if (App->render->camera.y + App->render->camera.h < (App->map->data.height * 16 * App->win->GetScale()) && -App->render->camera.y > 0) { if ((position.y + collider->rect.h) * App->win->GetScale() > App->render->camera.h + App->render->camera.y - (50 * App->win->GetScale())) App->render->camera.y -= speed.y * App->win->GetScale(); else if (position.y * App->win->GetScale() < App->render->camera.y + (50 * App->win->GetScale())) App->render->camera.y -= speed.y * App->win->GetScale(); else App->render->camera.y = (position.y * App->win->GetScale() + collider->rect.h / 2 - App->win->height / 2); }*/ } void j1Player::hitanim() { if (SDL_GetTicks() - aux_time > 100 && c_blink < 10) { aux_time = SDL_GetTicks(); if (c_blink % 2 == 0) blink = true; else blink = false; c_blink++; } if(c_blink == 10) { hit = false; c_blink = 0; } } void j1Player::deathAnim(float dt) { current_animation = &anim_death; if (position.y > App->render->camera.y + App->render->camera.h - App->render->camera.h / 4 && !isFalling && death_anim) { position.y -= 800 * dt; start_time = SDL_GetTicks(); } else if (SDL_GetTicks() - start_time > 500) isFalling = true; if (isFalling && death_anim) { position.y += 800 * dt; } if (isFalling && position.y > App->render->camera.y + App->render->camera.h) { isFalling = false; death_anim = false; if (current_life <= 0) dead = true; else { position = lastPosition; App->render->camera.x = -position.x * App->win->GetScale() + 300; if (App->render->camera.x > 0) App->render->camera.x = 0; start_time = SDL_GetTicks(); } } } void j1Player::resetPlayer() { flip = false; dead = false; win = false; death_anim = false; isFalling = true; OnGround = false; plane = false; hit = false; start_time = 0; aux_time = 0; current_life = life; } // Load Game State bool j1Player::Load(pugi::xml_node& data) { speed.x = data.child("speed").attribute("x").as_uint(); speed.y = data.child("speed").attribute("y").as_uint(); current_life = data.child("life").attribute("value").as_uint(); jumpSpeed = data.child("jumpSpeed").attribute("value").as_float(); maxFallingSpeed = data.child("maxFallingSpeed").attribute("value").as_float(); walkSpeed = data.child("walkSpeed").attribute("value").as_float(); gravity = data.child("gravity").attribute("value").as_float(); timer = data.child("timer").attribute("value").as_uint(); score = data.child("score").attribute("value").as_uint(); return true; } // Save Game State bool j1Player::Save(pugi::xml_node& data) const { pugi::xml_node player = data; player.append_child("speed").append_attribute("x") = speed.x; player.child("speed").append_attribute("y") = speed.y; player.append_child("position").append_attribute("x") = position.x; player.child("position").append_attribute("y") = position.y; player.child("position").append_attribute("w") = collider->rect.w; player.child("position").append_attribute("h") = collider->rect.h; player.append_child("life").append_attribute("value") = current_life; player.append_child("jumpSpeed").append_attribute("value") = jumpSpeed; player.append_child("maxFallingSpeed").append_attribute("value") = maxFallingSpeed; player.append_child("walkSpeed").append_attribute("value") = walkSpeed; player.append_child("gravity").append_attribute("value") = gravity; player.append_child("timer").append_attribute("value") = timer; player.append_child("score").append_attribute("value") = score; return true; } void j1Player::PlayFX(CharacterFX fx) { App->audio->StopFx(); App->audio->PlayFx(fx, 0); } void j1Player::AddLife() { current_life += 1; if (current_life > 3) current_life = 3; }
27.811224
167
0.640158
[ "render" ]
308a3c455e0af38ebb0a4a8d771772074dddfbec
1,333
cpp
C++
examples/example_deque.cpp
nwehr/kick
0f738e0895a639c977e8c473eb40ee595e301f32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
examples/example_deque.cpp
nwehr/kick
0f738e0895a639c977e8c473eb40ee595e301f32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
examples/example_deque.cpp
nwehr/kick
0f738e0895a639c977e8c473eb40ee595e301f32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include <iostream> #include "../deque.hpp" using namespace kick; int main( int argc, const char* argv[] ){ deque<int> numbers; numbers.push_back(1); numbers.push_back(2); numbers.push_back(3); numbers.push_back(4); numbers.push_back(5); { int sum = numbers .filter([](const int& val) -> bool { return val % 2 != 0; }) .transform<int>([](const int& val) -> int { return val * val; }) .reduce<int>([](const int& total, const int& val) -> int { return total + val; }); // for(auto const& it : odds) { // std::cout << it << std::endl; // } std::cout << sum << std::endl; } // { // deque<int> odds; // numbers.filter_to(odds, [](const int& val) -> bool { // return val % 2 != 0; // }); // std::cout << "odds:" << std::endl; // for(auto const& val : odds) { // std::cout << val << std::endl; // } // } // { // deque<int> squares; // numbers.map_to<int>(squares, [](const int& val) -> int { // return val * val; // }); // std::cout << "squares:" << std::endl; // for(auto const& val : squares) { // std::cout << val << std::endl; // } // } // { // int sum; // numbers.reduce_to<int>(sum, [](const int& sum, const int& val) -> int { // return sum * val; // }); // std::cout << "sum:" << std::endl << sum << std::endl; // } }
18.774648
76
0.515379
[ "transform" ]
308f591f1104b89387a189d0d8c1add9207a2846
32,548
cpp
C++
src/qtplugin/CPluginManager.cpp
SindenDev/3dimviewer
e23a3147edc35034ef4b75eae9ccdcbc7192b1a1
[ "Apache-2.0" ]
6
2020-04-14T16:10:55.000Z
2021-05-21T07:13:55.000Z
src/qtplugin/CPluginManager.cpp
SindenDev/3dimviewer
e23a3147edc35034ef4b75eae9ccdcbc7192b1a1
[ "Apache-2.0" ]
null
null
null
src/qtplugin/CPluginManager.cpp
SindenDev/3dimviewer
e23a3147edc35034ef4b75eae9ccdcbc7192b1a1
[ "Apache-2.0" ]
2
2020-07-24T16:25:38.000Z
2021-01-19T09:23:18.000Z
/////////////////////////////////////////////////////////////////////////////// // $Id$ // // 3DimViewer // Lightweight 3D DICOM viewer. // // Copyright 2008-2016 3Dim Laboratory s.r.o. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////////// #include "mainwindow.h" #include <CPluginManager.h> #include <PluginInterface.h> #include <QDir> #include <QPluginLoader> #include <QMainWindow> #include <QSettings> #include <QDockWidget> #include <QMenuBar> #include <QToolBar> #include <QUrl> #include <QMessageBox> #include <QDesktopServices> #include <qglobal.h> #include <QNetworkRequest> #include <QNetworkReply> #include <QDebug> #include <VPL/Base/Logging.h> #include <data/CModelManager.h> #include <actlog/ceventfilter.h> #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include <QStandardPaths> #endif #if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)) #define DATALOCATION() QDesktopServices::storageLocation(QDesktopServices::DataLocation) #else #define DATALOCATION() QStandardPaths::locate(QStandardPaths::DataLocation, QString(), QStandardPaths::LocateDirectory) #endif #define ONLINE_HELP_URL "https://www.3dim-laboratory.cz/manuals/" // Constructor CPluginManager::CPluginManager() { m_pMain = NULL; m_pluginsMenu = NULL; m_pluginsToolbar = NULL; m_pDockTo = NULL; initSignalTable(); } CPluginManager::~CPluginManager() { // make a note that we don't want any further online check today QSettings settings; settings.setValue("LastOnlineHelpCheck",QDate::currentDate().toString(Qt::ISODate)); unloadPlugins(false); } void CPluginManager::unloadPlugins(bool bCallUnload) { // Unload plugins and clear plugin array foreach (QPluginLoader* pluginLoader, m_plugins) { if (bCallUnload) pluginLoader->unload(); delete pluginLoader; } m_plugins.clear(); } // loads plugin from a specified directory and all subdirectories void CPluginManager::loadPluginsInDir(QString dirName) { QDir pluginsDir = QDir(dirName); // load dynamic plugins from dir #ifdef _WIN32 foreach (QString fileName, pluginsDir.entryList(QStringList("*.dll"),QDir::Files)) { #else foreach (QString fileName, pluginsDir.entryList(QDir::Files)) { #endif #ifdef _WIN32 // ignore microsoft libraries if (fileName.startsWith("api-ms-win", Qt::CaseInsensitive) || fileName.startsWith("msvc", Qt::CaseInsensitive)) continue; // ignore openscenegraph libraries if (fileName.contains(QRegExp("^osg\\d{2,3}-")) || fileName.startsWith("osgdb_",Qt::CaseInsensitive) || fileName.contains("OpenThreads")) continue; // ignore Qt libraries if (fileName.startsWith("Qt5")) continue; #endif QPluginLoader *loader = new QPluginLoader(pluginsDir.absoluteFilePath(fileName)); if (NULL!=loader) { QObject *plugin = loader->instance(); if (plugin) { initPlugin(plugin,fileName); m_pluginFileNames += pluginsDir.absolutePath()+"/"+fileName; m_plugins.push_back(loader); } else { #ifdef TENSORFLOW_BUILT_WITH_CUDA if ("DeepLearningPlugin.dll" == fileName) { QMessageBox::warning(m_pMain, QCoreApplication::applicationName(), tr("Deep Learning plugin could not be loaded. If 3DimViewer was built with GPU support make sure that CUDA 9.0 and cuDNN v7.0.5 are installed correctly.")); } #endif delete loader; } } } // load plugins from subdirectories foreach (QString subdirName, pluginsDir.entryList(QDir::Dirs|QDir::NoDotAndDotDot)) { loadPluginsInDir(pluginsDir.absolutePath()+"/"+subdirName); } } // calls disconnectPlugin method from the PluginInterface for every loaded plugin void CPluginManager::disconnectPlugins() { APP_MODE.disconnectAllDrawingHandlers(); APP_MODE.disconnectAllSceneHitHandlers(); // there's a problem with the deallocation of a model allocated in a dll, therefore we set it to null here if (!m_plugins.isEmpty() || !QPluginLoader::staticInstances().isEmpty()) { for (int i = 0; i<MAX_MODELS; ++i) { data::CObjectPtr<data::CModel> spModel(APP_STORAGE.getEntry(data::Storage::BonesModel::Id + i)); const geometry::CMesh* pMesh=spModel->getMesh(); if (NULL != pMesh) { spModel->setMesh(NULL); spModel->clearAllProperties(); APP_STORAGE.invalidate(spModel.getEntryPtr()); } } } // call disconnectPlugin for every static plugin foreach (QObject *plugin, QPluginLoader::staticInstances()) { PluginInterface *iPlugin = qobject_cast<PluginInterface *>(plugin); if (iPlugin) iPlugin->disconnectPlugin(); } // beware of QTBUG-13237, disable acceptDrops in line edits if you experience crashes foreach(QDockWidget* pDW, m_panelsWidgets) { m_pMain->removeDockWidget(pDW); } foreach(QToolBar* pTB, m_toolbarWidgets) { m_pMain->removeToolBar(pTB); } if (NULL!=m_pluginsMenu) foreach(QMenu* pMenu, m_menuWidgets) m_pluginsMenu->removeAction(pMenu->menuAction()); if (NULL!=m_pluginsToolbar) { m_pMain->removeToolBar(m_pluginsToolbar); delete m_pluginsToolbar; m_pluginsToolbar = NULL; } // call disconnectPlugin for every loaded plugin foreach (QPluginLoader* pluginLoader, m_plugins) { QObject *plugin = pluginLoader->instance(); if (plugin) { PluginInterface *iPlugin = qobject_cast<PluginInterface *>(plugin); if (iPlugin) { // disconnect renderer iPlugin->setRenderer(NULL); // disconnect other stuff iPlugin->disconnectPlugin(); // delete plugin ui, because plugin destructor can come after examination destructor -> problem QMenu *pMenu = iPlugin->getOrCreateMenu(); if (NULL!=pMenu) delete pMenu; QToolBar* pToolBar = iPlugin->getOrCreateToolBar(); if (NULL!=pToolBar) delete pToolBar; QWidget* pPanel = iPlugin->getOrCreatePanel(); if (NULL!=pPanel) delete pPanel; } } //pluginLoader->unload(); //delete pluginLoader; } //m_plugins.clear(); } // Loads plugins void CPluginManager::loadPlugins(QMainWindow* pMain, // pointer to main window - needed to add menu, toolbars etc QDir* pLocaleDir, // path to translations QDockWidget *dockTo) // window to tabify plugin panels with { m_pMain = pMain; m_localeDir = *pLocaleDir; m_pDockTo = dockTo; Q_ASSERT(m_pMain); if (NULL==m_pMain) return; // load static plugins foreach (QObject *plugin, QPluginLoader::staticInstances()) initPlugin(plugin,NULL); // set plugin path m_pluginsDir = QDir(qApp->applicationDirPath()); bool ok; #ifdef _DEBUG ok=m_pluginsDir.cd("pluginsd"); #else ok=m_pluginsDir.cd("plugins"); #endif if (!ok) { m_pluginsDir.cdUp(); #ifdef _DEBUG ok=m_pluginsDir.cd("pluginsd"); #else ok=m_pluginsDir.cd("plugins"); #endif } #ifdef __APPLE__ if (!ok) { m_pluginsDir.cdUp(); #ifdef _DEBUG ok=m_pluginsDir.cd("pluginsd"); #else ok=m_pluginsDir.cd("plugins"); #endif } #endif if (!ok) m_pluginsDir = QDir(qApp->applicationDirPath()); // load dynamic plugins loadPluginsInDir(m_pluginsDir.absolutePath()); // we can't be sure that the dockwidget will exist later, set to null m_pDockTo = NULL; } void CPluginManager::initSignalTable() { if (m_vplSignals.size()>0) return; m_vplSignals[VPL_SIGNAL(SigGetModelColor).getId()]=&(VPL_SIGNAL(SigGetModelColor)); m_vplSignals[VPL_SIGNAL(SigSetModelColor).getId()]=&(VPL_SIGNAL(SigSetModelColor)); m_vplSignals[VPL_SIGNAL(SigUndoSnapshot).getId()]=&(VPL_SIGNAL(SigUndoSnapshot)); m_vplSignals[VPL_SIGNAL(SigSetColoring).getId()] = &(VPL_SIGNAL(SigSetColoring)); m_vplSignals[VPL_SIGNAL(SigSetContoursVisibility).getId()] = &(VPL_SIGNAL(SigSetContoursVisibility)); m_vplSignals[VPL_SIGNAL(SigGetContoursVisibility).getId()] = &(VPL_SIGNAL(SigGetContoursVisibility)); m_vplSignals[VPL_SIGNAL(SigVolumeOfInterestChanged).getId()] = &(VPL_SIGNAL(SigVolumeOfInterestChanged)); m_vplSignals[VPL_SIGNAL(SigEnableRegionColoring).getId()] = &(VPL_SIGNAL(SigEnableRegionColoring)); m_vplSignals[VPL_SIGNAL(SigEnableMultiClassRegionColoring).getId()] = &(VPL_SIGNAL(SigEnableMultiClassRegionColoring)); m_vplSignals[VPL_SIGNAL(SigShowVolumeOfInterestDialog).getId()] = &(VPL_SIGNAL(SigShowVolumeOfInterestDialog)); m_vplSignals[VPL_SIGNAL(SigGetModelCutVisibility).getId()] = &(VPL_SIGNAL(SigGetModelCutVisibility)); m_vplSignals[VPL_SIGNAL(SigSetModelCutVisibility).getId()] = &(VPL_SIGNAL(SigSetModelCutVisibility)); m_vplSignals[VPL_SIGNAL(SigGetSelectedModelId).getId()] = &(VPL_SIGNAL(SigGetSelectedModelId)); m_vplSignals[VPL_SIGNAL(SigEstimateDensityWindow).getId()] = &(VPL_SIGNAL(SigEstimateDensityWindow)); m_vplSignals[VPL_SIGNAL(SigSetDensityWindow).getId()] = &(VPL_SIGNAL(SigSetDensityWindow)); m_vplSignals[VPL_SIGNAL(SigSaveModelExt).getId()] = &(VPL_SIGNAL(SigSaveModelExt)); m_vplSignals[VPL_SIGNAL(SigNewTransformMatrixFromNote).getId()] = &(VPL_SIGNAL(SigNewTransformMatrixFromNote)); m_vplSignals[VPL_SIGNAL(SigRemoveModel).getId()] = &(VPL_SIGNAL(SigRemoveModel)); } void CPluginManager::initPlugin(QObject* plugin, const QString& fileName) { if (!plugin) return; PluginInterface *iPlugin = qobject_cast<PluginInterface *>(plugin); if (iPlugin) { VPL_LOG_INFO("Plugin: " << fileName.toStdString()); // set app storage, app mode pointer and pointer to main window plugin->setProperty("FileName",fileName); plugin->setProperty("AppSignature",PLUG_APP_SIGNATURE); // "OpenSource" iPlugin->setAppMode(&APP_MODE); iPlugin->setDataStorage(&APP_STORAGE); iPlugin->setRenderer(VPL_SIGNAL(SigGetRenderer).invoke2()); iPlugin->setParentWindow(m_pMain); iPlugin->setVPLSignals(&m_vplSignals); if (!fileName.isEmpty()) { QSettings settings; QString lngFile=settings.value("Language","NA").toString(); if ("NA"==lngFile) // no language selected - set according to system locale lngFile = ( QLocale::system().name() ); if (!lngFile.isEmpty()) { QFileInfo file(lngFile); plugin->setProperty("LocaleName",file.baseName()); } iPlugin->setLanguage(m_localeDir.absolutePath(),lngFile, fileName); // load translation file } // PluginLicenseInterface *iPluginLic = qobject_cast<PluginLicenseInterface *>(plugin); if (NULL!=iPluginLic) { app::CProductInfo info=app::getProductInfo(); QString product=QString("%1 %2.%3").arg(QCoreApplication::applicationName()).arg(info.getVersion().getMajorNum()).arg(info.getVersion().getMinorNum()); iPluginLic->setCurrentHost(product); } // create menu populateMenus(plugin); // create toolbar QToolBar* pToolbar = iPlugin->getOrCreateToolBar(); if (pToolbar) { m_pMain->addToolBar(pToolbar); m_toolbarWidgets.append(pToolbar); } // create panel QWidget* pPanel = iPlugin->getOrCreatePanel(); if (pPanel) { // create dock widget for the plugin panel QDockWidget* pDW = new QDockWidget(pPanel->windowTitle()); pDW->setWidget(pPanel); pDW->setAllowedAreas(Qt::AllDockWidgetAreas); pDW->setFeatures(QDockWidget::DockWidgetClosable|QDockWidget::DockWidgetMovable); pDW->setObjectName(pPanel->objectName()); QString icon = plugin->property("PanelIcon").toString(); if (icon.isEmpty()) pDW->setProperty("Icon",":/svg/svg/page.svg"); else pDW->setProperty("Icon",icon); pDW->hide(); connect(pDW, SIGNAL(visibilityChanged(bool)), m_pMain, SLOT(dockWidgetVisiblityChanged(bool))); connect(pDW,SIGNAL(dockLocationChanged(Qt::DockWidgetArea)),m_pMain,SLOT(dockLocationChanged(Qt::DockWidgetArea))); // tabify or add to a dock area if (m_pDockTo) m_pMain->tabifyDockWidget(m_pDockTo,pDW); else m_pMain->addDockWidget(Qt::RightDockWidgetArea,pDW); m_panelsWidgets.append(pDW); } // call connectPlugin method to finish plugin initialization iPlugin->connectPlugin(); } } // Finds plugin with a given ID QObject* CPluginManager::findPluginByID(QString sPluginName) { foreach (QString fileName, m_pluginFileNames) { QPluginLoader loader(m_pluginsDir.absoluteFilePath(fileName)); QObject *plugin = loader.instance(); if (plugin) { PluginInterface *iPlugin = qobject_cast<PluginInterface *>(plugin); if (iPlugin) if (iPlugin->pluginID()==sPluginName) return plugin; } } return NULL; } void CPluginManager::sslErrorHandler(QNetworkReply* reply, const QList<QSslError> & errlist) { reply->ignoreSslErrors(); } void CPluginManager::dataDownloaded(QNetworkReply* reply) { QByteArray downloadedData; QNetworkReply::NetworkError err = reply->error(); if(err == QNetworkReply::NoError) { int httpstatuscode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt(); if (reply->isReadable()) downloadedData = reply->readAll(); } QString saveFileName = reply->property("SaveTo").toString(); reply->deleteLater(); if (!downloadedData.isEmpty()) { if (!saveFileName.isEmpty()) { QFileInfo inf(saveFileName); QDir dir(inf.absolutePath()); if (!dir.exists()) dir.mkpath("."); QFile file(saveFileName); if (file.open(QIODevice::WriteOnly)) { file.write(downloadedData); file.flush(); file.close(); } } } } // Adds entries void CPluginManager::populateMenus(QObject *plugin) { if (!plugin) return; // Create plugins menu in the apps main window if (!m_pluginsMenu) { m_pluginsMenu=m_pMain->menuBar()->addMenu(tr("&Plugins")); m_pluginsMenu->setObjectName("menuPlugins"); } if (!m_pluginsToolbar) { m_pluginsToolbar = m_pMain->addToolBar(tr("Plugins Toolbar")); m_pluginsToolbar->setObjectName("toolbarPlugins"); connect(m_pluginsToolbar,SIGNAL(actionTriggered(QAction*)),this,SLOT(pluginMenuAction(QAction*))); } if (NULL!=m_pluginsMenu) { // Basic plugin interface PluginInterface *iPlugin = qobject_cast<PluginInterface *>(plugin); // Licensed plugin interface PluginLicenseInterface *iPluginLic = qobject_cast<PluginLicenseInterface *>(plugin); if (iPlugin) { // show help action QAction* pShowDoc = NULL; QString fileName = plugin->property("FileName").toString(); if (!fileName.isEmpty()) { QFileInfo file(fileName.toLower()); #ifdef QT_DEBUG QString pluginFileName(file.baseName()); if (pluginFileName.endsWith('d')) { pluginFileName.chop(1); pluginFileName=pluginFileName+"."+file.completeSuffix(); file.setFile(pluginFileName); } #endif #ifdef __APPLE__ // remove lib prefix QString pluginFileNameA(file.baseName()); if (pluginFileNameA.startsWith("lib",Qt::CaseInsensitive)) { pluginFileNameA = pluginFileNameA.right(pluginFileNameA.length()-3)+"."+file.completeSuffix(); file.setFile(pluginFileNameA); } #endif const QString docPath = QDir::currentPath() + "/doc/"; const QString localeName = plugin->property("LocaleName").toString(); const QString wsDataPath = DATALOCATION()+"/Help/"; QDir dir(docPath); QString pdfHelp; // name templates QString baseName(file.baseName()+".pdf"), localizedName; if (!localeName.isEmpty()) localizedName = file.baseName() + "-" + localeName + ".pdf"; // look for installed help if (dir.exists(baseName)) pdfHelp = dir.absoluteFilePath(baseName); else { if (!localizedName.isEmpty() && dir.exists(localizedName)) pdfHelp = dir.absoluteFilePath(localizedName); } // no installed help? see if there is any downloaded if (pdfHelp.isEmpty()) { // is there downloaded one? QDir dirCache(wsDataPath); if (dirCache.exists(baseName)) pdfHelp = dirCache.absoluteFilePath(baseName); else if (!localizedName.isEmpty() && dirCache.exists(localizedName)) pdfHelp = dirCache.absoluteFilePath(localizedName); // check online (once per day only) if (pdfHelp.isEmpty()) { QSettings settings; QDate dateLastCheck; QVariant val = settings.value("LastOnlineHelpCheck"); if (QVariant::Date == val.type()) dateLastCheck = val.toDate(); if (QVariant::String == val.type()) dateLastCheck = QDate::fromString(val.toString(),Qt::ISODate); QString updateUrlBase = settings.value("OnlineHelpUrl",ONLINE_HELP_URL).toString(); if (dateLastCheck<QDate::currentDate()) { // we will get the data but we won't add them to the plugin menu because it is async operation, // user will see the downloaded help next time when he starts the application if (!updateUrlBase.endsWith('/')) updateUrlBase+='/'; QString updateUrl = updateUrlBase + baseName; m_networkManager.disconnect(this); connect(&m_networkManager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> &)), this, SLOT(sslErrorHandler(QNetworkReply*, const QList<QSslError> &))); connect(&m_networkManager, SIGNAL(finished(QNetworkReply*)), SLOT(dataDownloaded(QNetworkReply*))); QNetworkRequest request(updateUrl); request.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferNetwork); request.setRawHeader( "User-Agent" , "Mozilla Firefox" ); // returns 406 when not specified QNetworkReply* pReply = m_networkManager.get(request); pReply->setProperty("SaveTo",wsDataPath + baseName); } } } if (!pdfHelp.isEmpty()) { pShowDoc = new QAction(tr("Show Help"),this); pShowDoc->setObjectName("show_plugin_help"); pShowDoc->setProperty("OfflinePDF",pdfHelp); } } // create plugin menu QMenu* pPluginMenu=iPlugin->getOrCreateMenu(); if (NULL!=pPluginMenu) { if (pPluginMenu->objectName().isEmpty()) pPluginMenu->setObjectName(iPlugin->pluginID()); } // check presence of toolbar or panel to add entries to show/hide them QToolBar* pToolBar=iPlugin->getOrCreateToolBar(); QWidget* pPanel=iPlugin->getOrCreatePanel(); // if there's no plugin menu but there is a toolbar or panel, create our own menu if (NULL==pPluginMenu && (pToolBar || pPanel || iPluginLic || pShowDoc)) { pPluginMenu = new QMenu(iPlugin->pluginName()); pPluginMenu->setObjectName(iPlugin->pluginID()); } if (NULL!=pPluginMenu) { if (pToolBar || pPanel || iPluginLic || pShowDoc) { pPluginMenu->addSeparator(); if (pToolBar) { // create new action QAction* pActShowToolbar=new QAction(tr("Show/Hide Plugin Toolbar"),NULL); pActShowToolbar->setObjectName("show_hide_plugin_toolbar"); // set pointer to object as custom data - used by pluginMenuAction pActShowToolbar->setData(QVariant::fromValue((void*)pToolBar)); // add action pPluginMenu->addAction(pActShowToolbar); } if (pPanel) { QAction* pActShowPanel=new QAction(tr("Show/Hide Plugin Panel"),NULL); pActShowPanel->setObjectName("show_hide_plugin_panel"); pActShowPanel->setData(QVariant::fromValue((void*)pPanel)); QString icon = plugin->property("Icon").toString(); if (!icon.isEmpty()) pActShowPanel->setIcon(QIcon(icon)); pPluginMenu->addAction(pActShowPanel); } if (iPluginLic) { if (pToolBar || pPanel) pPluginMenu->addSeparator(); QAction* pActRegistration=new QAction(tr("Plugin Registration..."),NULL); pActRegistration->setObjectName("plugin_registration"); pActRegistration->setData(QVariant::fromValue((void*)plugin)); pPluginMenu->addAction(pActRegistration); } if (pShowDoc) { if (pToolBar || pPanel) pPluginMenu->addSeparator(); //QAction* pActRegistration=new QAction(tr("Plugin Registration..."),NULL); //pActRegistration->setData(QVariant::fromValue((void*)plugin)); pPluginMenu->addAction(pShowDoc); } // all actions are handled in one menu handler connect(pPluginMenu,SIGNAL(triggered(QAction*)),this,SLOT(pluginMenuAction(QAction*))); // connect menu actions to event filter IHasEventFilter *mw = dynamic_cast<IHasEventFilter *>(MainWindow::getInstance()); if (mw != NULL) { connect(pPluginMenu, SIGNAL(triggered(QAction*)), &mw->getEventFilter(), SLOT(catchPluginMenuAction(QAction*))); } } connect(pPluginMenu,SIGNAL(aboutToShow()),this,SLOT(pluginMenuAboutToShow())); m_pluginsMenu->addMenu(pPluginMenu); } if (NULL!=pPluginMenu) { m_menuWidgets.push_back(pPluginMenu); } if (NULL!=m_pluginsToolbar && NULL!=pPanel) { QAction* pActShowPanel=new QAction(iPlugin->pluginName(),NULL); pActShowPanel->setObjectName("show_plugin_panel"); pActShowPanel->setData(QVariant::fromValue((void*)pPanel)); QString icon = plugin->property("Icon").toString(); if (!icon.isEmpty()) pActShowPanel->setIcon(QIcon(icon)); else pActShowPanel->setIcon(QIcon(":/svg/svg/3dim.svg")); m_pluginsToolbar->addAction(pActShowPanel); // connect plugin menu button to event filter IHasEventFilter *mw = dynamic_cast<IHasEventFilter *>(MainWindow::getInstance()); if (mw != NULL) { connect(pActShowPanel, SIGNAL(triggered()), &mw->getEventFilter(), SLOT(catchMenuAction())); } } } } } // returns plugin panel's parent dockwidget QDockWidget* CPluginManager::getParentDockWidget(QWidget* view) { if (NULL==view) return NULL; QWidget* pParent=view->parentWidget(); if (NULL==pParent) return NULL; QDockWidget* pDockW=qobject_cast<QDockWidget*>(pParent); return pDockW; } // resets all plugin panels to a "default" layout void CPluginManager::tabifyAndHidePanels(QDockWidget* pDock1) { Q_ASSERT(pDock1); // run through static plugin panels foreach (QObject *plugin, QPluginLoader::staticInstances()) { PluginInterface *iPlugin = qobject_cast<PluginInterface *>(plugin); if (iPlugin) { QWidget* pPanel=iPlugin->getOrCreatePanel(); if (pPanel) { QDockWidget* pDock=getParentDockWidget(pPanel); if (pDock) { m_pMain->tabifyDockWidget(pDock1,pDock); pDock->hide(); } } } } // run through dynamic plugin panels foreach (QString fileName, m_pluginFileNames) { QPluginLoader loader(m_pluginsDir.absoluteFilePath(fileName)); QObject *plugin = loader.instance(); if (plugin) { PluginInterface *iPlugin = qobject_cast<PluginInterface *>(plugin); if (iPlugin) { QWidget* pPanel=iPlugin->getOrCreatePanel(); if (pPanel) { QDockWidget* pDock=getParentDockWidget(pPanel); if (pDock) { m_pMain->tabifyDockWidget(pDock1,pDock); pDock->hide(); } } } } } } // this method is called when some "general" action (show/hide plugin panel, toolbar, register) // in a plugin menu is triggered void CPluginManager::pluginMenuAction(QAction* action) { if (!action) return; // get custom data of that action QWidget* pObj=(QWidget*)action->data().value<void*>(); if (NULL!=pObj) { // if custom data contain a toolbar pointer, toggle its visibility QToolBar* pToolBar=qobject_cast<QToolBar*>(pObj); if (pToolBar) { if (pToolBar->isVisible()) pToolBar->hide(); else pToolBar->show(); } else { // for others assume that it's the panel, toggle its visibility QWidget* pPanel=qobject_cast<QWidget*>(pObj); if (pPanel) { bool bForceShow = (0==action->objectName().compare("show_plugin_panel",Qt::CaseInsensitive)); QDockWidget* pParentDock = qobject_cast<QDockWidget*>(pPanel->parentWidget()); if (pParentDock) { if (pParentDock->isVisible() && !bForceShow) { pParentDock->hide(); } else { pParentDock->show(); pParentDock->raise(); } } else { if (pPanel->isVisible() && !bForceShow) pPanel->hide(); else pPanel->show(); } } else { PluginLicenseInterface *iPluginLic = qobject_cast<PluginLicenseInterface *>(pObj); if (iPluginLic) { iPluginLic->validateLicense(PLUGIN_LICENSE_SHOW_DIALOG); } } } } else { QString pdfPath = action->property("OfflinePDF").toString(); if (!pdfPath.isEmpty()) { QFile file(pdfPath); if (file.exists()) { if (!QDesktopServices::openUrl(QUrl::fromLocalFile(file.fileName()))) QMessageBox::critical(NULL,QCoreApplication::applicationName(),tr("A PDF viewer is required to view help!")); } else QMessageBox::critical(NULL,QCoreApplication::applicationName(),tr("Help file is missing!")); } QString pdfUrl = action->property("OnlinePDF").toString(); if (!pdfUrl.isEmpty()) { if (!QDesktopServices::openUrl(QUrl(pdfUrl))) QMessageBox::critical(NULL,QCoreApplication::applicationName(),tr("Couldn't open online help! Please verify your internet connection.")); } } } // Using this method a desired action from a plugin can be triggered void CPluginManager::triggerPluginAction(const QString& pluginName, const QString& actionName) { QObject* pPlugin=findPluginByID(pluginName); if (NULL!=pPlugin) { PluginInterface *iPlugin = qobject_cast<PluginInterface *>(pPlugin); if (iPlugin) { QAction* pAct=iPlugin->getAction(actionName); if (pAct) pAct->trigger(); } } } // set visibility checkboxes for toolbar and panel in plugin menu void CPluginManager::pluginMenuAboutToShow() { // sender should be always a menu QMenu* pMenu=qobject_cast<QMenu*>(sender()); if (NULL!=pMenu) { // for every action in that menu QList<QAction *> actions = pMenu->actions(); for(QList<QAction*>::const_iterator it = actions.begin(); it != actions.end(); ++it) { QAction* pAct=(*it); // get custom data of that action QWidget* pObj=(QWidget*)pAct->data().value<void*>(); if (pObj) // if any than it should be a pointer to a widget { // a toolbar QToolBar* pToolBar=qobject_cast<QToolBar*>(pObj); if (pToolBar) { pAct->setCheckable(true); pAct->setChecked(pToolBar->isVisible()); } else { // or a dock widget containing the plugin's panel QDockWidget* pParentDock = qobject_cast<QDockWidget*>(pObj->parentWidget()); if (pParentDock) { pAct->setCheckable(true); pAct->setChecked(pParentDock->isVisible()); } } } } } }
39.789731
244
0.570849
[ "geometry", "object", "model", "3d" ]
30947b2ada2f58955a1e2345d74f50adafa3eadc
6,768
cc
C++
services/ui/demo/mus_demo.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
services/ui/demo/mus_demo.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
services/ui/demo/mus_demo.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "services/ui/demo/mus_demo.h" #include "base/memory/ptr_util.h" #include "base/time/time.h" #include "services/service_manager/public/cpp/connector.h" #include "services/service_manager/public/cpp/service_context.h" #include "services/ui/demo/bitmap_uploader.h" #include "services/ui/public/cpp/gpu_service.h" #include "services/ui/public/cpp/window.h" #include "services/ui/public/cpp/window_tree_client.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/core/SkRect.h" #include "ui/gfx/geometry/rect.h" namespace ui { namespace demo { namespace { // Milliseconds between frames. const int64_t kFrameDelay = 33; // Size of square in pixels to draw. const int kSquareSize = 300; const SkColor kBgColor = SK_ColorRED; const SkColor kFgColor = SK_ColorYELLOW; void DrawSquare(const gfx::Rect& bounds, double angle, SkCanvas* canvas) { // Create SkRect to draw centered inside the bounds. gfx::Point top_left = bounds.CenterPoint(); top_left.Offset(-kSquareSize / 2, -kSquareSize / 2); SkRect rect = SkRect::MakeXYWH(top_left.x(), top_left.y(), kSquareSize, kSquareSize); // Set SkPaint to fill solid color. SkPaint paint; paint.setStyle(SkPaint::kFill_Style); paint.setColor(kFgColor); // Rotate the canvas. const gfx::Size canvas_size = bounds.size(); if (angle != 0.0) { canvas->translate(SkFloatToScalar(canvas_size.width() * 0.5f), SkFloatToScalar(canvas_size.height() * 0.5f)); canvas->rotate(angle); canvas->translate(-SkFloatToScalar(canvas_size.width() * 0.5f), -SkFloatToScalar(canvas_size.height() * 0.5f)); } canvas->drawRect(rect, paint); } } // namespace MusDemo::MusDemo() {} MusDemo::~MusDemo() { display::Screen::SetScreenInstance(nullptr); } void MusDemo::OnStart() { screen_ = base::MakeUnique<display::ScreenBase>(); display::Screen::SetScreenInstance(screen_.get()); gpu_service_ = GpuService::Create(context()->connector()); window_tree_client_ = base::MakeUnique<WindowTreeClient>(this, this); window_tree_client_->ConnectAsWindowManager(context()->connector()); } bool MusDemo::OnConnect(const service_manager::ServiceInfo& remote_info, service_manager::InterfaceRegistry* registry) { return true; } void MusDemo::OnEmbed(Window* window) { // Not called for the WindowManager. NOTREACHED(); } void MusDemo::OnEmbedRootDestroyed(Window* root) { // Not called for the WindowManager. NOTREACHED(); } void MusDemo::OnLostConnection(WindowTreeClient* client) { window_ = nullptr; window_tree_client_.reset(); timer_.Stop(); } void MusDemo::OnPointerEventObserved(const PointerEvent& event, Window* target) {} void MusDemo::SetWindowManagerClient(WindowManagerClient* client) {} bool MusDemo::OnWmSetBounds(Window* window, gfx::Rect* bounds) { return true; } bool MusDemo::OnWmSetProperty(Window* window, const std::string& name, std::unique_ptr<std::vector<uint8_t>>* new_data) { return true; } Window* MusDemo::OnWmCreateTopLevelWindow( std::map<std::string, std::vector<uint8_t>>* properties) { return nullptr; } void MusDemo::OnWmClientJankinessChanged( const std::set<Window*>& client_windows, bool janky) { // Don't care } void MusDemo::OnWmNewDisplay(Window* window, const display::Display& display) { DCHECK(!window_); // Only support one display. window_ = window; // Initialize bitmap uploader for sending frames to MUS. uploader_.reset(new BitmapUploader(window_)); uploader_->Init(gpu_service_.get()); // Draw initial frame and start the timer to regularly draw frames. DrawFrame(); timer_.Start(FROM_HERE, base::TimeDelta::FromMilliseconds(kFrameDelay), base::Bind(&MusDemo::DrawFrame, base::Unretained(this))); } void MusDemo::OnWmDisplayRemoved(ui::Window* window) { window->Destroy(); } void MusDemo::OnWmDisplayModified(const display::Display& display) {} void MusDemo::OnWmPerformMoveLoop(Window* window, mojom::MoveLoopSource source, const gfx::Point& cursor_location, const base::Callback<void(bool)>& on_done) { // Don't care } void MusDemo::OnWmCancelMoveLoop(Window* window) {} void MusDemo::AllocBitmap() { const gfx::Rect bounds = window_->GetBoundsInRoot(); // Allocate bitmap the same size as the window for drawing. bitmap_.reset(); SkImageInfo image_info = SkImageInfo::MakeN32(bounds.width(), bounds.height(), kPremul_SkAlphaType); bitmap_.allocPixels(image_info); } void MusDemo::DrawFrame() { base::TimeTicks now = base::TimeTicks::Now(); VLOG(1) << (now - last_draw_frame_time_).InMilliseconds() << "ms since the last frame was drawn."; last_draw_frame_time_ = now; angle_ += 2.0; if (angle_ >= 360.0) angle_ = 0.0; const gfx::Rect bounds = window_->GetBoundsInRoot(); // Check that bitmap and window sizes match, otherwise reallocate bitmap. const SkImageInfo info = bitmap_.info(); if (info.width() != bounds.width() || info.height() != bounds.height()) { AllocBitmap(); } // Draw the rotated square on background in bitmap. SkCanvas canvas(bitmap_); canvas.clear(kBgColor); // TODO(kylechar): Add GL drawing instead of software rasterization in future. DrawSquare(bounds, angle_, &canvas); canvas.flush(); // Copy pixels data into vector that will be passed to BitmapUploader. // TODO(rjkroege): Make a 1/0-copy bitmap uploader for the contents of a // SkBitmap. bitmap_.lockPixels(); const unsigned char* addr = static_cast<const unsigned char*>(bitmap_.getPixels()); const int bytes = bounds.width() * bounds.height() * 4; std::unique_ptr<std::vector<unsigned char>> data( new std::vector<unsigned char>(addr, addr + bytes)); bitmap_.unlockPixels(); #if defined(OS_ANDROID) // TODO(jcivelli): find a way to not have an ifdef here. BitmapUploader::Format bitmap_format = BitmapUploader::RGBA; #else BitmapUploader::Format bitmap_format = BitmapUploader::BGRA; #endif // Send frame to MUS via BitmapUploader. uploader_->SetBitmap(bounds.width(), bounds.height(), std::move(data), bitmap_format); } } // namespace demo } // namespace ui
31.626168
80
0.692376
[ "geometry", "vector", "solid" ]
dd60a49d469c0de854c8638b9e2bc3327c9ddc03
9,811
hh
C++
cc/mapi-settings.hh
acorg/acmacs-map-draw
6f0711f2fc452d9a6770db05bed38f0f08c2ea42
[ "MIT" ]
null
null
null
cc/mapi-settings.hh
acorg/acmacs-map-draw
6f0711f2fc452d9a6770db05bed38f0f08c2ea42
[ "MIT" ]
null
null
null
cc/mapi-settings.hh
acorg/acmacs-map-draw
6f0711f2fc452d9a6770db05bed38f0f08c2ea42
[ "MIT" ]
null
null
null
#pragma once #include "acmacs-base/settings-v3.hh" #include "acmacs-base/point-style.hh" #include "acmacs-base/time-series.hh" #include "acmacs-chart-2/selected-antigens-sera.hh" #include "acmacs-map-draw/point-style-draw.hh" #include "acmacs-map-draw/coordinates.hh" #include "acmacs-map-draw/point-style.hh" #include "acmacs-map-draw/figure.hh" // ---------------------------------------------------------------------- namespace acmacs::chart { class PointIndexList; class Antigens; class Sera; class SerumCircle; } class ChartDraw; namespace map_elements::v1 { class LegendPointLabel; class Title; class SerumCircle; } class ChartAccess; // ---------------------------------------------------------------------- namespace acmacs::mapi::inline v1 { using error = settings::v3::error; class unrecognized : public error { public: using error::error; unrecognized() : error{""} {} }; // ---------------------------------------------------------------------- class Settings : public settings::v3::Data { public: enum class env_put_antigen_serum_names { no, yes }; // use chart_draw.settings() to create! Settings(ChartDraw& chart_draw, env_put_antigen_serum_names epasn = env_put_antigen_serum_names::yes) : chart_draw_{chart_draw} { update_env(epasn); } using settings::v3::Data::load; bool apply_built_in(std::string_view name) override; // returns true if built-in command with that name found and applied enum class if_null { empty, warn_empty, raise, all }; // return empty, return empty and print warning, throw exception, return all indexes acmacs::chart::SelectedAntigensModify selected_antigens(const rjson::v3::value& select_clause, if_null ifnull = if_null::raise) const; acmacs::chart::SelectedSeraModify selected_sera(const rjson::v3::value& select_clause, if_null ifnull = if_null::raise) const; // OBSOLETE acmacs::chart::PointIndexList select_antigens(const rjson::v3::value& select_clause, if_null ifnull = if_null::raise) const; acmacs::chart::PointIndexList select_sera(const rjson::v3::value& select_clause, if_null ifnull = if_null::raise) const; constexpr ChartDraw& chart_draw() const { return chart_draw_; } void filter_inside_path(acmacs::chart::PointIndexList& indexes, const rjson::v3::value& points, size_t index_base) const; // mapi-settings-drawing.cc struct time_series_data { const std::string filename_pattern; const std::vector<std::string_view> title; const acmacs::time_series::series series; const acmacs::chart::PointIndexList shown_on_all; }; void update_env_upon_projection_change(); // update stress protected: // ---------------------------------------------------------------------- // mapi-settings-antigens.cc virtual bool apply_antigens(); virtual bool apply_sera(); // returns if key has been processed virtual bool select(const acmacs::chart::Antigens& antigens, acmacs::chart::PointIndexList& indexes, std::string_view key, const rjson::v3::value& value) const; virtual bool select(const acmacs::chart::Sera& sera, acmacs::chart::PointIndexList& indexes, std::string_view key, const rjson::v3::value& value) const; void update_env(env_put_antigen_serum_names epasn); // ---------------------------------------------------------------------- // mapi-settings-antigens.cc template <typename AgSr> acmacs::chart::PointIndexList select(const AgSr& ag_sr, const rjson::v3::value& select_clause, if_null ifnull) const; template <typename AgSr> void check_titrated_against(acmacs::chart::PointIndexList& indexes, std::string_view key, const rjson::v3::value& value) const; void mark_serum(size_t serum_index, const rjson::v3::value& style); PointDrawingOrder drawing_order_from_environment() const; PointDrawingOrder drawing_order_from(const rjson::v3::value& source) const; PointDrawingOrder drawing_order_from(std::string_view key, const rjson::v3::value& val) const; point_style_t style_from_environment() const; point_style_t style_from(const rjson::v3::value& source) const; void update_style(point_style_t& style, std::string_view key, const rjson::v3::value& val) const; template <typename AgSr> bool color_according_to_passage(const AgSr& ag_sr, const acmacs::chart::PointIndexList& indexes, const point_style_t& point_style); bool color_according_to_aa_at_pos(const acmacs::chart::PointIndexList& indexes, const point_style_t& point_style); modifier_or_passage_t color(const rjson::v3::value& value, std::optional<Color> if_null = std::nullopt) const; // ---------------------------------------------------------------------- // mapi-settings-drawing.cc bool apply_circle(); bool apply_path(); bool apply_rotate(); bool apply_flip(); bool apply_viewport(); bool apply_background(); bool apply_border(); bool apply_grid(); bool apply_point_scale(); bool apply_connection_lines(); bool apply_error_lines(); std::optional<map_elements::v2::Coordinates> read_coordinates(const rjson::v3::value& source) const; FigureRaw read_figure(const rjson::v3::value& points, const rjson::v3::value& close) const; // ---------------------------------------------------------------------- // mapi-settings-labels.cc void add_labels(const acmacs::chart::PointIndexList& indexes, size_t index_base, const rjson::v3::value& label_data); void add_label(size_t index, size_t index_base, const rjson::v3::value& label_data); // ---------------------------------------------------------------------- // mapi-settings-legend.cc map_elements::v1::LegendPointLabel& legend(); bool apply_legend(); void add_legend_continent_map(); void add_legend(const acmacs::chart::PointIndexList& indexes, const acmacs::PointStyleModified& style, const rjson::v3::value& legend_data); void add_legend(const acmacs::chart::PointIndexList& indexes, const acmacs::PointStyleModified& style, std::string_view label, const rjson::v3::value& legend_data); virtual map_elements::v1::Title& title(); bool apply_title(); // ---------------------------------------------------------------------- // mapi-settings-serum-circles.cc bool apply_serum_circles(); bool hide_serum_circle(const rjson::v3::value& criteria, size_t serum_no, double radius) const; acmacs::chart::PointIndexList select_antigens_for_serum_circle(size_t serum_index, const rjson::v3::value& antigen_selector); void make_circle(size_t serum_index, Scaled radius, std::string_view serum_passage, const rjson::v3::value& plot); bool apply_serum_coverage(); void report_circles(fmt::memory_buffer& report, size_t serum_index, const acmacs::chart::Antigens& antigens, const acmacs::chart::PointIndexList& antigen_indexes, const acmacs::chart::SerumCircle& empirical, const acmacs::chart::SerumCircle& theoretical, const rjson::v3::value& hide_if, std::optional<std::string_view> forced_homologous_titer) const; // ---------------------------------------------------------------------- // mapi-settings-procrustes.cc bool apply_reset(); bool apply_export() const; bool apply_pdf() const; bool apply_relax(); bool apply_procrustes(); bool apply_remove_procrustes(); const ChartAccess& get_chart(const rjson::v3::value& source, size_t dflt) const; bool apply_move(); void make_pdf(std::string_view filename, double width, bool open) const; std::string get_filename() const; std::string substitute_in_filename(std::string_view filename) const; // ---------------------------------------------------------------------- // mapi-settings-sequences.cc bool apply_compare_sequences(); // ---------------------------------------------------------------------- // mapi-settings-vaccine.cc bool apply_vaccine(); // ---------------------------------------------------------------------- // mapi-settings-time-series.cc bool apply_time_series(); time_series_data time_series_settings() const; private: ChartDraw& chart_draw_; }; // class Settings } // namespace acmacs::mapi::inline v1 extern template bool acmacs::mapi::v1::Settings::color_according_to_passage(const acmacs::chart::Antigens&, const acmacs::chart::PointIndexList& indexes, const point_style_t& style); extern template bool acmacs::mapi::v1::Settings::color_according_to_passage(const acmacs::chart::Sera&, const acmacs::chart::PointIndexList& indexes, const point_style_t& style); template <> struct fmt::formatter<acmacs::mapi::v1::Settings::time_series_data> : fmt::formatter<acmacs::fmt_helper::default_formatter> { template <typename FormatCtx> auto format(const acmacs::mapi::v1::Settings::time_series_data& value, FormatCtx& ctx) { return format_to(ctx.out(), "time_series_data {{\n filename_pattern: {}\n title: {}\n series: {}\n}}", // value.filename_pattern, value.title, value.series); } }; // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End:
45.421296
182
0.61431
[ "vector" ]
dd63957658f638099a42fb631913c63e3318d111
19,004
cpp
C++
src/Type.cpp
RamblingMadMan/ilang-types
507a8215687f62555b4f8790a4d196076dc80c2d
[ "MIT" ]
null
null
null
src/Type.cpp
RamblingMadMan/ilang-types
507a8215687f62555b4f8790a4d196076dc80c2d
[ "MIT" ]
null
null
null
src/Type.cpp
RamblingMadMan/ilang-types
507a8215687f62555b4f8790a4d196076dc80c2d
[ "MIT" ]
null
null
null
#include <algorithm> #include "ilang/Type.hpp" using namespace ilang; TypeHandle createEncodedStringType(TypeData &data, StringEncoding encoding) noexcept{ auto type = std::make_unique<Type>(); type->base = data.stringType; switch(encoding){ case StringEncoding::ascii: type->str = "AsciiString"; type->mangled = "sa8"; break; case StringEncoding::utf8: type->str = "Utf8String"; type->mangled = "su8"; break; default: return nullptr; } return data.storage.emplace_back(std::move(type)).get(); } TypeHandle createSizedNumberType( TypeData &data, TypeHandle base, const std::string &name, const std::string &mangledName, std::uint32_t numBits ) noexcept { if(numBits == 0) return base; auto bitsStr = std::to_string(numBits); auto type = std::make_unique<Type>(); type->base = base; type->str = name + bitsStr; type->mangled = mangledName + bitsStr; return data.storage.emplace_back(std::move(type)).get(); } TypeHandle createFunctionType( TypeData &data, const std::vector<TypeHandle> &params, TypeHandle ret ) noexcept { auto type = std::make_unique<Type>(); type->base = data.functionType; type->str = params[0]->str; type->mangled = "f" + std::to_string(params.size()) + ret->mangled + params[0]->mangled; for(std::size_t i = 1; i < params.size(); i++){ type->str += " -> " + params[i]->str; type->mangled += params[i]->mangled; } type->str += " -> " + ret->str; type->types.reserve(params.size() + 1); type->types.insert(begin(type->types), begin(params), end(params)); type->types.emplace_back(ret); return data.storage.emplace_back(std::move(type)).get(); } template<typename Container, typename Key> TypeHandle findInnerType(const TypeData &data, TypeHandle base, const Container &cont, std::optional<Key> key) noexcept{ if(key){ auto res = cont.find(*key); if(res != end(cont)) return res->second; return nullptr; } else return base; } template<typename Container> TypeHandle findInnerNumberType(const TypeData &data, TypeHandle base, const Container &cont, std::uint32_t numBits) noexcept{ return findInnerType(data, base, cont, numBits ? std::make_optional(numBits) : std::nullopt); } template<typename Container, typename Key, typename Create> TypeHandle getInnerType( TypeData &data, TypeHandle base, Container &&container, std::optional<Key> key, Create &&create ){ auto res = findInnerType(data, base, container, key); return res ? res : create(data, *key); } template<typename Container, typename Create> TypeHandle getInnerNumberType( TypeData &data, TypeHandle base, Container &&container, std::uint32_t numBits, Create &&create ){ return getInnerType( data, base, container, numBits ? std::make_optional(numBits) : std::nullopt, std::forward<Create>(create) ); } bool impl_isInfinityType(TypeHandle type) noexcept{ return type->mangled == "??"; } bool ilang::hasBaseType(TypeHandle type, TypeHandle baseType) noexcept{ if(impl_isInfinityType(baseType)) return true; while(1){ if(type->base == baseType) return true; else if(impl_isInfinityType(type->base)) return false; else type = type->base; } } bool ilang::isRootType(TypeHandle type) noexcept{ return impl_isInfinityType(type->base) && !impl_isInfinityType(type); } bool ilang::isRefinedType(TypeHandle type) noexcept{ if(isRootType(type->base)) return true; else if(impl_isInfinityType(type->base)) return false; return isRefinedType(type->base); } bool ilang::isCompoundType(TypeHandle type) noexcept; bool ilang::isListType(TypeHandle type, const TypeData &data) noexcept{ if(type->types.size() != 1) return false; auto listBase = findListType(data, type->types[0]); if(!listBase) return false; return hasBaseType(type, listBase); } bool ilang::isArrayType(TypeHandle type, const TypeData& data) noexcept{ if(type->types.size() != 1) return false; auto arrayBase = findArrayType(data, type->types[0]); if(!arrayBase) return false; return hasBaseType(type, arrayBase); } #define REFINED_TYPE_CHECK(type, typeLower)\ bool ilang::is##type##Type(TypeHandle type, const TypeData &data) noexcept{\ auto baseType = data.typeLower##Type;\ return type == baseType || hasBaseType(type, baseType);\ } REFINED_TYPE_CHECK(Unit, unit) REFINED_TYPE_CHECK(Type, type) REFINED_TYPE_CHECK(Partial, partial) REFINED_TYPE_CHECK(Function, function) REFINED_TYPE_CHECK(Number, number) REFINED_TYPE_CHECK(Complex, complex) REFINED_TYPE_CHECK(Imaginary, imaginary) REFINED_TYPE_CHECK(Real, real) REFINED_TYPE_CHECK(Rational, rational) REFINED_TYPE_CHECK(Integer, integer) REFINED_TYPE_CHECK(Natural, natural) REFINED_TYPE_CHECK(Boolean, boolean) REFINED_TYPE_CHECK(String, string) #define NUMBER_VALUE_TYPE(T, t, mangledSig)\ TypeHandle create##T##Type(TypeData &data, std::uint32_t numBits){\ return createSizedNumberType(data, data.t##Type, #T, mangledSig, numBits);\ }\ TypeHandle ilang::find##T##Type(const TypeData &data, std::uint32_t numBits) noexcept{\ return findInnerNumberType(data, data.t##Type, data.sized##T##Types, numBits);\ }\ TypeHandle ilang::get##T##Type(TypeData &data, std::uint32_t numBits){\ return getInnerNumberType(data, data.t##Type, data.sized##T##Types, numBits, create##T##Type);\ } #define ROOT_TYPE(T, t)\ TypeHandle ilang::find##T##Type(const TypeData &data) noexcept{ return data.t##Type; }\ TypeHandle ilang::get##T##Type(TypeData &data){ return data.t##Type; } ROOT_TYPE(Infinity, infinity) ROOT_TYPE(Type, type) ROOT_TYPE(Unit, unit) ROOT_TYPE(Number, number) NUMBER_VALUE_TYPE(Boolean, boolean, "b") NUMBER_VALUE_TYPE(Natural, natural, "n") NUMBER_VALUE_TYPE(Integer, integer, "z") NUMBER_VALUE_TYPE(Rational, rational, "q") NUMBER_VALUE_TYPE(Real, real, "r") NUMBER_VALUE_TYPE(Imaginary, imaginary, "i") NUMBER_VALUE_TYPE(Complex, complex, "c") template<typename Comp> auto getSortedTypes(const TypeData &data, Comp &&comp = std::less<void>{}){ std::vector<TypeHandle> types; types.reserve(data.storage.size()); std::transform( begin(data.storage), end(data.storage), std::back_inserter(types), [](auto &&ptr){ return ptr.get(); } ); std::sort(begin(types), end(types), std::forward<Comp>(comp)); return types; } TypeHandle ilang::findTypeByString(const TypeData &data, std::string_view str){ auto strS = std::string(str); auto aliased = data.typeAliases.find(strS); if(aliased != end(data.typeAliases)) return aliased->second; auto types = getSortedTypes(data, [](auto lhs, auto rhs){ return lhs->str < rhs->str; }); auto res = std::lower_bound(begin(types), end(types), str, [](TypeHandle lhs, std::string_view rhs){ return lhs->str < std::string(rhs); }); if((res != end(types)) && (str < (*res)->str)) res = end(types); if(res != end(types)) return *res; return nullptr; } TypeHandle ilang::findTypeByMangled(const TypeData &data, std::string_view mangled){ auto types = getSortedTypes(data, [](auto lhs, auto rhs){ return lhs->mangled < rhs->mangled; }); auto res = std::lower_bound(begin(types), end(types), mangled, [](TypeHandle lhs, std::string_view rhs){ return lhs->mangled < std::string(rhs); }); if((res != end(types)) && (mangled < (*res)->mangled)) res = end(types); if(res != end(types)) return *res; return nullptr; } TypeHandle ilang::findCommonType(TypeHandle type0, TypeHandle type1) noexcept{ if(type0 == type1 || hasBaseType(type1, type0)) return type0; else if(hasBaseType(type0, type1)) return type1; else return findCommonType(type0->base, type1->base); } TypeHandle ilang::findPartialType(const TypeData &data, std::optional<std::uint32_t> id) noexcept{ if(!id) return data.partialType; auto num = *id; if(data.partialTypes.size() >= num) return nullptr; else return data.partialTypes[num]; } TypeHandle ilang::findStringType(const TypeData &data, std::optional<StringEncoding> encoding) noexcept{ return findInnerType(data, data.stringType, data.encodedStringTypes, encoding); } TypeHandle ilang::findTreeType(const TypeData &data, TypeHandle t) noexcept{ return findInnerType(data, nullptr, data.treeTypes, std::make_optional(t)); } TypeHandle ilang::findListType(const TypeData &data, TypeHandle t) noexcept{ return findInnerType(data, nullptr, data.listTypes, std::make_optional(t)); } TypeHandle ilang::findArrayType(const TypeData &data, TypeHandle t) noexcept{ return findInnerType(data, nullptr, data.arrayTypes, std::make_optional(t)); } TypeHandle ilang::findDynamicArrayType(const TypeData &data, TypeHandle t) noexcept{ return findInnerType(data, nullptr, data.listTypes, std::make_optional(t)); } TypeHandle ilang::findStaticArrayType(const TypeData &data, TypeHandle t, std::size_t n) noexcept{ auto res = data.staticArrayTypes.find(t); if(res != end(data.staticArrayTypes)) return findInnerType(data, nullptr, res->second, std::make_optional(n)); return nullptr; } TypeHandle findSumTypeInner(const TypeData &data, const std::vector<TypeHandle> &uniqueSortedInnerTypes) noexcept{ return findInnerType(data, nullptr, data.sumTypes, std::make_optional(std::ref(uniqueSortedInnerTypes))); } TypeHandle ilang::findSumType(const TypeData &data, std::vector<TypeHandle> innerTypes) noexcept{ std::sort(begin(innerTypes), end(innerTypes)); innerTypes.erase(std::unique(begin(innerTypes), end(innerTypes)), end(innerTypes)); return findSumTypeInner(data, innerTypes); } TypeHandle ilang::findProductType(const TypeData &data, const std::vector<TypeHandle> &innerTypes) noexcept{ return findInnerType(data, nullptr, data.productTypes, std::make_optional(std::ref(innerTypes))); } TypeHandle ilang::findFunctionType(const TypeData &data, const std::vector<TypeHandle> &params, TypeHandle result) noexcept{ auto paramsRes = data.functionTypes.find(params); if(paramsRes != end(data.functionTypes)){ auto resultRes = paramsRes->second.find(result); if(resultRes != end(paramsRes->second)) return resultRes->second; } return nullptr; } TypeHandle ilang::findFunctionType(const TypeData &data) noexcept{ return data.functionType; } TypeHandle ilang::getStringType(TypeData &data, std::optional<StringEncoding> encoding){ return getInnerType(data, data.stringType, data.encodedStringTypes, encoding, createEncodedStringType); } TypeHandle ilang::getTreeType(TypeData &data, TypeHandle t){ if(auto res = findTreeType(data, t)) return res; auto ptr = data.storage.emplace_back(std::make_unique<Type>()).get(); ptr->base = data.infinityType; ptr->str = "(Tree " + t->str + ")"; ptr->mangled = "ot0" + t->mangled; ptr->types = {t}; data.treeTypes[t] = ptr; return ptr; } TypeHandle ilang::getListType(TypeData &data, TypeHandle t){ if(auto res = findListType(data, t)) return res; auto newType = std::make_unique<Type>(); newType->base = getTreeType(data, t); newType->str = "(List " + t->str + ")"; newType->mangled = "ol0" + t->mangled; newType->types = {t}; auto ptr = data.storage.emplace_back(std::move(newType)).get(); data.listTypes[t] = ptr; return ptr; } TypeHandle ilang::getArrayType(TypeData &data, TypeHandle t){ if(auto res = findArrayType(data, t)) return res; auto newType = std::make_unique<Type>(); newType->base = getListType(data, t); newType->str = "(Array " + t->str + ")"; newType->mangled = "oa0" + t->mangled; newType->types = {t}; auto ptr = data.storage.emplace_back(std::move(newType)).get(); data.arrayTypes[t] = ptr; return ptr; } TypeHandle ilang::getDynamicArrayType(TypeData &data, TypeHandle t){ if(auto res = findDynamicArrayType(data, t)) return res; auto newType = std::make_unique<Type>(); newType->base = getArrayType(data, t); newType->str = "(DynamicArray " + t->str + ")"; newType->mangled = "a0" + t->mangled; newType->types = {t}; auto ptr = data.storage.emplace_back(std::move(newType)).get(); data.dynamicArrayTypes[t] = ptr; return ptr; } TypeHandle ilang::getStaticArrayType(TypeData &data, TypeHandle t, std::size_t n){ if(auto res = findStaticArrayType(data, t, n)) return res; auto newType = std::make_unique<Type>(); auto nStr = std::to_string(n); newType->base = getArrayType(data, t); newType->str = "(StaticArray " + t->str + " " + nStr + ")"; newType->mangled = "a" + nStr + t->mangled; newType->types = {t}; auto ptr = data.storage.emplace_back(std::move(newType)).get(); data.staticArrayTypes[t][n] = ptr; return ptr; } TypeHandle ilang::getPartialType(TypeData &data){ auto type = std::make_unique<Type>(); auto id = std::to_string(data.partialTypes.size()); type->base = data.partialType; type->str = "Partial" + id; type->mangled = "_" + id; auto &&typePtr = data.storage.emplace_back(std::move(type)); return typePtr.get(); } TypeHandle ilang::getSumType(TypeData &data, std::vector<TypeHandle> innerTypes){ std::sort(begin(innerTypes), end(innerTypes)); innerTypes.erase(std::unique(begin(innerTypes), end(innerTypes)), end(innerTypes)); if(auto res = findSumTypeInner(data, innerTypes)) return res; auto &&newType = data.storage.emplace_back(std::make_unique<Type>()); newType->base = findInfinityType(data); newType->types = std::move(innerTypes); newType->mangled = "u" + std::to_string(innerTypes.size()); newType->mangled += innerTypes[0]->mangled; newType->str = innerTypes[0]->str; for(std::size_t i = 1; i < innerTypes.size(); i++){ newType->mangled += innerTypes[i]->mangled; newType->str += " | " + innerTypes[i]->str; } auto[it, good] = data.sumTypes.try_emplace(newType->types, newType.get()); if(!good){ // TODO: throw TypeError } return newType.get(); } TypeHandle ilang::getProductType(TypeData &data, std::vector<TypeHandle> innerTypes){ if(innerTypes.size() < 2){ // TODO: throw TypeError throw std::runtime_error("product type can not have less than 2 inner types"); } if(auto res = findProductType(data, innerTypes)) return res; auto &&newType = data.storage.emplace_back(std::make_unique<Type>()); newType->base = findInfinityType(data); newType->mangled = "p" + std::to_string(innerTypes.size()) + innerTypes[0]->mangled; newType->str = innerTypes[0]->str; for(std::size_t i = 1; i < innerTypes.size(); i++){ newType->mangled += innerTypes[i]->mangled; newType->str += " * " + innerTypes[i]->str; } newType->types = std::move(innerTypes); auto[it, good] = data.productTypes.try_emplace(newType->types, newType.get()); if(!good){ // TODO: throw TypeError } return newType.get(); } TypeHandle ilang::getFunctionType(TypeData &data, std::vector<TypeHandle> params, TypeHandle result){ auto &&retMap = data.functionTypes[params]; auto res = retMap.find(result); if(res != end(retMap)) return res->second; return retMap[result] = createFunctionType(data, params, result); } TypeData::TypeData(){ auto newInfinityType = [this](){ auto &&ptr = storage.emplace_back(std::make_unique<Type>()); ptr->base = ptr.get(); ptr->str = "Infinity"; ptr->mangled = "??"; return ptr.get(); }; auto newType = [this](std::string str, std::string mangled, auto base){ auto &&ptr = storage.emplace_back(std::make_unique<Type>()); ptr->base = base; ptr->str = std::move(str); ptr->mangled = std::move(mangled); return ptr.get(); }; infinityType = newInfinityType(); auto newRootType = [&newType, this](auto str, auto mangled){ return newType(str, mangled, infinityType); }; partialType = newRootType("Partial", "_?"); typeType = newRootType("Type", "t?"); unitType = newRootType("Unit", "u0"); stringType = newRootType("String", "s?"); numberType = newRootType("Number", "w?"); functionType = newRootType("Function", "f?"); complexType = newType("Complex", "c?", numberType); imaginaryType = newType("Imaginary", "i?", complexType); realType = newType("Real", "r?", complexType); rationalType = newType("Rational", "q?", realType); integerType = newType("Integer", "z?", rationalType); naturalType = newType("Natural", "n?", integerType); booleanType = newType("Boolean", "b?", naturalType); typeAliases["Ratio"] = rationalType; typeAliases["Int"] = integerType; typeAliases["Nat"] = naturalType; typeAliases["Bool"] = booleanType; auto real64Type = createSizedNumberType(*this, realType, "Real", "r", 64); auto real32Type = createSizedNumberType(*this, real64Type, "Real", "r", 32); auto real16Type = createSizedNumberType(*this, real32Type, "Real", "r", 16); sizedRealTypes[64] = real64Type; sizedRealTypes[32] = real32Type; sizedRealTypes[16] = real16Type; auto rational128Type = createSizedNumberType(*this, realType, "Rational", "q", 128); auto rational64Type = createSizedNumberType(*this, rational128Type, "Rational", "q", 64); auto rational32Type = createSizedNumberType(*this, rational64Type, "Rational", "q", 32); auto rational16Type = createSizedNumberType(*this, rational32Type, "Rational", "q", 16); sizedRationalTypes[128] = rational128Type; sizedRationalTypes[64] = rational64Type; sizedRationalTypes[32] = rational32Type; sizedRationalTypes[16] = rational16Type; typeAliases["Ratio128"] = rational128Type; typeAliases["Ratio64"] = rational64Type; typeAliases["Ratio32"] = rational32Type; typeAliases["Ratio16"] = rational16Type; auto int64Type = createSizedNumberType(*this, integerType, "Integer", "i", 64); auto int32Type = createSizedNumberType(*this, int64Type, "Integer", "i", 32); auto int16Type = createSizedNumberType(*this, int32Type, "Integer", "i", 16); auto int8Type = createSizedNumberType(*this, int16Type, "Integer", "i", 8); sizedIntegerTypes[64] = int64Type; sizedIntegerTypes[32] = int32Type; sizedIntegerTypes[16] = int16Type; sizedIntegerTypes[8] = int8Type; typeAliases["Int64"] = int64Type; typeAliases["Int32"] = int32Type; typeAliases["Int16"] = int16Type; typeAliases["Int8"] = int8Type; auto nat64Type = createSizedNumberType(*this, naturalType, "Natural", "n", 64); auto nat32Type = createSizedNumberType(*this, nat64Type, "Natural", "n", 32); auto nat16Type = createSizedNumberType(*this, nat32Type, "Natural", "n", 16); auto nat8Type = createSizedNumberType(*this, nat16Type, "Natural", "n", 8); sizedNaturalTypes[64] = nat64Type; sizedNaturalTypes[32] = nat32Type; sizedNaturalTypes[16] = nat16Type; sizedNaturalTypes[8] = nat8Type; typeAliases["Nat64"] = nat64Type; typeAliases["Nat32"] = nat32Type; typeAliases["Nat16"] = nat16Type; typeAliases["Nat8"] = nat8Type; }
31.72621
150
0.692749
[ "vector", "transform" ]
dd644cb77afade76efd2ca66be2a9d32efe085c0
1,245
cpp
C++
src/Layer.cpp
dargonfyl/imgui-painter
b4b3008b127da86576429506d9ab5d378a6bcc4d
[ "Unlicense" ]
null
null
null
src/Layer.cpp
dargonfyl/imgui-painter
b4b3008b127da86576429506d9ab5d378a6bcc4d
[ "Unlicense" ]
null
null
null
src/Layer.cpp
dargonfyl/imgui-painter
b4b3008b127da86576429506d9ab5d378a6bcc4d
[ "Unlicense" ]
null
null
null
#include "Layer.hpp" #include <string.h> // memset #include <stdlib.h> namespace Im_Painter { Layer::Layer(layer_size_t height, layer_size_t width) { unsigned int total_bytes = 4 * height * width; unsigned char buf[total_bytes]; memset(buf, static_cast<unsigned char>(0), total_bytes); texture = new Texture(width, height, 1, buf, RGBA, RGBA); visible = true; } Layer::Layer(unsigned char *data, layer_size_t height, layer_size_t width) { unsigned int total_bytes = 4 * height * width; texture = new Texture(width, height, 1, data, RGBA, RGBA); visible = true; } Layer::~Layer() { delete texture; } void Layer::merge(Layer &to_merge) { } void Layer::update(unsigned char *data) { texture->update(1, data); } Texture_id_t Layer::get_texture_id() { return texture->get_id(); } void Layer::get_data(std::vector<unsigned char> &buffer) { unsigned char *data = texture->get_texture_data(); int size = buffer.size(); buffer.clear(); buffer = std::vector<unsigned char>(data, data + size); delete data; } void Layer::bind() { texture->bind(); } bool Layer::is_visible() { return visible; } void Layer::toggle_visible() { visible = !visible; } } // namespace Im_Painter
18.043478
77
0.671486
[ "vector" ]
dd6fb9ba236fa8c676b41f642a8936f8f8dab8e5
11,303
cc
C++
emu-ex-plus-alpha/imagine/src/audio/opensl/opensl.cc
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
1
2018-11-14T23:40:35.000Z
2018-11-14T23:40:35.000Z
emu-ex-plus-alpha/imagine/src/audio/opensl/opensl.cc
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
null
null
null
emu-ex-plus-alpha/imagine/src/audio/opensl/opensl.cc
damoonvisuals/GBA4iOS
95bfce0aca270b68484535ecaf0d3b2366739c77
[ "MIT" ]
null
null
null
/* This file is part of Imagine. Imagine is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Imagine is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Imagine. If not, see <http://www.gnu.org/licenses/> */ #define thisModuleName "audio:opensl" #include <engine-globals.h> #include <audio/Audio.hh> #include <logger/interface.h> #include <util/number.h> #include <util/thread/pthread.hh> #include <base/android/private.hh> #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> namespace Audio { using namespace Base; PcmFormat preferredPcmFormat { 44100, &SampleFormats::s16, 2 }; PcmFormat pcmFormat; static SLEngineItf slI = nullptr; static SLObjectItf outMix = nullptr, player = nullptr; static SLPlayItf playerI = nullptr; static SLAndroidSimpleBufferQueueItf slBuffQI = nullptr; static uint bufferFrames = 800, currQBuf = 0; static uint buffers = 10; static uchar **qBuffer = nullptr; static bool isPlaying = 0, reachedEndOfPlayback = 0, strictUnderrunCheck = 1; static BufferContext audioBuffLockCtx; static jobject audioManager = nullptr; static JavaInstMethod<jint> jRequestAudioFocus, jAbandonAudioFocus; static bool soloMix_ = true; static bool isInit() { return outMix; } // runs on internal OpenSL ES thread /*static void queueCallback(SLAndroidSimpleBufferQueueItf caller, void *) { }*/ // runs on internal OpenSL ES thread static void playCallback(SLPlayItf caller, void *, SLuint32 event) { //logMsg("play event %X", (int)event); assert(event == SL_PLAYEVENT_HEADSTALLED || event == SL_PLAYEVENT_HEADATEND); logMsg("got playback end event"); reachedEndOfPlayback = 1; } static void setupAudioManagerJNI(JNIEnv* jEnv) { if(!audioManager) { JavaInstMethod<jobject> jAudioManager; jAudioManager.setup(jEnv, jBaseActivityCls, "audioManager", "()Landroid/media/AudioManager;"); audioManager = jAudioManager(jEnv, jBaseActivity); assert(audioManager); audioManager = jEnv->NewGlobalRef(audioManager); jclass jAudioManagerCls = jEnv->GetObjectClass(audioManager); jRequestAudioFocus.setup(jEnv, jAudioManagerCls, "requestAudioFocus", "(Landroid/media/AudioManager$OnAudioFocusChangeListener;II)I"); jAbandonAudioFocus.setup(jEnv, jAudioManagerCls, "abandonAudioFocus", "(Landroid/media/AudioManager$OnAudioFocusChangeListener;)I"); } } static void requestAudioFocus(JNIEnv* jEnv) { setupAudioManagerJNI(jEnv); auto res = jRequestAudioFocus(jEnv, audioManager, jBaseActivity, 3, 1); //logMsg("%d from requestAudioFocus()", (int)res); } static void abandonAudioFocus(JNIEnv* jEnv) { setupAudioManagerJNI(jEnv); jAbandonAudioFocus(jEnv, audioManager, jBaseActivity); } CallResult openPcm(const PcmFormat &format) { if(player) { logWarn("called openPcm when pcm already on"); return OK; } pcmFormat = format; logMsg("creating playback %dHz, %d channels, %d buffers", format.rate, format.channels, buffers); assert(format.sample->bits == 16); SLDataLocator_AndroidSimpleBufferQueue buffQLoc = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, buffers }; SLDataFormat_PCM slFormat = { SL_DATAFORMAT_PCM, (SLuint32)format.channels, (SLuint32)format.rate * 1000, // as milliHz SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, format.channels == 1 ? SL_SPEAKER_FRONT_CENTER : SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, SL_BYTEORDER_LITTLEENDIAN }; SLDataSource audioSrc = { &buffQLoc, &slFormat }; SLDataLocator_OutputMix outMixLoc = { SL_DATALOCATOR_OUTPUTMIX, outMix }; SLDataSink sink = { &outMixLoc, nullptr }; const SLInterfaceID ids[] = { SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_VOLUME }; const SLboolean req[sizeofArray(ids)] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE }; SLresult result = (*slI)->CreateAudioPlayer(slI, &player, &audioSrc, &sink, sizeofArray(ids), ids, req); if(result != SL_RESULT_SUCCESS) { logErr("CreateAudioPlayer returned 0x%X", (uint)result); player = nullptr; return INVALID_PARAMETER; } result = (*player)->Realize(player, SL_BOOLEAN_FALSE); assert(result == SL_RESULT_SUCCESS); result = (*player)->GetInterface(player, SL_IID_PLAY, &playerI); assert(result == SL_RESULT_SUCCESS); result = (*player)->GetInterface(player, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &slBuffQI); assert(result == SL_RESULT_SUCCESS); /*result = (*slBuffQI)->RegisterCallback(slBuffQI, queueCallback, nullptr); assert(result == SL_RESULT_SUCCESS);*/ result = (*playerI)->RegisterCallback(playerI, playCallback, nullptr); assert(result == SL_RESULT_SUCCESS); uint playStateEvMask = SL_PLAYEVENT_HEADSTALLED; if(strictUnderrunCheck) playStateEvMask = SL_PLAYEVENT_HEADATEND; (*playerI)->SetCallbackEventsMask(playerI, playStateEvMask); (*playerI)->SetPlayState(playerI, SL_PLAYSTATE_PAUSED); auto bufferBytes = pcmFormat.framesToBytes(bufferFrames); logMsg("allocating %d bytes per buffer", bufferBytes); uint bufferPointerTableSize = sizeof(uchar*) * buffers; // combined allocation of pointer table and actual buffer data void *bufferStorage = mem_alloc(bufferPointerTableSize + (bufferBytes * buffers)); assert(bufferStorage); uchar **bufferBlock = (uchar**)bufferStorage; uchar *startOfBufferData = (uchar*)bufferStorage + bufferPointerTableSize; bufferBlock[0] = startOfBufferData; iterateTimes(buffers-1, i) { bufferBlock[i+1] = bufferBlock[i] + bufferBytes; } qBuffer = bufferBlock; return OK; } void closePcm() { if(player) { logMsg("closing pcm"); currQBuf = 0; isPlaying = 0; (*player)->Destroy(player); mem_free(qBuffer); player = nullptr; reachedEndOfPlayback = 0; } else logMsg("called closePcm when pcm already off"); } bool isOpen() { return player; } static void commitSLBuffer(void *b, uint bytes) { SLresult result = (*slBuffQI)->Enqueue(slBuffQI, b, bytes); if(result != SL_RESULT_SUCCESS) { logWarn("Enqueue returned 0x%X", (uint)result); return; } //logMsg("queued buffer %d with %d bytes, %d on queue, %lld %lld", currQBuf, (int)b->mAudioDataByteSize, buffersQueued+1, lastTimestamp.mHostTime, lastTimestamp.mWordClockTime); IG::incWrappedSelf(currQBuf, buffers); } static uint buffersQueued() { SLAndroidSimpleBufferQueueState state; (*slBuffQI)->GetState(slBuffQI, &state); /*static int debugCount = 0; if(countToValueLooped(debugCount, 30)) { //logMsg("queue state: %u count, %u index", (uint)state.count, (uint)state.index); }*/ return state.count; } static void checkXRun(uint queued) { /*SLmillisecond pos; (*playerI)->GetPosition(playerI, &pos); logMsg("pos: %u/, %d", pcmFormat.mSecsToFrames(pos));*/ if(unlikely(isPlaying && reachedEndOfPlayback)) { logMsg("xrun"); pausePcm(); } } static void startPlaybackIfNeeded(uint queued) { if(unlikely(!isPlaying && queued >= buffers-1)) { reachedEndOfPlayback = 0; SLresult result = (*playerI)->SetPlayState(playerI, SL_PLAYSTATE_PLAYING); if(result == SL_RESULT_SUCCESS) { logMsg("started playback with %d buffers", buffers); isPlaying = 1; } else logErr("SetPlayState returned 0x%X", (uint)result); } } void pausePcm() { if(unlikely(!player) || !isPlaying) return; logMsg("pausing playback"); auto result = (*playerI)->SetPlayState(playerI, SL_PLAYSTATE_PAUSED); isPlaying = 0; } void resumePcm() { if(unlikely(!player)) return; startPlaybackIfNeeded(buffersQueued()); } void clearPcm() { if(unlikely(!isOpen())) return; logMsg("clearing queued samples"); pausePcm(); SLresult result = (*slBuffQI)->Clear(slBuffQI); assert(result == SL_RESULT_SUCCESS); } BufferContext *getPlayBuffer(uint wantedFrames) { if(unlikely(!player)) return nullptr; auto queued = buffersQueued(); if(queued == buffers) { //logDMsg("can't write data with full buffers"); return nullptr; } auto b = qBuffer[currQBuf]; audioBuffLockCtx.data = b; audioBuffLockCtx.frames = std::min(wantedFrames, bufferFrames); return &audioBuffLockCtx; } void commitPlayBuffer(BufferContext *buffer, uint frames) { assert(frames <= buffer->frames); auto queued = buffersQueued(); checkXRun(queued); commitSLBuffer(qBuffer[currQBuf], pcmFormat.framesToBytes(frames)); startPlaybackIfNeeded(queued+1); } void writePcm(uchar *samples, uint framesToWrite) { if(unlikely(!player)) return; auto queued = buffersQueued(); checkXRun(queued); if(framesToWrite > bufferFrames) { logMsg("need more than one buffer to write %d frames", framesToWrite); } while(framesToWrite) { if(queued == buffers) { logMsg("can't write data with full buffers"); break; } uint framesToWriteInBuffer = std::min(framesToWrite, bufferFrames); uint bytesToWriteInBuffer = pcmFormat.framesToBytes(framesToWriteInBuffer); auto b = qBuffer[currQBuf]; memcpy(b, samples, bytesToWriteInBuffer); commitSLBuffer(b, bytesToWriteInBuffer); samples += bytesToWriteInBuffer; framesToWrite -= framesToWriteInBuffer; queued++; } startPlaybackIfNeeded(queued); } int frameDelay() { return 0; // TODO } int framesFree() { return 0; // TODO } void setHintPcmFramesPerWrite(uint frames) { if(frames != bufferFrames) { closePcm(); logMsg("setting queue buffer frames to %d", frames); assert(frames < 2000); bufferFrames = frames; } } void setHintPcmMaxBuffers(uint maxBuffers) { logMsg("setting max buffers to %d", maxBuffers); assert(maxBuffers < 100); buffers = maxBuffers; assert(!isOpen()); } uint hintPcmMaxBuffers() { return buffers; } void setHintStrictUnderrunCheck(bool on) { strictUnderrunCheck = on; } bool hintStrictUnderrunCheck() { return strictUnderrunCheck; } void setSoloMix(bool newSoloMix) { if(soloMix_ != newSoloMix) { logMsg("setting solo mix: %d", newSoloMix); soloMix_ = newSoloMix; if(!isInit()) return; // audio init() will take care of initial focus setting if(soloMix_) { requestAudioFocus(eEnv()); } else { abandonAudioFocus(eEnv()); } } } bool soloMix() { return soloMix_; } void updateFocusOnResume() { if(soloMix()) { requestAudioFocus(eEnv()); } } void updateFocusOnPause() { if(soloMix()) { abandonAudioFocus(eEnv()); } } CallResult init() { logMsg("doing init"); { auto jEnv = eEnv(); JavaInstMethod<void> jSetVolumeControlStream; jSetVolumeControlStream.setup(jEnv, jBaseActivityCls, "setVolumeControlStream", "(I)V"); jSetVolumeControlStream(jEnv, jBaseActivity, 3); } updateFocusOnResume(); // engine object SLObjectItf slE; SLresult result = slCreateEngine(&slE, 0, nullptr, 0, nullptr, nullptr); assert(result == SL_RESULT_SUCCESS); result = (*slE)->Realize(slE, SL_BOOLEAN_FALSE); assert(result == SL_RESULT_SUCCESS); result = (*slE)->GetInterface(slE, SL_IID_ENGINE, &slI); assert(result == SL_RESULT_SUCCESS); // output mix object result = (*slI)->CreateOutputMix(slI, &outMix, 0, nullptr, nullptr); assert(result == SL_RESULT_SUCCESS); result = (*outMix)->Realize(outMix, SL_BOOLEAN_FALSE); assert(result == SL_RESULT_SUCCESS); return OK; } }
26.286047
178
0.741219
[ "object" ]
dd74cb9d34f567f6481e8bcf721548ef981d35b2
1,703
hpp
C++
include/codegen/include/System/Runtime/Serialization/Formatters/Binary/SerStack.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Runtime/Serialization/Formatters/Binary/SerStack.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Runtime/Serialization/Formatters/Binary/SerStack.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Completed includes // Type namespace: System.Runtime.Serialization.Formatters.Binary namespace System::Runtime::Serialization::Formatters::Binary { // Autogenerated type: System.Runtime.Serialization.Formatters.Binary.SerStack class SerStack : public ::Il2CppObject { public: // System.Object[] objects // Offset: 0x10 ::Array<::Il2CppObject*>* objects; // System.String stackId // Offset: 0x18 ::Il2CppString* stackId; // System.Int32 top // Offset: 0x20 int top; // System.Void .ctor(System.String stackId) // Offset: 0xFEC76C static SerStack* New_ctor(::Il2CppString* stackId); // System.Void Push(System.Object obj) // Offset: 0xFF0844 void Push(::Il2CppObject* obj); // System.Object Pop() // Offset: 0xFF07C8 ::Il2CppObject* Pop(); // System.Void IncreaseCapacity() // Offset: 0xFF2B0C void IncreaseCapacity(); // System.Object Peek() // Offset: 0xFF2BA4 ::Il2CppObject* Peek(); // System.Object PeekPeek() // Offset: 0xFF2BF0 ::Il2CppObject* PeekPeek(); // System.Boolean IsEmpty() // Offset: 0xFF07B8 bool IsEmpty(); }; // System.Runtime.Serialization.Formatters.Binary.SerStack } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::Runtime::Serialization::Formatters::Binary::SerStack*, "System.Runtime.Serialization.Formatters.Binary", "SerStack"); #pragma pack(pop)
34.755102
148
0.664709
[ "object" ]
dd8ff04117f14d89ae6ceafc09b8d79c1b8495a9
15,257
cpp
C++
main.cpp
gmb9/CS211-TextEditor
5242488e3f3c5e5b65cbfcf99c95edfa77724485
[ "Apache-2.0" ]
null
null
null
main.cpp
gmb9/CS211-TextEditor
5242488e3f3c5e5b65cbfcf99c95edfa77724485
[ "Apache-2.0" ]
15
2019-10-11T16:25:40.000Z
2019-11-15T18:31:59.000Z
main.cpp
gmb9/CS211-TextEditor
5242488e3f3c5e5b65cbfcf99c95edfa77724485
[ "Apache-2.0" ]
null
null
null
#define PDC_DLL_BUILD 1 #include "curses.h" #include "TrieNode.h" #include "Trie.h" #include <algorithm> #include <string> #include <fstream> #include <vector> #include <unordered_map> #include <queue> #define ENTER_KEY 10 using namespace std; void saveToBinaryFile(vector<vector<int>> data); string decimalConvert(int n); vector<string> insertionSortWord(vector<vector<int>> data); vector<string> selectionSortWord(vector<vector<int>> data); vector<string> bubbleSortWord(vector<vector<int>> data); vector<string> quickSortWord(vector<vector<int>> data); template <typename T> void insertionSort(vector<T>& data); template <typename T> void selectionSort(vector<T>& data); template <typename T> void bubbleSort(vector<T>& data); template <typename T> void sortHelper(vector<T>& data, int start_index, int end_index); template <typename T> void quickSort(vector<T>& data); //unsigned char border_char = 219; int main(int argc, char* argv[]) { Trie dictionary; ifstream dictionaryFile; dictionaryFile.open("keywords.txt"); while (dictionaryFile.good()) { string line; getline(dictionaryFile, line); dictionary.addWord(line); } dictionaryFile.close(); WINDOW* main_window = nullptr; refresh(); int num_rows = 0; int num_cols = 0; //initialize screen, begin curses mode main_window = initscr(); //take up most of the screen getmaxyx(main_window, num_rows, num_cols); resize_term(num_rows - 1, num_cols - 1); getmaxyx(main_window, num_rows, num_cols); //turn off key echo noecho(); //nodelay(main_window, TRUE); //keypad(main_window, TRUE); curs_set(2); if (has_colors() == FALSE) { endwin(); printf("Your terminal does not support color\n"); exit(1); } //fun stuff happens here //Can print any message anywhere //mvwprintw(main_window, 3, 2, ""); //wrefresh(main_window); start_color(); //colors init_pair(1, COLOR_RED, COLOR_WHITE); //red init_pair(2, COLOR_YELLOW, COLOR_WHITE); //orange/yellow init_pair(3, COLOR_GREEN, COLOR_WHITE); //green init_pair(4, COLOR_BLUE, COLOR_WHITE); //blue init_pair(5, COLOR_CYAN, COLOR_WHITE); //light blue init_pair(6, COLOR_MAGENTA, COLOR_WHITE); //purple //highlights text wattron(main_window, A_REVERSE); wattron(main_window, A_BLINK); //top gui bar //mvaddstr(1, 1, "| File | Edit | Options | Buffers | Tools | Help |"); attron(COLOR_PAIR(1)); mvaddstr(1, 1, "| File "); attroff(COLOR_PAIR(1)); attron(COLOR_PAIR(2)); mvaddstr(1, 10, "| Edit "); attroff(COLOR_PAIR(2)); attron(COLOR_PAIR(3)); mvaddstr(1, 19, "| Options "); attroff(COLOR_PAIR(3)); attron(COLOR_PAIR(4)); mvaddstr(1, 30, "| Buffers "); attroff(COLOR_PAIR(4)); attron(COLOR_PAIR(6)); mvaddstr(1, 42, "| Tools "); attroff(COLOR_PAIR(6)); attron(COLOR_PAIR(1)); mvaddstr(1, 52, "| Help |"); attroff(COLOR_PAIR(1)); //bottom gui bars //mvaddstr(num_rows - 3, 1, "| ^G Get Help | ^O Write Out | ^R Read File | ^Y Prev Page | ^C Cur Pos |"); attron(COLOR_PAIR(1)); mvaddstr(num_rows - 3, 1, "| ^G Get Help "); attroff(COLOR_PAIR(1)); attron(COLOR_PAIR(2)); mvaddstr(num_rows - 3, 17, "| ^O Write Out "); attroff(COLOR_PAIR(2)); attron(COLOR_PAIR(3)); mvaddstr(num_rows - 3, 34, "| ^R Read File "); attroff(COLOR_PAIR(3)); attron(COLOR_PAIR(4)); mvaddstr(num_rows - 3, 51, "| ^Y Prev Page "); attroff(COLOR_PAIR(4)); attron(COLOR_PAIR(6)); mvaddstr(num_rows - 3, 68, "| ^C Cur Pos |"); attroff(COLOR_PAIR(6)); //mvaddstr(num_rows - 2, 1, "| ^X Exit | ^J Justify | ^W Where Is | ^V Next Page | ^T To Spell |"); attron(COLOR_PAIR(1)); mvaddstr(num_rows - 2, 1, "| ^X Exit "); attroff(COLOR_PAIR(1)); attron(COLOR_PAIR(2)); mvaddstr(num_rows - 2, 17, "| ^J Justify "); attroff(COLOR_PAIR(2)); attron(COLOR_PAIR(3)); mvaddstr(num_rows - 2, 34, "| ^W Where Is "); attroff(COLOR_PAIR(3)); attron(COLOR_PAIR(4)); mvaddstr(num_rows - 2, 51, "| ^V Next Page "); attroff(COLOR_PAIR(4)); attron(COLOR_PAIR(6)); mvaddstr(num_rows - 2, 68, "| ^T To Spell |"); attroff(COLOR_PAIR(6)); attron(COLOR_PAIR(5)); for (int i = 0; i < num_cols; i++) { //top border mvaddch(0, i, ACS_CKBOARD); //bottom border mvaddch(num_rows - 1, i, ACS_CKBOARD); } for (int i = 62; i < num_cols; i++) { //finish checkerboard line next to top gui bar mvaddch(1, i, ACS_CKBOARD); } for (int i = 85; i < num_cols; i++) { //finish checkerboard line next to bottom gui bars mvaddch(num_rows - 3, i, ACS_CKBOARD); } for (int i = 85; i < num_cols; i++) { //finish line next to bottom gui bars mvaddch(num_rows - 2, i, ACS_CKBOARD); } for (int i = 0; i < num_rows; i++) { //left column mvaddch(i, 0, ACS_CKBOARD); //right column mvaddch(i, num_cols - 1, ACS_CKBOARD); } attroff(COLOR_PAIR(5)); wattroff(main_window, A_REVERSE); wattroff(main_window, A_BLINK); for (int i = 1; i < num_cols - 1; i++) { //line directly under top gui bar mvaddch(2, i, ACS_HLINE); } for (int i = 1; i < num_cols - 1; i++) { //line directly above bottom gui bar mvaddch(num_rows - 4, i, ACS_HLINE); } touchwin(main_window); WINDOW* text_win = derwin(main_window, num_rows - 7, num_cols - 3, 3, 1); keypad(text_win, TRUE); touchwin(text_win); wrefresh(text_win); //detects when a user pressed F1 (KEY_F(1-9 or 0) for function keys), KEY_UP/DOWN/LEFT/RIGHT, etc and saves that as input keypad(main_window, TRUE); int input = getch(text_win); int x_loc = 0; int y_loc = 0; int start = 0; int textx = 0; int texty = 0; int enterTextX = 0; string line; vector<string> v1{}; vector<vector<int>> data{}; for (int i = 0; i < num_rows - 7; i++) { data.push_back(vector<int>{}); data[i].resize(num_cols - 3); for (int j = 0; j < data[i].size(); j++) { data[i][j] = -1; } } //outputting file information to window do { //allows for typing of a-z, A-Z, 0-9, and ./!/@/#/$/% etc if (input >= 32 && input <= 126) { mvwaddch(text_win, texty, textx, input); //add char to vector of vectors data[texty][textx] = input; textx++; if (textx > num_cols - 4) { texty++; textx = enterTextX; textx = 0; } } //pushes cursor down 1 line, saves that x value, and resets x to 0 else if(input == ENTER_KEY) { texty++; enterTextX = textx; textx = 0; } //backspace else if (input == KEY_DC) { mvwaddch(text_win, texty, textx, ' '); wmove(text_win, texty, textx - 1); wrefresh(text_win); //if it's at the start of the line, it will push it back //up a line and set it to the x value of that previous line if (textx == 0) { if (texty != 0) { //delete row if on edge of row texty--; //reset x to row above textx = enterTextX; } else { mvwaddch(text_win, texty, textx, ' '); wmove(text_win, texty, textx); wrefresh(text_win); } } //moves x back a column else { textx--; } } //allows user to move backwards in their text to edit previously typed things else if (input == KEY_LEFT) { textx--; wmove(text_win, texty, textx); wrefresh(text_win); } //allows user to move forwards else if (input == KEY_RIGHT) { if (textx < num_cols - 4) { textx++; wmove(text_win, texty, textx); wrefresh(text_win); } } //converts input on screen to binary else if (input == ALT_P) { saveToBinaryFile(data); } else if (input == ALT_Q) { wclear(text_win); wrefresh(text_win); } else if (input == ALT_Z) { vector<string> result = insertionSortWord(data); wclear(text_win); wrefresh(text_win); for (int i = 0; i < result.size(); i++) { for (int j = 0; j < result[i].length(); j++) { mvwaddch(text_win, i, j, result[i][j]); } } } else if (input == ALT_X) { vector<string> result = selectionSortWord(data); wclear(text_win); wrefresh(text_win); for (int i = 0; i < result.size(); i++) { for (int j = 0; j < result[i].length(); j++) { mvwaddch(text_win, i, j, result[i][j]); } } } else if (input == ALT_C) { int x = 0; vector<string> result = bubbleSortWord(data); wclear(text_win); wrefresh(text_win); for (int i = 0; i < result.size(); i++) { for (int j = 0; j < result[i].length(); j++) { mvwaddch(text_win, i, j, result[i][j]); } } } else if (input == ALT_V) { vector<string> result = quickSortWord(data); wclear(text_win); wrefresh(text_win); for (int i = 0; i < result.size(); i++) { for (int j = 0; j < result[i].length(); j++) { mvwaddch(text_win, i, j, result[i][j]); } } } wrefresh(text_win); input = wgetch(text_win); } while ((input != KEY_F(9))); //revert back to normal console mode nodelay(main_window, TRUE); mvaddstr(0, 0, "Press any key to continue..."); endwin(); } //ALT_Z vector<string> insertionSortWord(vector<vector<int>> data) { vector<string> wordsToSort; string word; for (int i = 0; i < data.size(); i++) { for (int j = 0; j < data[i].size(); j++) { if (data[i][j] == ' ') { wordsToSort.push_back(word); word = ""; } else if (data[i][j] != -1) { word += data[i][j]; } } } wordsToSort.push_back(word); word = ""; insertionSort(wordsToSort); return wordsToSort; } //ALT_X vector<string> selectionSortWord(vector<vector<int>> data) { vector<string> wordsToSort; string word; for (int i = 0; i < data.size(); i++) { for (int j = 0; j < data[i].size(); j++) { if (data[i][j] == ' ') { wordsToSort.push_back(word); word = ""; } else if (data[i][j] != -1) { word += data[i][j]; } } } wordsToSort.push_back(word); word = ""; selectionSort(wordsToSort); return wordsToSort; } //ALT_C vector<string> bubbleSortWord(vector<vector<int>> data) { vector<string> wordsToSort; string word; for (int i = 0; i < data.size(); i++) { for (int j = 0; j < data[i].size(); j++) { if (data[i][j] == ' ') { wordsToSort.push_back(word); word = ""; } else if (data[i][j] != -1) { word += data[i][j]; } } } wordsToSort.push_back(word); word = ""; bubbleSort(wordsToSort); return wordsToSort; } //ALT_V vector<string> quickSortWord(vector<vector<int>> data) { vector<string> wordsToSort; string word; for (int i = 0; i < data.size(); i++) { for (int j = 0; j < data[i].size(); j++) { if (data[i][j] == ' ') { wordsToSort.push_back(word); word = ""; } else if (data[i][j] != -1) { word += data[i][j]; } } } wordsToSort.push_back(word); word = ""; quickSort(wordsToSort); return wordsToSort; } //Insertion template <typename T> void insertionSort(vector<T>& data) { for (int i = 1; i < data.size(); i++) { for (int j = i; j > 0; j--) { if (data[j] < data[j - 1]) { T temp = data[j]; data[j] = data[j - 1]; data[j - 1] = temp; } else { //in correct position relative to //sorted set of list //This extra check ensures O(N) on sorted //data break; } } } } //Selection template <typename T> void selectionSort(vector<T>& data) { for (int i = 0; i < data.size(); i++) { int smallest_index = i; for (int j = i + 1; j < data.size(); j++) { if (data[j] < data[smallest_index]) { smallest_index = j; } } T temp = data[i]; data[i] = data[smallest_index]; data[smallest_index] = temp; } } //Bubble template <typename T> void bubbleSort(vector<T>& data) { for (int i = 0; i < data.size(); i++) { bool has_swapped = false; for (int j = 1; j < data.size() - i; j++) { if (data[j - 1] > data[j]) { T temp = data[j - 1]; data[j - 1] = data[j]; data[j] = temp; has_swapped = true; } } if (has_swapped == false) { //data is sorted, break out of loop break; } } } //Quick sort template <typename T> void sortHelper(vector<T>& data, int start_index, int end_index) { //array of size 1 or smaller if (end_index <= start_index) { return; } //array of size 2 if (end_index - start_index == 1) { if (data[end_index] < data[start_index]) { T temp = data[end_index]; data[end_index] = data[start_index]; data[start_index] = temp; } return; } //must be size 3 or larger //find pivot T first_item = data[start_index]; T last_item = data[end_index]; int mid_index = (start_index + end_index) / 2; T middle_item = data[mid_index]; int pivot_index = start_index; if ( middle_item > first_item && middle_item < last_item //ex: 1 5 10 || middle_item < first_item && middle_item > last_item //ex: 10 5 1 ) { pivot_index = mid_index; } else if ( last_item > first_item && last_item < middle_item //ex: 1 10 5 || last_item < first_item && last_item > middle_item //ex: 10 1 5 ) { pivot_index = end_index; } //swap pivot with end index T pivot_value = data[pivot_index]; data[pivot_index] = data[end_index]; data[end_index] = pivot_value; /* 1. Define i = front_index; j = end_index - 1; 2. While data[i] < pivot AND i < j a. i++ 3. While data[j] > pivot and i < j a. j-- 4. if i != j a. Swap(data[i], data[j]) b. GOTO #2 */ int i = start_index; int j = end_index - 1; while (i < j) { while (data[i] < pivot_value && i < j) { i++; } while (data[j] >= pivot_value && i < j) { j--; } if (i < j) { T temp = data[i]; data[i] = data[j]; data[j] = temp; } } //swap pivot back T temp = data[i]; data[i] = pivot_value; data[end_index] = temp; //recursively repeat sortHelper(data, start_index, i - 1); sortHelper(data, i + 1, end_index); } template <typename T> void quickSort(vector<T>& data) { sortHelper(data, 0, data.size() - 1); } void saveToBinaryFile(vector<vector<int>> data) { unordered_map<string, int> wordFrequency; unordered_map<string, string> finalWord; vector<string> englishWords; priority_queue<pair<string, int>> sort; int counter = 1; string word = ""; for (int i = 0; i < data.size(); i++) { for (int j = 0; j < data[i].size(); j++) { if (data[i][j] == ' ') { wordFrequency[word]++; englishWords.push_back(word); word = ""; } else if (data[i][j] != -1) { word += data[i][j]; } } } wordFrequency[word]++; englishWords.push_back(word); word = ""; for (auto pair : wordFrequency) { sort.push(pair); } while (!sort.empty()) { string word = sort.top().first; finalWord[word] = decimalConvert(counter++); sort.pop(); } ofstream binaryFile; binaryFile.open("binaryFile.txt"); if (binaryFile.is_open()) { for (auto pair : wordFrequency) { binaryFile << pair.first << " : " << pair.second << endl; } } binaryFile.close(); ofstream binaryFileNew; binaryFileNew.open("binaryFileNew.txt"); if (binaryFileNew.is_open()) { for (auto word : englishWords) { binaryFileNew << finalWord[word] << " "; } } binaryFileNew.close(); } string decimalConvert(int n) { vector<int> a; string word = ""; for (int i = 0; n > 0; i++) { a.push_back(n % 2); n /= 2; } for (auto characters : a) { word += to_string(characters); } return word; }
19.167085
122
0.60333
[ "vector" ]
dd91ffba5e1b06735f82a445c5e41271a0c70e51
14,438
cpp
C++
planner/src/kcl_pandora/planning_system/src/StrategicProblemGenerator.cpp
KCL-Planning/strategic-tactical-pandora
aa609af26a59e756b25212fa57fa72be937766e7
[ "BSD-2-Clause" ]
2
2019-01-27T05:17:06.000Z
2020-10-06T15:25:31.000Z
planner/src/kcl_pandora/planning_system/src/StrategicProblemGenerator.cpp
KCL-Planning/strategic-tactical-pandora
aa609af26a59e756b25212fa57fa72be937766e7
[ "BSD-2-Clause" ]
null
null
null
planner/src/kcl_pandora/planning_system/src/StrategicProblemGenerator.cpp
KCL-Planning/strategic-tactical-pandora
aa609af26a59e756b25212fa57fa72be937766e7
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include <sstream> #include <fstream> #include <vector> #include <string> namespace PandoraKCL { /*----------*/ /* planning */ /*----------*/ /* * Processes the strategic_plan.pddl into dispatchable actions. */ void prepareStrategicPlan(std::string dataPath) { // cp_vrp output std::ifstream planfile; planfile.open((dataPath + "cp_plan_strategic.txt").c_str()); int curr, next; std::string line; std::vector<planning_msgs::ActionDispatch> potentialPlan; double planDuration = -1; while(!planfile.eof()) { getline(planfile, line); //; **** FINAL **** Solution #3 ... if (line.substr(0,15).compare("**** FINAL ****") == 0) { potentialPlan.clear(); planDuration = 0; while(!planfile.eof() && line.compare("")!=0) { getline(planfile, line); if (line.substr(0,15).compare("auv_Dummy Start") == 0) continue; if (line.substr(0,9).compare("Dummy End") == 0) break; // auv_mission0 [112.805 -- 261.868 --> 374.673] // dock1 [886.182 -- 20 --> 906.182] // recharge1 [906.182 -- 1800 --> 2706.18] // undock1 [2706.18 -- 10 --> 2716.18] planning_msgs::ActionDispatch msg; // action ID doesn't matter msg.action_id = -1; // name curr=line.find(" "); std::string name = line.substr(0,curr).c_str(); msg.name = name; // duration curr=line.find("[")+1; next=line.find(" ",curr); msg.dispatch_time = (double)atof(line.substr(curr,next-curr).c_str()); // dispatchTime curr=line.find("--")+3; next=line.find(" ",curr); msg.duration = (double)atof(line.substr(curr,next-curr).c_str()); if(line.substr(0,4).compare("dock") == 0) { // parameters (?v - vehicle ?wp - waypoint) msg.name = "dock_auv"; if(msg.dispatch_time - planDuration > 0) { // insert do_hover planning_msgs::ActionDispatch dh_msg; dh_msg.action_id = -1; dh_msg.name = "goto_structure"; diagnostic_msgs::KeyValue dh_pair; dh_pair.key = "structure"; if (recharge_structures.size() > 0) { std::vector<std::string>::iterator rit = recharge_structures.begin(); dh_pair.value = structure_wp_names[*rit]; } else { ROS_ERROR("KCL: No recharge stations exist."); } dh_msg.parameters.push_back(dh_pair); dh_msg.dispatch_time = planDuration; dh_msg.duration = msg.dispatch_time - planDuration; potentialPlan.push_back(dh_msg); } } else if(line.substr(0,6).compare("undock") == 0) { // parameters (?v - vehicle ?wp - waypoint) msg.name = "undock_auv"; } else if(line.substr(0,8).compare("recharge") == 0) { // parameters (?v - vehicle ?wp - waypoint) msg.name = "recharge"; } else if(line.substr(0,11).compare("auv_mission") == 0) { msg.name = "complete_mission"; // parameters (?v - vehicle ?m - mission ?wp - waypoint) curr = 11; next=line.find(" "); std::string mission_id = line.substr(curr,next-curr); diagnostic_msgs::KeyValue pair; pair.key = "mission"; pair.value = "Mission" + mission_id; msg.parameters.push_back(pair); if(msg.dispatch_time - planDuration > 0) { // insert do_hover planning_msgs::ActionDispatch dh_msg; dh_msg.action_id = -1; dh_msg.name = "goto_structure"; diagnostic_msgs::KeyValue dh_pair; dh_pair.key = "structure"; std::map<std::string,std::string>::iterator it=mission_structure_map.begin(); for (; it!=mission_structure_map.end(); ++it) { if(it->first == pair.value) { dh_pair.value = structure_wp_names[it->second]; } } dh_msg.parameters.push_back(dh_pair); dh_msg.dispatch_time = planDuration; dh_msg.duration = msg.dispatch_time - planDuration; potentialPlan.push_back(dh_msg); } } potentialPlan.push_back(msg); // update plan duration planDuration = msg.duration + msg.dispatch_time; } strategic_plan.clear(); for(size_t i=0;i<potentialPlan.size();i++) strategic_plan.push_back(potentialPlan[i]); } } planfile.close(); /* // popf output std::ifstream planfile; planfile.open((dataPath + "plan_strategic.pddl").c_str()); int curr, next; std::string line; std::vector<planning_msgs::ActionDispatch> potentialPlan; double planDuration = -1; double expectedPlanDuration = 0; while(!planfile.eof()) { getline(planfile, line); if (line.substr(0,6).compare("; Cost") == 0) { //; Cost: xxx.xxx expectedPlanDuration = atof(line.substr(8).c_str()); } else if (line.substr(0,6).compare("; Time")!=0) { //consume useless lines } else { potentialPlan.clear(); planDuration = 0; while(!planfile.eof() && line.compare("")!=0) { getline(planfile, line); if (line.length()<2) break; planning_msgs::ActionDispatch msg; // action ID doesn't matter msg.action_id = -1; // dispatchTime curr=line.find(":"); double dispatchTime = (double)atof(line.substr(0,curr).c_str()); msg.dispatch_time = dispatchTime; // name curr=line.find("(")+1; next=line.find(" ",curr); std::string name = line.substr(curr,next-curr).c_str(); msg.name = name; // parameters std::vector<std::string> params; curr=next+5; next=line.find(")",curr); int at = curr; while(at < next) { int cc = line.find(" ",curr); int cc1 = line.find(")",curr); curr = cc<cc1?cc:cc1; std::string param = name_map[line.substr(at,curr-at)]; params.push_back(param); ++curr; at = curr; } if("do_hover" == msg.name) { // parameters (?v - vehicle ?from ?to - waypoint) std::string wp_id = params[1]; msg.name = "goto_structure"; diagnostic_msgs::KeyValue pair; pair.key = "structure"; pair.value = wp_id; msg.parameters.push_back(pair); } else if("complete_mission" == msg.name) { // parameters (?v - vehicle ?m - mission ?wp - waypoint) std::string mission_id = params[0]; msg.name = "complete_mission"; diagnostic_msgs::KeyValue pair; pair.key = "mission"; pair.value = mission_id; msg.parameters.push_back(pair); } else if("dock_auv" == msg.name) { // parameters (?v - vehicle ?wp - waypoint) msg.name = "dock_auv"; } else if("undock_auv" == msg.name) { // parameters (?v - vehicle ?wp - waypoint) msg.name = "undock_auv"; } // duration curr=line.find("[",curr)+1; next=line.find("]",curr); msg.duration = (double)atof(line.substr(curr,next-curr).c_str()); potentialPlan.push_back(msg); // update plan duration curr=line.find(":"); planDuration = msg.duration + atof(line.substr(0,curr).c_str()); } if(fabs(planDuration - expectedPlanDuration) < 0.01 || true) { // save better optimised plan strategic_plan.clear(); for(size_t i=0;i<potentialPlan.size();i++) strategic_plan.push_back(potentialPlan[i]); } else { ROS_INFO("Duration: %f, expected %f; plan discarded", planDuration, expectedPlanDuration); } } } planfile.close(); */ } /** * Passes the problem to the Planner; the plan to post-processing. */ bool runStrategicPlanner(std::string &dataPath) { /* std::string popfCommand = "rosrun planning_system bin/popf "; // run the planner std::string commandString = popfCommand + strategicDomain + " " + dataPath + "pandora_strategic_problem.pddl > " + dataPath + "plan_strategic.pddl"; ROS_INFO("KCL: Running: %s", commandString.c_str()); std::string plan = runCommand(commandString.c_str()); ROS_INFO("KCL: Planning complete"); // check the Planner solved the problem std::ifstream planfile; planfile.open((dataPath + "plan_strategic.pddl").c_str()); std::string line; bool solved = false; while(!planfile.eof() && !solved) { getline(planfile, line); if (line.find("; Time", 0) != std::string::npos) solved = true; } if(!solved) { planfile.close(); ROS_INFO("Plan was unsolvable! Try again?"); return false; } planfile.close(); */ ROS_INFO("KCL: Processing strategic plan"); std::string command_convert = "python3 " + dataPath + "/../../../../../cp/pddl2vrp/p2vrp.py " + strategicDomain + " " + dataPath + "pandora_strategic_problem.pddl | tee " + dataPath + "strategic_problem.vrp"; ROS_INFO("KCL: Running: %s", command_convert.c_str()); runCommand(command_convert.c_str()); /* 0 = maximize number of missions executed 1 = maximize number of missions executed then (given that number of missions) minimize number of recharges 2 = execute all missions and minimize the makespan */ std::string command_solve = dataPath + "/../../../../../cp/cp_vrp/cp_vrp " + dataPath + "strategic_problem.vrp 10 2 | tee " + dataPath + "cp_plan_strategic.txt"; ROS_INFO("KCL: Running: %s", command_solve.c_str()); runCommand(command_solve.c_str()); // Convert plan into message list for dispatch prepareStrategicPlan(dataPath); return true; } /*---------*/ /* problem */ /*---------*/ /** * Generate a PDDL problem file, saving the result in dataPath/pandora_strategic_problem.pddl. * This file is later read by the planner, and the result saved in dataPath/strategic_plan.pddl. */ void generateStrategicPDDLProblemFile(std::string &dataPath) { /*--------*/ /* header */ /*--------*/ ROS_INFO("KCL: Generating strategic PDDL problem file"); std::ofstream pFile; pFile.open((dataPath + "pandora_strategic_problem.pddl").c_str()); pFile << "(define (problem pandora_strategic_mission)" << std::endl; pFile << "(:domain pandora_domain_strategic)" << std::endl; /* objects */ pFile << "(:objects" << std::endl; // vehicles pFile << "auv - vehicle" << std::endl; // structure waypoints for(int s=0;s<structures.size();s++) pFile << structure_wp_names[structures[s]] << " "; for(size_t i=0;i<auv_names.size();i++) pFile << auv_starting_locations[auv_names[i]] << " "; if(structures.size()>0 || auv_names.size() > 0) pFile << "- waypoint" << std::endl; // missions for (std::map<std::string,std::string>::iterator it=mission_structure_map.begin(); it!=mission_structure_map.end(); ++it) pFile << it->first << " "; if(mission_structure_map.size()>0) pFile << "- mission" << std::endl; pFile << ")" << std::endl; /*---------------*/ /* initial state */ /*---------------*/ pFile << "(:init" << std::endl; pFile << "(vehicle_free auv)" << std::endl; pFile << "(= (mission_total) 0)" << std::endl; // position if (structures.size()>0) { for(size_t i=0;i<auv_names.size();i++) { pFile << "(at auv " << auv_starting_locations[auv_names[i]] << ") (= (charge auv) 1200)" << std::endl; pFile << std::endl; } } // recharge locations for(std::vector<std::string>::iterator rit=recharge_structures.begin(); rit!=recharge_structures.end(); ++rit) pFile << "(recharge_at " << structure_wp_names[*rit] << ")" << std::endl; pFile << std::endl; // mission active (TODO TILs) for (std::map<std::string,std::string>::iterator it=mission_structure_map.begin(); it!=mission_structure_map.end(); ++it) pFile << "(active " << it->first << ")" << std::endl; pFile << std::endl; // mission deadlines for (std::map<std::string,double>::iterator it=mission_deadline_map.begin(); it!=mission_deadline_map.end(); ++it) pFile << "(at " << it->second << " (not (active " << it->first << ")))" << std::endl; // strategic deadline (comment out if needed) for (std::map<std::string,std::string>::iterator it=mission_structure_map.begin(); it!=mission_structure_map.end(); ++it) { if(mission_deadline_map.find(it->first) == mission_deadline_map.end()) pFile << "(at 99999 (not (active " << it->first << ")))" << std::endl; } pFile << std::endl; // mission locations for (std::map<std::string,std::string>::iterator it=mission_structure_map.begin(); it!=mission_structure_map.end(); ++it) pFile << "(in " << it->first << " " << structure_wp_names[it->second] << ")" << std::endl; pFile << std::endl; // mission durations for (std::map<std::string,double>::iterator it=mission_duration_map.begin(); it!=mission_duration_map.end(); ++it) pFile << "(= (mission_duration " << it->first << ") " << (it->second+10) << ")" << std::endl; pFile << std::endl; // structure distances for(size_t i=0;i<structures.size();i++) { for(size_t j=0;j<structures.size();j++) { if(i==j) continue; pFile << "(connected " << structure_wp_names[structures[i]] << " " << structure_wp_names[structures[j]] << ") "; pFile << "(= (distance " << structure_wp_names[structures[i]] << " " << structure_wp_names[structures[j]] << ") " << computeDistance(structure_wps[structures[i]], structure_wps[structures[j]]) << ")" << std::endl; } for(size_t j=0;j<auv_names.size();j++) { pFile << "(connected " << structure_wp_names[structures[i]] << " " << auv_starting_locations[auv_names[j]] << ") "; pFile << "(= (distance " << structure_wp_names[structures[i]] << " " << auv_starting_locations[auv_names[j]] << ") " << computeDistance(structure_wps[structures[i]], auv_starting_waypoints[auv_names[j]]) << ")" << std::endl; pFile << "(connected " << auv_starting_locations[auv_names[j]] << " " << structure_wp_names[structures[i]] << ") "; pFile << "(= (distance " << auv_starting_locations[auv_names[j]] << " " << structure_wp_names[structures[i]] << ") " << computeDistance(structure_wps[structures[i]], auv_starting_waypoints[auv_names[j]]) << ")" << std::endl; } }; pFile << std::endl; pFile << ")" << std::endl; /*-------*/ /* goals */ /*-------*/ /* // complete all missions! pFile << "(:goal (and" << std::endl; for (std::map<std::string,std::string>::iterator it=mission_structure_map.begin(); it!=mission_structure_map.end(); ++it) pFile << "(completed " << it->first << ")" << std::endl; pFile << ")))" << std::endl; */ // try to complete some missions. pFile << "(:metric maximize (mission_total))" << std::endl; pFile << "(:goal (> (mission_total) 0))" << std::endl; pFile << ")" << std::endl; } } // close namespace
31.731868
125
0.610334
[ "vector" ]
dda00b94c3b45f9da5b5cd27556f2774975c0d02
64,139
cpp
C++
win32_source/Contrib/NGram/wz_utilities.cpp
yathit/waitzar
be0d1f2fe48ebc6094dbe2312ab18f4f05cf9136
[ "Apache-2.0" ]
1
2017-09-10T03:09:46.000Z
2017-09-10T03:09:46.000Z
win32_source/Contrib/NGram/wz_utilities.cpp
yathit/waitzar
be0d1f2fe48ebc6094dbe2312ab18f4f05cf9136
[ "Apache-2.0" ]
null
null
null
win32_source/Contrib/NGram/wz_utilities.cpp
yathit/waitzar
be0d1f2fe48ebc6094dbe2312ab18f4f05cf9136
[ "Apache-2.0" ]
3
2016-07-26T17:42:30.000Z
2019-11-11T14:18:20.000Z
/* * Copyright 2009 by Seth N. Hetu * * Please refer to the end of the file for licensing information */ #include "wz_utilities.h" using std::vector; using std::wstringstream; using std::wstring; using std::string; ////////////////////////////////////////////////////////////////////////////////// // Please note that the wz_utilities library is currently considered // to be UNSTABLE, and is not included in the Linux build by default. // This is because most of its functionality is of direct benefit to the // Windows build, so we hope to test its correctness through the next // two Windows releases of WaitZar. // Since there is some universally-useful code here, we will eventually // include this in both releases, but we want to avoid bumping libwaitzar's // major revision for breakages caused by code that wasn't originally intended // for Linux to begin with. ////////////////////////////////////////////////////////////////////////////////// //A hidden namespace for our "private" methods namespace { //Various constants enum { //Constant pseudo-letters ZG_DASH = 0xE000, ZG_KINZI, //Constant pseudo-letters (stacked) ZG_STACK_KA = 0xE100, ZG_STACK_KHA, ZG_STACK_GA, ZG_STACK_GHA, ZG_STACK_NGA, ZG_STACK_SA, ZG_STACK_SSA, ZG_STACK_ZA, ZG_STACK_ZHA, //Skip one... ZG_STACK_NYA, ZG_STACK_TTA, ZG_STACK_HTA1, ZG_STACK_DHA1, ZG_STACK_EXTRA, ZG_STACK_NHA, ZG_STACK_TA, ZG_STACK_HTA2, ZG_STACK_DDA, ZG_STACK_DHA2, ZG_STACK_NA, ZG_STACK_PA, ZG_STACK_PHA, ZG_STACK_VA, ZG_STACK_BA, ZG_STACK_MA, //Break sequence ZG_STACK_YA, ZG_STACK_LA, ZG_STACK_THA, ZG_STACK_A, //Special-purpose indented stacked letters ZG_STACK_SSA_INDENT, ZG_STACK_TA_INDENT, ZG_STACK_HTA2_INDENT, //Some complex letters ZG_COMPLEX_1 = 0xE200, ZG_COMPLEX_2, ZG_COMPLEX_3, ZG_COMPLEX_4, ZG_COMPLEX_5, ZG_COMPLEX_NA, //Letters which share similar semantic functionality ZG_TALL_WITH_ASAT, ZG_DOTTED_CIRCLE_ABOVE, ZG_LEGGED_CIRCLE_BELOW, ZG_LEGS_BOTH_WAYS, ZG_LEGS_OF_THREE, ZG_KINZI_102D, ZG_KINZI_102E, ZG_KINZI_1036, //Some more substitures ZG_DOT_BELOW_SHIFT_1, ZG_DOT_BELOW_SHIFT_2, ZG_TALL_SINGLE_LEG, ZG_TALL_DOUBLE_LEG, ZG_YA_PIN_CUT, ZG_YA_PIN_SA, ZG_YA_YIT_LONG, ZG_YA_YIT_HIGHCUT, ZG_YA_YIT_LONG_HIGHCUT, ZG_YA_YIT_LOWCUT, ZG_YA_YIT_LONG_LOWCUT, ZG_YA_YIT_BOTHCUT, ZG_YA_YIT_LONG_BOTHCUT, ZG_LEG_FWD_SMALL, ZG_NA_CUT, ZG_YA_CUT, ZG_NYA_CUT, ZG_O_CUT, }; //Constants for our counting sort algorithm enum { ID_MED_Y = 0, ID_MED_R, ID_MED_W, ID_MED_H, ID_VOW_E, ID_VOW_ABOVE, ID_VOW_BELOW, ID_VOW_A, ID_ANUSVARA, ID_DOW_BELOW, ID_VISARGA, ID_TOTAL }; //Bitflags for our step-three algorithm const uint64_t S3_TOTAL_FLAGS = 42; const uint64_t S3_VISARGA = 0x20000000000; const uint64_t S3_LEG_SINGLE = 0x10000000000; const uint64_t S3_LEG_SINGLE_TALL = 0x8000000000; const uint64_t S3_LEG_DOUBLE = 0x4000000000; const uint64_t S3_LEG_DOUBLE_TALL = 0x2000000000; const uint64_t S3_TWO_LEGS = 0x1000000000; const uint64_t S3_THREE_LEGS = 0x800000000; const uint64_t S3_MED_YA_PIN = 0x400000000; const uint64_t S3_MED_YA_PIN_SHORT = 0x200000000; const uint64_t S3_MED_YA_PIN_SSA_STACK = 0x100000000; const uint64_t S3_MED_YA_YIT = 0x80000000; const uint64_t S3_MED_YA_YIT_LONG = 0x40000000; const uint64_t S3_MED_YA_YIT_HIGH_CUT = 0x20000000; const uint64_t S3_MED_YA_YIT_LONG_HIGH_CUT = 0x10000000; const uint64_t S3_MED_YA_YIT_LOW_CUT = 0x8000000; const uint64_t S3_MED_YA_YIT_LONG_LOW_CUT = 0x4000000; const uint64_t S3_MED_YA_YIT_BOTH_CUT = 0x2000000; const uint64_t S3_MED_YA_YIT_LONG_BOTH_CUT = 0x1000000; const uint64_t S3_STACKED = 0x800000; //(includes indented) const uint64_t S3_CIRC_BELOW = 0x400000; const uint64_t S3_CIRC_BELOW_W_LEG = 0x200000; const uint64_t S3_LEG_FWD = 0x100000; const uint64_t S3_LEG_FWD_SMALL = 0x80000; const uint64_t S3_DOT_BELOW = 0x40000; const uint64_t S3_DOT_BELOW_2 = 0x20000; const uint64_t S3_DOT_BELOW_3 = 0x10000; const uint64_t S3_VOW_AR_TALL = 0x8000; const uint64_t S3_VOW_AR_TALL_ASAT = 0x4000; const uint64_t S3_VOW_AR_SHORT = 0x2000; const uint64_t S3_DOT_ABOVE = 0x1000; const uint64_t S3_CIRCLE_ABOVE = 0x800; const uint64_t S3_CIRCLE_DOT_ABOVE = 0x400; const uint64_t S3_CIRCLE_CROSSED_ABOVE = 0x200; const uint64_t S3_KINZI = 0x100; const uint64_t S3_KINZI_DOT = 0x80; const uint64_t S3_KINZI_CIRC = 0x40; const uint64_t S3_KINZI_CIRC_CROSSED = 0x20; const uint64_t S3_MED_SLANT_ABOVE = 0x10; const uint64_t S3_VOW_A = 0x8; const uint64_t S3_CONSONANT_WIDE = 0x4; const uint64_t S3_CONSONANT_NARROW = 0x2; const uint64_t S3_CONSONANT_OTHER = 0x1; const uint64_t S3_OTHER = 0x0; //Bitflags for our zawgyi conversion algorithm const uint16_t BF_CONSONANT = 2048; const uint16_t BF_STACKER = 1024; const uint16_t BF_DOT_LOW = 512; const uint16_t BF_DOT_OVER = 256; const uint16_t BF_VOW_AR = 128; const uint16_t BF_LEG_NORM = 64; const uint16_t BF_VOW_OVER = 32; const uint16_t BF_VOW_A = 16; const uint16_t BF_LEG_REV = 8; const uint16_t BF_CIRC_LOW = 4; const uint16_t BF_MED_YA = 2; const uint16_t BF_ASAT = 1; const uint16_t BF_OTHER = 0; //Match into this array const unsigned int matchFlags[] = {0xBDE, 0x801, 0x803, 0x887, 0x80F, 0x89E, 0x93F, 0xB7F, 0x8FF, 0x9FF, 0x800}; //Useful global vars //FILE *wzUtilLogFile = NULL; //A fun struct enum { RULE_MODIFY = 1, RULE_COMBINE, RULE_ORDER, }; struct Rule { int type; wchar_t at_letter; uint64_t match_flags; wstring match_additional; wchar_t replace; bool blacklisted; Rule(int type, wchar_t atLetter, uint64_t matchFlags, const wstring& matchAdditional, wchar_t replace) { this->type = type; this->at_letter = atLetter; this->match_flags = matchFlags; this->match_additional = matchAdditional; this->replace = replace; this->blacklisted = false; } wstring matchFlagsBin() const { std::wstringstream res; for (uint64_t i=S3_VISARGA; i>0; i>>=1) { if (match_flags&i) res <<L"1"; else res <<L"0"; } return res.str(); } wstring toString() const { std::wstringstream res; res <<L"Rule{"; res <<((type==RULE_MODIFY)?L"MODIFY":(type==RULE_COMBINE)?L"COMBINE":(type==RULE_ORDER)?L"ORDER":L"<ERR>"); res <<L", at[" <<at_letter <<"]"; res <<L", match[" <<matchFlagsBin() <<L"]"; if (!match_additional.empty()) res <<L", additional[" <<match_additional <<L"]"; res <<L", replace[" <<replace <<L"]"; res <<L"}"; return res.str(); } }; vector<Rule*> matchRules; vector<wstring> reorderPairs; bool isMyanmar(wchar_t letter) { return (letter>=0x1000 && letter<=0x1021) || (letter>=0x1023 && letter<=0x1032 && letter!=0x1028) || (letter>=0x1036 && letter<=0x104F); } bool isConsonant(wchar_t letter) { return (letter>=0x1000 && letter<=0x1021) || (letter>=0x1023 && letter<=0x1027) || (letter==0x103F) || (letter==0x200B); } bool isDigit(wchar_t letter) { return (letter>=0x1040 && letter<=0x1049); } bool isPunctuation(wchar_t letter) { return (letter==0x104A || letter==0x104B); } bool shouldRestartCount(wchar_t letter) { return isConsonant(letter) || letter==0x1029 || letter==0x102A || isDigit(letter) || isPunctuation(letter) || !isMyanmar(letter); } //There are several other stopping conditions besides a stopping character //For example, the last character in a string triggers a stop. //uniString[i+1]==0x103A catches "vowell_a" followed by "asat". This might be hackish; not sure. bool atStoppingPoint(const wstring &uniString, size_t id, size_t length) { return id==length || (isMyanmar(uniString[id])&&uniString[id+1]==0x103A) || uniString[id]==0x103A || uniString[id]==0x1039; } int getRhymeID(wchar_t letter) { switch (letter) { case L'\u103B': return ID_MED_Y; case L'\u103C': return ID_MED_R; case L'\u103D': return ID_MED_W; case L'\u103E': return ID_MED_H; case L'\u1031': return ID_VOW_E; case L'\u102D': case L'\u102E': case L'\u1032': return ID_VOW_ABOVE; case L'\u102F': case L'\u1030': return ID_VOW_BELOW; case L'\u102B': case L'\u102C': return ID_VOW_A; case L'\u1036': return ID_ANUSVARA; case L'\u1037': return ID_DOW_BELOW; case L'\u1038': return ID_VISARGA; default: return -1; } } int getBitflag(wchar_t uniLetter) { switch (uniLetter) { case L'\u1039': return BF_STACKER; case L'\u1037': return BF_DOT_LOW; case L'\u1036': return BF_DOT_OVER; case L'\u102B': case L'\u102C': return BF_VOW_AR; case L'\u102F': case L'\u1030': return BF_LEG_NORM; case L'\u102D': case L'\u102E': case L'\u1032': return BF_VOW_OVER; case L'\u1031': return BF_VOW_A; case L'\u103E': return BF_LEG_REV; case L'\u103D': return BF_CIRC_LOW; case L'\u103B': case L'\u103C': return BF_MED_YA; case L'\u103A': return BF_ASAT; case L'\u1025': case L'\u1027': case L'\u1029': case L'\u103F': case ZG_DASH: return BF_CONSONANT; default: if (uniLetter>=L'\u1000' && uniLetter<=L'\u1021') return BF_CONSONANT; return BF_OTHER; } } uint64_t getStage3BitFlags(wchar_t letter) { switch (letter) { case L'\u1038': return S3_VISARGA; case L'\u102F': return S3_LEG_SINGLE; case ZG_TALL_SINGLE_LEG: return S3_LEG_SINGLE_TALL; case L'\u1030': return S3_LEG_DOUBLE; case ZG_TALL_DOUBLE_LEG: return S3_LEG_DOUBLE_TALL; case ZG_LEGS_BOTH_WAYS: return S3_TWO_LEGS; case ZG_LEGS_OF_THREE: return S3_THREE_LEGS; case L'\u103B': return S3_MED_YA_PIN; case ZG_YA_PIN_CUT: return S3_MED_YA_PIN_SHORT; case ZG_YA_PIN_SA: return S3_MED_YA_PIN_SSA_STACK; case L'\u103C': return S3_MED_YA_YIT; case ZG_YA_YIT_LONG: return S3_MED_YA_YIT_LONG; case ZG_YA_YIT_HIGHCUT: return S3_MED_YA_YIT_HIGH_CUT; case ZG_YA_YIT_LONG_HIGHCUT: return S3_MED_YA_YIT_LONG_HIGH_CUT; case ZG_YA_YIT_LOWCUT: return S3_MED_YA_YIT_LOW_CUT; case ZG_YA_YIT_LONG_LOWCUT: return S3_MED_YA_YIT_LONG_LOW_CUT; case ZG_YA_YIT_BOTHCUT: return S3_MED_YA_YIT_BOTH_CUT; case ZG_YA_YIT_LONG_BOTHCUT: return S3_MED_YA_YIT_LONG_BOTH_CUT; case L'\u103D': return S3_CIRC_BELOW; case ZG_LEGGED_CIRCLE_BELOW: return S3_CIRC_BELOW_W_LEG; case L'\u103E': return S3_LEG_FWD; case ZG_LEG_FWD_SMALL: return S3_LEG_FWD_SMALL; case L'\u1037': return S3_DOT_BELOW; case ZG_DOT_BELOW_SHIFT_1: return S3_DOT_BELOW_2; case ZG_DOT_BELOW_SHIFT_2: return S3_DOT_BELOW_3; case L'\u102B': return S3_VOW_AR_TALL; case ZG_TALL_WITH_ASAT: return S3_VOW_AR_TALL_ASAT; case L'\u102C': return S3_VOW_AR_SHORT; case L'\u1036': return S3_DOT_ABOVE; case L'\u102D': return S3_CIRCLE_ABOVE; case ZG_DOTTED_CIRCLE_ABOVE: return S3_CIRCLE_DOT_ABOVE; case L'\u102E': return S3_CIRCLE_CROSSED_ABOVE; case ZG_KINZI: return S3_KINZI; case ZG_KINZI_1036: return S3_KINZI_DOT; case ZG_KINZI_102D: return S3_KINZI_CIRC; case ZG_KINZI_102E: return S3_KINZI_CIRC_CROSSED; case L'\u1032': return S3_MED_SLANT_ABOVE; case L'\u1031': return S3_VOW_A; case L'\u1000': case L'\u1003': case L'\u1006': case L'\u100F': case L'\u1010': case L'\u1011': case L'\u1018': case L'\u101A': case L'\u101C': case L'\u101E': case L'\u101F': case L'\u1021': case L'\u103F': return S3_CONSONANT_WIDE; case L'\u1001': case L'\u1002': case L'\u1004': case L'\u1005': case L'\u1007': case L'\u100E': case L'\u1012': case L'\u1013': case L'\u1014': case L'\u1015': case L'\u1016': case L'\u1017': case L'\u1019': case L'\u101B': case L'\u101D': case L'\u1027': case ZG_NA_CUT: case ZG_YA_CUT: return S3_CONSONANT_NARROW; case L'\u1008': case L'\u1009': case L'\u100A': case ZG_NYA_CUT: case L'\u100B': case L'\u100C': case L'\u100D': case L'\u1020': case L'\u1025': case ZG_O_CUT: case L'\u1029': return S3_CONSONANT_OTHER; default: if (letter>=ZG_STACK_KA && letter<=ZG_STACK_HTA2_INDENT) return S3_STACKED; return S3_OTHER; } } int getStage3ID(uint64_t bitflags) { switch (bitflags) { case S3_VISARGA: return 41; case S3_LEG_SINGLE: return 40; case S3_LEG_SINGLE_TALL: return 39; case S3_LEG_DOUBLE: return 38; case S3_LEG_DOUBLE_TALL: return 37; case S3_TWO_LEGS: return 36; case S3_THREE_LEGS: return 35; case S3_MED_YA_PIN: return 34; case S3_MED_YA_PIN_SHORT: return 33; case S3_MED_YA_PIN_SSA_STACK: return 32; case S3_MED_YA_YIT: return 31; case S3_MED_YA_YIT_LONG: return 30; case S3_MED_YA_YIT_HIGH_CUT: return 29; case S3_MED_YA_YIT_LONG_HIGH_CUT: return 28; case S3_MED_YA_YIT_LOW_CUT: return 27; case S3_MED_YA_YIT_LONG_LOW_CUT: return 26; case S3_MED_YA_YIT_BOTH_CUT: return 25; case S3_MED_YA_YIT_LONG_BOTH_CUT: return 24; case S3_STACKED: return 23; case S3_CIRC_BELOW: return 22; case S3_CIRC_BELOW_W_LEG: return 21; case S3_LEG_FWD: return 20; case S3_LEG_FWD_SMALL: return 19; case S3_DOT_BELOW: return 18; case S3_DOT_BELOW_2: return 17; case S3_DOT_BELOW_3: return 16; case S3_VOW_AR_TALL: return 15; case S3_VOW_AR_TALL_ASAT: return 14; case S3_VOW_AR_SHORT: return 13; case S3_DOT_ABOVE: return 12; case S3_CIRCLE_ABOVE: return 11; case S3_CIRCLE_DOT_ABOVE: return 10; case S3_CIRCLE_CROSSED_ABOVE: return 9; case S3_KINZI: return 8; case S3_KINZI_DOT: return 7; case S3_KINZI_CIRC: return 6; case S3_KINZI_CIRC_CROSSED: return 5; case S3_MED_SLANT_ABOVE: return 4; case S3_VOW_A: return 3; case S3_CONSONANT_WIDE: return 2; case S3_CONSONANT_NARROW: return 1; case S3_CONSONANT_OTHER: return 0; default: return -1; } } unsigned int flag2id(unsigned int flag) { switch (flag) { case BF_STACKER: return 10; case BF_DOT_LOW: return 9; case BF_DOT_OVER: return 8; case BF_VOW_AR: return 7; case BF_LEG_NORM: return 6; case BF_VOW_OVER: return 5; case BF_VOW_A: return 4; case BF_LEG_REV: return 3; case BF_CIRC_LOW: return 2; case BF_MED_YA: return 1; case BF_ASAT: return 0; default: return -1; } } wchar_t getStackedVersion(wchar_t uniLetter) { switch (uniLetter) { case L'\u101B': return ZG_STACK_YA; case L'\u101C': return ZG_STACK_LA; case L'\u101E': return ZG_STACK_THA; case L'\u1021': return ZG_STACK_A; default: if (uniLetter>=L'\u1000' && uniLetter<=L'\u1008') { return (uniLetter-L'\u1000')+ZG_STACK_KA; } else if (uniLetter>=L'\u100A' && uniLetter<=L'\u100D') { return (uniLetter-L'\u100A')+ZG_STACK_NYA; } else if (uniLetter>=L'\u100F' && uniLetter<=L'\u1019') { return (uniLetter-L'\u100F')+ZG_STACK_NHA; } else if (uniLetter==L'\u100E') { return ZG_STACK_EXTRA; //Todo: we can merge this & the top 2 "if"s. } } return 0; } wchar_t zawgyiLetter(wchar_t uniLetter) { switch (uniLetter) { case L'\u1039': return L'\u005E'; //Leftover stack letters as ^ case L'\u103A': return L'\u1039'; case L'\u103B': return L'\u103A'; case L'\u103C': return L'\u103B'; case L'\u103D': return L'\u103C'; case L'\u103E': return L'\u103D'; case L'\u103F': return L'\u1086'; /*case : return L'\u1092';*/ //Add later; this is actually a typing issue, not a rendering one. case ZG_DASH: return L'\u200B'; case ZG_KINZI: return L'\u1064'; case ZG_STACK_KA: return L'\u1060'; case ZG_STACK_KHA: return L'\u1061'; case ZG_STACK_GA: return L'\u1062'; case ZG_STACK_GHA: return L'\u1063'; case ZG_STACK_NGA: return L'\u003F'; //It appears Zawgyi cannot stack "NGA" case ZG_STACK_SA: return L'\u1065'; case ZG_STACK_SSA: return L'\u1066'; case ZG_STACK_SSA_INDENT: return L'\u1067'; case ZG_STACK_ZA: return L'\u1068'; case ZG_STACK_ZHA: return L'\u1069'; case ZG_STACK_NYA: return L'\u003F'; //Can't stack "NYA" either case ZG_STACK_TTA: return L'\u106C'; case ZG_STACK_HTA1: return L'\u106D'; case ZG_STACK_DHA1: return L'\u003F'; //Appears we can't stack this either. case ZG_STACK_EXTRA: return L'\u003F'; //Appears we can't stack this either. case ZG_STACK_NHA: return L'\u1070'; case ZG_STACK_TA: return L'\u1071'; case ZG_STACK_TA_INDENT: return L'\u1072'; case ZG_STACK_HTA2: return L'\u1073'; case ZG_STACK_HTA2_INDENT: return L'\u1074'; case ZG_STACK_DDA: return L'\u1075'; case ZG_STACK_DHA2: return L'\u1076'; case ZG_STACK_NA: return L'\u1077'; case ZG_STACK_PA: return L'\u1078'; case ZG_STACK_PHA: return L'\u1079'; case ZG_STACK_VA: return L'\u107A'; case ZG_STACK_BA: return L'\u107B'; case ZG_STACK_MA: return L'\u107C'; case ZG_STACK_YA: return L'\u003F'; //Can't stack "ya" case ZG_STACK_LA: return L'\u1085'; case ZG_STACK_THA: return L'\u003F'; //Can't stack "tha" case ZG_STACK_A: return L'\u003F'; //Can't stack "a" case ZG_COMPLEX_1: return L'\u1092'; case ZG_COMPLEX_2: return L'\u1097'; case ZG_COMPLEX_3: return L'\u106E'; case ZG_COMPLEX_4: return L'\u106F'; case ZG_COMPLEX_5: return L'\u1096'; case ZG_COMPLEX_NA: return L'\u1091'; case ZG_TALL_WITH_ASAT: return L'\u105A'; case ZG_DOTTED_CIRCLE_ABOVE: return L'\u108E'; case ZG_LEGGED_CIRCLE_BELOW: return L'\u108A'; case ZG_LEGS_BOTH_WAYS: return L'\u1088'; case ZG_LEGS_OF_THREE: return L'\u1089'; case ZG_KINZI_102D: return L'\u108B'; case ZG_KINZI_102E: return L'\u108C'; case ZG_KINZI_1036: return L'\u108D'; case ZG_DOT_BELOW_SHIFT_1: return L'\u1094'; case ZG_DOT_BELOW_SHIFT_2: return L'\u1095'; case ZG_TALL_SINGLE_LEG: return L'\u1033'; case ZG_TALL_DOUBLE_LEG: return L'\u1034'; case ZG_YA_PIN_CUT: return L'\u107D'; case ZG_YA_PIN_SA: return L'\u1069'; case ZG_YA_YIT_LONG: return L'\u107E'; case ZG_YA_YIT_HIGHCUT: return L'\u107F'; case ZG_YA_YIT_LONG_HIGHCUT: return L'\u1080'; case ZG_YA_YIT_LOWCUT: return L'\u1081'; case ZG_YA_YIT_LONG_LOWCUT: return L'\u1082'; case ZG_YA_YIT_BOTHCUT: return L'\u1083'; case ZG_YA_YIT_LONG_BOTHCUT: return L'\u1084'; case ZG_LEG_FWD_SMALL: return L'\u1087'; case ZG_NA_CUT: return L'\u108F'; case ZG_YA_CUT: return L'\u1090'; case ZG_NYA_CUT: return L'\u106B'; case ZG_O_CUT: return L'\u106A'; default: return uniLetter; //Assume it's correct. } } //And finally, locale-driven nonsense with to_lower: template<class T> class ToLower { public: ToLower(const std::locale& loc):loc(loc) { } T operator()(const T& src) const { return std::tolower<T>(src, loc); } protected: const std::locale& loc; }; } //End of hidden namespace namespace waitzar { //TODO: This will sometimes append "\0" to a string for no apparent reason. // Try: U+1000 U+1037 // Need to fix eventually... std::wstring sortMyanmarString(const std::wstring &uniString) { //Count array for use with counting sort //We store a count, but we also need separate strings for the types. wstring res; int rhyme_flags[ID_TOTAL]; wchar_t rhyme_vals[ID_TOTAL]; size_t len = uniString.length(); wstring vow_above_buffer; wstring vow_below_buffer; wstring vow_ar_buffer; for (int res=0; res<ID_TOTAL; res++) { rhyme_flags[res] = 0; rhyme_vals[res] = 0x0000; } //Scan each letter //size_t destI = 0; //Allows us to eliminate duplicate letters size_t prevStop = 0; //What was our last-processed letter for (size_t i=0; i<=len;) { //We count up to the trailing 0x0 //Does this letter restart our algorithm? if (atStoppingPoint(uniString, i, len) || shouldRestartCount(uniString[i]) || getRhymeID(uniString[i])==-1) { //Now that we've counted, sort if (i!=prevStop) { for (int x=0; x<ID_TOTAL; x++) { //Add and restart for (int r_i=0; r_i <rhyme_flags[x]; r_i++) { wchar_t letter = rhyme_vals[x]; if (x==ID_VOW_ABOVE) letter = vow_above_buffer[r_i]; else if (x==ID_VOW_BELOW) letter = vow_below_buffer[r_i]; else if (x==ID_VOW_A) letter = vow_ar_buffer[r_i]; res += letter; } rhyme_flags[x] = 0; rhyme_vals[x] = 0x0000; } vow_above_buffer.clear(); vow_below_buffer.clear(); vow_ar_buffer.clear(); //vow_above_index = 0; //vow_below_index = 0; //vow_ar_index = 0; } //Increment if this is asat or virama res += uniString[i++]; while (i<len && (uniString[i]==0x103A||uniString[i]==0x1039||shouldRestartCount(uniString[i]))) res += uniString[i++]; //Don't sort until after this point prevStop = i; continue; } //Count, if possible. Else, copy in int rhymeID = getRhymeID(uniString[i]); rhyme_flags[rhymeID] += 1; rhyme_vals[rhymeID] = uniString[i]; if (rhymeID == ID_VOW_ABOVE) vow_above_buffer.push_back(uniString[i]); else if (rhymeID == ID_VOW_BELOW) vow_below_buffer.push_back(uniString[i]); else if (rhymeID == ID_VOW_A) vow_ar_buffer.push_back(uniString[i]); //Standard increment i++; } return res; } //TODO: Merge readUTF8File with this, and also clean up mymbstowcs string ReadBinaryFile(const string& path) { //Open the file, read-only, binary. FILE* userFile = fopen(path.c_str(), "rb"); if (userFile == NULL) throw std::runtime_error(std::string("File doesn't exist: " + path).c_str()); //File doesn't exist //Get file size fseek (userFile, 0, SEEK_END); long fileSize = ftell(userFile); rewind(userFile); //Read that file as a sequence of bytes char* buffer = new char[fileSize]; size_t buff_size = fread(buffer, 1, fileSize, userFile); fclose(userFile); if (buff_size==0) return ""; //Empty file //Done, clean up resources string res = string(buffer, fileSize); delete [] buffer; //And return return res; } //TODO: We should remove the BOM here; it's just a nuisance elsewhere. wstring readUTF8File(const string& path) { //Open the file, read-only, binary. FILE* userFile = fopen(path.c_str(), "rb"); if (userFile == NULL) throw std::runtime_error(std::string("File doesn't exist: " + path).c_str()); //File doesn't exist //Get file size fseek (userFile, 0, SEEK_END); long fileSize = ftell(userFile); rewind(userFile); //Read that file as a sequence of bytes char* buffer = new char[fileSize]; size_t buff_size = fread(buffer, 1, fileSize, userFile); fclose(userFile); if (buff_size==0) return L""; //Empty file //Finally, convert this array to unicode wchar_t * uniBuffer = new wchar_t[buff_size]; size_t numUniChars = mymbstowcs(NULL, buffer, buff_size); /*if (buff_size==numUniChars) { std::stringstream msg; msg <<"Error reading file. Buffer size: " <<buff_size << " , numUniChars: " <<numUniChars; throw std::runtime_error(msg.str().c_str()); //Conversion probably failed. }*/ //Not true! What about an ascii-only file? uniBuffer = new wchar_t[numUniChars]; // (wchar_t*) malloc(sizeof(wchar_t)*numUniChars); if (mymbstowcs(uniBuffer, buffer, buff_size)==0) throw std::runtime_error("Invalid UTF-8 characters in file."); //Invalid UTF-8 characters //Done, clean up resources wstring res = wstring(uniBuffer, numUniChars); delete [] buffer; delete [] uniBuffer; //And return return res; } wstring renderAsZawgyi(const wstring &uniString) { //Temp: if (uniString.empty()) return uniString; const std::wstring tab = L" "; Logger::writeLogLine('Z', tab + L"norm: {" + uniString + L"}"); //For now, just wrap a low-level data structure. // I want to re-write the entire algorithm to use // bitflags, so for now we'll just preserve the STL interface. wchar_t zawgyiStr[1000]; //Perform conversion //Step 1: Determine which finals won't likely combine; add // dashes beneath them. wchar_t prevLetter = 0x0000; wchar_t currLetter; int prevType = BF_OTHER; int currType; size_t destID = 0; size_t length = uniString.length(); for (size_t i=0; i<length; i++) { //Get the current letter and type currLetter = uniString[i]; currType = getBitflag(currLetter); //Match bool passed = true; if (currType!=BF_OTHER && currType!=BF_CONSONANT) { //Complex matching (simple ones will work with passed==true) if ((prevType&matchFlags[flag2id(currType)])==0) { //Handle kinzi if (currType==BF_STACKER && prevType==BF_ASAT && i>=2 && uniString[i-2]==0x1004) { //Store this two letters back destID-=2; //Kinzi might be considered a "stacker", but since nothing matches // against stacker in phase 1, it's not necessary. So we'll call it "other" currLetter = ZG_KINZI; currType = BF_OTHER; } else passed = false; } else { //Handle special cases if (currType==BF_ASAT && prevLetter==0x103C) passed = false; else if (currType==BF_STACKER && prevType==BF_CONSONANT) { if (prevLetter==0x1029 || prevLetter==0x103F) passed = false; } } } //Special case: U+1008 if (currLetter==0x1008) { zawgyiStr[destID++] = L'\u1005'; currLetter = L'\u103B'; } //Append it, and a dash if necessary //Don't dash our stack letter; it's not necessary if (!passed && currType!=BF_STACKER) zawgyiStr[destID++] = ZG_DASH; zawgyiStr[destID++] = currLetter; //Increment prevLetter = currLetter; prevType = currType; } zawgyiStr[destID] = 0x0000; Logger::writeLogLine('Z', tab + L"dash: {" + wstring(zawgyiStr, destID) + L"}"); //Step 2: Stack letters. This will only reduce the string's length, so // we can perform it in-place. destID = 0; length = wcslen(zawgyiStr); prevLetter = 0x0000; prevType = BF_OTHER; for (size_t i=0; i<length; i++) { //Special: skip "ghost letters" left from previous combines if (zawgyiStr[i]==0x0000) continue; //Get the current letter and type currLetter = zawgyiStr[i]; currType = getBitflag(currLetter); //Should we stack this? if (prevType==BF_STACKER && currType==BF_CONSONANT) { //Note: We must make an active check for letters with no stacked Zawgyi representation (0x003F) wchar_t stacked = getStackedVersion(currLetter); if (stacked!=0) { //General case int oldDestID = destID; if (zawgyiLetter(stacked)!=0x003F) { destID--; currLetter = stacked; } //Special cases (stacked) if (oldDestID>1) { if (stacked==ZG_STACK_HTA1 && zawgyiStr[oldDestID-2]==L'\u100B') { destID = oldDestID-2; currLetter = ZG_COMPLEX_1; } else if (stacked==ZG_STACK_TTA && zawgyiStr[oldDestID-2]==L'\u100B') { destID = oldDestID-2; currLetter = ZG_COMPLEX_2; } else if (stacked==ZG_STACK_DHA1 && zawgyiStr[oldDestID-2]==L'\u100F') { destID = oldDestID-2; currLetter = ZG_COMPLEX_NA; } else if (zawgyiStr[destID-2]==L'\u100D' && zawgyiStr[destID-1]==L'\u1039') { //There are a few letters without a rendering in Zawgyi that can stack specially. // So, the "if" block might look different for this one. if (zawgyiStr[destID]==L'\u100D') { destID -= 2; currLetter = ZG_COMPLEX_3; } else if (zawgyiStr[destID]==L'\u100E') { destID -= 2; currLetter = ZG_COMPLEX_4; } } } } } //Re-copy this letter zawgyiStr[destID++] = currLetter; //Increment prevType = currType; prevLetter = currLetter; } zawgyiStr[destID++] = 0x0000; Logger::writeLogLine('Z', tab + L"stck: {" + wstring(zawgyiStr, destID) + L"}"); //Step 3: Apply a series of specific rules if (matchRules.empty()) { //Add initial rules; do this manually for now //1-7 matchRules.push_back(new Rule(RULE_MODIFY, L'\u102F', 0x7FFE00000, L"\u1009\u1025\u100A", ZG_TALL_SINGLE_LEG)); matchRules.push_back(new Rule(RULE_MODIFY, L'\u1030', 0x7FFE00000, L"\u1009\u1025\u100A", ZG_TALL_DOUBLE_LEG)); matchRules.push_back(new Rule(RULE_COMBINE, L'\u102F', 0x180000, L"", ZG_LEGS_BOTH_WAYS)); matchRules.push_back(new Rule(RULE_COMBINE, L'\u1030', 0x180000, L"", ZG_LEGS_OF_THREE)); matchRules.push_back(new Rule(RULE_MODIFY, L'\u1037', 0x1580018C000, L"\u1014", ZG_DOT_BELOW_SHIFT_1)); matchRules.push_back(new Rule(RULE_MODIFY, L'\u1037', 0xA700E00000, L"\u101B", ZG_DOT_BELOW_SHIFT_2)); matchRules.push_back(new Rule(RULE_MODIFY, ZG_DOT_BELOW_SHIFT_1, 0xA700E00000, L"\u101B", ZG_DOT_BELOW_SHIFT_2)); matchRules.push_back(new Rule(RULE_COMBINE, L'\u103A', 0x8000, L"", ZG_TALL_WITH_ASAT)); //8 matchRules.push_back(new Rule(RULE_COMBINE, L'\u1036', 0x800, L"", ZG_DOTTED_CIRCLE_ABOVE)); //A new rule! Combine "stacked TA" with "circle below" matchRules.push_back(new Rule(RULE_COMBINE, ZG_STACK_TA, 0x400000, L"", ZG_COMPLEX_5)); //9-14 matchRules.push_back(new Rule(RULE_COMBINE, L'\u1036', 0x100, L"", ZG_KINZI_1036)); matchRules.push_back(new Rule(RULE_COMBINE, L'\u102D', 0x100, L"", ZG_KINZI_102D)); matchRules.push_back(new Rule(RULE_COMBINE, L'\u102E', 0x100, L"", ZG_KINZI_102E)); matchRules.push_back(new Rule(RULE_COMBINE, L'\u102E', 0, L"\u1025", L'\u1026')); matchRules.push_back(new Rule(RULE_MODIFY, L'\u103E', 0xFF000000, L"\u1020\u100A", ZG_LEG_FWD_SMALL)); matchRules.push_back(new Rule(RULE_COMBINE, L'\u103E', 0x400000, L"", ZG_LEGGED_CIRCLE_BELOW)); matchRules.push_back(new Rule(RULE_COMBINE, ZG_LEG_FWD_SMALL, 0x400000, L"", ZG_LEGGED_CIRCLE_BELOW)); matchRules.push_back(new Rule(RULE_ORDER, L'\u1036', 0xFF000000, L"", 0x0000)); //15-20 matchRules.push_back(new Rule(RULE_ORDER, L'\u103C', 0x7, L"", 0x0000)); matchRules.push_back(new Rule(RULE_ORDER, L'\u1031', 0x7, L"", 0x0000)); matchRules.push_back(new Rule(RULE_ORDER, L'\u1031', 0xFF000000, L"", 0x0000)); matchRules.push_back(new Rule(RULE_COMBINE, ZG_STACK_SA, 0x600000000, L"", ZG_YA_PIN_SA)); matchRules.push_back(new Rule(RULE_MODIFY, L'\u103C', 0x4, L"", ZG_YA_YIT_LONG)); matchRules.push_back(new Rule(RULE_MODIFY, L'\u103B', 0x100E00000, L"", ZG_YA_PIN_CUT)); //21-30 matchRules.push_back(new Rule(RULE_MODIFY, ZG_STACK_SSA, 0x2, L"", ZG_STACK_SSA_INDENT)); matchRules.push_back(new Rule(RULE_MODIFY, ZG_STACK_TA, 0x2, L"", ZG_STACK_TA_INDENT)); matchRules.push_back(new Rule(RULE_MODIFY, ZG_STACK_HTA2, 0x2, L"", ZG_STACK_HTA2_INDENT)); matchRules.push_back(new Rule(RULE_MODIFY, L'\u1014', 0x15F00F80000, L"", ZG_NA_CUT)); matchRules.push_back(new Rule(RULE_MODIFY, L'\u1009', 0x15800800000, L"\u103A", L'\u1025')); matchRules.push_back(new Rule(RULE_MODIFY, L'\u101B', 0x1800000000, L"", ZG_YA_CUT)); matchRules.push_back(new Rule(RULE_MODIFY, L'\u100A', 0x4000600000, L"", ZG_NYA_CUT)); matchRules.push_back(new Rule(RULE_MODIFY, L'\u1025', 0x800000, L"", ZG_O_CUT)); matchRules.push_back(new Rule(RULE_MODIFY, ZG_DOT_BELOW_SHIFT_1, 0x2000, L"", L'\u1037')); matchRules.push_back(new Rule(RULE_MODIFY, ZG_DOT_BELOW_SHIFT_2, 0x2000, L"", L'\u1037')); } Logger::writeLogLine('Z', tab + L"Begin Match"); //We maintain a series of offsets for the most recent match. This is used to speed up the process of // pattern matching. We only track the first occurrance, from left-to-right, of the given flag. //We scan from left-to-right, then apply rules from right-to-left breaking after each consonant. // A "minor break" occurs after each killed consonant, which is not tracked. "CONSONANT" always refers // to the main consonant. int firstOccurrence[S3_TOTAL_FLAGS]; uint64_t currMatchFlags = 0; for (size_t i=0; i<S3_TOTAL_FLAGS; i++) firstOccurrence[i] = -1; length = wcslen(zawgyiStr); size_t prevConsonant = 0; //int kinziCascade = 0; bool switchedKinziOnce = false; for (size_t i=0; i<=length; i++) { //Get properties on this letter wchar_t currLetter = zawgyiStr[i]; uint64_t currFlag = getStage3BitFlags(currLetter); int currFlagID = getStage3ID(currFlag); //Are we at a stopping point? //NOTE: kinzi occurs before the consonant for Unicode if ((!switchedKinziOnce && currLetter==ZG_KINZI) || isConsonant(currLetter) || i==length) { //First, scan for and fix "tall leg"s for (size_t x=i-1; x>=prevConsonant&&x<length; x--) { //Note: checking x<length is a very weird way of handling overflow (it works, though) if (zawgyiStr[x]==0x102F || zawgyiStr[x]==0x1030) { Rule *r = matchRules[zawgyiStr[x]-0x102F]; bool matches = ((r->match_flags&currMatchFlags)!=0); if (!matches) { for (size_t sID=0; sID<r->match_additional.length()&&!matches; sID++) { for (size_t zID=prevConsonant; zID<i && !matches; zID++) { if (zawgyiStr[zID]==r->match_additional[sID]) { matches = true; } } } } if (matches) { Logger::writeLogLine('Z', tab+tab + r->toString() + L" (pre)"); int currID = getStage3ID(getStage3BitFlags(zawgyiStr[x])); int replacementID = getStage3ID(getStage3BitFlags(r->replace)); if (currID!=-1) { currMatchFlags ^= getStage3BitFlags(zawgyiStr[x]); firstOccurrence[currID] = -1; } if (replacementID != -1) { currMatchFlags |= getStage3BitFlags(r->replace); firstOccurrence[replacementID] = x; } zawgyiStr[x] = r->replace; } } } //Apply our filters, from right-to-left wstringstream lLine; if ((i-1)<length) lLine <<L"Dealing with syllable from " <<(i-1) <<" to " <<prevConsonant; Logger::writeLogLine('Z', tab+tab + lLine.str()); for (size_t x=i-1; x>=prevConsonant&&x<length; x--) { bool resetRules = false; for (size_t ruleID=2; ruleID<matchRules.size(); ruleID++) { if (resetRules) { ruleID = 2; resetRules = false; } //Unfortunately, we have to apply ALL filters. Rule *r = matchRules[ruleID]; if (r->at_letter!=zawgyiStr[x]) continue; //First, match the input uint64_t matchRes = r->match_flags&currMatchFlags; int matchLoc = -1; if (matchRes==0) { bool foundAdditional = false; if (!r->match_additional.empty()) { for (size_t sID=0; sID<r->match_additional.length()&&!foundAdditional; sID++) { for (size_t zID=prevConsonant; zID<i && !foundAdditional; zID++) { if (zawgyiStr[zID]==r->match_additional[sID]) { matchLoc = zID; foundAdditional = true; } } } } if (!foundAdditional) continue; } else { //Where did it match? matchLoc = getStage3ID(matchRes); if (matchLoc!=-1) matchLoc = firstOccurrence[matchLoc]; } Logger::writeLogLine('Z', tab+tab + r->toString()); //Then, apply the rule. Make sure to keep our index array up-to-date //Note that protocol specifies that we DON'T re-scan for the next occurrence of a medial // after modifying or combining it. int matchResID = getStage3ID(matchRes); int replacementID = getStage3ID(getStage3BitFlags(r->replace)); int currID = getStage3ID(getStage3BitFlags(zawgyiStr[x])); bool checkMissingRules = false; switch (r->type) { case RULE_MODIFY: if (currID!=-1) { currMatchFlags ^= getStage3BitFlags(zawgyiStr[x]); firstOccurrence[currID] = -1; } if (replacementID != -1) { currMatchFlags |= getStage3BitFlags(r->replace); firstOccurrence[replacementID] = x; } zawgyiStr[x] = r->replace; //We now have to re-scan old rules checkMissingRules = true; break; case RULE_ORDER: { //With c+j+c+j, the second syllable doesn't trigger a match at all (Must be incrementing wrongly) if (matchLoc==-1) break; //Our rules shouldn't have this problem. if ((int)x<matchLoc) break; //Don't shift right if (r->blacklisted) break; //Avoid cycles wstringstream logLine; logLine <<L"shift sequence[" <<matchLoc <<".." <<x <<"] right 1, wrap around"; Logger::writeLogLine('Z', tab+tab+tab + logLine.str()); wchar_t prevLetter = zawgyiStr[x]; for (size_t repID=matchLoc; repID<=x; repID++) { int prevID = getStage3ID(getStage3BitFlags(prevLetter)); if (prevID!=-1) firstOccurrence[prevID] = repID; wchar_t cached = zawgyiStr[repID]; zawgyiStr[repID] = prevLetter; prevLetter = cached; } //We actually have to apply rules from the beginning, unfortunately. However, // we prevent an infinite cycle by blacklisting this rule until the next // consonant occurs. r->blacklisted = true; resetRules = true; break; } case RULE_COMBINE: if (matchLoc==-1) break; //Shouldn't exist if (matchResID!=-1) { currMatchFlags ^= matchRes; firstOccurrence[matchResID] = -1; } if (currID!=-1) { currMatchFlags ^= getStage3BitFlags(zawgyiStr[x]); firstOccurrence[currID] = -1; } if (replacementID != -1) { currMatchFlags |= getStage3BitFlags(r->replace); firstOccurrence[replacementID] = x; } zawgyiStr[matchLoc] = 0x0000; zawgyiStr[x] = r->replace; //We now have to re-scan old rules checkMissingRules = true; break; } //Double-check for missing rules if (checkMissingRules && /*TEMP*/false/*ENDTEMP*/ /*Logger::isLogging('L')*/) { for (size_t prevRule=2; prevRule < ruleID; prevRule++) { Rule *r = matchRules[prevRule]; if (r->at_letter==zawgyiStr[x] && ((r->match_flags&currMatchFlags)!=0) && !r->blacklisted) { matchLoc = -1; matchLoc = getStage3ID(r->match_flags&currMatchFlags); if (r->type==RULE_ORDER && (int)x<matchLoc) continue; //Special cases added as we detect them: //Dot below if (matchRules[ruleID]->at_letter==ZG_DOT_BELOW_SHIFT_1 || matchRules[ruleID]->at_letter==ZG_DOT_BELOW_SHIFT_2) continue; /*TODO: Re-enable logging wstringstream line; line <<L"WARNING: Rule " <<prevRule <<L" was skipped after matching rule " <<ruleID; Logger::writeLogLine('L', line.str());*/ } } } //Make sure our cached data is up-to-date //No! Bad Seth! /*currLetter = zawgyiStr[x]; currFlag = getStage3BitFlags(currLetter); currFlagID = getStage3ID(currFlag);*/ } } //Final special cases int yaYitID = firstOccurrence[getStage3ID(S3_MED_YA_YIT)]; bool yaLong = false; if (yaYitID==-1) { yaYitID = firstOccurrence[getStage3ID(S3_MED_YA_YIT_LONG)]; yaLong = true; } if (yaYitID != -1) { //111111110000 bool cutTop = false; bool cutBottom = false; if ((currMatchFlags&0xFF0)!=0) cutTop = true; if ((currMatchFlags&0x100E00000)!=0) cutBottom = true; wchar_t yaFinal = 'X'; if (yaLong) { if (cutTop) { if(cutBottom) yaFinal = ZG_YA_YIT_LONG_BOTHCUT; else yaFinal = ZG_YA_YIT_LONG_HIGHCUT; } else { if(cutBottom) yaFinal = ZG_YA_YIT_LONG_LOWCUT; else yaFinal = ZG_YA_YIT_LONG; } } else { if (cutTop) { if(cutBottom) yaFinal = ZG_YA_YIT_BOTHCUT; else yaFinal = ZG_YA_YIT_HIGHCUT; } else { if(cutBottom) yaFinal = ZG_YA_YIT_LOWCUT; else yaFinal = L'\u103C'; } } zawgyiStr[yaYitID] = yaFinal; std::wstringstream logline; logline <<L"YA at [" <<yaYitID <<L"], cut? " <<cutTop <<"T " <<cutBottom <<"B"; Logger::writeLogLine('Z', tab+tab + logline.str()); } //Is this a soft-stop or a hard stop? bool softStop = (i<length && zawgyiStr[i+1]==0x103A); currMatchFlags &= (S3_CONSONANT_NARROW|S3_CONSONANT_OTHER|S3_CONSONANT_WIDE); for (size_t x=0; x<S3_TOTAL_FLAGS; x++) { if (softStop && (x==S3_CONSONANT_NARROW || x==S3_CONSONANT_WIDE || x==S3_CONSONANT_OTHER)) continue; firstOccurrence[x] = -1; } if (!softStop) { //Special case: re-order "kinzi + consonant" on "kinzi" if (i+1<length && isConsonant(zawgyiStr[i+1]) && zawgyiStr[i]==ZG_KINZI && !switchedKinziOnce) { //if (i>0 && kinziCascade==0 && zawgyiStr[i-1]==ZG_KINZI && zawgyiStr[i]!=0x0000) { zawgyiStr[i] = zawgyiStr[i+1]; zawgyiStr[i+1] = ZG_KINZI; //i--; switchedKinziOnce = true; } //Reset our black-list. for (size_t rID=0; rID<matchRules.size(); rID++) matchRules[rID]->blacklisted = false; //Reeset letter & flags currLetter = zawgyiStr[i]; currFlag = getStage3BitFlags(currLetter); currFlagID = getStage3ID(currFlag); //Propagate if (currFlagID!=-1) { firstOccurrence[currFlagID] = i; currMatchFlags = currFlag; } else currMatchFlags = 0; //if (kinziCascade>0) // kinziCascade--; } prevConsonant = i; } else { //Just track this letter's location if (currFlagID!=-1) { if (firstOccurrence[currFlagID]==-1) firstOccurrence[currFlagID] = i; currMatchFlags |= currFlag; } //Allow kinzi to work again for the next letter if (currLetter==ZG_KINZI) switchedKinziOnce = false; //Fix some segmentation problems /*if (currLetter==L'\u200B') { //ZWS will _always_ reset everything prevConsonant = i; for (size_t itr=0; itr<S3_TOTAL_FLAGS; itr++) firstOccurrence[itr] = -1; currMatchFlags = 0; }*/ } } Logger::writeLogLine('Z', tab + L"End Match"); Logger::writeLogLine('Z', tab + L"mtch: {" + wstring(zawgyiStr, length) + L"}"); //Step 4: Convert each letter to its Zawgyi-equivalent //length = wcslen(zawgyiStr); //Keep embedded zeroes destID =0; for (size_t i=0; i<length; i++) { if (zawgyiStr[i]==0x0000 || zawgyiStr[i]==ZG_DASH) continue; zawgyiStr[destID++] = zawgyiLetter(zawgyiStr[i]); } zawgyiStr[destID++] = 0x0000; Logger::writeLogLine('Z', tab + L"subs: {" + wstring(zawgyiStr, destID) + L"}"); Logger::writeLogLine('Z', tab + L"Begin Re-Ordering"); //Stage 5: Apply rules for re-ordering the Zawgyi text to fit our weird model. length = wcslen(zawgyiStr); if (reorderPairs.size()==0) { reorderPairs.push_back(L"\u102F\u102D"); reorderPairs.push_back(L"\u103A\u102D"); reorderPairs.push_back(L"\u103D\u102D"); reorderPairs.push_back(L"\u1075\u102D"); reorderPairs.push_back(L"\u102D\u1087"); reorderPairs.push_back(L"\u103D\u102E"); reorderPairs.push_back(L"\u103D\u103A"); reorderPairs.push_back(L"\u1039\u103A"); reorderPairs.push_back(L"\u1030\u102D"); reorderPairs.push_back(L"\u1037\u1039"); reorderPairs.push_back(L"\u1032\u1037"); reorderPairs.push_back(L"\u1032\u1094"); reorderPairs.push_back(L"\u1064\u1094"); reorderPairs.push_back(L"\u102D\u1094"); reorderPairs.push_back(L"\u102D\u1071"); reorderPairs.push_back(L"\u1036\u1037"); reorderPairs.push_back(L"\u1036\u1088"); reorderPairs.push_back(L"\u1039\u1037"); reorderPairs.push_back(L"\u102D\u1033"); reorderPairs.push_back(L"\u103C\u1032"); reorderPairs.push_back(L"\u103C\u102D"); reorderPairs.push_back(L"\u103C\u102E"); reorderPairs.push_back(L"\u1036\u102F"); reorderPairs.push_back(L"\u1036\u1088"); reorderPairs.push_back(L"\u1036\u103D"); reorderPairs.push_back(L"\u1036\u103C"); reorderPairs.push_back(L"\u103C\u107D"); reorderPairs.push_back(L"\u1088\u102D"); reorderPairs.push_back(L"\u1039\u103D"); reorderPairs.push_back(L"\u108A\u107D"); reorderPairs.push_back(L"\u103A\u1064"); reorderPairs.push_back(L"\u1036\u1033"); } for (size_t i=1; i<length; i++) { //Apply stage-2 rules for (size_t ruleID=0; ruleID<reorderPairs.size(); ruleID++) { const wstring& rule = reorderPairs[ruleID]; if (zawgyiStr[i]==rule[0] && zawgyiStr[i-1]==rule[1]) { Logger::writeLogLine('Z', tab+tab + L"Order{" + wstring(rule) + L"}"); zawgyiStr[i-1] = rule[0]; zawgyiStr[i] = rule[1]; } } //Apply stage 3 fixed rules if (i>1) { if (zawgyiStr[i-2]==0x1019 && zawgyiStr[i-1]==0x102C && zawgyiStr[i]==0x107B) { Logger::writeLogLine('Z', tab+tab + L"Order{L3[1]}"); zawgyiStr[i-1]=0x107B; zawgyiStr[i]=0x102C; } if (zawgyiStr[i-2]==0x103A && zawgyiStr[i-1]==0x102D && zawgyiStr[i]==0x1033) { Logger::writeLogLine('Z', tab+tab + L"Order{L3[2]}"); zawgyiStr[i-1]=0x1033; zawgyiStr[i]=0x102D; } if (zawgyiStr[i-2]==0x103C && zawgyiStr[i-1]==0x1033 && zawgyiStr[i]==0x102D) { Logger::writeLogLine('Z', tab+tab + L"Order{L3[3]}"); zawgyiStr[i-1]=0x102D; zawgyiStr[i]=0x1033; } if (zawgyiStr[i-2]==0x103A && zawgyiStr[i-1]==0x1033 && zawgyiStr[i]==0x1036) { Logger::writeLogLine('Z', tab+tab + L"Order{L3[4]}"); zawgyiStr[i-1]=0x1036; zawgyiStr[i]=0x1033; } if (zawgyiStr[i-2]==0x103A && zawgyiStr[i-1]==0x108B && zawgyiStr[i]==0x1033) { Logger::writeLogLine('Z', tab+tab + L"Order{L3[5]}"); zawgyiStr[i-1]=0x1033; zawgyiStr[i]=0x108B; } //This one's a little different if (zawgyiStr[i]==0x1036 && zawgyiStr[i-2]==0x103C && zawgyiStr[i-1]==0x107D) { Logger::writeLogLine('Z', tab+tab + L"Order{L3[6]}"); zawgyiStr[i-2]=0x1036; zawgyiStr[i-1]=0x103C; zawgyiStr[i]=0x107D; } } //Apply stage 4 multi-rules if (i>2) { if (zawgyiStr[i-3]==0x1019 && ( (zawgyiStr[i-2]==0x107B && zawgyiStr[i-1]==0x1037 && zawgyiStr[i]==0x102C) ||(zawgyiStr[i-2]==0x102C && zawgyiStr[i-1]==0x107B && zawgyiStr[i]==0x1037) ||(zawgyiStr[i-2]==0x102C && zawgyiStr[i-1]==0x1037 && zawgyiStr[i]==0x107B) ||(zawgyiStr[i-2]==0x1037 && zawgyiStr[i-1]==0x107B && zawgyiStr[i]==0x102C) )) { Logger::writeLogLine('Z', tab+tab + L"Order{L4[1]}"); zawgyiStr[i-2]=0x107B; zawgyiStr[i-1]=0x102C; zawgyiStr[i]=0x1037; } if (zawgyiStr[i-3]==0x107E && zawgyiStr[i-1]==0x1033 && zawgyiStr[i]==0x1036) { Logger::writeLogLine('Z', tab+tab + L"Order{L4[2]}"); zawgyiStr[i-1]=0x1036; zawgyiStr[i]=0x1033; } } } Logger::writeLogLine('Z', tab + L"End Re-Ordering"); return wstring(zawgyiStr); } std::string escape_wstr(const std::wstring& str, bool errOnUnicode) { std::stringstream res; for (wstring::const_iterator c=str.begin(); c!=str.end(); c++) { //if (*c < std::numeric_limits<char>::max()) if (*c < 0x7F) //TODO: This might not be correct.. res << static_cast<char>(*c); else if (errOnUnicode) throw std::runtime_error("String contains unicode"); else res << "\\u" << std::hex << *c << std::dec; } return res.str(); } std::string wcs2mbs(const std::wstring& str) { std::stringstream res; for (wstring::const_iterator c=str.begin(); c!=str.end(); c++) { if (*c >= 0x0000 && *c <= 0x007F) res << static_cast<char>(*c); else if (*c >= 0x0080 && *c <= 0x07FF) { char c1 = (((*c)>>6)&0x1F) | 0xC0; char c2 = ((*c)&0x3F) | 0x80; res <<c1 <<c2; } else if (*c >= 0x0800 && *c <= 0xFFFF) { char c1 = (((*c)>>12)&0xF) | 0xE0; char c2 = (((*c)>>6)&0x3F) | 0x80; char c3 = ((*c)&0x3F) | 0x80; res <<c1 <<c2 <<c3; } else throw std::runtime_error("Unicode value out of range."); } return res.str(); } std::wstring mbs2wcs(const std::string& src) { std::wstringstream res; for (size_t i=0; i<src.size(); i++) { unsigned short curr = (src[i]&0xFF); if (((curr>>3)^0x1E)==0) { //We can't handle anything outside the BMP throw std::runtime_error("Error: mbs2wcs does not handle bytes outside the BMP"); } else if (((curr>>4)^0xE)==0) { //Verify the next two bytes if (i>=src.length()-2 || (((src[i+1]&0xFF)>>6)^0x2)!=0 || (((src[i+2]&0xFF)>>6)^0x2)!=0) throw std::runtime_error("Error: 2-byte character error in UTF-8 file"); //Combine all three bytes, check, increment wchar_t destVal = 0x0000 | ((curr&0xF)<<12) | ((src[i+1]&0x3F)<<6) | (src[i+2]&0x3F); if (destVal>=0x0800 && destVal<=0xFFFF) { i+=2; } else throw std::runtime_error("Error: 2-byte character error in UTF-8 file"); //Set res <<destVal; } else if (((curr>>5)^0x6)==0) { //Verify the next byte if (i>=src.length()-1 || (((src[i+1]&0xFF)>>6)^0x2)!=0) throw std::runtime_error("Error: 1-byte character error in UTF-8 file"); //Combine both bytes, check, increment wchar_t destVal = 0x0000 | ((curr&0x1F)<<6) | (src[i+1]&0x3F); if (destVal>=0x80 && destVal<=0x07FF) { i++; } else throw std::runtime_error("Error: 1-byte character error in UTF-8 file"); //Set res <<destVal; } else if ((curr>>7)==0) { wchar_t destVal = 0x0000 | curr; //Set res <<destVal; } else { throw std::runtime_error("Error: Unknown sequence in UTF-8 file"); } } return res.str(); } //Remove: // space_p, comment_p('#'), U+FEFF (BOM) std::wstring preparse_json(const std::wstring& str) { std::wstringstream res; for (size_t i=0; i<str.length(); i++) { //If you're on a whitespace/BOM, keep skipping until you reach non-whitespace. while (i<str.length() && (iswspace(str[i]) || str[i]==L'\uFEFF' || str[i]==L'\uFFFE')) i++; if (i>=str.length()) break; //If you're on a quote, read until the endquote (skip escapes) and append. (Then continue) //TODO: We can speed this up later, but for now it doesn't matter. if (str[i]==L'"') { size_t start = i++; while (i<str.length() && (str[i]!=L'"' || str[i-1]==L'\\')) //Skip \" too i++; res <<str.substr(start, i+1-start); //Note: even if this overruns the length of the string, it won't err. continue; } //If you're on a comment character, skip until the end of the line and continue if (str[i]==L'#') { while (i<str.length() && str[i]!=L'\n') //Skip until the end of the line; should skip \r too. i++; continue; } //Now, we know we're on a valid character. So keep reading until we encounter: // A double quote, a comment marker, or whitespace (BOMs won't occur more than once) // The end of the stream size_t start = i; while (i<str.length() && str[i]!=L'#' && !iswspace(str[i])) i++; res <<str.substr(start, i-start); } return res.str(); } //Removes some errors that typically occur in Burglish strings. A more solid normalization may be performed later. //Return the same string if unknown characters are encountered. //TODO: We also need to fix tall/short "ar". std::wstring normalize_bgunicode(const std::wstring& str) { //Unicode order goes something like this: //KINZI, CONSONANT, STACKED, ASAT, YA-PIN, YA-YIT, WA, HA, AY, "UPPER VOWEL", "LOWER VOWEL", AR, SLASH, DOT UP, DOT DOWN, ASAT, VIS //KINZI = \u1004\u103A\u1039 //CONSONANT = [\u1000..\u102A, \u103F, \u104E] //STACKED = \u1039 [\u1000..\u1019 \u101C, \u101E, \u1020, \u1021] //...exclusively for Myanmar. Now... we just have to flag each item, and avoid adding it twice. If something unknown // if found, return the orig. word. //This function is very fragile; we'll have to replace it with something better eventually. //We can assume kinzi & stacked letters aren't abused. Also consonant. wstringstream res; bool flags[] = {false,false,false,false,false,false,false,false,false,false,false,false,false}; size_t numFlags = 13; for (size_t i=0; i<str.size(); i++) { //First, skip stuff we don't care about if (str[i]==L'\u1004' && i+2<str.size() && str[i+1]==L'\u103A' && str[i+2]==L'\u1039') { //Kinzi, skip res <<L"\u1004\u103A\u1039"; i += 2; continue; } else if (str[i]==L'\u1039' && i+1<str.size()) { //Stacked letter, skip res <<str[i] <<str[i+1]; i += 1; continue; } else if ((str[i]>=L'\u1000' && str[i]<=L'\u102A') || str[i]==L'\u103F' || str[i]==L'\u104E') { //Consonant, skip res <<str[i]; //Also, reset our "flags" array so that multiple killed consants parse ok. for (size_t x=0; x<numFlags; x++) flags[x] = false; continue; } //Now, we're at some definite data. Skip duplicates, return early if we don't know this letter. int x=-1; //Use fallthrough to build up an array index, 0..12 (-1 is filtered by the default statement) switch (str[i]) { case L'\u103A': x++; case L'\u103B': x++; case L'\u103C': x++; case L'\u103D': x++; case L'\u103E': x++; case L'\u1031': x++; case L'\u102D': case L'\u102E': x++; case L'\u102F': case L'\u1030': x++; case L'\u102B': case L'\u102C': x++; case L'\u1032': x++; case L'\u1036': x++; case L'\u1037': x++; case L'\u1038': x++; break; default: return str; } //Check our ID anyway if (x<0 || x>=(int)numFlags) throw std::runtime_error("normalize_bgunicode id error!"); //Now, append the letter ONLY if this flag is false if (!flags[x]) { flags[x] = true; //Adjust one more letter (tall/short "AR") wchar_t toAppend = str[i]; if (toAppend==L'\u102C') { //We need to search backwards like so: //Continue on [\u1039\u1000 - \u1039\u1019 \u103E \u102F \u1030 \u103D \u1031 (but not \u103C)] //Stop on [\u1001 \u1002 \u1004 \u1012 \u1015 \u101D \u101D] //(We'll have to check this against the WZ wordlist eventually.). bool match = false; for (int si = ((int)i)-1;si>=0;si--) { //Simple letters if (str[si]==L'\u103E' || str[si]==L'\u102F' || str[si]==L'\u1030' || str[si]==L'\u103D' || str[si]==L'\u1031') continue; //Stacked letters if (str[si]>=L'\u1030' && str[si]<=L'\u1019') { if (si>=1 && str[si-1]==L'\u1039') { si--; continue; } else break; } //What we're searching for. if (str[si]==L'\u1001' || str[si]==L'\u1002' || str[si]==L'\u1004' || str[si]==L'\u1012' || str[si]==L'\u1015' || str[si]==L'\u101D' || str[si]==L'\u101D') { match = true; break; } //Else... (no match) break; } if (match) toAppend=L'\u102B'; } res <<toAppend; } } //Every test passed return res.str(); } //Add everything EXCEPT what's in the filterStr. std::wstring removeZWS(const std::wstring& str, const std::wstring& filterStr) { std::wstringstream res; for (size_t i=0; i<str.length(); i++) { if (filterStr.find(str[i])==wstring::npos) res <<str[i]; } return res.str(); } size_t count_letter(const std::wstring& str, wchar_t letter) { size_t res = 0; for (size_t i=0; i<str.length(); i++) { if (str[i]==letter) res++; } return res; } //Implementations of "glue" string glue(string str1, string str2, string str3, string str4) { std::stringstream msg; msg <<str1 <<str2 <<str3 <<str4; return msg.str(); } string glue(wstring str1, wstring str2, wstring str3, wstring str4) { return glue(escape_wstr(str1),escape_wstr(str2),escape_wstr(str3),escape_wstr(str4)); } wstring purge_filename(const wstring& str) { size_t lastSlash = str.rfind(L'\\'); if (lastSlash!=wstring::npos && lastSlash!=str.size()-1) return str.substr(lastSlash+1, wstring::npos); return str; } wstring sanitize_id(const wstring& str) { std::wstring res = str; //Copy out the "const"-ness. //res = std::wstring(res.begin(), std::remove_if(res.begin(), res.end(), is_id_delim<wchar_t>())); auto is_id_delim = [](wchar_t letter)->bool { if ((letter==' ')||(letter=='\t')||(letter=='\n')||(letter=='-')||(letter=='_')) return true; //Remove it return false; //Don't remove it }; res = std::wstring(res.begin(), std::remove_if(res.begin(), res.end(), is_id_delim)); loc_to_lower(res); //Operates in-place. return res; } bool read_bool(const std::wstring& str) { std::wstring test = str; loc_to_lower(test); if (test == L"yes" || test==L"true") return true; else if (test==L"no" || test==L"false") return false; else throw std::runtime_error(glue(std::wstring(L"Bad boolean value: \""), str, std::wstring(L"\"")).c_str()); } int read_int(const std::wstring& str) { //Read int resInt; std::wistringstream reader(str); reader >>resInt; //Problem? if (reader.fail()) { //TEMP throw std::runtime_error(glue(std::wstring(L"Bad integer value: \""), str, L"\"").c_str()); } //Done return resInt; } //Locale-aware "toLower" converter void loc_to_lower(wstring& str) { std::locale loc(""); //Get native locale std::transform(str.begin(),str.end(),str.begin(),ToLower<wchar_t>(loc)); } //Tokenize on a character //Inelegant, but it does what I want it to. vector<wstring> separate(wstring str, wchar_t delim) { vector<wstring> tokens; std::wstringstream curr; for (size_t i=0; i<str.length(); i++) { if (str[i]!=delim) curr << str[i]; if (str[i]==delim || i==str.length()-1) { tokens.push_back(curr.str()); curr.str(L""); } } return tokens; } //Take an educated guess as to whether or not this is a file. bool IsProbablyFile(const std::wstring& str) { //First, get the right-most "." size_t lastDot = str.rfind(L'.'); if (lastDot==wstring::npos) return false; //It's a file if there are between 1 and 4 characters after this dot int diff = str.size() - 1 - (int)lastDot; return (diff>=1 && diff<=4); } //Remove leading and trailing whitespace wstring sanitize_value(const wstring& str, const std::wstring& filePath) { //First, remove spurious spaces/tabs/newlines size_t firstLetter = str.find_first_not_of(L" \t\n"); size_t lastLetter = str.find_last_not_of(L" \t\n"); if (firstLetter==wstring::npos||lastLetter==wstring::npos) return L""; //Next, try to guess if this represents a file wstring res = str.substr(firstLetter, lastLetter-firstLetter+1); if (IsProbablyFile(res)) { //Replace all "/" with "\\" std::replace(res.begin(), res.end(), L'/', L'\\'); //Ensure it references no sub-directories whatsoever if (res.find(L'\\')!=wstring::npos) throw std::runtime_error("Config files cannot reference files outside their own directories."); //Append the directory (and a "\\" if needed) res = filePath + (filePath[filePath.size()-1]==L'\\'?L"":L"\\") + res; } return res; } INPUT_TYPE read_input_type(const wstring& str) { wstring key = sanitize_id(str); if (key==L"builtin") return INPUT_TYPE::BUILTIN; else if (key==L"keymagic") return INPUT_TYPE::KEYBOARD; else if (key==L"roman") return INPUT_TYPE::ROMAN; throw std::runtime_error(waitzar::glue(L"Unknown \"type\": ", str).c_str()); } DISPLAY_TYPE read_display_type(const wstring& str) { wstring key = sanitize_id(str); if (key==L"builtin") return DISPLAY_TYPE::BUILTIN; else if (key==L"png") return DISPLAY_TYPE::PNG; else if (key==L"ttf") return DISPLAY_TYPE::TTF; throw std::runtime_error(waitzar::glue(L"Unknown \"type\": ", str).c_str()); } TRANSFORM_TYPE read_transform_type(const wstring& str) { wstring key = sanitize_id(str); if (key==L"builtin") return TRANSFORM_TYPE::BUILTIN; else if (key==L"javascript") return TRANSFORM_TYPE::JAVASCRIPT; throw std::runtime_error(waitzar::glue(L"Unknown \"type\": ", str).c_str()); } CONTROL_KEY_TYPE read_control_key_style(const wstring& str) { wstring key = sanitize_id(str); if (key==L"chinese") return CONTROL_KEY_TYPE::CHINESE; else if (key==L"japanese") return CONTROL_KEY_TYPE::JAPANESE; throw std::runtime_error(waitzar::glue(L"Unknown \"control-key-style\": ", str).c_str()); } string GetMD5Hash(const std::string& fileName) { //Some variables const size_t digest_size = 16; md5_state_t state; md5_byte_t digest[digest_size]; //Get the file's binary data string data = waitzar::ReadBinaryFile(fileName); //Run the algorithm on the data md5_init(&state); md5_append(&state, (const md5_byte_t *)data.c_str(), data.size()); md5_finish(&state, digest); std::stringstream md5Res; md5Res <<std::hex; for (size_t i=0; i<digest_size; i++) { md5Res <<((digest[i]<0x10)?"0":"") <<(unsigned int)(digest[i]); } return md5Res.str(); } } //End waitzar namespace /* * 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. */
29.887698
163
0.622617
[ "vector", "model", "transform", "solid" ]
dda1cf88d0c28a259a3064ab265f9ff85e45d9c8
588
cpp
C++
Top_100_Liked/01-Two_Sum.cpp
authetic-x/LeetCode-Solution
5458b6bd2176246d4931aaf81faf8f69cae7b8ea
[ "MIT" ]
null
null
null
Top_100_Liked/01-Two_Sum.cpp
authetic-x/LeetCode-Solution
5458b6bd2176246d4931aaf81faf8f69cae7b8ea
[ "MIT" ]
null
null
null
Top_100_Liked/01-Two_Sum.cpp
authetic-x/LeetCode-Solution
5458b6bd2176246d4931aaf81faf8f69cae7b8ea
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* * Description: 给出一个数组,和一个目标值,返回数组中两个数之和 * 等于目标值的对应下标 * Key: 用unordered_map存储,遍历数组。 * Note: unorder_map为无序存储的map,效率更高 */ class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> mp; for (int i = 0; i < nums.size(); i ++ ) { auto p = mp.find(target-nums[i]); if (p != mp.end()) { return {p->second, i}; } mp[nums[i]] = i; } // 其实不需要这行语句,但leetcode编译通不过 return {0,1}; } };
23.52
55
0.518707
[ "vector" ]
ddab112231fa8a97048a77ffdc5f5dd4e4924129
6,728
cpp
C++
riptide_autonomy/src/object_describer.cpp
clabough2/riptide_software
3ac70fac9e2fb6a5a7f761939a9b5c401605ad27
[ "BSD-2-Clause" ]
1
2020-07-17T23:57:58.000Z
2020-07-17T23:57:58.000Z
riptide_autonomy/src/object_describer.cpp
clabough2/riptide_software
3ac70fac9e2fb6a5a7f761939a9b5c401605ad27
[ "BSD-2-Clause" ]
null
null
null
riptide_autonomy/src/object_describer.cpp
clabough2/riptide_software
3ac70fac9e2fb6a5a7f761939a9b5c401605ad27
[ "BSD-2-Clause" ]
1
2019-08-29T03:39:56.000Z
2019-08-29T03:39:56.000Z
#include "riptide_autonomy/object_describer.h" ObjectDescriber::ObjectDescriber(BeAutonomous *master) { this->master = master; } void ObjectDescriber::GetRouletteHeading(void (Roulette::*callback)(double), Roulette *object) { bbox_sub = master->nh.subscribe<darknet_ros_msgs::BoundingBoxes>("/task/bboxes", 1, &ObjectDescriber::BBoxCB, this); image_sub = master->nh.subscribe<sensor_msgs::Image>("/downward/image_undistorted", 1, &ObjectDescriber::ImageCB, this); rouletteCallbackFunction = callback; rouletteCallbackObject = object; rouletteImagesLeft = IMAGES_TO_SAMPLE; averageRouletteAngle = 0; } void ObjectDescriber::GetPathHeading(void (PathMarker::*callback)(double), PathMarker *object) { ROS_INFO("Get path"); if(pathImagesLeft == 0) { bbox_sub = master->nh.subscribe<darknet_ros_msgs::BoundingBoxes>("/task/bboxes", 1, &ObjectDescriber::BBoxCB, this); image_sub = master->nh.subscribe<sensor_msgs::Image>("/downward/image_undistorted", 1, &ObjectDescriber::ImageCB, this); pathCallbackFunction = callback; pathCallbackObject = object; pathImagesLeft = IMAGES_TO_SAMPLE; averagePathAngle = 0; } } void ObjectDescriber::ImageCB(const sensor_msgs::Image::ConstPtr &msg) { cv_bridge::CvImagePtr cv_ptr; try { // Use the BGR8 image_encoding for proper color encoding cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception &e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } lastImage = cv_ptr->image.clone(); } void ObjectDescriber::BBoxCB(const darknet_ros_msgs::BoundingBoxes::ConstPtr &bboxes) { if (lastImage.size().width != 0 && lastImage.size().height != 0) { darknet_ros_msgs::BoundingBox bbox = bboxes->bounding_boxes[0]; int64 width = bbox.xmax - bbox.xmin; int64 height = bbox.ymax - bbox.ymin; cv::Rect myROI(bbox.xmin, bbox.ymin, width, height); Mat cropped = lastImage(myROI); if (rouletteImagesLeft > 0) { Mat a; cropped.convertTo(a, CV_16S); Mat bgr[3]; //destination array split(a, bgr); //split source Mat values = bgr[0] + bgr[1]; double min, max; minMaxLoc(values, &min, &max); Mat g = ((values - min) / (max - min) * 255); g.convertTo(values, CV_8U); double maxRadius = std::min(width, height) / 2 - 1; double scores[180]; for (int angle = 0; angle < 180; angle++) { scores[angle] = 0; double radians = angle / 180.0 * 3.14159265; double dx = cos(radians); double dy = -sin(radians); for (int r = 0; r < maxRadius; r += 2) { int y = dy * r; int x = dx * r; scores[angle] += values.at<uchar>(height / 2 + y, width / 2 + x); scores[angle] += values.at<uchar>(height / 2 - y, width / 2 - x); } } int maxIndex = 0; int maxVal = 0; for (int i = 0; i < 180; i++) { int score = 0; for (int a = 0; a < 10; a++) { score += scores[(i + a) % 180]; score += scores[(i - a + 180) % 180]; } if (maxVal < score) { maxIndex = i; maxVal = score; } } double currentAverage = averageRouletteAngle / (IMAGES_TO_SAMPLE - rouletteImagesLeft); // Check for edge case where it goes from 1 degree to 179 degrees (-1 degrees) if (maxIndex - currentAverage > 90) maxIndex -= 180; else if (currentAverage - maxIndex > 90) maxIndex += 180; averageRouletteAngle += maxIndex; if (--rouletteImagesLeft == 0) { bbox_sub.shutdown(); image_sub.shutdown(); averageRouletteAngle /= IMAGES_TO_SAMPLE; if (averageRouletteAngle < 0) averageRouletteAngle += 180; if (averageRouletteAngle > 180) averageRouletteAngle -= 180; (rouletteCallbackObject->*rouletteCallbackFunction)(averageRouletteAngle); } } if (pathImagesLeft > 0) { Mat a; cropped.convertTo(a, CV_16S); Mat bgr[3]; //destination array split(a, bgr); //split source Mat values = bgr[2] - (bgr[0] + bgr[1]); double min, max; minMaxLoc(values, &min, &max); Mat g = ((values - min) / (max - min) * 255); g.convertTo(values, CV_8U); Scalar mean, dev; meanStdDev(values, mean, dev); threshold(values, values, mean[0] + dev[0] / 2, 255, 0); vector<vector<cv::Point>> contours; findContours(values, contours, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0)); vector<cv::Point> largestContour; int largestArea = 0; for (int c = 0; c < contours.size(); c++) { if (contourArea(contours[c]) > largestArea) { largestContour = contours[c]; largestArea = contourArea(contours[c]); } } vector<int> hull; convexHull(largestContour, hull); vector<Vec4i> defects; if (hull.size() > 3) // You need more than 3 indices { convexityDefects(largestContour, hull, defects); } Vec4i largestDefect; float largestDepth = 0; for (int i = 0; i < defects.size(); i++) { Vec4i v = defects[i]; float depth = v[3]; if (depth > largestDepth) // filter defects by depth, e.g more than 10 { largestDefect = v; largestDepth = depth; } } int startidx = largestDefect[0]; cv::Point ptStart(largestContour[startidx]); int endidx = largestDefect[1]; cv::Point ptEnd(largestContour[endidx]); double angle = atan2(ptStart.x - ptEnd.x, ptStart.y - ptEnd.y) / 3.1415926535897932384626433832795028841 * 180; double currentAverage = averagePathAngle / (IMAGES_TO_SAMPLE - pathImagesLeft); // Check for edge case where it goes from 1 degree to 179 degrees (-1 degrees) if (angle - currentAverage > 90) angle -= 180; else if (currentAverage - angle > 90) angle += 180; averagePathAngle += angle; if (--pathImagesLeft == 0) { bbox_sub.shutdown(); image_sub.shutdown(); averagePathAngle /= IMAGES_TO_SAMPLE; if (averagePathAngle < -180) averagePathAngle += 360; if (averagePathAngle > 180) averagePathAngle -= 360; (pathCallbackObject->*pathCallbackFunction)(averagePathAngle); } } } }
30.581818
125
0.582491
[ "object", "vector" ]
ddae84cce12384420199005b322a73277927b4bc
3,055
hpp
C++
source/modules/conduit/distributed/distributed.hpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
43
2018-07-26T07:20:42.000Z
2022-03-02T10:23:12.000Z
source/modules/conduit/distributed/distributed.hpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
212
2018-09-21T10:44:07.000Z
2022-03-22T14:33:05.000Z
source/modules/conduit/distributed/distributed.hpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
16
2018-07-25T15:00:36.000Z
2022-03-22T14:19:46.000Z
/** \namespace conduit * @brief Namespace declaration for modules of type: conduit. */ /** \file * @brief Header file for module: Distributed. */ /** \dir conduit/distributed * @brief Contains code, documentation, and scripts for module: Distributed. */ #pragma once #include "auxiliar/MPIUtils.hpp" #include "config.hpp" #include "modules/conduit/conduit.hpp" #include <map> #include <queue> #include <vector> namespace korali { namespace conduit { ; /** * @brief Class declaration for module: Distributed. */ class Distributed : public Conduit { public: /** * @brief Specifies the number of MPI ranks per Korali worker (k). */ int _ranksPerWorker; /** * @brief Obtains the entire current state and configuration of the module. * @param js JSON object onto which to save the serialized state of the module. */ void getConfiguration(knlohmann::json& js) override; /** * @brief Sets the entire state and configuration of the module, given a JSON object. * @param js JSON object from which to deserialize the state of the module. */ void setConfiguration(knlohmann::json& js) override; /** * @brief Applies the module's default configuration upon its creation. * @param js JSON object containing user configuration. The defaults will not override any currently defined settings. */ void applyModuleDefaults(knlohmann::json& js) override; /** * @brief Applies the module's default variable configuration to each variable in the Experiment upon creation. */ void applyVariableDefaults() override; /** * @brief ID of the current rank. */ int _rankId; /** * @brief Total number of ranks in execution */ int _rankCount; /** * @brief Number of Korali Teams in execution */ int _workerCount; /** * @brief Signals whether the worker has been assigned a team */ int _workerIdSet; /** * @brief Local ID the rank within its Korali Worker */ int _localRankId; /** * @brief Storage that contains the rank teams for each worker */ std::vector<std::vector<int>> _workerTeams; /** * @brief Map that indicates to which worker does the current rank correspond to */ std::vector<int> _rankToWorkerMap; /** * @brief Checks whether the number of MPI workers satisfies the requirement */ void checkRankCount(); void initServer() override; void initialize() override; void terminateServer() override; void stackEngine(Engine *engine) override; void popEngine() override; void listenWorkers() override; void broadcastMessageToWorkers(knlohmann::json &message) override; void sendMessageToEngine(knlohmann::json &message) override; knlohmann::json recvMessageFromEngine() override; void sendMessageToSample(Sample &sample, knlohmann::json &message) override; size_t getProcessId() override; /** * @brief Determines which rank is the root. * @return The rank id of the root rank. */ int getRootRank(); bool isRoot() override; bool isWorkerLeadRank() override; }; } //conduit } //korali ;
24.246032
119
0.706383
[ "object", "vector" ]
ddb068133e176df705013cfee932fa344cd405dc
820
cpp
C++
UVA/uva 11734.cpp
dipta007/Competitive-Programming
998d47f08984703c5b415b98365ddbc84ad289c4
[ "MIT" ]
6
2018-10-15T18:45:05.000Z
2022-03-29T04:30:10.000Z
UVA/uva 11734.cpp
dipta007/Competitive-Programming
998d47f08984703c5b415b98365ddbc84ad289c4
[ "MIT" ]
null
null
null
UVA/uva 11734.cpp
dipta007/Competitive-Programming
998d47f08984703c5b415b98365ddbc84ad289c4
[ "MIT" ]
4
2018-01-07T06:20:07.000Z
2019-08-21T15:45:59.000Z
#include<cstdio> #include<sstream> #include<cstdlib> #include<cctype> #include<cmath> #include<algorithm> #include<set> #include<queue> #include<stack> #include<list> #include<iostream> #include<fstream> #include<numeric> #include<string> #include<vector> #include<cstring> #include<map> #include<iterator> using namespace std; int main() { int t,i,k; char team[24],judge[24]; scanf("%d ",&t); for(i=1;i<=t;i++) { gets(team); gets(judge); k=strcmp(team,judge); if(k==0) cout << "Case " << i << ": Yes" << endl; else { if(strlen(team)>strlen(judge)) cout << "Case " << i << ": Output Format Error" << endl; else cout << "Case " << i << ": Wrong Answer" << endl; } } }
18.222222
72
0.530488
[ "vector" ]