hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
12e1ea4e39550673c30f59bd9bc947d4f9ffc50d
1,819
hpp
C++
ObjectHandler/Examples/ExampleObjects/Objects/accountobject.hpp
txu2014/quantlib
95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec
[ "BSD-3-Clause" ]
null
null
null
ObjectHandler/Examples/ExampleObjects/Objects/accountobject.hpp
txu2014/quantlib
95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec
[ "BSD-3-Clause" ]
null
null
null
ObjectHandler/Examples/ExampleObjects/Objects/accountobject.hpp
txu2014/quantlib
95c7d94906c30d0c3c4e0758a2ebfe2a62b075ec
[ "BSD-3-Clause" ]
1
2022-02-24T04:54:18.000Z
2022-02-24T04:54:18.000Z
/*! Copyright (C) 2004, 2005, 2006, 2007 Eric Ehlers This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #ifndef example_account_object_hpp #define example_account_object_hpp #include <oh/libraryobject.hpp> #include <ExampleObjects/Library/account.hpp> namespace AccountExample { class AccountObject : public ObjectHandler::LibraryObject<Account> { public: AccountObject( const boost::shared_ptr<ObjectHandler::ValueObject>& properties, const boost::shared_ptr<Customer>& customer, const Account::Type &type, const long &number, const double &balance, bool permanent) : ObjectHandler::LibraryObject<Account>(properties, permanent) { libraryObject_ = boost::shared_ptr<Account>( new Account(customer, type, number, balance)); } void setBalance(const double &balance) { libraryObject_->setBalance(balance); } const double &balance() { return libraryObject_->balance(); } std::string type() { return libraryObject_->type(); } }; } #endif
28.873016
78
0.672347
txu2014
12e2bbd0fd4211ed71f3ca599a3633bc077a2eee
2,292
hpp
C++
code/source/util/profiling.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
12
2015-01-12T00:19:20.000Z
2021-08-05T10:47:20.000Z
code/source/util/profiling.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
code/source/util/profiling.hpp
crafn/clover
586acdbcdb34c3550858af125e9bb4a6300343fe
[ "MIT" ]
null
null
null
#ifndef CLOVER_UTIL_PROFILING_HPP #define CLOVER_UTIL_PROFILING_HPP #include "build.hpp" #include "util/preproc_join.hpp" #include <thread> // No profiling on windows due to odd crashes with mingw 4.8.2 #define PROFILING_ENABLED (ATOMIC_PTR_READWRITE == true) namespace clover { namespace util { namespace detail { struct BlockInfo { const char* funcName; uint32 line; /// Don't assume that labels with same string will point to /// the same memory - depends on compiler optimizations const char* label; uint64 exclusiveMemAllocs; uint64 inclusiveMemAllocs; }; struct BlockProfiler { static BlockInfo createBlockInfo( const char* func, uint32 line, const char* label); BlockProfiler(BlockInfo& info); ~BlockProfiler(); }; struct StackJoiner { StackJoiner(); ~StackJoiner(); }; struct StackDetacher { StackDetacher(); ~StackDetacher(); }; void setSuperThread(std::thread::id super_id); } // detail /// Call in main() -- we don't want to see any impl defined pre-main stuff void tryEnableProfiling(); #if PROFILING_ENABLED /// Should be called on system memory allocation void profileSystemMemAlloc(); #else inline void profileSystemMemAlloc() {}; #endif } // util } // clover #if PROFILING_ENABLED /// Same as PROFILE but with a label #define PROFILE_(label)\ static util::detail::BlockInfo JOIN(profiler_block_info_, __LINE__)= \ util::detail::BlockProfiler::createBlockInfo( \ __PRETTY_FUNCTION__, \ __LINE__, \ label); \ util::detail::BlockProfiler JOIN(profiler_, __LINE__)(JOIN(profiler_block_info_, __LINE__)) /// Marks current block to be profiled #define PROFILE()\ PROFILE_(nullptr) /// Notifies profiler of a super thread #define PROFILER_SUPER_THREAD(thread_id)\ util::detail::setSuperThread(thread_id) /// Joins callstacks of this and super thread in current scope #define PROFILER_STACK_JOIN()\ util::detail::StackJoiner JOIN(stack_joiner_, __LINE__) /// Detaches callstacks of this and super thread in current scope #define PROFILER_STACK_DETACH()\ util::detail::StackDetacher JOIN(stack_detacher_, __LINE__) #else #define PROFILE_(label) #define PROFILE() #define PROFILER_SUPER_THREAD(thread_id) #define PROFILER_STACK_JOIN() #define PROFILER_STACK_DETACH() #endif #endif // CLOVER_UTIL_PROFILING_HPP
23.387755
92
0.756108
crafn
12e58bca092d23af2cab801bee2e0b6248e5d27d
7,949
cpp
C++
loginframe.cpp
mobile-pos/amp
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
[ "MIT" ]
6
2020-09-12T08:16:46.000Z
2020-11-19T04:05:35.000Z
loginframe.cpp
mobile-pos/amp
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
[ "MIT" ]
null
null
null
loginframe.cpp
mobile-pos/amp
efe4eb4fda1e6f1ad2ee6113c3bf0a9a61068763
[ "MIT" ]
2
2020-12-11T02:27:56.000Z
2021-11-18T02:15:01.000Z
#include "loginframe.h" #include <QLabel> #include <QLineEdit> #include <QDebug> #include <QCryptographicHash> #include <QMessageBox> #include "vkeyboardex.h" #include "datathread.h" #include "mainwindow.h" extern MainWindow* gWnd; /////////////////////////////////////////////////////////// /// \brief LoginFrame::LoginFrame /// \param parent /// LoginFrame::LoginFrame(QWidget *parent) : QFrame(parent) { this->setObjectName("loginWnd"); this->setStyleSheet("LoginFrame#loginWnd{ border-image: url(:/res/img/grass.jpg);}"); _layout = new GridLayoutEx(15, this); _layout->setObjectName("loginArea"); _layout->setStyleSheet("#loginArea{ background: gray;}"); _layout->setCellBord(0); //半透明设置 // _layout->setWindowFlags(Qt::FramelessWindowHint); // _layout->setAttribute(Qt::WA_TranslucentBackground); _layout->setWindowOpacity(0.5); _vkb = new VKeyboardEx(this); _vkb->setObjectName("virtualKB"); _vkb->setCellBord(0); _vkb->setStyleSheet("#virtualKB{ background: rgb(116, 122, 131);}"); init(); } LoginFrame::~LoginFrame() { } void LoginFrame::init() { /** +------------------------+ | title | | name: | | pwd : | |------------------------| | OK cancel | |------------------------| | virtual keyboard | +------------------------+ */ qDebug() << "LoginFrame::init"; //1行15个单元 { //title { QLabel* _l = new QLabel("", _layout); _layout->addWidget(_l, 3, 2); } { QLabel* _l = new POSLabelEx(QObject::tr("请登录"), _layout); // _l->setStyleSheet("background-color: rgb(80, 114, 165)"); _l->setAlignment(Qt::AlignCenter); _l->setObjectName("LoginTitle"); _layout->addWidget(_l, 10, 2); } { QLabel* _l = new QLabel("", _layout); _layout->addWidget(_l, 2, 2); } } { //输入用户名 { QLabel* _l = new POSLabelEx(QObject::tr("账号:"), _layout); _l->setAlignment(Qt::AlignRight |Qt::AlignCenter); _layout->addWidget(_l, 4, 2); } { LineEditEx* _e = new LineEditEx(_layout); this->connect(_e, SIGNAL(focussed(QWidget*, bool)), this, SLOT(focussed(QWidget*, bool))); _e->setPlaceholderText(QObject::tr("请输入账号")); _e->setObjectName("LoginAccout"); _e->setText("demoroot"); _layout->addWidget(_e, 10, 2, 1000); } { QLabel* _l = new QLabel("", _layout); _layout->addWidget(_l, 1, 2); } }{ //输入密码 { QLabel* _l = new POSLabelEx(QObject::tr("密码:"), _layout); _l->setAlignment(Qt::AlignRight |Qt::AlignCenter); _layout->addWidget(_l, 4, 2); } { LineEditEx* _e = new LineEditEx(_layout); this->connect(_e, SIGNAL(focussed(QWidget*, bool)), this, SLOT(focussed(QWidget*, bool))); _e->setEchoMode(QLineEdit::Password); _e->setPlaceholderText(QObject::tr("请输入密码")); _e->setObjectName("LoginPasswd"); _e->setText("1356@aiwaiter"); _layout->addWidget(_e, 10, 2, 1001); } { QLabel* _l = new QLabel("", _layout); _layout->addWidget(_l, 1, 2); } } { //空行 { QLabel* _l = new QLabel("", _layout); _layout->addWidget(_l, 15, 1); } } { { QLabel* _l = new QLabel("", _layout); _layout->addWidget(_l, 3, 2); } { VKeyItemButton* _btn = new VKeyItemButton("OK", this, _layout); _btn->setText(QObject::tr("点击登录")); _btn->setStyleSheet("background-color: rgb(80, 114, 165)"); _btn->setFocus(); _layout->addWidget(_btn, 3, 2); } { QLabel* _l = new QLabel("", _layout); _layout->addWidget(_l, 3, 2); } { VKeyItemButton* _btn = new VKeyItemButton("Cancel", this, _layout); _btn->setText(QObject::tr("重置")); _btn->setStyleSheet("background-color: rgb(80, 114, 165)"); _layout->addWidget(_btn, 3, 2); } { QLabel* _l = new QLabel("", _layout); _layout->addWidget(_l, 3, 2); } } { //空一行 { QLabel* _l = new QLabel("", _layout); _layout->addWidget(_l, 15, 1); } } { _vkb->init(0); _vkb->hide(); } qDebug() << "LoginFrame::init end"; } void LoginFrame::login(bool isAdmin) { QLabel* lab = dynamic_cast<QLabel*>( _layout->getItembyObjectName("LoginTitle") ); if(true == isAdmin) { lab->setText(tr("请管理员登陆")); } else { lab->setText(tr("请登陆")); } this->showMaximized(); } void LoginFrame::resizeEvent(QResizeEvent* e) { QFrame::resizeEvent(e); QRect rect = this->geometry(); int w = 400; int h = 200; QRect center( rect.width()/2 - w/2, rect.height() * 0.3 - h/2, w, h); _layout->setRowHeight(h/10); _layout->setGeometry(center); QRect lrect = _layout->geometry(); _vkb->setGeometry(lrect.left() - 100, lrect.bottom() + 5, lrect.width() + 200, rect.height() -lrect.bottom() - 30); } void LoginFrame::onKeyDown(const QString& value) { qDebug() << "onKeyDown: " << value; if( "Cancel" == value) { LineEditEx* _edit = dynamic_cast<LineEditEx*>(_layout->getItembyID(1000)); _edit->setText(""); _edit = dynamic_cast<LineEditEx*>(_layout->getItembyID(1001)); _edit->setText(""); } else if("OK" == value) { //调用登录接口 LineEditEx* _en = dynamic_cast<LineEditEx*>(dynamic_cast<LineEditEx*>(_layout->getItembyID(1000))); LineEditEx* _ep = dynamic_cast<LineEditEx*>(dynamic_cast<LineEditEx*>(_layout->getItembyID(1001))); QString name = _en->text(); QString pwd = _ep->text(); if(name == "") { _en->setPlaceholderText(QObject::tr("账号不能为空")); return; } if(pwd == "") { _en->setPlaceholderText(QObject::tr("密码不能为空")); return; } QString key = name + pwd; QString md5 = QString(QCryptographicHash::hash( key.toUtf8(),QCryptographicHash::Md5).toHex()); QVariantMap ret = DataThread::inst().login(name, md5); // //@Task Todo for test // ret["account"] = "r002"; // ret["id"] = 2; if(ret.empty() || 0 != ret["code"].toInt()) { QMessageBox::warning(this, "登录失败", QString("用户名或密码不对,请重试 或是网络异常: %1").arg(ret["msg"].toString())); gWnd->recordPOSEvent("login", "login failed, 用户名或密码不对,请重试 或是网络异常"); return; } if( ret["id"].toInt() != DataThread::inst().getRestaurantInfo()["rid"].toInt()) { QMessageBox::warning(this, "登录失败", "非本店账号不能登录"); gWnd->recordPOSEvent("login", "login failed, 非本店账号不能登录"); return; } DataThread::inst().setLogin(ret["account"].toString(), ret); _ep->setText(""); this->hide(); gWnd->Home(); gWnd->updateLoginInfo(); // if(0 != DataThread::inst().updateTables2Cloud()) { QMessageBox::warning(this, "出错", "更新桌台信息到云端失败,可能影响到扫码点餐"); } gWnd->recordPOSEvent("login", "login OK"); } } void LoginFrame::onVKeyDown(const QString& value) { qDebug() << "onVKeyDown: " << value; if("OK" == value) { } } void LoginFrame::focussed(QWidget* _this, bool hasFocus) { if(true == hasFocus) { LineEditEx* _edit = dynamic_cast<LineEditEx*>(_this); // _edit->setStyleSheet("background-color: red(255, 255, 255)"); _vkb->setTarget( _edit ); _vkb->show(); } else { _vkb->hide(); } }
29.550186
119
0.525349
mobile-pos
12ea62d0db69b61036a551c835420cfeb49ab506
3,229
cxx
C++
modules/ardrivo/test/Servo.cxx
platisd/group-09
a905c8c6409c0a3d73f53884e167571d8f482667
[ "Apache-2.0" ]
4
2020-06-02T16:01:10.000Z
2021-10-17T22:23:26.000Z
modules/ardrivo/test/Servo.cxx
platisd/group-09
a905c8c6409c0a3d73f53884e167571d8f482667
[ "Apache-2.0" ]
76
2020-04-03T09:15:45.000Z
2020-12-17T16:55:14.000Z
modules/ardrivo/test/Servo.cxx
platisd/group-09
a905c8c6409c0a3d73f53884e167571d8f482667
[ "Apache-2.0" ]
1
2020-06-02T15:52:31.000Z
2020-06-02T15:52:31.000Z
#include <catch2/catch.hpp> #include <range/v3/algorithm/for_each.hpp> #include "BoardDataDef.hxx" #include "Entrypoint.hxx" #include "Servo.h" static void init_fake() { if(board_data) (delete board_data), board_data = nullptr; if(board_info) (delete board_info), board_info = nullptr; auto loc_board_data = std::make_unique<BoardData>(); loc_board_data->interrupt_mut = std::make_unique<std::recursive_mutex>(); loc_board_data->pwm_values = std::vector<std::atomic_uint8_t>(255); auto loc_board_info = std::make_unique<BoardInfo>(); loc_board_info->pins_caps.resize(255); ranges::for_each(loc_board_info->pins_caps, [](PinCapability& pin) { pin.pwm_able = true; }); loc_board_info->pins_caps[2].pwm_able = false; init(loc_board_data.release(), loc_board_info.release()); } bool writtenSuccessful(Servo currentServo, int attchedPin, int expectWrittenValue) { return currentServo.read() == expectWrittenValue && board_data->pwm_values[attchedPin].load() == expectWrittenValue; } TEST_CASE("Attach pin", "[Attach]") { init_fake(); Servo test; test.attach(1); REQUIRE(test.attached()); // Attach pin out of the boundary test.detach(); board_data->silence_errors = true; test.attach(500); REQUIRE(!test.attached()); // Attach PWM-unable pin test.attach(2); REQUIRE(!test.attached()); board_data->silence_errors = false; REQUIRE_THROWS_AS(test.attach(500), std::runtime_error); REQUIRE_THROWS_AS(test.attach(2), std::runtime_error); } TEST_CASE("Attached", "[Attached]") { init_fake(); Servo test; REQUIRE(!test.attached()); test.attach(1); REQUIRE(test.attached()); } TEST_CASE("Detach pin", "[Detach]") { init_fake(); Servo test; test.attach(1); REQUIRE(test.attached()); test.detach(); REQUIRE(!test.attached()); } TEST_CASE("Write servo value", "[Write]") { init_fake(); Servo test; // Unattached case test.write(100); REQUIRE(test.read() == -1); // Attached cases test.attach(1); REQUIRE(test.attached()); test.write(100); // Inside boundary REQUIRE(writtenSuccessful(test, 1, 100)); test.write(-100); // Lower than boundary REQUIRE(writtenSuccessful(test, 1, 0)); test.write(1000); // Higher than boundary REQUIRE(writtenSuccessful(test, 1, 180)); } TEST_CASE("Write servo value as MicroSeconds", "[WriteMicroseconds]") { init_fake(); Servo test; // Unattached case test.write(1500); REQUIRE(test.read() == -1); // Attached cases test.attach(1); REQUIRE(test.attached()); test.writeMicroseconds(1500); // Inside boundary REQUIRE(writtenSuccessful(test, 1, 89)); test.writeMicroseconds(500); // Lower than boundary REQUIRE(writtenSuccessful(test, 1, 0)); test.writeMicroseconds(2500); // Higher than boundary REQUIRE(writtenSuccessful(test, 1, 179)); } TEST_CASE("Read servo value", "[Read]") { init_fake(); Servo test; // Unattached case test.write(90); REQUIRE(test.read() == -1); // Attached case test.attach(1); REQUIRE(test.attached()); test.write(90); REQUIRE(writtenSuccessful(test, 1, 90)); }
29.09009
120
0.663983
platisd
12eb3ee17b7645d9c852af55f8621a97b515b1e0
4,197
cpp
C++
hihope_neptune-oh_hid/00_src/v0.1/base/global/i18n_lite/frameworks/i18n/src/date_time_data.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
1
2022-02-15T08:51:55.000Z
2022-02-15T08:51:55.000Z
hihope_neptune-oh_hid/00_src/v0.1/base/global/i18n_lite/frameworks/i18n/src/date_time_data.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
hihope_neptune-oh_hid/00_src/v0.1/base/global/i18n_lite/frameworks/i18n/src/date_time_data.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "date_time_data.h" using namespace OHOS::I18N; using namespace std; DateTimeData::DateTimeData(const string &amPmMarkers, const char *sepAndHour, const int size) { this->amPmMarkers = amPmMarkers; // size must >= 2, The first 2 element of sepAndHour need to be extracted, the first element // is the time separator and the second is the default hour. if (sepAndHour && size >= 2) { timeSeparator = sepAndHour[0]; defaultHour = sepAndHour[1]; } } /** * split str with "_" */ string DateTimeData::Parse(const string &str, int32_t count) { if (str.empty()) { return ""; } int length = str.size(); int tempCount = 0; int ind = 0; while ((ind < length) && (tempCount < count)) { if (str.at(ind) == '_') { ++tempCount; } ++ind; } int last = ind; --ind; while (last < length) { if (str.at(last) == '_') { break; } ++last; } if (last - ind - 1 <= 0) { return ""; } return str.substr(ind + 1, last - ind - 1); } string DateTimeData::GetMonthName(int32_t index, DateTimeDataType type) { if ((index < 0) || (index >= MONTH_SIZE)) { return ""; } switch (type) { case DateTimeDataType::FORMAT_ABBR: { return Parse(formatAbbreviatedMonthNames, index); } case DateTimeDataType::FORMAT_WIDE: { return Parse(formatWideMonthNames, index); } case DateTimeDataType::STANDALONE_ABBR: { return Parse(standaloneAbbreviatedMonthNames, index); } default: { return Parse(standaloneWideMonthNames, index); } } } string DateTimeData::GetDayName(int32_t index, DateTimeDataType type) { if ((index < 0) || (index >= DAY_SIZE)) { return ""; } switch (type) { case DateTimeDataType::FORMAT_ABBR: { return Parse(formatAbbreviatedDayNames, index); } case DateTimeDataType::FORMAT_WIDE: { return Parse(formatWideDayNames, index); } case DateTimeDataType::STANDALONE_ABBR: { return Parse(standaloneAbbreviatedDayNames, index); } default: { return Parse(standaloneWideDayNames, index); } } } string DateTimeData::GetAmPmMarker(int32_t index, DateTimeDataType type) { if ((index < 0) || (index >= AM_SIZE)) { return ""; } return (amPmMarkers != "") ? Parse(amPmMarkers, index) : ""; } char DateTimeData::GetTimeSeparator(void) const { return timeSeparator; } char DateTimeData::GetDefaultHour(void) const { return defaultHour; } std::string DateTimeData::GetPattern(int32_t index, PatternType type) { switch (type) { case PatternType::HOUR_MINUTE_SECOND_PATTERN: { if ((index < 0) || (index >= HOUR_MINUTE_SECOND_PATTERN_SIZE)) { return ""; } return Parse(hourMinuteSecondPatterns, index); } case PatternType::REGULAR_PATTERN: { if ((index < 0) || (index >= REGULAR_PATTERN_SIZE)) { return ""; } return Parse(patterns, index); } default: { if ((index < 0) || (index >= FULL_MEDIUM_SHORT_PATTERN_SIZE)) { return ""; } return Parse(fullMediumShortPatterns, index); } } }
28.746575
97
0.573505
dawmlight
12ec1ed28f7742e603f70263f0fc5939e8d1c872
2,807
cpp
C++
moe/natj/natj/natj-cxxtests/src/test/native/binding/Functions.cpp
ark100/multi-os-engine
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
[ "Apache-2.0" ]
3
2016-08-25T03:26:16.000Z
2017-04-23T11:42:36.000Z
moe/natj/natj/natj-cxxtests/src/test/native/binding/Functions.cpp
ark100/multi-os-engine
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
[ "Apache-2.0" ]
1
2016-11-23T03:11:01.000Z
2016-11-23T03:11:01.000Z
moe/natj/natj/natj-cxxtests/src/test/native/binding/Functions.cpp
ark100/multi-os-engine
f71d66a58b3d7e5eb2a68541480b7a0d88c7b908
[ "Apache-2.0" ]
7
2016-09-10T02:19:04.000Z
2021-07-29T17:19:41.000Z
/* Copyright 2014-2016 Intel Corporation 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 "Functions.hpp" namespace ns_fn = natj::cxx::tests::binding::functions; void testFunctionSimple() { ns_fn::lastInvocation = ns_fn::FunctionID::SIMPLE; } namespace natj { namespace cxx { namespace tests { namespace binding { namespace functions { enum FunctionID lastInvocation = FunctionID::ILLEGAL; void testFunctionWhichHasAUniqueName() { lastInvocation = FunctionID::UNIQUENAME; } } } } } } void testFunctionLotsOfArgsTest1(int a, float b, long long c, bool d, double e) { __NATJ_ASSERT(a == 1); __NATJ_ASSERT(b == 3.5); __NATJ_ASSERT(c == 156); __NATJ_ASSERT(d == 0); __NATJ_ASSERT(e == 89165.4151); ns_fn::lastInvocation = ns_fn::FunctionID::TEST1; } void testFunctionLotsOfArgsTest2(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8, int p9, int p10, int p11, int p12, int p13, int p14, int p15, int p16, int p17, int p18, int p19, int p20, int p21, int p22, int p23, int p24, int p25, int p26, int p27, int p28, int p29, int p30, int p31, int p32, int p33, int p34, int p35, int p36, int p37, int p38, int p39, int p40, long long p41, int p42, int p43, int p44, int p45, int p46, int p47, int p48, int p49, int p50, int p51, int p52, int p53, int p54, int p55, int p56, int p57, int p58, int p59, int p60, int p61, int p62, int p63, int p64) { auto result = p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10 + p11 + p12 + p13 + p14 + p15 + p16 + p17 + p18 + p19 + p20 + p21 + p22 + p23 + p24 + p25 + p26 + p27 + p28 + p29 + p30 + p31 + p32 + p33 + p34 + p35 + p36 + p37 + p38 + p39 + p40 + p41 + p42 + p43 + p44 + p45 + p46 + p47 + p48 + p49 + p50 + p51 + p52 + p53 + p54 + p55 + p56 + p57 + p58 + p59 + p60 + p61 + p62 + p63 + p64; ns_fn::lastInvocation = ns_fn::FunctionID::TEST2; __NATJ_ASSERT(result == 2080); } void testThrowsIntegerException() { throw 20; }
41.279412
93
0.58746
ark100
12ec4045586b0a03ddb1f52dc847cd06f99b7244
7,183
cpp
C++
libgpopt/src/operators/CLogicalDynamicGet.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
1
2019-03-05T10:08:56.000Z
2019-03-05T10:08:56.000Z
libgpopt/src/operators/CLogicalDynamicGet.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
libgpopt/src/operators/CLogicalDynamicGet.cpp
khannaekta/gporca
94e509d0a2456851a2cabf02e933c3523946b87b
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2012 EMC Corp. // // @filename: // CLogicalDynamicGet.cpp // // @doc: // Implementation of dynamic table access //--------------------------------------------------------------------------- #include "gpos/base.h" #include "gpopt/base/CUtils.h" #include "gpopt/base/CConstraintInterval.h" #include "gpopt/base/CColRefSet.h" #include "gpopt/base/CPartIndexMap.h" #include "gpopt/base/CColRefSetIter.h" #include "gpopt/base/CColRefTable.h" #include "gpopt/base/COptCtxt.h" #include "gpopt/operators/CExpressionHandle.h" #include "gpopt/operators/CLogicalDynamicGet.h" #include "gpopt/metadata/CTableDescriptor.h" #include "gpopt/metadata/CName.h" using namespace gpopt; //--------------------------------------------------------------------------- // @function: // CLogicalDynamicGet::CLogicalDynamicGet // // @doc: // ctor - for pattern // //--------------------------------------------------------------------------- CLogicalDynamicGet::CLogicalDynamicGet ( IMemoryPool *pmp ) : CLogicalDynamicGetBase(pmp) { } //--------------------------------------------------------------------------- // @function: // CLogicalDynamicGet::CLogicalDynamicGet // // @doc: // ctor // //--------------------------------------------------------------------------- CLogicalDynamicGet::CLogicalDynamicGet ( IMemoryPool *pmp, const CName *pnameAlias, CTableDescriptor *ptabdesc, ULONG ulPartIndex, DrgPcr *pdrgpcrOutput, DrgDrgPcr *pdrgpdrgpcrPart, ULONG ulSecondaryPartIndexId, BOOL fPartial, CPartConstraint *ppartcnstr, CPartConstraint *ppartcnstrRel ) : CLogicalDynamicGetBase(pmp, pnameAlias, ptabdesc, ulPartIndex, pdrgpcrOutput, pdrgpdrgpcrPart, ulSecondaryPartIndexId, fPartial, ppartcnstr, ppartcnstrRel) { } //--------------------------------------------------------------------------- // @function: // CLogicalDynamicGet::CLogicalDynamicGet // // @doc: // ctor // //--------------------------------------------------------------------------- CLogicalDynamicGet::CLogicalDynamicGet ( IMemoryPool *pmp, const CName *pnameAlias, CTableDescriptor *ptabdesc, ULONG ulPartIndex ) : CLogicalDynamicGetBase(pmp, pnameAlias, ptabdesc, ulPartIndex) { } //--------------------------------------------------------------------------- // @function: // CLogicalDynamicGet::~CLogicalDynamicGet // // @doc: // dtor // //--------------------------------------------------------------------------- CLogicalDynamicGet::~CLogicalDynamicGet() { } //--------------------------------------------------------------------------- // @function: // CLogicalDynamicGet::UlHash // // @doc: // Operator specific hash function // //--------------------------------------------------------------------------- ULONG CLogicalDynamicGet::UlHash() const { ULONG ulHash = gpos::UlCombineHashes(COperator::UlHash(), m_ptabdesc->Pmdid()->UlHash()); ulHash = gpos::UlCombineHashes(ulHash, CUtils::UlHashColArray(m_pdrgpcrOutput)); return ulHash; } //--------------------------------------------------------------------------- // @function: // CLogicalDynamicGet::FMatch // // @doc: // Match function on operator level // //--------------------------------------------------------------------------- BOOL CLogicalDynamicGet::FMatch ( COperator *pop ) const { return CUtils::FMatchDynamicScan(this, pop); } //--------------------------------------------------------------------------- // @function: // CLogicalDynamicGet::PopCopyWithRemappedColumns // // @doc: // Return a copy of the operator with remapped columns // //--------------------------------------------------------------------------- COperator * CLogicalDynamicGet::PopCopyWithRemappedColumns ( IMemoryPool *pmp, HMUlCr *phmulcr, BOOL fMustExist ) { DrgPcr *pdrgpcrOutput = NULL; if (fMustExist) { pdrgpcrOutput = CUtils::PdrgpcrRemapAndCreate(pmp, m_pdrgpcrOutput, phmulcr); } else { pdrgpcrOutput = CUtils::PdrgpcrRemap(pmp, m_pdrgpcrOutput, phmulcr, fMustExist); } DrgDrgPcr *pdrgpdrgpcrPart = PdrgpdrgpcrCreatePartCols(pmp, pdrgpcrOutput, m_ptabdesc->PdrgpulPart()); CName *pnameAlias = GPOS_NEW(pmp) CName(pmp, *m_pnameAlias); m_ptabdesc->AddRef(); CPartConstraint *ppartcnstr = m_ppartcnstr->PpartcnstrCopyWithRemappedColumns(pmp, phmulcr, fMustExist); CPartConstraint *ppartcnstrRel = m_ppartcnstrRel->PpartcnstrCopyWithRemappedColumns(pmp, phmulcr, fMustExist); return GPOS_NEW(pmp) CLogicalDynamicGet(pmp, pnameAlias, m_ptabdesc, m_ulScanId, pdrgpcrOutput, pdrgpdrgpcrPart, m_ulSecondaryScanId, m_fPartial, ppartcnstr, ppartcnstrRel); } //--------------------------------------------------------------------------- // @function: // CLogicalDynamicGet::FInputOrderSensitive // // @doc: // Not called for leaf operators // //--------------------------------------------------------------------------- BOOL CLogicalDynamicGet::FInputOrderSensitive() const { GPOS_ASSERT(!"Unexpected function call of FInputOrderSensitive"); return false; } //--------------------------------------------------------------------------- // @function: // CLogicalDynamicGet::PxfsCandidates // // @doc: // Get candidate xforms // //--------------------------------------------------------------------------- CXformSet * CLogicalDynamicGet::PxfsCandidates ( IMemoryPool *pmp ) const { CXformSet *pxfs = GPOS_NEW(pmp) CXformSet(pmp); (void) pxfs->FExchangeSet(CXform::ExfDynamicGet2DynamicTableScan); return pxfs; } //--------------------------------------------------------------------------- // @function: // CLogicalDynamicGet::OsPrint // // @doc: // debug print // //--------------------------------------------------------------------------- IOstream & CLogicalDynamicGet::OsPrint ( IOstream &os ) const { if (m_fPattern) { return COperator::OsPrint(os); } else { os << SzId() << " "; // alias of table as referenced in the query m_pnameAlias->OsPrint(os); // actual name of table in catalog and columns os << " ("; m_ptabdesc->Name().OsPrint(os); os <<"), "; m_ppartcnstr->OsPrint(os); os << "), Columns: ["; CUtils::OsPrintDrgPcr(os, m_pdrgpcrOutput); os << "] Scan Id: " << m_ulScanId << "." << m_ulSecondaryScanId; if (!m_ppartcnstr->FUnbounded()) { os << ", "; m_ppartcnstr->OsPrint(os); } } return os; } //--------------------------------------------------------------------------- // @function: // CLogicalDynamicGet::PstatsDerive // // @doc: // Load up statistics from metadata // //--------------------------------------------------------------------------- IStatistics * CLogicalDynamicGet::PstatsDerive ( IMemoryPool *pmp, CExpressionHandle &exprhdl, DrgPstat * // not used ) const { CReqdPropRelational *prprel = CReqdPropRelational::Prprel(exprhdl.Prp()); IStatistics *pstats = PstatsDeriveFilter(pmp, exprhdl, prprel->PexprPartPred()); CColRefSet *pcrs = GPOS_NEW(pmp) CColRefSet(pmp, m_pdrgpcrOutput); CUpperBoundNDVs *pubndv = GPOS_NEW(pmp) CUpperBoundNDVs(pcrs, pstats->DRows()); CStatistics::PstatsConvert(pstats)->AddCardUpperBound(pubndv); return pstats; } // EOF
24.940972
174
0.540303
khannaekta
12ee154c18c8d7d109812ea326b135f82a7bdae4
6,486
cpp
C++
src/customprofession.cpp
jimhester/dwarftherapist
44b48fc87f07011d348be12b9abdf5206d54ba40
[ "MIT" ]
3
2015-03-21T00:24:13.000Z
2021-08-04T07:18:46.000Z
src/customprofession.cpp
jimhester/dwarftherapist
44b48fc87f07011d348be12b9abdf5206d54ba40
[ "MIT" ]
null
null
null
src/customprofession.cpp
jimhester/dwarftherapist
44b48fc87f07011d348be12b9abdf5206d54ba40
[ "MIT" ]
null
null
null
/* Dwarf Therapist Copyright (c) 2009 Trey Stout (chmod) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <QtGui> #include "customprofession.h" #include "gamedatareader.h" #include "ui_customprofession.h" #include "dwarf.h" #include "defines.h" #include "labor.h" #include "profession.h" /*! Default ctor. Creates a blank skill template with no name */ CustomProfession::CustomProfession(QObject *parent) : QObject(parent) , ui(new Ui::CustomProfessionEditor) , m_dwarf(0) , m_dialog(0) {} /*! When passed in a pointer to a Dwarf, this new custom profession will adopt whatever labors that Dwarf has enabled as its own template. This is used by the "Create custom profession from this dwarf..." action. \param[in] d The Dwarf to use as a labor template \param[in] parent The Qt owner of this object */ CustomProfession::CustomProfession(Dwarf *d, QObject *parent) : QObject(parent) , ui(new Ui::CustomProfessionEditor) , m_dialog(0) , m_dwarf(d) { GameDataReader *gdr = GameDataReader::ptr(); QList<Labor*> labors = gdr->get_ordered_labors(); foreach(Labor *l, labors) { if (m_dwarf && m_dwarf->labor_enabled(l->labor_id) && l->labor_id != -1) add_labor(l->labor_id); } } /*! Change the enabled status of a template labor. This doesn't affect any dwarves using this custom profession, only the template itself. \param[in] labor_id The id of the labor to change \param[in] active Should the labor be enabled or not */ void CustomProfession::set_labor(int labor_id, bool active) { if (m_active_labors.contains(labor_id) && !active) m_active_labors.remove(labor_id); if (active) m_active_labors.insert(labor_id, true); } /*! Check if the template has a labor enabled \param[in] labor_id The id of the labor to check \returns true if this labor is enabled */ bool CustomProfession::is_active(int labor_id) { return m_active_labors.value(labor_id, false); } /*! Get a vector of all enabled labors in this template by labor_id */ QVector<int> CustomProfession::get_enabled_labors() { QVector<int> labors; foreach(int labor, m_active_labors.uniqueKeys()) { if (m_active_labors.value(labor) && labor != -1) { labors << labor; } } return labors; } /*! Pops up a dialog box asking for a name for this object as well as a list of labors that can be enabled/disabled via checkboxes \param[in] parent If set, the dialog will launch as a model under parent \returns QDialog::exec() result (int) */ int CustomProfession::show_builder_dialog(QWidget *parent) { GameDataReader *gdr = GameDataReader::ptr(); m_dialog = new QDialog(parent); ui->setupUi(m_dialog); ui->name_edit->setText(m_name); connect(ui->name_edit, SIGNAL(textChanged(const QString &)), this, SLOT(set_name(QString))); connect(ui->buttonBox, SIGNAL(accepted()), this, SLOT(accept())); QList<Labor*> labors = gdr->get_ordered_labors(); int num_active = 0; foreach(Labor *l, labors) { if (l->is_weapon) continue; QListWidgetItem *item = new QListWidgetItem(l->name, ui->labor_list); item->setData(Qt::UserRole, l->labor_id); item->setFlags(item->flags() | Qt::ItemIsUserCheckable); if (is_active(l->labor_id)) { item->setCheckState(Qt::Checked); num_active++; } else { item->setCheckState(Qt::Unchecked); } ui->labor_list->addItem(item); } connect(ui->labor_list, SIGNAL(itemChanged(QListWidgetItem*)), this, SLOT(item_check_state_changed(QListWidgetItem*))); ui->lbl_skill_count->setNum(num_active); int code = m_dialog->exec(); m_dialog->deleteLater(); return code; } /*! Called when the show_builder_dialog widget's OK button is pressed, or the dialog is otherwise accepted by the user We intercept this call to verify the form is valid before saving it. \sa is_valid() */ void CustomProfession::accept() { if (!is_valid()) { return; } m_dialog->accept(); } /*! Called after the show_builder_dialog widget is accepted, used to verify that the CustomProfession has all needed information to save \returns true if this instance is ok to save. */ bool CustomProfession::is_valid() { if (!m_dialog) return true; QString proposed_name = ui->name_edit->text(); if (proposed_name.isEmpty()) { QMessageBox::warning(m_dialog, tr("Naming Error!"), tr("You must enter a name for this custom profession!")); return false; } /* Let's not do this... QHash<short, Profession*> profs = GameDataReader::ptr()->get_professions(); foreach(Profession *p, profs) { if (proposed_name == p->name(true)) { QMessageBox::warning(m_dialog, tr("Naming Error!"), tr("The profession '%1' is a default game profession, please choose a different name.").arg(proposed_name)); return false; } } */ return true; } void CustomProfession::item_check_state_changed(QListWidgetItem *item) { if (item->checkState() == Qt::Checked) { add_labor(item->data(Qt::UserRole).toInt()); ui->lbl_skill_count->setNum(ui->lbl_skill_count->text().toInt() + 1); } else { remove_labor(item->data(Qt::UserRole).toInt()); ui->lbl_skill_count->setNum(ui->lbl_skill_count->text().toInt() - 1); } } void CustomProfession::delete_from_disk() { QSettings s(QSettings::IniFormat, QSettings::UserScope, COMPANY, PRODUCT, this); s.beginGroup("custom_professions"); s.remove(m_name); s.endGroup(); }
30.739336
113
0.707524
jimhester
12ef742d3c9a363edfe3a16ac10836266ef09723
6,179
cpp
C++
visualization/determinant/determinant.cpp
mika314/simuleios
0b05660c7df0cd6e31eb5e70864cbedaec29b55a
[ "MIT" ]
197
2015-07-26T02:04:17.000Z
2022-01-21T11:53:33.000Z
visualization/determinant/determinant.cpp
shiffman/simuleios
57239350d2cbed10893483bda65fa323e5e3a06d
[ "MIT" ]
18
2015-08-04T22:55:46.000Z
2020-11-06T02:33:48.000Z
visualization/determinant/determinant.cpp
shiffman/simuleios
57239350d2cbed10893483bda65fa323e5e3a06d
[ "MIT" ]
55
2015-08-02T21:43:18.000Z
2021-12-13T18:25:08.000Z
/*-------------determinant.cpp------------------------------------------------// * * Purpose: Simple multiplication to help visualize eigenvectors * * Notes: compile with: * g++ -I /usr/include/eigen3/ eigentest.cpp -Wno-ignored-attributes -Wno-deprecated-declarations * *-----------------------------------------------------------------------------*/ #include <iostream> #include <Eigen/Core> #include <vector> #include <fstream> using namespace Eigen; int main(){ // Opening file to writing std::ofstream output; output.open("out.dat"); int size = 2, count=0; // setting up positions of all the desired points to transform double x[size*size*size], y[size*size*size], z[size*size*size], x2[size*size*size], y2[size*size*size], z2[size*size*size], xval = -1, yval = -1, zval = -1; MatrixXd Arr(3, 3); MatrixXd pos(3, 1); // Putting in "random" values for matrix Arr << 1, 2, 0, 2, 1, 0, 0, 0, -3; /* Arr << 1, 0, 0, 0, 1, 0, 0, 0, 1; */ std::cout << Arr << '\n'; // Creating initial x, y, and z locations for (int i = 0; i < size; ++i){ for (int j = 0; j < size; ++j){ for (int k = 0; k < size; ++k){ xval = -1 + 2 * ((double)i / ((double)size - 1)); yval = -1 + 2 * ((double)j / ((double)size - 1)); zval = -1 + 2 * ((double)k / ((double)size - 1)); x[count] = xval; y[count] = yval; z[count] = zval; // Performing multiplication / setting up vector pos(0) = xval; pos(1) = yval; pos(2) = zval; pos = Arr * pos; // Storing values in x2, y2, and z2 x2[count] = pos(0); y2[count] = pos(1); z2[count] = pos(2); count += 1; } } } count = 8; for (int i = 0; i < count; ++i){ std::cout << x[i] << '\t' << y[i] << '\t' << z[i] << '\n'; pos(0) = x[i]; pos(1) = y[i]; pos(2) = z[i]; pos = Arr * pos; // Storing values in x2, y2, and z2 x2[i] = pos(0); y2[i] = pos(1); z2[i] = pos(2); } /* // Creating initial x, y, and z locations for (int i = 0; i < size; ++i){ for (int j = 0; j < size; ++j){ for (int k = 0; k < size; ++k){ xval = -1 + 2 * ((double)i / (double)size); yval = -1 + 2 * ((double)j / (double)size); zval = -1 + 2 * ((double)k / (double)size); x[count] = xval; y[count] = yval; z[count] = zval; // Performing multiplication / setting up vector pos(0) = xval; pos(1) = yval; pos(2) = zval; pos = Arr * pos; // Storing values in x2, y2, and z2 x2[count] = pos(0); y2[count] = pos(1); z2[count] = pos(2); count += 1; } } } // Writing to file in correct format count = 0; for (int i = 0; i < size; ++i){ for (int j = 0; j < size; ++j){ for (int k = 0; k < size; ++k){ output << x[count] << '\t' << y[count] << '\t' << z[count] << '\t' << count << '\n'; count++; } } } output << '\n' << '\n'; count = 0; for (int i = 0; i < size; ++i){ for (int j = 0; j < size; ++j){ for (int k = 0; k < size; ++k){ output << x2[count] << '\t' << y2[count] << '\t' << z2[count] << '\t' << count << '\n'; count++; } } } */ int frames = 60; count = 0; double xvel[size*size*size], yvel[size*size*size], zvel[size*size*size]; double vid_time = 1.0; count = 8; for (int i = 0; i < count; ++i){ xvel[i] = (x[i] - x2[i]) / vid_time; yvel[i] = (y[i] - y2[i]) / vid_time; zvel[i] = (z[i] - z2[i]) / vid_time; } for (int f = 0; f < frames; ++f){ for (int i = 0; i < count; ++i){ xval = x[i] + ((x2[i] - x[i]) * ((double)f / (double)frames)); yval = y[i] + ((y2[i] - y[i]) * ((double)f / (double)frames)); zval = z[i] + ((z2[i] - z[i]) * ((double)f / (double)frames)); output << xval << '\t' << yval << '\t' << zval << '\t' << xvel[i] << '\t' << yvel[i] << '\t' << zvel[i] << '\t' << 1 << '\t' << i << '\n'; } output << '\n' << '\n'; } /* for (int i = 0; i < size; ++i){ for (int j = 0; j < size; ++j){ for (int k = 0; k < size; ++k){ xvel[count] = (x[count] - x2[count]) / vid_time; yvel[count] = (y[count] - y2[count]) / vid_time; zvel[count] = (z[count] - z2[count]) / vid_time; count = count + 1; } } } for (int f = 0; f < frames; ++f){ count = 0; for (int i = 0; i < size; ++i){ for (int j = 0; j < size; ++j){ for (int k = 0; k < size; ++k){ xval = x[count] + ((x2[count] - x[count]) * ((double)f / (double)frames)); yval = y[count] + ((y2[count] - y[count]) * ((double)f / (double)frames)); zval = z[count] + ((z2[count] - z[count]) * ((double)f / (double)frames)); output << xval << '\t' << yval << '\t' << zval << '\t' << xvel[count] << '\t' << yvel[count] << '\t' << zvel[count] << '\t' << 1 << '\t' << count << '\n'; count++; } } } output << '\n' << '\n'; } */ output.close(); }
29.564593
107
0.362195
mika314
12f20952bf329e98c0583356186b08930a02c495
4,514
hpp
C++
include/GlobalNamespace/BeatmapEditorSceneSetupData.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/BeatmapEditorSceneSetupData.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/BeatmapEditorSceneSetupData.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: SceneSetupData #include "GlobalNamespace/SceneSetupData.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: namespace GlobalNamespace { // Size: 0x20 #pragma pack(push, 1) // Autogenerated type: BeatmapEditorSceneSetupData // [TokenAttribute] Offset: FFFFFFFF class BeatmapEditorSceneSetupData : public GlobalNamespace::SceneSetupData { public: // private System.String _levelDirPath // Size: 0x8 // Offset: 0x10 ::Il2CppString* levelDirPath; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // private System.String _levelAssetPath // Size: 0x8 // Offset: 0x18 ::Il2CppString* levelAssetPath; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // Creating value type constructor for type: BeatmapEditorSceneSetupData BeatmapEditorSceneSetupData(::Il2CppString* levelDirPath_ = {}, ::Il2CppString* levelAssetPath_ = {}) noexcept : levelDirPath{levelDirPath_}, levelAssetPath{levelAssetPath_} {} // Get instance field reference: private System.String _levelDirPath ::Il2CppString*& dyn__levelDirPath(); // Get instance field reference: private System.String _levelAssetPath ::Il2CppString*& dyn__levelAssetPath(); // public System.String get_levelDirPath() // Offset: 0x11EB008 ::Il2CppString* get_levelDirPath(); // public System.String get_levelAssetPath() // Offset: 0x11EB010 ::Il2CppString* get_levelAssetPath(); // public System.Void .ctor(System.String levelDirPath, System.String levelAssetPath) // Offset: 0x11EB018 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static BeatmapEditorSceneSetupData* New_ctor(::Il2CppString* levelDirPath, ::Il2CppString* levelAssetPath) { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::BeatmapEditorSceneSetupData::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<BeatmapEditorSceneSetupData*, creationType>(levelDirPath, levelAssetPath))); } }; // BeatmapEditorSceneSetupData #pragma pack(pop) static check_size<sizeof(BeatmapEditorSceneSetupData), 24 + sizeof(::Il2CppString*)> __GlobalNamespace_BeatmapEditorSceneSetupDataSizeCheck; static_assert(sizeof(BeatmapEditorSceneSetupData) == 0x20); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::BeatmapEditorSceneSetupData*, "", "BeatmapEditorSceneSetupData"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::BeatmapEditorSceneSetupData::get_levelDirPath // Il2CppName: get_levelDirPath template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::BeatmapEditorSceneSetupData::*)()>(&GlobalNamespace::BeatmapEditorSceneSetupData::get_levelDirPath)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapEditorSceneSetupData*), "get_levelDirPath", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::BeatmapEditorSceneSetupData::get_levelAssetPath // Il2CppName: get_levelAssetPath template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (GlobalNamespace::BeatmapEditorSceneSetupData::*)()>(&GlobalNamespace::BeatmapEditorSceneSetupData::get_levelAssetPath)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::BeatmapEditorSceneSetupData*), "get_levelAssetPath", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::BeatmapEditorSceneSetupData::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
55.728395
208
0.746566
Fernthedev
12f215192f86742dedb82ba99afe65550028fa23
886
cpp
C++
mcomp_C/common/datatypes/path/Path.cpp
kasmaslrn/MCOMP_Team_Project_2017-2018
5e20c49c0d7a30083944ddc71ed9d595783a12a5
[ "MIT" ]
1
2019-03-18T14:27:46.000Z
2019-03-18T14:27:46.000Z
mcomp_C/common/datatypes/path/Path.cpp
kasmaslrn/MCOMP_Team_Project_2017-2018
5e20c49c0d7a30083944ddc71ed9d595783a12a5
[ "MIT" ]
null
null
null
mcomp_C/common/datatypes/path/Path.cpp
kasmaslrn/MCOMP_Team_Project_2017-2018
5e20c49c0d7a30083944ddc71ed9d595783a12a5
[ "MIT" ]
null
null
null
/* * mcomp_C.ino * * Created on: 26 Nov 2017 * Author: David Avery 15823926 * */ #include "Path.h" #include "../Waypoint.h" int length; Path::Path(Waypoint w) { destination = new LinkedItem(w); head = nullptr; lastItem = nullptr; length = 0; } Path::~Path() { // TODO Auto-generated destructor stub } void Path::addNode(Waypoint w) { if (length > 0) { (*lastItem).setNext(new LinkedItem(w)); lastItem = (*lastItem).getNext(); } else { head = new LinkedItem(w); lastItem = head; } length++; } Waypoint Path::poll() { Waypoint res = (*destination).getData(); if (length > 0) { res = (*head).getData(); head = (*head).getNext(); if (head == nullptr) { lastItem = nullptr; } length--; } return res; } int Path::getLength() { return length; }
15.821429
44
0.544018
kasmaslrn
12f3fcf8b2653271ac4021d0de49448b66472c07
17,881
cpp
C++
OpenXaml/XamlObjects/TextBlock.cpp
benroywillis/OpenXaml
a6313c096b5221344ee2dbcfe6e5a4db8345115c
[ "MIT" ]
1
2019-09-23T03:11:04.000Z
2019-09-23T03:11:04.000Z
OpenXaml/XamlObjects/TextBlock.cpp
benroywillis/OpenXaml
a6313c096b5221344ee2dbcfe6e5a4db8345115c
[ "MIT" ]
null
null
null
OpenXaml/XamlObjects/TextBlock.cpp
benroywillis/OpenXaml
a6313c096b5221344ee2dbcfe6e5a4db8345115c
[ "MIT" ]
2
2019-11-03T01:12:22.000Z
2022-03-07T16:59:32.000Z
#include "OpenXaml/XamlObjects/TextBlock.h" #include "OpenXaml/Environment/Environment.h" #include "OpenXaml/Environment/Window.h" #include "OpenXaml/GL/GLConfig.h" #include "OpenXaml/Properties/Alignment.h" #include "OpenXaml/Properties/TextWrapping.h" #include <algorithm> #include <codecvt> #include <glad/glad.h> #include <harfbuzz/hb.h> #include <iostream> #include <locale> #include <cmath> #include <sstream> #include <string> #include <utility> using namespace std; namespace OpenXaml::Objects { void TextBlock::Draw() { glBindVertexArray(TextBlock::VAO); glUseProgram(GL::xamlShader); int vertexColorLocation = glGetUniformLocation(GL::xamlShader, "thecolor"); int modeLoc = glGetUniformLocation(GL::xamlShader, "mode"); glUniform4f(vertexColorLocation, 0.0F, 0.0F, 0.0F, 1.0F); glUniform1i(modeLoc, 2); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, edgeBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBindTexture(GL_TEXTURE_2D, font->getFontAtlasTexture()); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), nullptr); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void *)(2 * sizeof(float))); glDrawElements(GL_TRIANGLES, 6 * glyphCount, GL_UNSIGNED_SHORT, nullptr); } void TextBlock::Initialize() { glGenVertexArrays(1, &(TextBlock::VAO)); glBindVertexArray(TextBlock::VAO); glGenBuffers(1, &edgeBuffer); glGenBuffers(1, &vertexBuffer); Update(); } void TextBlock::Update() { XamlObject::Update(); font = Environment::GetFont(FontProperties{FontFamily, FontSize}); if (font == nullptr) { return; } vector<size_t> indexes; for (size_t i = 0; i < Text.size(); i++) { char32_t a = Text.at(i); if (a == U'\n') { indexes.push_back(i); } } float wordWidth = 0; //width of current word size_t currentIndex = 0; int lineCount = 0; //number of lines float width = 0; //width of current line float maxWidth = 0; //max line width size_t charsToRender = 0; float fBounds = (localMax.x - localMin.x); vector<u32string> splitStrings; for (uint32_t i = 0; i < indexes.size() + 1; i++) { size_t index = i == indexes.size() ? Text.size() : indexes.at(i); u32string subString = Text.substr(currentIndex, index - currentIndex); if (i < indexes.size()) { currentIndex = indexes.at(i) + 1; } //we should render this line auto formattedText = font->FormatText(subString); for (auto character : formattedText) { wordWidth += character.xAdvance; if (font->IsSeperator(character.Character)) { if (TextWrapping != TextWrapping::NoWrap && width + wordWidth > fBounds) { lineCount++; maxWidth = std::max(maxWidth, width); width = wordWidth; wordWidth = 0; } else { width += wordWidth; wordWidth = 0; } } } //we now know the number of lines in this 'line' as well as its width, so increment and set the width lineCount++; maxWidth = std::max(maxWidth, wordWidth); charsToRender += formattedText.size(); } maxWidth = std::max(maxWidth, width); //we now know the true number of lines and the true width //so we can start rendering if (charsToRender == 0) { lineCount = 0; //return; } auto *vBuffer = (float *)calloc(16 * charsToRender, sizeof(float)); auto *eBuffer = (unsigned short *)calloc(6 * charsToRender, sizeof(unsigned short)); wordWidth = 0; width = 0; int height = (font->Height >> 6); float fWidth = maxWidth; float fHeight = height * lineCount; switch (VerticalAlignment) { case VerticalAlignment::Bottom: { minRendered.y = localMin.y; maxRendered.y = min(localMax.y, localMin.y + fHeight); break; } case VerticalAlignment::Top: { maxRendered.y = localMax.y; minRendered.y = max(localMin.y, localMax.y - fHeight); break; } case VerticalAlignment::Center: { float mean = 0.5F * (localMax.y + localMin.y); maxRendered.y = min(localMax.y, mean + fHeight / 2); minRendered.y = max(localMin.y, mean - fHeight / 2); break; } case VerticalAlignment::Stretch: { maxRendered.y = localMax.y; minRendered.y = localMin.y; break; } } switch (HorizontalAlignment) { case HorizontalAlignment::Left: { minRendered.x = localMin.x; maxRendered.x = min(localMax.x, localMin.x + fWidth); break; } case HorizontalAlignment::Right: { maxRendered.x = localMax.x; minRendered.x = max(localMin.x, localMax.x - fWidth); break; } case HorizontalAlignment::Center: { float mean = 0.5F * (localMax.x + localMin.x); maxRendered.x = min(localMax.x, mean + fWidth / 2); minRendered.x = max(localMin.x, mean - fWidth / 2); break; } case HorizontalAlignment::Stretch: { maxRendered.x = localMax.x; minRendered.x = localMin.x; break; } } int arrayIndex = 0; float penX; float penY = maxRendered.y - (height - (font->VerticalOffset >> 6)); currentIndex = 0; for (uint32_t i = 0; i < indexes.size() + 1; i++) { int priorIndex = 0; int ppIndex = 0; size_t index = i == indexes.size() ? Text.size() : indexes.at(i); u32string subString = Text.substr(currentIndex, index - currentIndex); if (i < indexes.size()) { currentIndex = indexes.at(i) + 1; } auto formattedText = font->FormatText(subString); int k = 0; for (auto character : formattedText) { wordWidth += character.xAdvance; if (font->IsSeperator(character.Character)) { if (TextWrapping != TextWrapping::NoWrap && width + wordWidth > fBounds) { switch (TextAlignment) { case TextAlignment::Center: { penX = (minRendered.x + maxRendered.x) * 0.5F - width * 0.5F; break; } case TextAlignment::End: { penX = (maxRendered.x) - width; break; } case TextAlignment::Start: { penX = minRendered.x; break; } } for (int j = priorIndex; j < ppIndex + 1; j++) { if (penX > localMax.x) { break; } RenderCharacter(formattedText.at(j), penX, penY, vBuffer, eBuffer, arrayIndex); } priorIndex = ++ppIndex; penY -= height; if (penY < localMin.y - height) { break; } width = wordWidth; } else { width += wordWidth; } wordWidth = 0; ppIndex = k; } k++; } switch (TextAlignment) { case TextAlignment::Center: { penX = (minRendered.x + maxRendered.x) * 0.5F - wordWidth * 0.5F; break; } case TextAlignment::End: { penX = (maxRendered.x) - width; break; } case TextAlignment::Start: { penX = minRendered.x; break; } } for (uint32_t j = priorIndex; j < formattedText.size(); j++) { if (penX > localMax.x) { break; } RenderCharacter(formattedText.at(j), penX, penY, vBuffer, eBuffer, arrayIndex); } penY -= height; width = 0; } boxWidth = (maxRendered.x - minRendered.x); boxHeight = (maxRendered.y - minRendered.y); glBindVertexArray(TextBlock::VAO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, edgeBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, 6 * (size_t)arrayIndex * sizeof(unsigned short), eBuffer, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, 16 * (size_t)arrayIndex * sizeof(float), vBuffer, GL_STATIC_DRAW); std::free(eBuffer); std::free(vBuffer); glyphCount = arrayIndex; } void TextBlock::RenderCharacter(UChar ch, float &penX, float &penY, float *vertexBuffer, unsigned short *edgeBuffer, int &index) { auto uchar = font->GlyphMap[ch.Character]; float x0; float x1; float y0; float y1; float tx0; float tx1; float ty0; float ty1; float dx0; float dx1; float dy0; float dy1; dx0 = penX + (ch.xOffset + uchar.xBearingH); dx1 = dx0 + uchar.width; dy1 = penY + (ch.yOffset + uchar.yBearingH); dy0 = dy1 - uchar.height; x0 = clamp(dx0, localMin.x, localMax.x); x1 = clamp(dx1, localMin.x, localMax.x); y0 = clamp(dy0, localMin.y, localMax.y); y1 = clamp(dy1, localMin.y, localMax.y); float dwidth = dx1 - dx0; float dheight = dy1 - dy0; auto textureLoc = font->GlyphMap[ch.Character]; //handle the font textures, note that they are upside down if (x0 != dx0) { //we are missing part of the left tx0 = textureLoc.txMax - (textureLoc.txMax - textureLoc.txMin) * (x1 - x0) / dwidth; } else { tx0 = textureLoc.txMin; } if (x1 != dx1) { //we are missing part of the right tx1 = textureLoc.txMin + (textureLoc.txMax - textureLoc.txMin) * (x1 - x0) / dwidth; } else { tx1 = textureLoc.txMax; } if (y0 != dy0) { //we are missing part of the bottom ty0 = textureLoc.tyMax - (textureLoc.tyMax - textureLoc.tyMin) * (y1 - y0) / dheight; } else { ty0 = textureLoc.tyMin; } if (y1 != dy1) { //we are missing part of the bottom ty1 = textureLoc.tyMin + (textureLoc.tyMax - textureLoc.tyMin) * (y1 - y0) / dheight; } else { ty1 = textureLoc.tyMax; } vertexBuffer[16 * index + 0] = x0; vertexBuffer[16 * index + 1] = y1; vertexBuffer[16 * index + 2] = tx0; vertexBuffer[16 * index + 3] = ty1; vertexBuffer[16 * index + 4] = x1; vertexBuffer[16 * index + 5] = y1; vertexBuffer[16 * index + 6] = tx1; vertexBuffer[16 * index + 7] = ty1; vertexBuffer[16 * index + 8] = x0; vertexBuffer[16 * index + 9] = y0; vertexBuffer[16 * index + 10] = tx0; vertexBuffer[16 * index + 11] = ty0; vertexBuffer[16 * index + 12] = x1; vertexBuffer[16 * index + 13] = y0; vertexBuffer[16 * index + 14] = tx1; vertexBuffer[16 * index + 15] = ty0; edgeBuffer[6 * index + 0] = 0 + 4 * index; edgeBuffer[6 * index + 1] = 1 + 4 * index; edgeBuffer[6 * index + 2] = 2 + 4 * index; edgeBuffer[6 * index + 3] = 1 + 4 * index; edgeBuffer[6 * index + 4] = 2 + 4 * index; edgeBuffer[6 * index + 5] = 3 + 4 * index; index++; penX += ch.xAdvance; penY -= ch.yAdvance; } TextBlock::TextBlock() { boxHeight = 0; boxWidth = 0; edgeBuffer = 0; vertexBuffer = 0; font = nullptr; } TextBlock::~TextBlock() { //glBindVertexArray(TextBlock::VAO); //glDeleteVertexArrays(1, &TextBlock::VAO); XamlObject::~XamlObject(); } void TextBlock::setText(u32string text) { this->Text = std::move(text); } u32string TextBlock::getText() { return this->Text; } void TextBlock::setText(const string &text) { std::wstring_convert<codecvt_utf8<char32_t>, char32_t> conv; this->Text = conv.from_bytes(text); } void TextBlock::setTextWrapping(OpenXaml::TextWrapping textWrapping) { this->TextWrapping = textWrapping; } TextWrapping TextBlock::getTextWrapping() { return this->TextWrapping; } void TextBlock::setFontFamily(string family) { this->FontFamily = std::move(family); } string TextBlock::getFontFamily() { return this->FontFamily; } void TextBlock::setFontSize(float size) { this->FontSize = size; } float TextBlock::getFontSize() const { return this->FontSize; } void TextBlock::setFill(unsigned int fill) { this->Fill = fill; } unsigned int TextBlock::getFill() const { return this->Fill; } void TextBlock::setTextAlignment(OpenXaml::TextAlignment alignment) { this->TextAlignment = alignment; } TextAlignment TextBlock::getTextAlignment() { return this->TextAlignment; } int TextBlock::getWidth() { return std::ceil(max(this->Width, this->boxWidth)); } int TextBlock::getHeight() { return std::ceil(max(this->Height, this->boxHeight)); } vec2<float> TextBlock::getDesiredDimensions() { if (font == nullptr) { font = Environment::GetFont(FontProperties{FontFamily, FontSize}); } vec2<float> result = {0, 0}; vector<size_t> indexes; for (size_t i = 0; i < Text.size(); i++) { char32_t a = Text.at(i); if (a == U'\n') { indexes.push_back(i); } } float wordWidth = 0; //width of current word size_t currentIndex = 0; int lineCount = 0; //number of lines float width = 0; //width of current line float maxWidth = 0; //max line width size_t charsToRender = 0; vector<u32string> splitStrings; for (uint32_t i = 0; i < indexes.size() + 1; i++) { size_t index = i == indexes.size() ? Text.size() : indexes.at(i); u32string subString = Text.substr(currentIndex, index - currentIndex); if (i < indexes.size()) { currentIndex = indexes.at(i) + 1; } //we should render this line auto formattedText = font->FormatText(subString); for (auto character : formattedText) { wordWidth += character.xAdvance; if (font->IsSeperator(character.Character)) { width += wordWidth; wordWidth = 0; } } //we now know the number of lines in this 'line' as well as its width, so increment and set the width lineCount++; maxWidth = std::max(maxWidth, wordWidth); charsToRender += formattedText.size(); } maxWidth = std::max(maxWidth, width); result.x = std::ceil(maxWidth); result.y = lineCount * (font->Height >> 6); return result; } } // namespace OpenXaml::Objects
34.189293
133
0.472904
benroywillis
12f46b29d5676b69947ac6fcd389eb7817116c7a
17,917
cpp
C++
export/windows/obj/src/openfl/_internal/stage3D/atf/ATFReader.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/openfl/_internal/stage3D/atf/ATFReader.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/openfl/_internal/stage3D/atf/ATFReader.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
// Generated by Haxe 3.4.7 #include <hxcpp.h> #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_lime_utils_Log #include <lime/utils/Log.h> #endif #ifndef INCLUDED_openfl__internal_stage3D_atf_ATFReader #include <openfl/_internal/stage3D/atf/ATFReader.h> #endif #ifndef INCLUDED_openfl_errors_Error #include <openfl/errors/Error.h> #endif #ifndef INCLUDED_openfl_errors_IllegalOperationError #include <openfl/errors/IllegalOperationError.h> #endif #ifndef INCLUDED_openfl_utils_ByteArrayData #include <openfl/utils/ByteArrayData.h> #endif #ifndef INCLUDED_openfl_utils_IDataInput #include <openfl/utils/IDataInput.h> #endif #ifndef INCLUDED_openfl_utils_IDataOutput #include <openfl/utils/IDataOutput.h> #endif #ifndef INCLUDED_openfl_utils__ByteArray_ByteArray_Impl_ #include <openfl/utils/_ByteArray/ByteArray_Impl_.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_9e15a0b592410441_30_new,"openfl._internal.stage3D.atf.ATFReader","new",0x0b38c27e,"openfl._internal.stage3D.atf.ATFReader.new","openfl/_internal/stage3D/atf/ATFReader.hx",30,0x63888776) HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_82_readHeader,"openfl._internal.stage3D.atf.ATFReader","readHeader",0x33e29b25,"openfl._internal.stage3D.atf.ATFReader.readHeader","openfl/_internal/stage3D/atf/ATFReader.hx",82,0x63888776) HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_126_readTextures,"openfl._internal.stage3D.atf.ATFReader","readTextures",0x07ab1ed0,"openfl._internal.stage3D.atf.ATFReader.readTextures","openfl/_internal/stage3D/atf/ATFReader.hx",126,0x63888776) HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_163___readUInt24,"openfl._internal.stage3D.atf.ATFReader","__readUInt24",0xb1c572f4,"openfl._internal.stage3D.atf.ATFReader.__readUInt24","openfl/_internal/stage3D/atf/ATFReader.hx",163,0x63888776) HX_LOCAL_STACK_FRAME(_hx_pos_9e15a0b592410441_174___readUInt32,"openfl._internal.stage3D.atf.ATFReader","__readUInt32",0xb1c573d1,"openfl._internal.stage3D.atf.ATFReader.__readUInt32","openfl/_internal/stage3D/atf/ATFReader.hx",174,0x63888776) namespace openfl{ namespace _internal{ namespace stage3D{ namespace atf{ void ATFReader_obj::__construct( ::openfl::utils::ByteArrayData data,int byteArrayOffset){ HX_GC_STACKFRAME(&_hx_pos_9e15a0b592410441_30_new) HXLINE( 38) this->version = (int)0; HXLINE( 44) data->position = byteArrayOffset; HXLINE( 45) ::String signature = data->readUTFBytes((int)3); HXLINE( 46) data->position = byteArrayOffset; HXLINE( 48) if ((signature != HX_("ATF",f3,9b,31,00))) { HXLINE( 50) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF signature not found",a0,f7,2f,3a))); } HXLINE( 54) int length = (int)0; HXLINE( 57) if ((data->b->__get((byteArrayOffset + (int)6)) == (int)255)) { HXLINE( 59) this->version = data->b->__get((byteArrayOffset + (int)7)); HXLINE( 60) data->position = (byteArrayOffset + (int)8); HXLINE( 61) length = this->_hx___readUInt32(data); } else { HXLINE( 65) this->version = (int)0; HXLINE( 66) data->position = (byteArrayOffset + (int)3); HXLINE( 67) length = this->_hx___readUInt24(data); } HXLINE( 71) int _hx_tmp = (byteArrayOffset + length); HXDLIN( 71) if ((_hx_tmp > ::openfl::utils::_ByteArray::ByteArray_Impl__obj::get_length(data))) { HXLINE( 73) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF length exceeds byte array length",d7,29,45,0f))); } HXLINE( 77) this->data = data; } Dynamic ATFReader_obj::__CreateEmpty() { return new ATFReader_obj; } void *ATFReader_obj::_hx_vtable = 0; Dynamic ATFReader_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ATFReader_obj > _hx_result = new ATFReader_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool ATFReader_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x687242c6; } bool ATFReader_obj::readHeader(int _hx___width,int _hx___height,bool cubeMap){ HX_GC_STACKFRAME(&_hx_pos_9e15a0b592410441_82_readHeader) HXLINE( 84) int tdata = this->data->readUnsignedByte(); HXLINE( 85) int type = ((int)tdata >> (int)(int)7); HXLINE( 87) bool _hx_tmp; HXDLIN( 87) if (!(cubeMap)) { HXLINE( 87) _hx_tmp = (type != (int)0); } else { HXLINE( 87) _hx_tmp = false; } HXDLIN( 87) if (_hx_tmp) { HXLINE( 89) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF Cube map not expected",a7,74,ca,c8))); } HXLINE( 93) bool _hx_tmp1; HXDLIN( 93) if (cubeMap) { HXLINE( 93) _hx_tmp1 = (type != (int)1); } else { HXLINE( 93) _hx_tmp1 = false; } HXDLIN( 93) if (_hx_tmp1) { HXLINE( 95) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF Cube map expected",fa,fe,ed,52))); } HXLINE( 99) this->cubeMap = cubeMap; HXLINE( 101) this->atfFormat = ((int)tdata & (int)(int)127); HXLINE( 104) bool _hx_tmp2; HXDLIN( 104) if ((this->atfFormat != (int)3)) { HXLINE( 104) _hx_tmp2 = (this->atfFormat != (int)5); } else { HXLINE( 104) _hx_tmp2 = false; } HXDLIN( 104) if (_hx_tmp2) { HXLINE( 106) ::lime::utils::Log_obj::warn(HX_("Only ATF block compressed textures without JPEG-XR+LZMA are supported",25,8c,50,6a),hx::SourceInfo(HX_("ATFReader.hx",e8,b6,75,e1),106,HX_("openfl._internal.stage3D.atf.ATFReader",8c,6b,52,5f),HX_("readHeader",83,ed,7b,f6))); } HXLINE( 110) this->width = ((int)(int)1 << (int)this->data->readUnsignedByte()); HXLINE( 111) this->height = ((int)(int)1 << (int)this->data->readUnsignedByte()); HXLINE( 113) bool _hx_tmp3; HXDLIN( 113) if ((this->width == _hx___width)) { HXLINE( 113) _hx_tmp3 = (this->height != _hx___height); } else { HXLINE( 113) _hx_tmp3 = true; } HXDLIN( 113) if (_hx_tmp3) { HXLINE( 115) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF width and height dont match",3f,49,15,70))); } HXLINE( 119) this->mipCount = this->data->readUnsignedByte(); HXLINE( 121) return (this->atfFormat == (int)5); } HX_DEFINE_DYNAMIC_FUNC3(ATFReader_obj,readHeader,return ) void ATFReader_obj::readTextures( ::Dynamic uploadCallback){ HX_GC_STACKFRAME(&_hx_pos_9e15a0b592410441_126_readTextures) HXLINE( 130) int gpuFormats; HXDLIN( 130) if ((this->version < (int)3)) { HXLINE( 130) gpuFormats = (int)3; } else { HXLINE( 130) gpuFormats = (int)4; } HXLINE( 131) int sideCount; HXDLIN( 131) if (this->cubeMap) { HXLINE( 131) sideCount = (int)6; } else { HXLINE( 131) sideCount = (int)1; } HXLINE( 133) { HXLINE( 133) int _g1 = (int)0; HXDLIN( 133) int _g = sideCount; HXDLIN( 133) while((_g1 < _g)){ HXLINE( 133) _g1 = (_g1 + (int)1); HXDLIN( 133) int side = (_g1 - (int)1); HXLINE( 134) { HXLINE( 134) int _g3 = (int)0; HXDLIN( 134) int _g2 = this->mipCount; HXDLIN( 134) while((_g3 < _g2)){ HXLINE( 134) _g3 = (_g3 + (int)1); HXDLIN( 134) int level = (_g3 - (int)1); HXLINE( 136) { HXLINE( 136) int _g5 = (int)0; HXDLIN( 136) int _g4 = gpuFormats; HXDLIN( 136) while((_g5 < _g4)){ HXLINE( 136) _g5 = (_g5 + (int)1); HXDLIN( 136) int gpuFormat = (_g5 - (int)1); HXLINE( 138) int blockLength; HXDLIN( 138) if ((this->version == (int)0)) { HXLINE( 138) blockLength = this->_hx___readUInt24(this->data); } else { HXLINE( 138) blockLength = this->_hx___readUInt32(this->data); } HXLINE( 140) int a = (this->data->position + blockLength); HXDLIN( 140) int b = ::openfl::utils::_ByteArray::ByteArray_Impl__obj::get_length(this->data); HXDLIN( 140) bool aNeg = (a < (int)0); HXDLIN( 140) bool bNeg = (b < (int)0); HXDLIN( 140) bool _hx_tmp; HXDLIN( 140) if ((aNeg != bNeg)) { HXLINE( 140) _hx_tmp = aNeg; } else { HXLINE( 140) _hx_tmp = (a > b); } HXDLIN( 140) if (_hx_tmp) { HXLINE( 142) HX_STACK_DO_THROW( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("Block length exceeds ATF file length",15,23,c0,24))); } HXLINE( 146) bool aNeg1 = (blockLength < (int)0); HXDLIN( 146) bool bNeg1 = ((int)0 < (int)0); HXDLIN( 146) bool _hx_tmp1; HXDLIN( 146) if ((aNeg1 != bNeg1)) { HXLINE( 146) _hx_tmp1 = aNeg1; } else { HXLINE( 146) _hx_tmp1 = (blockLength > (int)0); } HXDLIN( 146) if (_hx_tmp1) { HXLINE( 148) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::alloc(blockLength); HXLINE( 149) ::openfl::utils::ByteArrayData _hx_tmp2 = this->data; HXDLIN( 149) _hx_tmp2->readBytes(::openfl::utils::_ByteArray::ByteArray_Impl__obj::fromArrayBuffer(bytes),(int)0,blockLength); HXLINE( 151) int _hx_tmp3 = ((int)this->width >> (int)level); HXDLIN( 151) uploadCallback(side,level,gpuFormat,_hx_tmp3,((int)this->height >> (int)level),blockLength,bytes); } } } } } } } } HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,readTextures,(void)) int ATFReader_obj::_hx___readUInt24( ::openfl::utils::ByteArrayData data){ HX_STACKFRAME(&_hx_pos_9e15a0b592410441_163___readUInt24) HXLINE( 165) int value = ((int)data->readUnsignedByte() << (int)(int)16); HXLINE( 167) value = ((int)value | (int)((int)data->readUnsignedByte() << (int)(int)8)); HXLINE( 168) value = ((int)value | (int)data->readUnsignedByte()); HXLINE( 169) return value; } HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,_hx___readUInt24,return ) int ATFReader_obj::_hx___readUInt32( ::openfl::utils::ByteArrayData data){ HX_STACKFRAME(&_hx_pos_9e15a0b592410441_174___readUInt32) HXLINE( 176) int value = ((int)data->readUnsignedByte() << (int)(int)24); HXLINE( 178) value = ((int)value | (int)((int)data->readUnsignedByte() << (int)(int)16)); HXLINE( 179) value = ((int)value | (int)((int)data->readUnsignedByte() << (int)(int)8)); HXLINE( 180) value = ((int)value | (int)data->readUnsignedByte()); HXLINE( 181) return value; } HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,_hx___readUInt32,return ) hx::ObjectPtr< ATFReader_obj > ATFReader_obj::__new( ::openfl::utils::ByteArrayData data,int byteArrayOffset) { hx::ObjectPtr< ATFReader_obj > __this = new ATFReader_obj(); __this->__construct(data,byteArrayOffset); return __this; } hx::ObjectPtr< ATFReader_obj > ATFReader_obj::__alloc(hx::Ctx *_hx_ctx, ::openfl::utils::ByteArrayData data,int byteArrayOffset) { ATFReader_obj *__this = (ATFReader_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ATFReader_obj), true, "openfl._internal.stage3D.atf.ATFReader")); *(void **)__this = ATFReader_obj::_hx_vtable; __this->__construct(data,byteArrayOffset); return __this; } ATFReader_obj::ATFReader_obj() { } void ATFReader_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ATFReader); HX_MARK_MEMBER_NAME(atfFormat,"atfFormat"); HX_MARK_MEMBER_NAME(cubeMap,"cubeMap"); HX_MARK_MEMBER_NAME(data,"data"); HX_MARK_MEMBER_NAME(height,"height"); HX_MARK_MEMBER_NAME(mipCount,"mipCount"); HX_MARK_MEMBER_NAME(version,"version"); HX_MARK_MEMBER_NAME(width,"width"); HX_MARK_END_CLASS(); } void ATFReader_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(atfFormat,"atfFormat"); HX_VISIT_MEMBER_NAME(cubeMap,"cubeMap"); HX_VISIT_MEMBER_NAME(data,"data"); HX_VISIT_MEMBER_NAME(height,"height"); HX_VISIT_MEMBER_NAME(mipCount,"mipCount"); HX_VISIT_MEMBER_NAME(version,"version"); HX_VISIT_MEMBER_NAME(width,"width"); } hx::Val ATFReader_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"data") ) { return hx::Val( data ); } break; case 5: if (HX_FIELD_EQ(inName,"width") ) { return hx::Val( width ); } break; case 6: if (HX_FIELD_EQ(inName,"height") ) { return hx::Val( height ); } break; case 7: if (HX_FIELD_EQ(inName,"cubeMap") ) { return hx::Val( cubeMap ); } if (HX_FIELD_EQ(inName,"version") ) { return hx::Val( version ); } break; case 8: if (HX_FIELD_EQ(inName,"mipCount") ) { return hx::Val( mipCount ); } break; case 9: if (HX_FIELD_EQ(inName,"atfFormat") ) { return hx::Val( atfFormat ); } break; case 10: if (HX_FIELD_EQ(inName,"readHeader") ) { return hx::Val( readHeader_dyn() ); } break; case 12: if (HX_FIELD_EQ(inName,"readTextures") ) { return hx::Val( readTextures_dyn() ); } if (HX_FIELD_EQ(inName,"__readUInt24") ) { return hx::Val( _hx___readUInt24_dyn() ); } if (HX_FIELD_EQ(inName,"__readUInt32") ) { return hx::Val( _hx___readUInt32_dyn() ); } } return super::__Field(inName,inCallProp); } hx::Val ATFReader_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"data") ) { data=inValue.Cast< ::openfl::utils::ByteArrayData >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"width") ) { width=inValue.Cast< int >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"height") ) { height=inValue.Cast< int >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"cubeMap") ) { cubeMap=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"version") ) { version=inValue.Cast< int >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"mipCount") ) { mipCount=inValue.Cast< int >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"atfFormat") ) { atfFormat=inValue.Cast< int >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void ATFReader_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_HCSTRING("atfFormat","\xaa","\xd3","\x04","\x9c")); outFields->push(HX_HCSTRING("cubeMap","\xa7","\x4c","\xd0","\x8c")); outFields->push(HX_HCSTRING("data","\x2a","\x56","\x63","\x42")); outFields->push(HX_HCSTRING("height","\xe7","\x07","\x4c","\x02")); outFields->push(HX_HCSTRING("mipCount","\x9b","\x6a","\x51","\x0e")); outFields->push(HX_HCSTRING("version","\x18","\xe7","\xf1","\x7c")); outFields->push(HX_HCSTRING("width","\x06","\xb6","\x62","\xca")); super::__GetFields(outFields); }; #if HXCPP_SCRIPTABLE static hx::StorageInfo ATFReader_obj_sMemberStorageInfo[] = { {hx::fsInt,(int)offsetof(ATFReader_obj,atfFormat),HX_HCSTRING("atfFormat","\xaa","\xd3","\x04","\x9c")}, {hx::fsBool,(int)offsetof(ATFReader_obj,cubeMap),HX_HCSTRING("cubeMap","\xa7","\x4c","\xd0","\x8c")}, {hx::fsObject /*::openfl::utils::ByteArrayData*/ ,(int)offsetof(ATFReader_obj,data),HX_HCSTRING("data","\x2a","\x56","\x63","\x42")}, {hx::fsInt,(int)offsetof(ATFReader_obj,height),HX_HCSTRING("height","\xe7","\x07","\x4c","\x02")}, {hx::fsInt,(int)offsetof(ATFReader_obj,mipCount),HX_HCSTRING("mipCount","\x9b","\x6a","\x51","\x0e")}, {hx::fsInt,(int)offsetof(ATFReader_obj,version),HX_HCSTRING("version","\x18","\xe7","\xf1","\x7c")}, {hx::fsInt,(int)offsetof(ATFReader_obj,width),HX_HCSTRING("width","\x06","\xb6","\x62","\xca")}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *ATFReader_obj_sStaticStorageInfo = 0; #endif static ::String ATFReader_obj_sMemberFields[] = { HX_HCSTRING("atfFormat","\xaa","\xd3","\x04","\x9c"), HX_HCSTRING("cubeMap","\xa7","\x4c","\xd0","\x8c"), HX_HCSTRING("data","\x2a","\x56","\x63","\x42"), HX_HCSTRING("height","\xe7","\x07","\x4c","\x02"), HX_HCSTRING("mipCount","\x9b","\x6a","\x51","\x0e"), HX_HCSTRING("version","\x18","\xe7","\xf1","\x7c"), HX_HCSTRING("width","\x06","\xb6","\x62","\xca"), HX_HCSTRING("readHeader","\x83","\xed","\x7b","\xf6"), HX_HCSTRING("readTextures","\xae","\x44","\x04","\xa1"), HX_HCSTRING("__readUInt24","\xd2","\x98","\x1e","\x4b"), HX_HCSTRING("__readUInt32","\xaf","\x99","\x1e","\x4b"), ::String(null()) }; static void ATFReader_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(ATFReader_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void ATFReader_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ATFReader_obj::__mClass,"__mClass"); }; #endif hx::Class ATFReader_obj::__mClass; void ATFReader_obj::__register() { hx::Object *dummy = new ATFReader_obj; ATFReader_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("openfl._internal.stage3D.atf.ATFReader","\x8c","\x6b","\x52","\x5f"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = ATFReader_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(ATFReader_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< ATFReader_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = ATFReader_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ATFReader_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ATFReader_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace openfl } // end namespace _internal } // end namespace stage3D } // end namespace atf
41.86215
274
0.673718
seanbashaw
12f5591da05d6c59955f5a184bef2c6547d7eee4
1,465
cpp
C++
gym/100283/I.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
1
2021-07-16T19:59:39.000Z
2021-07-16T19:59:39.000Z
gym/100283/I.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
gym/100283/I.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #ifdef Adrian #include "debug.h" #else #define debug(...) #endif typedef long long ll; typedef long double ld; typedef complex<ll> point; #define F first #define S second const double EPS=1e-8,oo=1e9; struct fraction { ll x,y; fraction(ll _x, ll _y) { ll g = __gcd(_x,_y); x = _x / g; y = _y / g; } bool operator <(const fraction other)const { return x * other.y < y * other.x; } fraction operator -(fraction other) { return fraction(other.y * x - other.x * y, y * other.y); } fraction operator +(fraction other) { return fraction(other.y * x + other.x * y, y * other.y); } void print() { cout<<x<<"/"<<y<<'\n'; } }; void generate(vector<fraction> &v, ll pos, fraction f) { if(f.x != 0) v.push_back(f); if(pos == 14) return; for(ll i = 0; i<pos; i++) { fraction temp = f + fraction(i,pos); if(temp < fraction(1,1)) generate(v, pos + 1, temp); } } int main() { freopen("zanzibar.in", "r", stdin); ios_base::sync_with_stdio(0), cin.tie(0); vector<fraction> v; generate(v, 2, fraction(0, 1)); v.push_back(fraction(1,1)); v.push_back(fraction(0,1)); sort(v.begin(), v.end()); int t; cin>>t; for(int c = 1; c<=t; c++) { ll x,y; cin>>x>>y; fraction f(x,y); int pos = lower_bound(v.begin(), v.end(), f) - v.begin(); fraction ans = v[pos] - f; if(pos != 0) ans = min(ans, f - v[pos - 1]); cout<<"Case "<<c<<": "; ans.print(); } return 0; }
16.647727
59
0.585666
albexl
12fa797a258ef128ff053fdf0cdc7bb9d06a08bc
4,803
hpp
C++
test_interface.hpp
Anadani/oop4
133508256b02dd3cd45569b51cea2367cf880c7a
[ "MIT" ]
null
null
null
test_interface.hpp
Anadani/oop4
133508256b02dd3cd45569b51cea2367cf880c7a
[ "MIT" ]
null
null
null
test_interface.hpp
Anadani/oop4
133508256b02dd3cd45569b51cea2367cf880c7a
[ "MIT" ]
null
null
null
#ifndef TEST_INTERFACE_HPP #define TEST_INTERFACE_HPP #include <iostream> #include <iomanip> #include <limits> #include <string> #include <sstream> #include "tests.hpp" #include "Money.hpp" #include "HotdogStand.hpp" void TEST_INSERTION(bool sign); void TEST_EXTRACTION(bool dSign); void runTests() { using std::cout; using std::left; using std::setw; using std::endl; namespace MAB = MyAwesomeBusiness; char prev = cout.fill('.'); cout << "Money Class Tests\n"; cout << setw(40) << left << "Negative (+ -> -)" << (IS_EQUAL(-550, (-(MAB::Money(5.50)).getPennies()))) << endl; cout << setw(40) << left << "Negative (- -> +)" << (IS_EQUAL(550, (-(MAB::Money(-5.50)).getPennies()))) << endl; cout << setw(40) << left << "Equality (T)" << (EXPECT_TRUE((MAB::Money(6) == MAB::Money(6)))) << endl; cout << setw(40) << left << "Equality (F)" << (EXPECT_FALSE((MAB::Money(6) == MAB::Money(2)))) << endl; cout << setw(40) << left << "Prefix++" << (IS_EQUAL(MAB::Money(6), ++(MAB::Money(5)))) << endl; cout << setw(40) << left << "Postfix++" << (IS_EQUAL(MAB::Money(5), (MAB::Money(5))++)) << endl; cout << setw(40) << left << "Prefix--" << (IS_EQUAL(MAB::Money(6), --(MAB::Money(7)))) << endl; cout << setw(40) << left << "Postfix--" << (IS_EQUAL(MAB::Money(6), (MAB::Money(6))--)) << endl; cout << setw(40) << left << "Addition" << (IS_EQUAL(MAB::Money(7), (MAB::Money(2.5) + MAB::Money(4, 50)))) << endl; cout << setw(40) << left << "Multiplication (Money x int)" << (IS_EQUAL(MAB::Money(11), (MAB::Money(2.75) * 4))) << endl; cout << setw(40) << left << "Multiplication (int x Money)" << (IS_EQUAL(MAB::Money(11), (4 * MAB::Money(2.75)))) << endl; cout << setw(40) << left << "Multiplication (Money x double)" << (IS_EQUAL(MAB::Money(2.75), (MAB::Money(11) * 0.25))) << endl; cout << setw(40) << left << "Multiplication (double x Money)" << (IS_EQUAL(MAB::Money(2.75), (0.25 * MAB::Money(11)))) << endl; cout << setw(40) << left << "Less Than (T)" << (EXPECT_TRUE((MAB::Money(1) < MAB::Money(6)))) << endl; cout << setw(40) << left << "Less Than (F)" << (EXPECT_FALSE((MAB::Money(10) < MAB::Money(2)))) << endl; cout << setw(40) << left << "Less Than (F, ==)" << (EXPECT_FALSE((MAB::Money(2) < MAB::Money(2)))) << endl; cout << setw(40) << left << "Less Than or Equal (T)" << (EXPECT_TRUE((MAB::Money(6) <= MAB::Money(6)))) << endl; cout << setw(40) << left << "Less Than or Equal (T, ==)" << (EXPECT_TRUE((MAB::Money(6) <= MAB::Money(6)))) << endl; cout << setw(40) << left << "Less Than or Equal (F)" << (EXPECT_FALSE((MAB::Money(6) <= MAB::Money(2)))) << endl; cout << setw(40) << left << "Greater Than (T)" << (EXPECT_TRUE((MAB::Money(6) > MAB::Money(4)))) << endl; cout << setw(40) << left << "Greater Than (F)" << (EXPECT_FALSE((MAB::Money(2) > MAB::Money(6)))) << endl; cout << setw(40) << left << "Greater Than (F, ==)" << (EXPECT_FALSE((MAB::Money(6) > MAB::Money(6)))) << endl; cout << setw(40) << left << "Greater Than or Equal (T)" << (EXPECT_TRUE((MAB::Money(6) >= MAB::Money(5)))) << endl; cout << setw(40) << left << "Greater Than or Equal (T, ==)" << (EXPECT_TRUE((MAB::Money(6) >= MAB::Money(6)))) << endl; cout << setw(40) << left << "Greater Than or Equal (F)" << (EXPECT_FALSE((MAB::Money(2) >= MAB::Money(6)))) << endl; cout << setw(40) << left << "Inequality (T)" << (EXPECT_TRUE((MAB::Money(2) != MAB::Money(6)))) << endl; cout << setw(40) << left << "Inequality (F)" << (EXPECT_FALSE((MAB::Money(6) != MAB::Money(6)))) << endl; cout << setw(40) << left << "Insertion (<<, +)"; (TEST_INSERTION(true)); std::cout << endl; cout << setw(40) << left << "Insertion (<<, -)"; (TEST_INSERTION(false)); std::cout << endl; cout << setw(40) << left << "Extraction (>>, $)"; (TEST_EXTRACTION(true)); std::cout << endl; cout << setw(40) << left << "Extraction (>>)"; (TEST_EXTRACTION(false)); std::cout << endl; cout.fill(prev); } void TEST_INSERTION(bool sign) { namespace MAB = MyAwesomeBusiness; std::stringstream ss; std::string str; if (sign) { MAB::Money money(5, 75); ss << money; str = ss.str(); std::cout << (IS_EQUAL(std::string("$5.75"), str)); } else { MAB::Money money(-5, -75); ss << money; str = ss.str(); std::cout << (IS_EQUAL(std::string("($5.75)"), str)); } ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } void TEST_EXTRACTION(bool dSign) { namespace MAB = MyAwesomeBusiness; std::stringstream ss; std::string str; if (dSign) ss << "$5.75"; else ss << "5.75"; MAB::Money money; ss >> money; std::cout << (IS_EQUAL(575, money.getPennies())); } #endif
48.515152
131
0.549865
Anadani
420173a5e0f49f6d9fc8da4b577e813c3708bfdc
2,152
hh
C++
yagi/include/typemanager.hh
IDAPluginProject/Yagi
a4528c83dff7f87c804140727b06e0359aca1d99
[ "Apache-2.0" ]
null
null
null
yagi/include/typemanager.hh
IDAPluginProject/Yagi
a4528c83dff7f87c804140727b06e0359aca1d99
[ "Apache-2.0" ]
null
null
null
yagi/include/typemanager.hh
IDAPluginProject/Yagi
a4528c83dff7f87c804140727b06e0359aca1d99
[ "Apache-2.0" ]
null
null
null
#ifndef __YAGI_TYPEMANAGER__ #define __YAGI_TYPEMANAGER__ #include <libdecomp.hh> #include <vector> #include <string> #include <optional> #include <map> #include <string> #include "yagiarchitecture.hh" namespace yagi { /*! * \brief Factory become a manager because it's based on the factory backend link to IDA */ class TypeManager : public TypeFactory { protected: /*! * \brief pointer the global architecture */ YagiArchitecture* m_archi; /*! * \brief find type by inner id * \param n name of the type * \param id id of the type * \return found type */ Datatype* findById(const string& n, uint8 id) override; /*! * \brief inject API is not available throw normal API * We need to use XML tricks... * \param fd function data to update * \param inject_name name of th injection */ void setInjectAttribute(Funcdata& fd, std::string inject_name); public: /*! * \brief ctor */ explicit TypeManager(YagiArchitecture* architecture); virtual ~TypeManager() = default; /*! * \brief Disable copy of IdaTypeFactory prefer moving */ TypeManager(const TypeManager&) = delete; TypeManager& operator=(const TypeManager&) = delete; /*! * \brief Moving is allowed because unique_ptr allow it * and we use std map as container */ TypeManager(TypeManager&&) noexcept = default; TypeManager& operator=(TypeManager&&) noexcept = default; /*! * \brief Parse a function information type interface * Try to create a Ghidra type code * \param typeInfo backend type information */ TypeCode* parseFunc(const FuncInfo& typeInfo); /*! * \brief parse a type information generic interface * to transform into ghidra type * \param backend type information interface * \return ghidra type */ Datatype* parseTypeInfo(const TypeInfo& typeInfo); /*! * \brief Find a type from typeinformation interface * \param typeInfo interface to find * \return ghidra type */ Datatype* findByTypeInfo(const TypeInfo& typeInfo); /*! * \brief update function information data */ void update(Funcdata& func); }; } #endif
23.139785
89
0.687268
IDAPluginProject
4202991db01e0316b69e96b60cf6cbb67b6cd5c4
4,708
hh
C++
RAVL2/Math/Optimisation/ObsVectorBiGaussian.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Optimisation/ObsVectorBiGaussian.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Optimisation/ObsVectorBiGaussian.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2002, 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 RAVLMATH_OBSVECTORBIGAUSSIAN_HEADER #define RAVLMATH_OBSVECTORBIGAUSSIAN_HEADER 1 //! userlevel=Normal //! author="Phil McLauchlan" //! date="24/7/2002" //! rcsid="$Id: ObsVectorBiGaussian.hh 6819 2008-05-30 12:01:36Z ees1wc $" //! docentry="Ravl.API.Pattern Recognition.Optimisation2" //! lib=RavlOptimise //! file="Ravl/Math/Optimisation/ObsVectorBiGaussian.hh" #include "Ravl/ObsVector.hh" namespace RavlN { //! userlevel=Develop //: Robust bi-gaussian observation vector body. class ObsVectorBiGaussianBodyC : public ObsVectorBodyC { public: ObsVectorBiGaussianBodyC(const VectorC &z, const MatrixRSC &Ni, RealT varScale, RealT chi2Thres); //: Constructor. ObsVectorBiGaussianBodyC(const VectorC &z, const MatrixRSC &Ni, const VectorC &zstep, RealT varScale, RealT chi2Thres); //: Constructor. virtual double Residual(const VectorC &v, const MatrixRSC &Ni); //: Return residual adjusted for any robust aspects to the observation virtual bool AdjustInformation(MatrixRSC &Aterm, VectorC &aterm); //: Adjust information matrix/vector term for any robustness virtual bool Restore(); //: Restore values are an aborted modification bool Outlier() const; //: Get outlier flag void SetAsInlier(); //: Set observation to be an inlier void SetAsOutlier(); //: Set observation to be an outlier protected: RealT varInvScale; // inverse scaling of outlier covariance RealT chi2Thres; // cut-off point for chi^2 to switch to outlier // distribution RealT chi2Offset; // adjustment to chi^2 residual for outlier distribution bool outlier; // whether the observation is an outlier (true) or an inlier bool previousOutlierFlag; // stored outlier flag }; //! userlevel=Normal //! autoLink=on //: Robust bi-gaussian observation vector class // This class adds robustness to the ObsVectorC class, using a simple // bi-Gaussian error model with a narrow inlier Gaussian and a wider // outlier Gaussian distribution, as described // <a href="../../../LevenbergMarquardt/node1.html">here</a>. class ObsVectorBiGaussianC : public ObsVectorC { public: ObsVectorBiGaussianC(const VectorC &z, const MatrixRSC &Ni, RealT varScale, RealT chi2Thres) : ObsVectorC(*new ObsVectorBiGaussianBodyC(z,Ni,varScale,chi2Thres)) {} //: Constructor // varScale is the covariance scaling K parameter in the // <a href="../../../LevenbergMarquardt/node1.html">theory document</a>, // and chi2Thres is the chi-squared cutoff parameter. ObsVectorBiGaussianC(const VectorC &z, const MatrixRSC &Ni, const VectorC &zstep, RealT varScale, RealT chi2Thres) : ObsVectorC(*new ObsVectorBiGaussianBodyC(z,Ni,zstep,varScale,chi2Thres)) {} //: Constructor // varScale is the covariance scaling K parameter in the // <a href="../../../LevenbergMarquardt/node1.html">theory document</a>, // and chi2Thres is the chi-squared cutoff parameter. // This constructor also allows you to specify a vector zstep of step // sizes for numerical differentiation with respect to the elements of z, // overriding the default step size (1e-6). ObsVectorBiGaussianC(const ObsVectorC &obs) : ObsVectorC(dynamic_cast<const ObsVectorBiGaussianBodyC *>(BodyPtr(obs))) {} //: Base class constructor. ObsVectorBiGaussianC() {} //: Default constructor. // Creates an invalid handle. protected: ObsVectorBiGaussianC(ObsVectorBiGaussianBodyC &bod) : ObsVectorC(bod) {} //: Body constructor. ObsVectorBiGaussianC(const ObsVectorBiGaussianBodyC *bod) : ObsVectorC(bod) {} //: Body constructor. ObsVectorBiGaussianBodyC &Body() { return static_cast<ObsVectorBiGaussianBodyC &>(ObsVectorC::Body()); } //: Access body. const ObsVectorBiGaussianBodyC &Body() const { return static_cast<const ObsVectorBiGaussianBodyC &>(ObsVectorC::Body()); } //: Access body. public: bool Outlier() const { return Body().Outlier(); } //: Get outlier flag void SetAsInlier() { Body().SetAsInlier(); } //: Set observation to be an inlier void SetAsOutlier() { Body().SetAsOutlier(); } //: Set observation to be an outlier }; } #endif
32.468966
81
0.692863
isuhao
4209ff0888a7f6dca51e4085495aad3986c64da4
4,052
cpp
C++
qamsource/podmgr/podserver/cardmanager/cardMibAcc.cpp
rdkcmf/rdk-mediaframework
55c7753eedaeb15719c5825f212372857459a87e
[ "Apache-2.0" ]
null
null
null
qamsource/podmgr/podserver/cardmanager/cardMibAcc.cpp
rdkcmf/rdk-mediaframework
55c7753eedaeb15719c5825f212372857459a87e
[ "Apache-2.0" ]
null
null
null
qamsource/podmgr/podserver/cardmanager/cardMibAcc.cpp
rdkcmf/rdk-mediaframework
55c7753eedaeb15719c5825f212372857459a87e
[ "Apache-2.0" ]
null
null
null
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2011 RDK Management * * 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 <unistd.h> #ifdef GCC4_XXX #include <list> #else #include <list.h> #endif //#include "pfcresource.h" #include "cardUtils.h" #include "cmhash.h" #include "rmf_osal_event.h" #include "core_events.h" #include "cardmanager.h" #include "cmevents.h" #include "cardMibAcc.h" //#include "pfcpluginbase.h" //#include "pmt.h" #include "poddriver.h" #include "cm_api.h" //#include <string.h> #define __MTAG__ VL_CARD_MANAGER cCardMibAcc::cCardMibAcc(CardManager *cm,char *name):CMThread(name) { //RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardRes::cCardRes()\n"); RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD","Entered ..... cCardMibAcc::cCardMibAcc ###################### \n"); this->cm = cm; event_queue = 0; } cCardMibAcc::~cCardMibAcc(){} void cCardMibAcc::initialize(void) { rmf_osal_eventmanager_handle_t em = get_pod_event_manager(); rmf_osal_eventqueue_handle_t eq ; rmf_osal_eventqueue_create ( (const uint8_t* ) "cCardMibAcc", &eq ); // PodMgrEventListener *listener; RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD","Entered ..... cCardMibAcc::initialize ###################### \n"); RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardMibAcc::initialize()\n"); rmf_osal_eventmanager_register_handler( em, eq, RMF_OSAL_EVENT_CATEGORY_CARD_MIB_ACC ); this->event_queue = eq; //listener = new PodMgrEventListener(cm, eq,"ResourceManagerThread); ////VLALLOC_INFO2(listener, sizeof(PodMgrEventListener)); RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardMibAcc::initialize() eq=%p\n",(void *)eq); //listener->start(); } //static vlCableCardCertInfo_t CardCertInfo; void cCardMibAcc::run(void ) { rmf_osal_eventmanager_handle_t em = get_pod_event_manager(); rmf_osal_event_handle_t event_handle_rcv; rmf_osal_event_params_t event_params_rcv = {0}; rmf_osal_event_category_t event_category; uint32_t event_type; RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD","Entered ..... cCardMibAcc::run ###################### \n"); RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardMibAcc::Run()\n"); cardMibAcc_init(); while (1) { int result = 0; RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD","#############cCardMibAcc::run waiting for Event #################\n"); rmf_osal_eventqueue_get_next_event( event_queue, &event_handle_rcv, &event_category, &event_type, &event_params_rcv); RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD","#############cCardMibAcc::After run waiting for Event #################\n"); switch (event_category) { case RMF_OSAL_EVENT_CATEGORY_CARD_MIB_ACC: RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardMibAcc::PFC_EVENT_CATEGORY_CARD_MIB_ACC\n"); RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD"," ########### cCardMibAcc:RMF_OSAL_EVENT_CATEGORY_CARD_MIB_ACC ######### \n"); RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.POD"," ########### calling cardMibAccProc ########## \n"); if( event_params_rcv.data ) cardMibAccProc(event_params_rcv.data); // GetCableCardCertInfo(&CardCertInfo); break; default: RDK_LOG(RDK_LOG_DEBUG, "LOG.RDK.TARGET","cCardMibAcc::default\n"); break; } rmf_osal_event_delete(event_handle_rcv); } }
31.905512
131
0.662142
rdkcmf
420a42cce075876c01340818edbe4721e3914442
2,370
hpp
C++
include/mgpp/signals/dispatcher.hpp
mjgigli/libmgpp
87cec591ccb2a9d9e1f0eb4a2121ff95128c0bb0
[ "MIT" ]
1
2018-12-22T17:35:45.000Z
2018-12-22T17:35:45.000Z
include/mgpp/signals/dispatcher.hpp
mjgigli/libmgpp
87cec591ccb2a9d9e1f0eb4a2121ff95128c0bb0
[ "MIT" ]
null
null
null
include/mgpp/signals/dispatcher.hpp
mjgigli/libmgpp
87cec591ccb2a9d9e1f0eb4a2121ff95128c0bb0
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018 Matt Gigli * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE * SOFTWARE. */ #ifndef MGPP_SIGNALS_DISPATCHER_HPP_ #define MGPP_SIGNALS_DISPATCHER_HPP_ #include <memory> #include <unordered_map> #include <boost/signals2.hpp> #include <mgpp/signals/event.hpp> namespace mgpp { namespace signals { // Define callback templates and pointer types using EventCallbackTemplate = void(EventConstPtr); using EventCallback = std::function<EventCallbackTemplate>; template <typename T> using EventMemberCallback = void (T::*)(EventConstPtr); // Use boost signals2 signals/slots for the event dispatcher typedef boost::signals2::signal<EventCallbackTemplate> EventSignal; typedef boost::signals2::connection Connection; // Subscribe functions Connection Subscribe(const int id, const EventCallback cb); template <typename T> Connection Subscribe(const int id, const EventMemberCallback<T> mcb, const T &obj) { return Subscribe(id, boost::bind(mcb, const_cast<T *>(&obj), _1)); } // Unsubscribe functions void Unsubscribe(const int id, const Connection &conn); // UnsubscribeAll function void UnsubscribeAll(const int id = -1); // Publish function void Publish(EventConstPtr event); int NumSlots(const int id); } // namespace signals } // namespace mgpp #endif // MGPP_SIGNALS_DISPATCHER_HPP_
32.465753
79
0.760338
mjgigli
420a73e53d87a32974de4f226355d88e52041e13
1,245
hpp
C++
gvsoc/gvsoc_gap/models/pulp/udma/sfu/udma_sfu_v1_empty.hpp
00-01/gap_sdk
25444d752b26ccf0b848301c381692d77172852c
[ "Apache-2.0" ]
118
2018-05-22T08:45:59.000Z
2022-03-30T07:00:45.000Z
gvsoc/gvsoc_gap/models/pulp/udma/sfu/udma_sfu_v1_empty.hpp
00-01/gap_sdk
25444d752b26ccf0b848301c381692d77172852c
[ "Apache-2.0" ]
213
2018-07-25T02:37:32.000Z
2022-03-30T18:04:01.000Z
gvsoc/gvsoc_gap/models/pulp/udma/sfu/udma_sfu_v1_empty.hpp
00-01/gap_sdk
25444d752b26ccf0b848301c381692d77172852c
[ "Apache-2.0" ]
76
2018-07-04T08:19:27.000Z
2022-03-24T09:58:05.000Z
/* * Copyright (C) 2020 GreenWaves Technologies, SAS * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ /* * Authors: Vladimir Popovic, GreenWaves Technologies (vladimir.popovic@greenwaves-technologies.com) */ #ifndef __PULP_UDMA_UDMA_SFU_V1_EMPTY_HPP__ #define __PULP_UDMA_UDMA_SFU_V1_EMPTY_HPP__ #include <vp/vp.hpp> #include "../udma_impl.hpp" class Sfu_periph_empty : public Udma_periph { public: Sfu_periph_empty(udma *top, int id, int itf_id); vp::io_req_status_e custom_req(vp::io_req *req, uint64_t offset); vp::trace trace; private: vp::wire_master<bool> irq; }; #endif
27.666667
100
0.738956
00-01
420eea7d8446fc86ddd296db29aee2919795b575
1,733
cpp
C++
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fake_quantize_transformation.cpp
szabi-luxonis/openvino
c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be
[ "Apache-2.0" ]
2
2020-11-18T14:14:06.000Z
2020-11-28T04:55:57.000Z
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fake_quantize_transformation.cpp
szabi-luxonis/openvino
c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be
[ "Apache-2.0" ]
30
2020-11-13T11:44:07.000Z
2022-02-21T13:03:16.000Z
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fake_quantize_transformation.cpp
szabi-luxonis/openvino
c8dd831fc3ba68a256ab47edb4f6bf3cb5e804be
[ "Apache-2.0" ]
1
2020-12-18T15:47:45.000Z
2020-12-18T15:47:45.000Z
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "low_precision_transformations/fake_quantize_transformation.hpp" #include <memory> #include <tuple> #include <vector> #include <string> #include <ie_core.hpp> #include <transformations/init_node_info.hpp> namespace LayerTestsDefinitions { std::string FakeQuantizeTransformation::getTestCaseName(testing::TestParamInfo<FakeQuantizeTransformationParams> obj) { InferenceEngine::Precision netPrecision; InferenceEngine::SizeVector inputShapes; std::string targetDevice; ngraph::pass::low_precision::LayerTransformation::Params params; ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantizeOnData; std::tie(netPrecision, inputShapes, targetDevice, params, fakeQuantizeOnData) = obj.param; std::ostringstream result; result << getTestCaseNameByParams(netPrecision, inputShapes, targetDevice, params) << "_" << fakeQuantizeOnData; return result.str(); } void FakeQuantizeTransformation::SetUp() { InferenceEngine::SizeVector inputShape; InferenceEngine::Precision netPrecision; ngraph::pass::low_precision::LayerTransformation::Params params; ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantizeOnData; std::tie(netPrecision, inputShape, targetDevice, params, fakeQuantizeOnData) = this->GetParam(); function = ngraph::builder::subgraph::FakeQuantizeFunction::getOriginal( FuncTestUtils::PrecisionUtils::convertIE2nGraphPrc(netPrecision), inputShape, fakeQuantizeOnData); ngraph::pass::InitNodeInfo().run_on_function(function); } TEST_P(FakeQuantizeTransformation, CompareWithRefImpl) { Run(); }; } // namespace LayerTestsDefinitions
34.66
119
0.772072
szabi-luxonis
420fa54eaa3be9dcf96fa5c8b82d540805cf1f24
2,021
cpp
C++
src/test/mempool_sync_tests.cpp
MONIMAKER365/BitcoinUnlimited
8aea282c44ee23ca65cdd895c99b3f6347f46dfc
[ "MIT" ]
535
2015-09-04T15:10:08.000Z
2022-03-17T20:51:05.000Z
src/test/mempool_sync_tests.cpp
MONIMAKER365/BitcoinUnlimited
8aea282c44ee23ca65cdd895c99b3f6347f46dfc
[ "MIT" ]
1,269
2016-01-31T20:21:24.000Z
2022-03-16T01:20:08.000Z
src/test/mempool_sync_tests.cpp
MONIMAKER365/BitcoinUnlimited
8aea282c44ee23ca65cdd895c99b3f6347f46dfc
[ "MIT" ]
295
2015-10-19T16:12:29.000Z
2021-08-02T20:05:17.000Z
// Copyright (c) 2018-2019 The Bitcoin Unlimited developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "blockrelay/mempool_sync.h" #include "serialize.h" #include "streams.h" #include "test/test_bitcoin.h" #include <boost/test/unit_test.hpp> #include <cassert> #include <iostream> BOOST_FIXTURE_TEST_SUITE(mempool_sync_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(mempool_sync_can_serde) { uint64_t sync_version = DEFAULT_MEMPOOL_SYNC_MAX_VERSION_SUPPORTED; uint64_t nReceiverMemPoolTx = 0; uint64_t nSenderMempoolPlusBlock = 1; uint64_t shorttxidk0 = 7; uint64_t shorttxidk1 = 11; CBlock block; CTransaction tx; CDataStream stream( ParseHex("01000000010b26e9b7735eb6aabdf358bab62f9816a21ba9ebdb719d5299e88607d722c190000000008b4830450220070aca4" "4506c5cef3a16ed519d7c3c39f8aab192c4e1c90d065f37b8a4af6141022100a8e160b856c2d43d27d8fba71e5aef6405b864" "3ac4cb7cb3c462aced7f14711a0141046d11fee51b0e60666d5049a9101a72741df480b96ee26488a4d3466b95c9a40ac5eee" "f87e10a5cd336c19a84565f80fa6c547957b7700ff4dfbdefe76036c339ffffffff021bff3d11000000001976a91404943fdd" "508053c75000106d3bc6e2754dbcff1988ac2f15de00000000001976a914a266436d2965547608b9e15d9032a7b9d64fa4318" "8ac00000000"), SER_DISK, CLIENT_VERSION); stream >> tx; std::vector<uint256> senderMempoolTxHashes; std::vector<uint256> receiverMempoolTxHashes; senderMempoolTxHashes.push_back(tx.GetHash()); CMempoolSync senderMempoolSync( senderMempoolTxHashes, nReceiverMemPoolTx, nSenderMempoolPlusBlock, shorttxidk0, shorttxidk1, sync_version); CMempoolSync receiverMempoolSync(sync_version); CDataStream ss(SER_DISK, 0); ss << senderMempoolSync; ss >> receiverMempoolSync; receiverMempoolSync.pGrapheneSet->Reconcile(receiverMempoolTxHashes); } BOOST_AUTO_TEST_SUITE_END()
41.244898
120
0.787234
MONIMAKER365
4216b89205de378cc7124b41a1112dcc6c99396b
1,804
cpp
C++
pyis/bindings/python/model_context_exports.cpp
microsoft/python-inference-script
cbbbe9d16be0839e4df357b1bd9e8274ca44f1f7
[ "MIT" ]
5
2021-11-29T01:49:22.000Z
2022-02-23T10:26:46.000Z
pyis/bindings/python/model_context_exports.cpp
microsoft/python-inference-script
cbbbe9d16be0839e4df357b1bd9e8274ca44f1f7
[ "MIT" ]
1
2021-11-01T02:22:32.000Z
2021-11-01T02:22:32.000Z
pyis/bindings/python/model_context_exports.cpp
microsoft/python-inference-script
cbbbe9d16be0839e4df357b1bd9e8274ca44f1f7
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "pyis/share/model_context.h" namespace pyis { namespace python { namespace py = pybind11; void init_model_context(py::module& m) { py::class_<ModelContext, std::shared_ptr<ModelContext>>(m, "ModelContext") .def(py::init<std::string, std::string>(), py::arg("model_path"), py::arg("data_archive") = "", R"pbdoc( Create a ModelContext for loading and saving external data files. The data file should contains two columns, separated by WHITESPACE characters. The first and second columns are source words and target words correspondingly. For example, Args: model_path (str): The model file path. data_archive (str): If specified, the external data files will be archived into a single archive file. By default, external files are not archived and live in the same directory as model file. )pbdoc") .def("set_file_prefix", &ModelContext::SetFilePrefix, py::arg("prefix"), R"pbdoc( Add a common prefix to model file and all external data files. It is useful to avoid file path conflicts. If the model file name already starts with the prefix, the prefix will be ignored. But it still works for external files. Args: prefix (str): Common prefix. )pbdoc") .def_static("activate", &ModelContext::Activate) .def_static("deactivate", &ModelContext::Deactivate); } } // namespace python } // namespace pyis
39.217391
118
0.618625
microsoft
42190727be040632b2fb81d13aac31992fd155d3
1,333
cpp
C++
f9tws/ExgTradingLineFixFactory.cpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
21
2019-01-29T14:41:46.000Z
2022-03-11T00:22:56.000Z
f9tws/ExgTradingLineFixFactory.cpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
null
null
null
f9tws/ExgTradingLineFixFactory.cpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
9
2019-01-27T14:19:33.000Z
2022-03-11T06:18:24.000Z
// \file f9tws/ExgTradingLineFixFactory.cpp // \author fonwinz@gmail.com #include "f9tws/ExgTradingLineFixFactory.hpp" #include "fon9/fix/FixBusinessReject.hpp" namespace f9tws { ExgTradingLineFixFactory::ExgTradingLineFixFactory(std::string fixLogPathFmt, Named&& name) : base(std::move(fixLogPathFmt), std::move(name)) { ExgTradingLineFix::InitFixConfig(this->FixConfig_); f9fix::InitRecvRejectMessage(this->FixConfig_); } fon9::io::SessionSP ExgTradingLineFixFactory::CreateTradingLine(ExgTradingLineMgr& lineMgr, const fon9::IoConfigItem& cfg, std::string& errReason) { ExgTradingLineFixArgs args; args.Market_ = lineMgr.Market_; errReason = ExgTradingLineFixArgsParser(args, ToStrView(cfg.SessionArgs_)); if (!errReason.empty()) return fon9::io::SessionSP{}; std::string fixLogPath; errReason = this->MakeLogPath(fixLogPath); if (!errReason.empty()) return fon9::io::SessionSP{}; fon9::fix::IoFixSenderSP fixSender; errReason = MakeExgTradingLineFixSender(args, &fixLogPath, fixSender); if (!errReason.empty()) return fon9::io::SessionSP{}; return this->CreateTradingLineFix(lineMgr, args, std::move(fixSender)); } } // namespaces
35.078947
94
0.672918
fonwin
421973a95cbe356d815d7aec228dca6a50238f5f
17,585
cpp
C++
aws-cpp-sdk-appflow/source/model/ConnectorConfiguration.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-appflow/source/model/ConnectorConfiguration.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-appflow/source/model/ConnectorConfiguration.cpp
truthiswill/aws-sdk-cpp
6e854b6a8bc7945f150c3a11551196bda341962a
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/appflow/model/ConnectorConfiguration.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Appflow { namespace Model { ConnectorConfiguration::ConnectorConfiguration() : m_canUseAsSource(false), m_canUseAsSourceHasBeenSet(false), m_canUseAsDestination(false), m_canUseAsDestinationHasBeenSet(false), m_supportedDestinationConnectorsHasBeenSet(false), m_supportedSchedulingFrequenciesHasBeenSet(false), m_isPrivateLinkEnabled(false), m_isPrivateLinkEnabledHasBeenSet(false), m_isPrivateLinkEndpointUrlRequired(false), m_isPrivateLinkEndpointUrlRequiredHasBeenSet(false), m_supportedTriggerTypesHasBeenSet(false), m_connectorMetadataHasBeenSet(false), m_connectorType(ConnectorType::NOT_SET), m_connectorTypeHasBeenSet(false), m_connectorLabelHasBeenSet(false), m_connectorDescriptionHasBeenSet(false), m_connectorOwnerHasBeenSet(false), m_connectorNameHasBeenSet(false), m_connectorVersionHasBeenSet(false), m_connectorArnHasBeenSet(false), m_connectorModesHasBeenSet(false), m_authenticationConfigHasBeenSet(false), m_connectorRuntimeSettingsHasBeenSet(false), m_supportedApiVersionsHasBeenSet(false), m_supportedOperatorsHasBeenSet(false), m_supportedWriteOperationsHasBeenSet(false), m_connectorProvisioningType(ConnectorProvisioningType::NOT_SET), m_connectorProvisioningTypeHasBeenSet(false), m_connectorProvisioningConfigHasBeenSet(false), m_logoURLHasBeenSet(false), m_registeredAtHasBeenSet(false), m_registeredByHasBeenSet(false) { } ConnectorConfiguration::ConnectorConfiguration(JsonView jsonValue) : m_canUseAsSource(false), m_canUseAsSourceHasBeenSet(false), m_canUseAsDestination(false), m_canUseAsDestinationHasBeenSet(false), m_supportedDestinationConnectorsHasBeenSet(false), m_supportedSchedulingFrequenciesHasBeenSet(false), m_isPrivateLinkEnabled(false), m_isPrivateLinkEnabledHasBeenSet(false), m_isPrivateLinkEndpointUrlRequired(false), m_isPrivateLinkEndpointUrlRequiredHasBeenSet(false), m_supportedTriggerTypesHasBeenSet(false), m_connectorMetadataHasBeenSet(false), m_connectorType(ConnectorType::NOT_SET), m_connectorTypeHasBeenSet(false), m_connectorLabelHasBeenSet(false), m_connectorDescriptionHasBeenSet(false), m_connectorOwnerHasBeenSet(false), m_connectorNameHasBeenSet(false), m_connectorVersionHasBeenSet(false), m_connectorArnHasBeenSet(false), m_connectorModesHasBeenSet(false), m_authenticationConfigHasBeenSet(false), m_connectorRuntimeSettingsHasBeenSet(false), m_supportedApiVersionsHasBeenSet(false), m_supportedOperatorsHasBeenSet(false), m_supportedWriteOperationsHasBeenSet(false), m_connectorProvisioningType(ConnectorProvisioningType::NOT_SET), m_connectorProvisioningTypeHasBeenSet(false), m_connectorProvisioningConfigHasBeenSet(false), m_logoURLHasBeenSet(false), m_registeredAtHasBeenSet(false), m_registeredByHasBeenSet(false) { *this = jsonValue; } ConnectorConfiguration& ConnectorConfiguration::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("canUseAsSource")) { m_canUseAsSource = jsonValue.GetBool("canUseAsSource"); m_canUseAsSourceHasBeenSet = true; } if(jsonValue.ValueExists("canUseAsDestination")) { m_canUseAsDestination = jsonValue.GetBool("canUseAsDestination"); m_canUseAsDestinationHasBeenSet = true; } if(jsonValue.ValueExists("supportedDestinationConnectors")) { Array<JsonView> supportedDestinationConnectorsJsonList = jsonValue.GetArray("supportedDestinationConnectors"); for(unsigned supportedDestinationConnectorsIndex = 0; supportedDestinationConnectorsIndex < supportedDestinationConnectorsJsonList.GetLength(); ++supportedDestinationConnectorsIndex) { m_supportedDestinationConnectors.push_back(ConnectorTypeMapper::GetConnectorTypeForName(supportedDestinationConnectorsJsonList[supportedDestinationConnectorsIndex].AsString())); } m_supportedDestinationConnectorsHasBeenSet = true; } if(jsonValue.ValueExists("supportedSchedulingFrequencies")) { Array<JsonView> supportedSchedulingFrequenciesJsonList = jsonValue.GetArray("supportedSchedulingFrequencies"); for(unsigned supportedSchedulingFrequenciesIndex = 0; supportedSchedulingFrequenciesIndex < supportedSchedulingFrequenciesJsonList.GetLength(); ++supportedSchedulingFrequenciesIndex) { m_supportedSchedulingFrequencies.push_back(ScheduleFrequencyTypeMapper::GetScheduleFrequencyTypeForName(supportedSchedulingFrequenciesJsonList[supportedSchedulingFrequenciesIndex].AsString())); } m_supportedSchedulingFrequenciesHasBeenSet = true; } if(jsonValue.ValueExists("isPrivateLinkEnabled")) { m_isPrivateLinkEnabled = jsonValue.GetBool("isPrivateLinkEnabled"); m_isPrivateLinkEnabledHasBeenSet = true; } if(jsonValue.ValueExists("isPrivateLinkEndpointUrlRequired")) { m_isPrivateLinkEndpointUrlRequired = jsonValue.GetBool("isPrivateLinkEndpointUrlRequired"); m_isPrivateLinkEndpointUrlRequiredHasBeenSet = true; } if(jsonValue.ValueExists("supportedTriggerTypes")) { Array<JsonView> supportedTriggerTypesJsonList = jsonValue.GetArray("supportedTriggerTypes"); for(unsigned supportedTriggerTypesIndex = 0; supportedTriggerTypesIndex < supportedTriggerTypesJsonList.GetLength(); ++supportedTriggerTypesIndex) { m_supportedTriggerTypes.push_back(TriggerTypeMapper::GetTriggerTypeForName(supportedTriggerTypesJsonList[supportedTriggerTypesIndex].AsString())); } m_supportedTriggerTypesHasBeenSet = true; } if(jsonValue.ValueExists("connectorMetadata")) { m_connectorMetadata = jsonValue.GetObject("connectorMetadata"); m_connectorMetadataHasBeenSet = true; } if(jsonValue.ValueExists("connectorType")) { m_connectorType = ConnectorTypeMapper::GetConnectorTypeForName(jsonValue.GetString("connectorType")); m_connectorTypeHasBeenSet = true; } if(jsonValue.ValueExists("connectorLabel")) { m_connectorLabel = jsonValue.GetString("connectorLabel"); m_connectorLabelHasBeenSet = true; } if(jsonValue.ValueExists("connectorDescription")) { m_connectorDescription = jsonValue.GetString("connectorDescription"); m_connectorDescriptionHasBeenSet = true; } if(jsonValue.ValueExists("connectorOwner")) { m_connectorOwner = jsonValue.GetString("connectorOwner"); m_connectorOwnerHasBeenSet = true; } if(jsonValue.ValueExists("connectorName")) { m_connectorName = jsonValue.GetString("connectorName"); m_connectorNameHasBeenSet = true; } if(jsonValue.ValueExists("connectorVersion")) { m_connectorVersion = jsonValue.GetString("connectorVersion"); m_connectorVersionHasBeenSet = true; } if(jsonValue.ValueExists("connectorArn")) { m_connectorArn = jsonValue.GetString("connectorArn"); m_connectorArnHasBeenSet = true; } if(jsonValue.ValueExists("connectorModes")) { Array<JsonView> connectorModesJsonList = jsonValue.GetArray("connectorModes"); for(unsigned connectorModesIndex = 0; connectorModesIndex < connectorModesJsonList.GetLength(); ++connectorModesIndex) { m_connectorModes.push_back(connectorModesJsonList[connectorModesIndex].AsString()); } m_connectorModesHasBeenSet = true; } if(jsonValue.ValueExists("authenticationConfig")) { m_authenticationConfig = jsonValue.GetObject("authenticationConfig"); m_authenticationConfigHasBeenSet = true; } if(jsonValue.ValueExists("connectorRuntimeSettings")) { Array<JsonView> connectorRuntimeSettingsJsonList = jsonValue.GetArray("connectorRuntimeSettings"); for(unsigned connectorRuntimeSettingsIndex = 0; connectorRuntimeSettingsIndex < connectorRuntimeSettingsJsonList.GetLength(); ++connectorRuntimeSettingsIndex) { m_connectorRuntimeSettings.push_back(connectorRuntimeSettingsJsonList[connectorRuntimeSettingsIndex].AsObject()); } m_connectorRuntimeSettingsHasBeenSet = true; } if(jsonValue.ValueExists("supportedApiVersions")) { Array<JsonView> supportedApiVersionsJsonList = jsonValue.GetArray("supportedApiVersions"); for(unsigned supportedApiVersionsIndex = 0; supportedApiVersionsIndex < supportedApiVersionsJsonList.GetLength(); ++supportedApiVersionsIndex) { m_supportedApiVersions.push_back(supportedApiVersionsJsonList[supportedApiVersionsIndex].AsString()); } m_supportedApiVersionsHasBeenSet = true; } if(jsonValue.ValueExists("supportedOperators")) { Array<JsonView> supportedOperatorsJsonList = jsonValue.GetArray("supportedOperators"); for(unsigned supportedOperatorsIndex = 0; supportedOperatorsIndex < supportedOperatorsJsonList.GetLength(); ++supportedOperatorsIndex) { m_supportedOperators.push_back(OperatorsMapper::GetOperatorsForName(supportedOperatorsJsonList[supportedOperatorsIndex].AsString())); } m_supportedOperatorsHasBeenSet = true; } if(jsonValue.ValueExists("supportedWriteOperations")) { Array<JsonView> supportedWriteOperationsJsonList = jsonValue.GetArray("supportedWriteOperations"); for(unsigned supportedWriteOperationsIndex = 0; supportedWriteOperationsIndex < supportedWriteOperationsJsonList.GetLength(); ++supportedWriteOperationsIndex) { m_supportedWriteOperations.push_back(WriteOperationTypeMapper::GetWriteOperationTypeForName(supportedWriteOperationsJsonList[supportedWriteOperationsIndex].AsString())); } m_supportedWriteOperationsHasBeenSet = true; } if(jsonValue.ValueExists("connectorProvisioningType")) { m_connectorProvisioningType = ConnectorProvisioningTypeMapper::GetConnectorProvisioningTypeForName(jsonValue.GetString("connectorProvisioningType")); m_connectorProvisioningTypeHasBeenSet = true; } if(jsonValue.ValueExists("connectorProvisioningConfig")) { m_connectorProvisioningConfig = jsonValue.GetObject("connectorProvisioningConfig"); m_connectorProvisioningConfigHasBeenSet = true; } if(jsonValue.ValueExists("logoURL")) { m_logoURL = jsonValue.GetString("logoURL"); m_logoURLHasBeenSet = true; } if(jsonValue.ValueExists("registeredAt")) { m_registeredAt = jsonValue.GetDouble("registeredAt"); m_registeredAtHasBeenSet = true; } if(jsonValue.ValueExists("registeredBy")) { m_registeredBy = jsonValue.GetString("registeredBy"); m_registeredByHasBeenSet = true; } return *this; } JsonValue ConnectorConfiguration::Jsonize() const { JsonValue payload; if(m_canUseAsSourceHasBeenSet) { payload.WithBool("canUseAsSource", m_canUseAsSource); } if(m_canUseAsDestinationHasBeenSet) { payload.WithBool("canUseAsDestination", m_canUseAsDestination); } if(m_supportedDestinationConnectorsHasBeenSet) { Array<JsonValue> supportedDestinationConnectorsJsonList(m_supportedDestinationConnectors.size()); for(unsigned supportedDestinationConnectorsIndex = 0; supportedDestinationConnectorsIndex < supportedDestinationConnectorsJsonList.GetLength(); ++supportedDestinationConnectorsIndex) { supportedDestinationConnectorsJsonList[supportedDestinationConnectorsIndex].AsString(ConnectorTypeMapper::GetNameForConnectorType(m_supportedDestinationConnectors[supportedDestinationConnectorsIndex])); } payload.WithArray("supportedDestinationConnectors", std::move(supportedDestinationConnectorsJsonList)); } if(m_supportedSchedulingFrequenciesHasBeenSet) { Array<JsonValue> supportedSchedulingFrequenciesJsonList(m_supportedSchedulingFrequencies.size()); for(unsigned supportedSchedulingFrequenciesIndex = 0; supportedSchedulingFrequenciesIndex < supportedSchedulingFrequenciesJsonList.GetLength(); ++supportedSchedulingFrequenciesIndex) { supportedSchedulingFrequenciesJsonList[supportedSchedulingFrequenciesIndex].AsString(ScheduleFrequencyTypeMapper::GetNameForScheduleFrequencyType(m_supportedSchedulingFrequencies[supportedSchedulingFrequenciesIndex])); } payload.WithArray("supportedSchedulingFrequencies", std::move(supportedSchedulingFrequenciesJsonList)); } if(m_isPrivateLinkEnabledHasBeenSet) { payload.WithBool("isPrivateLinkEnabled", m_isPrivateLinkEnabled); } if(m_isPrivateLinkEndpointUrlRequiredHasBeenSet) { payload.WithBool("isPrivateLinkEndpointUrlRequired", m_isPrivateLinkEndpointUrlRequired); } if(m_supportedTriggerTypesHasBeenSet) { Array<JsonValue> supportedTriggerTypesJsonList(m_supportedTriggerTypes.size()); for(unsigned supportedTriggerTypesIndex = 0; supportedTriggerTypesIndex < supportedTriggerTypesJsonList.GetLength(); ++supportedTriggerTypesIndex) { supportedTriggerTypesJsonList[supportedTriggerTypesIndex].AsString(TriggerTypeMapper::GetNameForTriggerType(m_supportedTriggerTypes[supportedTriggerTypesIndex])); } payload.WithArray("supportedTriggerTypes", std::move(supportedTriggerTypesJsonList)); } if(m_connectorMetadataHasBeenSet) { payload.WithObject("connectorMetadata", m_connectorMetadata.Jsonize()); } if(m_connectorTypeHasBeenSet) { payload.WithString("connectorType", ConnectorTypeMapper::GetNameForConnectorType(m_connectorType)); } if(m_connectorLabelHasBeenSet) { payload.WithString("connectorLabel", m_connectorLabel); } if(m_connectorDescriptionHasBeenSet) { payload.WithString("connectorDescription", m_connectorDescription); } if(m_connectorOwnerHasBeenSet) { payload.WithString("connectorOwner", m_connectorOwner); } if(m_connectorNameHasBeenSet) { payload.WithString("connectorName", m_connectorName); } if(m_connectorVersionHasBeenSet) { payload.WithString("connectorVersion", m_connectorVersion); } if(m_connectorArnHasBeenSet) { payload.WithString("connectorArn", m_connectorArn); } if(m_connectorModesHasBeenSet) { Array<JsonValue> connectorModesJsonList(m_connectorModes.size()); for(unsigned connectorModesIndex = 0; connectorModesIndex < connectorModesJsonList.GetLength(); ++connectorModesIndex) { connectorModesJsonList[connectorModesIndex].AsString(m_connectorModes[connectorModesIndex]); } payload.WithArray("connectorModes", std::move(connectorModesJsonList)); } if(m_authenticationConfigHasBeenSet) { payload.WithObject("authenticationConfig", m_authenticationConfig.Jsonize()); } if(m_connectorRuntimeSettingsHasBeenSet) { Array<JsonValue> connectorRuntimeSettingsJsonList(m_connectorRuntimeSettings.size()); for(unsigned connectorRuntimeSettingsIndex = 0; connectorRuntimeSettingsIndex < connectorRuntimeSettingsJsonList.GetLength(); ++connectorRuntimeSettingsIndex) { connectorRuntimeSettingsJsonList[connectorRuntimeSettingsIndex].AsObject(m_connectorRuntimeSettings[connectorRuntimeSettingsIndex].Jsonize()); } payload.WithArray("connectorRuntimeSettings", std::move(connectorRuntimeSettingsJsonList)); } if(m_supportedApiVersionsHasBeenSet) { Array<JsonValue> supportedApiVersionsJsonList(m_supportedApiVersions.size()); for(unsigned supportedApiVersionsIndex = 0; supportedApiVersionsIndex < supportedApiVersionsJsonList.GetLength(); ++supportedApiVersionsIndex) { supportedApiVersionsJsonList[supportedApiVersionsIndex].AsString(m_supportedApiVersions[supportedApiVersionsIndex]); } payload.WithArray("supportedApiVersions", std::move(supportedApiVersionsJsonList)); } if(m_supportedOperatorsHasBeenSet) { Array<JsonValue> supportedOperatorsJsonList(m_supportedOperators.size()); for(unsigned supportedOperatorsIndex = 0; supportedOperatorsIndex < supportedOperatorsJsonList.GetLength(); ++supportedOperatorsIndex) { supportedOperatorsJsonList[supportedOperatorsIndex].AsString(OperatorsMapper::GetNameForOperators(m_supportedOperators[supportedOperatorsIndex])); } payload.WithArray("supportedOperators", std::move(supportedOperatorsJsonList)); } if(m_supportedWriteOperationsHasBeenSet) { Array<JsonValue> supportedWriteOperationsJsonList(m_supportedWriteOperations.size()); for(unsigned supportedWriteOperationsIndex = 0; supportedWriteOperationsIndex < supportedWriteOperationsJsonList.GetLength(); ++supportedWriteOperationsIndex) { supportedWriteOperationsJsonList[supportedWriteOperationsIndex].AsString(WriteOperationTypeMapper::GetNameForWriteOperationType(m_supportedWriteOperations[supportedWriteOperationsIndex])); } payload.WithArray("supportedWriteOperations", std::move(supportedWriteOperationsJsonList)); } if(m_connectorProvisioningTypeHasBeenSet) { payload.WithString("connectorProvisioningType", ConnectorProvisioningTypeMapper::GetNameForConnectorProvisioningType(m_connectorProvisioningType)); } if(m_connectorProvisioningConfigHasBeenSet) { payload.WithObject("connectorProvisioningConfig", m_connectorProvisioningConfig.Jsonize()); } if(m_logoURLHasBeenSet) { payload.WithString("logoURL", m_logoURL); } if(m_registeredAtHasBeenSet) { payload.WithDouble("registeredAt", m_registeredAt.SecondsWithMSPrecision()); } if(m_registeredByHasBeenSet) { payload.WithString("registeredBy", m_registeredBy); } return payload; } } // namespace Model } // namespace Appflow } // namespace Aws
34.616142
223
0.799488
truthiswill
4221d95f7fba35dfefa01fc155e4456ebdb81482
1,188
cpp
C++
lang/C++/zeckendorf-number-representation-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
5
2021-01-29T20:08:05.000Z
2022-03-22T06:16:05.000Z
lang/C++/zeckendorf-number-representation-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
null
null
null
lang/C++/zeckendorf-number-representation-1.cpp
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2021-04-13T04:19:31.000Z
2021-04-13T04:19:31.000Z
// For a class N which implements Zeckendorf numbers: // I define an increment operation ++() // I define a comparison operation <=(other N) // Nigel Galloway October 22nd., 2012 #include <iostream> class N { private: int dVal = 0, dLen; public: N(char const* x = "0"){ int i = 0, q = 1; for (; x[i] > 0; i++); for (dLen = --i/2; i >= 0; i--) { dVal+=(x[i]-48)*q; q*=2; }} const N& operator++() { for (int i = 0;;i++) { if (dLen < i) dLen = i; switch ((dVal >> (i*2)) & 3) { case 0: dVal += (1 << (i*2)); return *this; case 1: dVal += (1 << (i*2)); if (((dVal >> ((i+1)*2)) & 1) != 1) return *this; case 2: dVal &= ~(3 << (i*2)); }}} const bool operator<=(const N& other) const {return dVal <= other.dVal;} friend std::ostream& operator<<(std::ostream&, const N&); }; N operator "" N(char const* x) {return N(x);} std::ostream &operator<<(std::ostream &os, const N &G) { const static std::string dig[] {"00","01","10"}, dig1[] {"","1","10"}; if (G.dVal == 0) return os << "0"; os << dig1[(G.dVal >> (G.dLen*2)) & 3]; for (int i = G.dLen-1; i >= 0; i--) os << dig[(G.dVal >> (i*2)) & 3]; return os; }
33
87
0.509259
ethansaxenian
4224193f63fde7260b305d76f39e2554c9c08301
1,050
hpp
C++
TypeTraits/IsClassType.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
2
2021-06-09T00:38:46.000Z
2021-09-04T21:55:33.000Z
TypeTraits/IsClassType.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
null
null
null
TypeTraits/IsClassType.hpp
jlandess/LandessDevCore
3319c36c3232415d6bdba7da8b4896c0638badf2
[ "BSD-3-Clause" ]
1
2021-08-30T00:46:12.000Z
2021-08-30T00:46:12.000Z
// // Created by James Landess on 2/4/20. // #ifndef LANDESSDEVCORE_ISCLASSTYPE_HPP #define LANDESSDEVCORE_ISCLASSTYPE_HPP #include "TypeTraits/IsIntegralType.hpp" #include "TypeTraits/IsUnion.hpp" namespace LD { namespace Detail { template<typename T> struct IsClassType { static const bool value = !IsIntegrelType<T>::value; }; //template <bool _Bp, class _Tp = void> using Enable_If_T = typename EnableIf<_Bp, _Tp>::type; template<typename T> using IsClassType_V = typename IsClassType<T>::value; } } namespace LD { namespace Detail { template <class T> LD::Detail::IntegralConstant<bool, !LD::Detail::IsUnion<T>::value> test(int T::*); template <class> LD::FalseType test(...); template <class T> struct IsClass : decltype(LD::Detail::test<T>(nullptr)) {}; } template<typename T> constexpr bool IsClass = LD::Detail::IsClass<T>::value; } #endif //LANDESSDEVCORE_ISCLASSTYPE_HPP
18.421053
102
0.630476
jlandess
4224b28d0f04b68fc399e1a3533d685b15c63cfe
6,066
cpp
C++
Source/WebCore/loader/ResourceCryptographicDigest.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/loader/ResourceCryptographicDigest.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/loader/ResourceCryptographicDigest.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2017 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ResourceCryptographicDigest.h" #include "ParsingUtilities.h" #include <pal/crypto/CryptoDigest.h> #include <wtf/Optional.h> #include <wtf/text/Base64.h> #include <wtf/text/StringParsingBuffer.h> namespace WebCore { template<typename CharacterType> static Optional<ResourceCryptographicDigest::Algorithm> parseHashAlgorithmAdvancingPosition(StringParsingBuffer<CharacterType>& buffer) { // FIXME: This would be much cleaner with a lookup table of pairs of label / algorithm enum values, but I can't // figure out how to keep the labels compiletime strings for skipExactlyIgnoringASCIICase. if (skipExactlyIgnoringASCIICase(buffer, "sha256")) return ResourceCryptographicDigest::Algorithm::SHA256; if (skipExactlyIgnoringASCIICase(buffer, "sha384")) return ResourceCryptographicDigest::Algorithm::SHA384; if (skipExactlyIgnoringASCIICase(buffer, "sha512")) return ResourceCryptographicDigest::Algorithm::SHA512; return WTF::nullopt; } template<typename CharacterType> static Optional<ResourceCryptographicDigest> parseCryptographicDigestImpl(StringParsingBuffer<CharacterType>& buffer) { if (buffer.atEnd()) return WTF::nullopt; auto algorithm = parseHashAlgorithmAdvancingPosition(buffer); if (!algorithm) return WTF::nullopt; if (!skipExactly(buffer, '-')) return WTF::nullopt; auto beginHashValue = buffer.position(); skipWhile<isBase64OrBase64URLCharacter>(buffer); skipExactly(buffer, '='); skipExactly(buffer, '='); if (buffer.position() == beginHashValue) return WTF::nullopt; Vector<uint8_t> digest; StringView hashValue(beginHashValue, buffer.position() - beginHashValue); if (!base64Decode(hashValue, digest, Base64ValidatePadding)) { if (!base64URLDecode(hashValue, digest)) return WTF::nullopt; } return ResourceCryptographicDigest { *algorithm, WTFMove(digest) }; } Optional<ResourceCryptographicDigest> parseCryptographicDigest(StringParsingBuffer<UChar>& buffer) { return parseCryptographicDigestImpl(buffer); } Optional<ResourceCryptographicDigest> parseCryptographicDigest(StringParsingBuffer<LChar>& buffer) { return parseCryptographicDigestImpl(buffer); } template<typename CharacterType> static Optional<EncodedResourceCryptographicDigest> parseEncodedCryptographicDigestImpl(StringParsingBuffer<CharacterType>& buffer) { if (buffer.atEnd()) return WTF::nullopt; auto algorithm = parseHashAlgorithmAdvancingPosition(buffer); if (!algorithm) return WTF::nullopt; if (!skipExactly(buffer, '-')) return WTF::nullopt; auto beginHashValue = buffer.position(); skipWhile<isBase64OrBase64URLCharacter>(buffer); skipExactly(buffer, '='); skipExactly(buffer, '='); if (buffer.position() == beginHashValue) return WTF::nullopt; return EncodedResourceCryptographicDigest { *algorithm, String(beginHashValue, buffer.position() - beginHashValue) }; } Optional<EncodedResourceCryptographicDigest> parseEncodedCryptographicDigest(StringParsingBuffer<UChar>& buffer) { return parseEncodedCryptographicDigestImpl(buffer); } Optional<EncodedResourceCryptographicDigest> parseEncodedCryptographicDigest(StringParsingBuffer<LChar>& buffer) { return parseEncodedCryptographicDigestImpl(buffer); } Optional<ResourceCryptographicDigest> decodeEncodedResourceCryptographicDigest(const EncodedResourceCryptographicDigest& encodedDigest) { Vector<uint8_t> digest; if (!base64Decode(encodedDigest.digest, digest, Base64ValidatePadding)) { if (!base64URLDecode(encodedDigest.digest, digest)) return WTF::nullopt; } return ResourceCryptographicDigest { encodedDigest.algorithm, WTFMove(digest) }; } static PAL::CryptoDigest::Algorithm toCryptoDigestAlgorithm(ResourceCryptographicDigest::Algorithm algorithm) { switch (algorithm) { case ResourceCryptographicDigest::Algorithm::SHA256: return PAL::CryptoDigest::Algorithm::SHA_256; case ResourceCryptographicDigest::Algorithm::SHA384: return PAL::CryptoDigest::Algorithm::SHA_384; case ResourceCryptographicDigest::Algorithm::SHA512: return PAL::CryptoDigest::Algorithm::SHA_512; } ASSERT_NOT_REACHED(); return PAL::CryptoDigest::Algorithm::SHA_512; } ResourceCryptographicDigest cryptographicDigestForBytes(ResourceCryptographicDigest::Algorithm algorithm, const void* bytes, size_t length) { auto cryptoDigest = PAL::CryptoDigest::create(toCryptoDigestAlgorithm(algorithm)); cryptoDigest->addBytes(bytes, length); return { algorithm, cryptoDigest->computeHash() }; } }
38.392405
168
0.760303
jacadcaps
4225050630bbee8dac61f9eab48420340b96eec3
624
cpp
C++
thirdparty/ULib/tests/ulib/test_twilio.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/ULib/tests/ulib/test_twilio.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/ULib/tests/ulib/test_twilio.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
// test_twilio.cpp #include <ulib/net/client/twilio.h> int main(int argc, char *argv[]) { U_ULIB_INIT(argv); U_TRACE(5,"main(%d)",argc) UTwilioClient tc(U_STRING_FROM_CONSTANT("SID"), U_STRING_FROM_CONSTANT("TOKEN")); bool ok = tc.getCompletedCalls(); U_INTERNAL_ASSERT(ok) ok = tc.makeCall(U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("http://xxxx")); U_INTERNAL_ASSERT(ok) ok = tc.sendSMS(U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("xxx-xxx-xxxx"), U_CONSTANT_TO_PARAM("\"Hello, how are you?\"")); U_INTERNAL_ASSERT(ok) }
24.96
141
0.709936
liftchampion
422833be4725423ad37c6953658757a96f12a245
21,894
cpp
C++
src/lib.cpp
anticrisis/act-http
18a48a35efc76c54e38a1eac762828bd7addf8c0
[ "BSD-3-Clause" ]
2
2021-02-05T21:20:09.000Z
2022-01-19T13:43:39.000Z
src/lib.cpp
anticrisis/tcl-http
18a48a35efc76c54e38a1eac762828bd7addf8c0
[ "BSD-3-Clause" ]
null
null
null
src/lib.cpp
anticrisis/tcl-http
18a48a35efc76c54e38a1eac762828bd7addf8c0
[ "BSD-3-Clause" ]
null
null
null
#include "dllexport.h" #include "http_tcl/http_tcl.h" #include "util.h" #include "version.h" #include <algorithm> #include <iostream> #include <memory> #include <optional> #include <tcl.h> #include <thread> #include <vector> // need a macro for compile-time string concatenation #define theNamespaceName "::act::http" #define theUrlNamespaceName "::act::url" static constexpr auto theParentNamespace = "::act"; static constexpr auto thePackageName = "act::http"; static constexpr auto thePackageVersion = PROJECT_VERSION; // Configuration structure with refcounted Tcl objects. Managed using // the 'http::configure' command. // // TCL callbacks have the following specifications: // // OPTIONS: -> {status content content_type} or see below // HEAD: -> {status content_length content_type} // GET: -> {status content content_type} // POST: -> {status content content_type} // PUT: -> {status} // DELETE: -> {status content content_type} // // where // // target = string request path, e.g. "/foo" // body = string request body // status = integer HTTP status code // content_length = integer to place in 'Content-Length' header // content_type = string to place in 'Content-Type' header // // and // // Each callback, not just OPTIONS, may optionally return an additional value // as the last element of the list. That value is a dictionary of key/value // pairs to add to the response headers. For example: // // proc post {target body} { // list 200 "hello" "text/plain" {Set-Cookie foo X-Other-Header bar} // } // struct config_t { bool valid{ false }; TclObj options{}; TclObj head{}; TclObj get{}; TclObj post{}; TclObj put{}; TclObj delete_{}; TclObj req_target{}; TclObj req_body{}; TclObj req_headers{}; TclObj host{}; TclObj port{}; TclObj exit_target{}; TclObj max_connections{}; void init(); }; void config_t::init() { // call after Tcl_InitStubs auto empty_string = [] { return Tcl_NewStringObj("", 0); }; options = empty_string(); head = empty_string(); get = empty_string(); post = empty_string(); put = empty_string(); delete_ = empty_string(); req_target = empty_string(); req_body = empty_string(); req_headers = empty_string(); host = empty_string(); port = empty_string(); exit_target = empty_string(); max_connections = empty_string(); valid = true; } struct tcl_handler final : public http_tcl::thread_safe_handler<tcl_handler> { Tcl_Interp* interp_; config_t config_; void set_target(std::string_view target) { maybe_set_var(interp_, config_.req_target.value(), target); } void set_body(std::string_view body) { maybe_set_var(interp_, config_.req_body.value(), body); } void set_headers(headers_access&& get_headers) { // only ask server to copy headers out of its internal // structure if we're actually going to use them. auto var_name_sv = get_string(config_.req_headers.value()); if (! var_name_sv.empty()) { auto dict = to_dict(interp_, get_headers()); Tcl_ObjSetVar2(interp_, config_.req_headers.value(), nullptr, dict, TCL_GLOBAL_ONLY | TCL_LEAVE_ERR_MSG); } } std::optional<int> get_int(Tcl_Obj* obj) { int val{ 0 }; if (Tcl_GetIntFromObj(interp_, obj, &val) == TCL_OK) return val; return std::nullopt; } std::optional<std::tuple<int, Tcl_Obj**>> get_list(Tcl_Obj* list) { int length{ 0 }; Tcl_Obj** objv; if (Tcl_ListObjGetElements(interp_, list, &length, &objv) != TCL_OK) return std::nullopt; return std::make_tuple(length, objv); } std::optional<http_tcl::headers> get_dict(Tcl_Obj* dict) { return ::get_dict(interp_, dict); } std::optional<std::tuple<int, Tcl_Obj**>> eval_to_list(Tcl_Obj* obj) { if (Tcl_EvalObjEx(interp_, obj, TCL_EVAL_GLOBAL) != TCL_OK) return std::nullopt; return get_list(Tcl_GetObjResult(interp_)); } std::string error_info() { if (auto cs = Tcl_GetVar(interp_, "errorInfo", TCL_GLOBAL_ONLY); cs) return cs; return ""; } public: void init(Tcl_Interp* i) { interp_ = i; config_.init(); } auto& config() { return config_; } options_r do_options(std::string_view target, std::string_view body, headers_access&& get_headers) { constexpr auto req_args = 3; const auto make_error = [&](char const* msg = nullptr) -> options_r { return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" }; }; // Not-so-secret back door to force exit, only if -exittarget is set. This // is used for test suites. if (auto exit = get_string(config_.exit_target.value()); ! exit.empty()) { if (target == exit) { // exit after 50ms, hopefully enough time to cleanly complete the // response std::thread{ [] { using namespace std::chrono_literals; std::this_thread::sleep_for(100ms); Tcl_Exit(0); } }.detach(); return { 204, std::nullopt, "", "" }; } } set_target(target); set_body(body); set_headers(std::move(get_headers)); auto list = eval_to_list(config_.options.value()); if (! list) return make_error(); auto [objc, objv] = *list; if (objc < req_args) return make_error("wrong number of items returned from callback"); auto sc = get_int(*objv++); auto res_body = get_string(*objv++); auto content_type = get_string(*objv++); std::optional<http_tcl::headers> headers; if (objc > req_args) headers = get_dict(*objv++); if (! sc) return make_error( "could not understand status code returned from callback"); return { *sc, headers, { res_body.data(), res_body.size() }, { content_type.data(), content_type.size() } }; } head_r do_head(std::string_view target, headers_access&& get_headers) { static const auto error = std::make_tuple(500, std::nullopt, 0, "text/plain"); constexpr auto req_args = 3; set_target(target); set_body(""); set_headers(std::move(get_headers)); auto list = eval_to_list(config_.head.value()); if (! list) return error; auto [objc, objv] = *list; if (objc < req_args) return error; auto sc = get_int(*objv++); auto content_length = get_int(*objv++); auto content_type = get_string(*objv++); std::optional<http_tcl::headers> headers; if (objc > req_args) headers = get_dict(*objv++); if (! sc || ! content_length) return error; return { *sc, headers, static_cast<size_t>(*content_length), { content_type.data(), content_type.size() } }; } get_r do_get(std::string_view target, headers_access&& get_headers) { constexpr auto req_args = 3; const auto make_error = [&](char const* msg = nullptr) -> get_r { return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" }; }; set_target(target); set_body(""); set_headers(std::move(get_headers)); auto list = eval_to_list(config_.get.value()); if (! list) return make_error(); auto [objc, objv] = *list; if (objc < req_args) return make_error("wrong number of items returned from callback"); auto sc = get_int(*objv++); auto body = get_string(*objv++); auto content_type = get_string(*objv++); std::optional<http_tcl::headers> headers; if (objc > req_args) headers = get_dict(*objv++); if (! sc) return make_error( "could not understand status code returned from callback"); return { *sc, headers, { body.data(), body.size() }, { content_type.data(), content_type.size() } }; } post_r do_post(std::string_view target, std::string_view body, headers_access&& get_headers) { constexpr auto req_args = 3; const auto make_error = [&](char const* msg = nullptr) -> post_r { return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" }; }; set_target(target); set_body(body); set_headers(std::move(get_headers)); auto list = eval_to_list(config_.post.value()); if (! list) return make_error(); auto [objc, objv] = *list; if (objc < req_args) return make_error("wrong number of items returned from callback"); auto sc = get_int(*objv++); auto res_body = get_string(*objv++); auto content_type = get_string(*objv++); std::optional<http_tcl::headers> headers; if (objc > req_args) headers = get_dict(*objv++); if (! sc) return make_error( "could not understand status code returned from callback"); return { *sc, headers, { res_body.data(), res_body.size() }, { content_type.data(), content_type.size() } }; } put_r do_put(std::string_view target, std::string_view body, headers_access&& get_headers) { static const auto error = std::make_tuple(500, http_tcl::headers{}); constexpr auto req_args = 1; set_target(target); set_body(body); set_headers(std::move(get_headers)); auto list = eval_to_list(config_.put.value()); if (! list) return error; auto [objc, objv] = *list; if (objc < req_args) return error; auto sc = get_int(*objv++); std::optional<http_tcl::headers> headers; if (objc > req_args) headers = get_dict(*objv++); if (! sc) return error; return { *sc, headers }; } delete_r do_delete_(std::string_view target, std::string_view body, headers_access&& get_headers) { constexpr auto req_args = 3; const auto make_error = [&](char const* msg = nullptr) -> delete_r { return { 500, std::nullopt, msg ? msg : error_info(), "text/plain" }; }; set_target(target); set_body(body); set_headers(std::move(get_headers)); auto list = eval_to_list(config_.delete_.value()); if (! list) return make_error(); auto [objc, objv] = *list; if (objc < req_args) return make_error("wrong number of items returned from callback"); auto sc = get_int(*objv++); auto res_body = get_string(*objv++); auto content_type = get_string(*objv++); std::optional<http_tcl::headers> headers; if (objc > req_args) headers = get_dict(*objv++); if (! sc) return make_error( "could not understand status code returned from callback"); return { *sc, headers, { res_body.data(), res_body.size() }, { content_type.data(), content_type.size() } }; } }; struct client_data { tcl_handler handler; void init(Tcl_Interp*); }; void client_data::init(Tcl_Interp* i) { handler.init(i); } // global client_data theClientData; // int configure(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[]) { static const char* options[] = { "-head", "-get", "-post", "-put", "-delete", "-reqtargetvariable", "-reqbodyvariable", "-reqheadersvariable", "-host", "-port", "-options", "-exittarget", "-maxconnections", nullptr }; auto cd_ptr = static_cast<client_data*>(cd); auto& my_config = cd_ptr->handler.config(); if (objc == 2) { // return value of single option int opt{ -1 }; if (Tcl_GetIndexFromObj(i, objv[1], options, "option", 0, &opt) != TCL_OK) return TCL_ERROR; std::vector<Tcl_Obj*> objv; switch (opt) { case 0: objv.push_back(my_config.head.value()); break; case 1: objv.push_back(my_config.get.value()); break; case 2: objv.push_back(my_config.post.value()); break; case 3: objv.push_back(my_config.put.value()); break; case 4: objv.push_back(my_config.delete_.value()); break; case 5: objv.push_back(my_config.req_target.value()); break; case 6: objv.push_back(my_config.req_body.value()); break; case 7: objv.push_back(my_config.req_headers.value()); break; case 8: objv.push_back(my_config.host.value()); break; case 9: objv.push_back(my_config.port.value()); break; case 10: objv.push_back(my_config.options.value()); break; case 11: objv.push_back(my_config.exit_target.value()); break; case 12: objv.push_back(my_config.max_connections.value()); break; default: return TCL_ERROR; } auto list = Tcl_NewListObj(objv.size(), objv.data()); Tcl_SetObjResult(i, list); return TCL_OK; } // require odd number of arguments if (objc % 2 == 0) { Tcl_WrongNumArgs( i, objc, objv, "?-host host? ?-port port? ?-head headCmd? ?-get getCmd? " "?-post postCmd? ?-put " "putCmd? ?-delete delCmd? ?-options optCmd? ?-reqtargetvariable varName? " "?-reqbodyvariable varName? ?-reqheadersvariable varName? ?-exittarget " "target? ?-maxconnections n?"); return TCL_ERROR; } if (objc == 1) { // return list of configuration std::vector<Tcl_Obj*> objv; objv.reserve(20); objv.push_back(Tcl_NewStringObj("-host", -1)); objv.push_back(my_config.host.value()); objv.push_back(Tcl_NewStringObj("-port", -1)); objv.push_back(my_config.port.value()); objv.push_back(Tcl_NewStringObj("-head", -1)); objv.push_back(my_config.head.value()); objv.push_back(Tcl_NewStringObj("-get", -1)); objv.push_back(my_config.get.value()); objv.push_back(Tcl_NewStringObj("-post", -1)); objv.push_back(my_config.post.value()); objv.push_back(Tcl_NewStringObj("-put", -1)); objv.push_back(my_config.put.value()); objv.push_back(Tcl_NewStringObj("-delete", -1)); objv.push_back(my_config.delete_.value()); objv.push_back(Tcl_NewStringObj("-options", -1)); objv.push_back(my_config.options.value()); objv.push_back(Tcl_NewStringObj("-reqtargetvariable", -1)); objv.push_back(my_config.req_target.value()); objv.push_back(Tcl_NewStringObj("-reqbodyvariable", -1)); objv.push_back(my_config.req_body.value()); objv.push_back(Tcl_NewStringObj("-reqheadersvariable", -1)); objv.push_back(my_config.req_headers.value()); objv.push_back(Tcl_NewStringObj("-exittarget", -1)); objv.push_back(my_config.exit_target.value()); objv.push_back(Tcl_NewStringObj("-maxconnections", -1)); objv.push_back(my_config.max_connections.value()); auto list = Tcl_NewListObj(objv.size(), objv.data()); Tcl_SetObjResult(i, list); return TCL_OK; } for (auto idx = 1; idx < objc - 1; idx += 2) { int opt{ -1 }; if (Tcl_GetIndexFromObj(i, objv[idx], options, "option", 0, &opt) != TCL_OK) return TCL_ERROR; auto obj = objv[idx + 1]; switch (opt) { case 0: my_config.head = obj; break; case 1: my_config.get = obj; break; case 2: my_config.post = obj; break; case 3: my_config.put = obj; break; case 4: my_config.delete_ = obj; break; case 5: my_config.req_target = obj; break; case 6: my_config.req_body = obj; break; case 7: my_config.req_headers = obj; break; case 8: my_config.host = obj; break; case 9: my_config.port = obj; break; case 10: my_config.options = obj; break; case 11: my_config.exit_target = obj; break; case 12: my_config.max_connections = obj; break; default: return TCL_ERROR; } } return TCL_OK; } int http_client(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[]) { static const char* options[] = { "-host", "-port", "-target", "-method", "-body", "-headers", nullptr }; auto const error = [&i, &objc, &objv] { Tcl_WrongNumArgs( i, objc, objv, "?-host host? ?-port port? ?-target target? ?-method http-method? " "?-body body? ?-headers headerDict?"); return TCL_ERROR; }; // require odd number of arguments if (objc % 2 == 0) return error(); std::string host; std::string port{ "80" }; std::string target{ "/" }; std::string method{ "get" }; std::string body; std::optional<http_tcl::headers> headers; for (auto idx = 1; idx < objc - 1; idx += 2) { int opt{ -1 }; if (Tcl_GetIndexFromObj(i, objv[idx], options, "option", 0, &opt) != TCL_OK) return TCL_ERROR; auto obj = objv[idx + 1]; switch (opt) { case 0: host = get_string(obj); break; case 1: port = get_string(obj); break; case 2: target = get_string(obj); break; case 3: method = get_string(obj); break; case 4: body = get_string(obj); break; case 5: headers = get_dict(i, obj); break; default: return TCL_ERROR; } } if (host.empty()) return error(); tolower(method); auto [sc, heads, res_body] = http_tcl::http_client(method, host, port, target, headers, body); std::vector<Tcl_Obj*> resv{ Tcl_NewStringObj(std::to_string(sc).c_str(), -1), to_dict(i, heads), Tcl_NewStringObj(res_body.c_str(), -1), }; auto list = Tcl_NewListObj(resv.size(), resv.data()); Tcl_SetObjResult(i, list); return TCL_OK; } int run(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[]) { auto cd_ptr = static_cast<client_data*>(cd); auto& my_config = cd_ptr->handler.config(); auto host = Tcl_GetString(my_config.host.value()); int port{ 0 }; int max_connections{ 0 }; if (Tcl_GetIntFromObj(i, my_config.port.value(), &port) != TCL_OK) { Tcl_SetObjResult(i, Tcl_NewStringObj("Invalid port number.", -1)); return TCL_ERROR; } // if bad value or not set, ignore the option and use server's default if (Tcl_GetIntFromObj(i, my_config.max_connections.value(), &max_connections) != TCL_OK) max_connections = 0; if (max_connections) http_tcl::run(host, port, &cd_ptr->handler, max_connections); else http_tcl::run(host, port, &cd_ptr->handler); return TCL_OK; } int percent_encode(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[]) { if (objc != 2) { Tcl_WrongNumArgs(i, objc, objv, "string"); return TCL_ERROR; } auto in = get_string(objv[1]); auto out = url::percent_encode(in); Tcl_SetObjResult(i, Tcl_NewStringObj(out.c_str(), out.size())); return TCL_OK; } int percent_decode(ClientData cd, Tcl_Interp* i, int objc, Tcl_Obj* const objv[]) { if (objc != 2) { Tcl_WrongNumArgs(i, objc, objv, "string"); return TCL_ERROR; } auto in = get_string(objv[1]); auto out = url::percent_decode(in); if (out) { Tcl_SetObjResult(i, Tcl_NewStringObj(out->c_str(), out->size())); return TCL_OK; } else { Tcl_AddErrorInfo(i, "could not decode string."); return TCL_ERROR; } } extern "C" { DllExport int Act_http_Init(Tcl_Interp* i) { if (Tcl_InitStubs(i, TCL_VERSION, 0) == nullptr) return TCL_ERROR; theClientData.init(i); #define def(name, func) \ Tcl_CreateObjCommand(i, \ theNamespaceName "::" name, \ (func), \ &theClientData, \ nullptr) #define urldef(name, func) \ Tcl_CreateObjCommand(i, \ theUrlNamespaceName "::" name, \ (func), \ &theClientData, \ nullptr) auto parent_ns = Tcl_CreateNamespace(i, theParentNamespace, nullptr, nullptr); auto ns = Tcl_CreateNamespace(i, theNamespaceName, nullptr, nullptr); auto url_ns = Tcl_CreateNamespace(i, theUrlNamespaceName, nullptr, nullptr); def("configure", configure); def("run", run); def("client", http_client); urldef("encode", percent_encode); urldef("decode", percent_decode); if (Tcl_Export(i, ns, "*", 0) != TCL_OK) return TCL_ERROR; if (Tcl_Export(i, url_ns, "*", 0) != TCL_OK) return TCL_ERROR; if (Tcl_Export(i, parent_ns, "*", 0) != TCL_OK) return TCL_ERROR; Tcl_CreateEnsemble(i, theNamespaceName, ns, 0); Tcl_CreateEnsemble(i, theUrlNamespaceName, url_ns, 0); Tcl_PkgProvide(i, thePackageName, thePackageVersion); return TCL_OK; #undef def #undef urldef } DllExport int Act_http_Unload(Tcl_Interp* i, int flags) { auto ns = Tcl_FindNamespace(i, theNamespaceName, nullptr, 0); auto url_ns = Tcl_CreateNamespace(i, theUrlNamespaceName, nullptr, nullptr); Tcl_DeleteNamespace(ns); Tcl_DeleteNamespace(url_ns); // init client data again to free variables in the prior configuration theClientData.init(i); return TCL_OK; } }
27.784264
80
0.591669
anticrisis
42284a1b50025daf4b313acf93994d4c4491247c
4,314
hxx
C++
ImageSharpOpenJpegNative/src/openjpeg.stream.hxx
cinderblocks/ImageSharp.OpenJpeg
bf5c976a6dbfa0d2666be566c845a7410440cea2
[ "Apache-2.0" ]
null
null
null
ImageSharpOpenJpegNative/src/openjpeg.stream.hxx
cinderblocks/ImageSharp.OpenJpeg
bf5c976a6dbfa0d2666be566c845a7410440cea2
[ "Apache-2.0" ]
null
null
null
ImageSharpOpenJpegNative/src/openjpeg.stream.hxx
cinderblocks/ImageSharp.OpenJpeg
bf5c976a6dbfa0d2666be566c845a7410440cea2
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2022 Sjofn LLC. 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. */ #ifndef _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_STREAM_H_ #define _ISOJ_OPENJPEG_OPENJP2_OPENJPEG_STREAM_H_ #include "ImageSharpOpenJpeg_Exports.hxx" #include "shared.hxx" IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_destroy(opj_stream_t* p_stream) { ::opj_stream_destroy(p_stream); } IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_default_create(const bool p_is_read_stream) { const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE; return ::opj_stream_default_create(b); } IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_create(const uint64_t p_buffer_size, const bool p_is_read_stream) { const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE; return ::opj_stream_create(p_buffer_size, b); } IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_read_function(opj_stream_t* p_stream, const opj_stream_read_fn p_function) { ::opj_stream_set_read_function(p_stream, p_function); } IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_write_function(opj_stream_t* p_stream, const opj_stream_write_fn p_function) { ::opj_stream_set_write_function(p_stream, p_function); } IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_skip_function(opj_stream_t* p_stream, const opj_stream_skip_fn p_function) { ::opj_stream_set_skip_function(p_stream, p_function); } IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_seek_function(opj_stream_t* p_stream, const opj_stream_seek_fn p_function) { ::opj_stream_set_seek_function(p_stream, p_function); } IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_user_data(opj_stream_t* p_stream, void* p_data, const opj_stream_free_user_data_fn p_function) { ::opj_stream_set_user_data(p_stream, p_data, p_function); } IMAGESHARPOPENJPEG_EXPORT void openjpeg_openjp2_opj_stream_set_user_data_length(opj_stream_t* p_stream, const uint64_t data_length) { ::opj_stream_set_user_data_length(p_stream, data_length); } IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_create_default_file_stream(const char *fname, const uint32_t fname_len, const bool p_is_read_stream) { const auto str = std::string(fname, fname_len); const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE; return ::opj_stream_create_default_file_stream(str.c_str(), b); } IMAGESHARPOPENJPEG_EXPORT const opj_stream_t* openjpeg_openjp2_opj_stream_create_file_stream(const char *fname, const uint32_t fname_len, const uint64_t p_buffer_size, const bool p_is_read_stream) { const auto str = std::string(fname, fname_len); const auto b = p_is_read_stream ? OPJ_TRUE : OPJ_FALSE; return ::opj_stream_create_file_stream(str.c_str(), p_buffer_size, b); } #endif // _CPP_OPENJPEG_OPENJP2_OPENJPEG_STREAM_H_
44.474227
119
0.64905
cinderblocks
422a2115bc21c765bd1cca906ed584b4d1ca0c01
3,783
cpp
C++
.RemoteTalk/Plugin/RemoteTalkCeVIOCS/rtcvTalkServer.cpp
i-saint/RemoteTalk
3ac2528ab66ed923cb9c56596944effdeaecee50
[ "MIT" ]
36
2018-12-18T22:33:36.000Z
2021-10-31T07:03:15.000Z
.RemoteTalk/Plugin/RemoteTalkCeVIOCS/rtcvTalkServer.cpp
i-saint/RemoteTalk
3ac2528ab66ed923cb9c56596944effdeaecee50
[ "MIT" ]
1
2020-04-04T16:13:43.000Z
2020-04-05T05:08:17.000Z
.RemoteTalk/Plugin/RemoteTalkCeVIOCS/rtcvTalkServer.cpp
i-saint/RemoteTalk
3ac2528ab66ed923cb9c56596944effdeaecee50
[ "MIT" ]
3
2019-04-12T17:37:23.000Z
2020-09-30T15:50:31.000Z
#include "pch.h" #include "rtcvCommon.h" #include "rtcvHookHandler.h" #include "rtcvTalkServer.h" namespace rtcv { TalkServer::TalkServer() { auto exe_path = rt::GetMainModulePath(); auto config_path = rt::GetCurrentModuleDirectory() + "\\" + rtcvConfigFile; auto settings = rt::GetOrAddServerSettings(config_path, exe_path, rtcvDefaultPort); m_settings.port = settings.port; m_tmp_path = rt::GetCurrentModuleDirectory() + "\\tmp.wav"; } void TalkServer::addMessage(MessagePtr mes) { super::addMessage(mes); processMessages(); } bool TalkServer::isReady() { return false; } TalkServer::Status TalkServer::onStats(StatsMessage& mes) { auto ifs = rtGetTalkInterface_(); auto& stats = mes.stats; ifs->getParams(stats.params); { int n = ifs->getNumCasts(); for (int i = 0; i < n; ++i) stats.casts.push_back(*ifs->getCastInfo(i)); } stats.host = ifs->getClientName(); stats.plugin_version = ifs->getPluginVersion(); stats.protocol_version = ifs->getProtocolVersion(); return Status::Succeeded; } TalkServer::Status TalkServer::onTalk(TalkMessage& mes) { if (m_task_talk.valid()) { if (m_task_talk.wait_for(std::chrono::milliseconds(0)) == std::future_status::timeout) return Status::Failed; } m_params = mes.params; auto ifs = rtGetTalkInterface_(); ifs->setParams(mes.params); ifs->setText(mes.text.c_str()); if (m_mode == Mode::ExportFile) { ifs->setTempFilePath(m_tmp_path.c_str()); if (!ifs->play()) return Status::Failed; auto data = std::make_shared<rt::AudioData>(); if (!rt::ImportWave(*data, m_tmp_path.c_str())) return Status::Failed; std::remove(m_tmp_path.c_str()); m_data_queue.push_back(data); m_data_queue.push_back(std::make_shared<rt::AudioData>()); } else { ifs->setTempFilePath(""); WaveOutHandler::getInstance().mute = m_params.mute; if (!ifs->play()) Status::Failed; m_task_talk = std::async(std::launch::async, [this, ifs]() { ifs->wait(); WaveOutHandler::getInstance().mute = false; { auto terminator = std::make_shared<rt::AudioData>(); std::unique_lock<std::mutex> lock(m_data_mutex); m_data_queue.push_back(terminator); } }); } mes.task = std::async(std::launch::async, [this, &mes]() { std::vector<rt::AudioDataPtr> tmp; for (;;) { { std::unique_lock<std::mutex> lock(m_data_mutex); tmp = m_data_queue; m_data_queue.clear(); } for (auto& ad : tmp) { ad->serialize(*mes.respond_stream); } if (!tmp.empty() && tmp.back()->data.empty()) break; else std::this_thread::sleep_for(std::chrono::milliseconds(10)); } }); return Status::Succeeded; } TalkServer::Status TalkServer::onStop(StopMessage& mes) { auto ifs = rtGetTalkInterface_(); return ifs->stop() ? Status::Succeeded : Status::Failed; } #ifdef rtDebug TalkServer::Status TalkServer::onDebug(DebugMessage& mes) { return rtGetTalkInterface_()->onDebug() ? Status::Succeeded : Status::Failed; } #endif void TalkServer::onUpdateBuffer(const rt::AudioData& data) { auto ifs = rtGetTalkInterface_(); if (!ifs->isPlaying()) return; auto tmp = std::make_shared<rt::AudioData>(data); if (m_params.force_mono) tmp->convertToMono(); { std::unique_lock<std::mutex> lock(m_data_mutex); m_data_queue.push_back(tmp); } } } // namespace rtcv
27.215827
94
0.597409
i-saint
422abceab02e1f78d551c813dcfafaeb7b3316f8
1,027
cpp
C++
DSA Crack Sheet/solutions/4. Sort An Array Of 0s 1s And 2s.cpp
sumanthbolle/DataStructures-Algorithms
d04edbcdd0794f5668e26bd003b46548150eccbc
[ "MIT" ]
1
2021-02-11T15:07:17.000Z
2021-02-11T15:07:17.000Z
DSA Crack Sheet/solutions/4. Sort An Array Of 0s 1s And 2s.cpp
sumanthbolle/DataStructures-Algorithms
d04edbcdd0794f5668e26bd003b46548150eccbc
[ "MIT" ]
null
null
null
DSA Crack Sheet/solutions/4. Sort An Array Of 0s 1s And 2s.cpp
sumanthbolle/DataStructures-Algorithms
d04edbcdd0794f5668e26bd003b46548150eccbc
[ "MIT" ]
null
null
null
// O(nlogn) #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> arr(n, 0); for (int i = 0; i < n; ++i) cin >> arr[i]; sort(arr.begin(), arr.end()); for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << endl; } return 0; } /* =============================== */ // O(n) #include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; vector<int> arr(n, 0); int num[3] = {0}; for (int i = 0; i < n; ++i) { cin >> arr[i]; num[arr[i]]++; } for (int i = 0; i < n; ++i) { if (num[0]) { arr[i] = 0; num[0]--; } else if (num[1]) { arr[i] = 1; num[1]--; } else if (num[2]) { arr[i] = 2; num[2]--; } } for (int i = 0; i < n; ++i) cout << arr[i] << " "; cout << endl; } return 0; }
13.693333
37
0.351509
sumanthbolle
422f8f65625cf6e361471362aadeddbdb1afa670
2,040
cpp
C++
als/main.cpp
al-petrushin/kubsu-cpp-tasks
c280a7c7a743742f5b0ba2bb8bc0e02cd2e7bdc9
[ "MIT" ]
null
null
null
als/main.cpp
al-petrushin/kubsu-cpp-tasks
c280a7c7a743742f5b0ba2bb8bc0e02cd2e7bdc9
[ "MIT" ]
null
null
null
als/main.cpp
al-petrushin/kubsu-cpp-tasks
c280a7c7a743742f5b0ba2bb8bc0e02cd2e7bdc9
[ "MIT" ]
null
null
null
// // Created by Александр Петрушин on 26.04.2021. // #include <vector> #include <functional> #include <iostream> #include <fstream> #include "linear_regression.h" #include "gradient.h" #include "errors.h" //#include "matplotlibcpp.h" using namespace std; std::function<double(double)> Eval(vector<double> input, vector<double> output, vector<double> start_params) { auto function = [](double v, vector<double> params) { return params[0] * (v * v) + params[1] * v + params[2]; }; auto minized = [input, output, function](vector<double> params) { vector<double> result(input.size()); for (int i = 0; i < input.size(); i++) { result[i] = function(input[i], params); } return MSE(result, output); }; auto best_params = GradientSolve((std::function<double(vector<double>)>)minized, start_params, 0.01, 1000); return [best_params, function](double v) { return function(v, best_params); }; } int main() { vector<double> input = {1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3}; vector<double> output = {5.21, 4.196, 3.759, 3.672, 4.592, 4.621, 5.758, 7.173, 9.269}; int size = input.size(); auto evalFunc = Eval(input, output, {1, 1, 1}); auto regression = LinearRegression(input, output); vector<double> nonLinearRegressionOut(size), linearRegressionOut(size); for (int i = 0; i < size; i++) { nonLinearRegressionOut[i] = evalFunc(input[i]); linearRegressionOut[i] = regression(input[i]); } cout << "MSE for non-linear regression = " << MSE(output, nonLinearRegressionOut) << endl; cout << "MSE for linear regression = " << MSE(output, linearRegressionOut) << endl; // matplotlibcpp::figure_size(1200, 780); // matplotlibcpp::named_plot("target", input); // matplotlibcpp::named_plot("linear", out2); // matplotlibcpp::named_plot("linear", out1); // matplotlibcpp::title("Sample figure"); // matplotlibcpp::legend(); // matplotlibcpp::save("./basic.png"); return 0; }
29.565217
111
0.631373
al-petrushin
4230390bb7e512943db7e5e32ea2f6b9d20132e2
4,489
cpp
C++
Classes/dragondash/TowerManager.cpp
Dotosoft/game02-cpp-blueprints
781db6935658cdef7e07087a88f9ce1a22aee2d5
[ "MIT" ]
1
2016-08-25T15:33:09.000Z
2016-08-25T15:33:09.000Z
Classes/dragondash/TowerManager.cpp
Dotosoft/game02-cpp-blueprints
781db6935658cdef7e07087a88f9ce1a22aee2d5
[ "MIT" ]
null
null
null
Classes/dragondash/TowerManager.cpp
Dotosoft/game02-cpp-blueprints
781db6935658cdef7e07087a88f9ce1a22aee2d5
[ "MIT" ]
2
2020-03-06T01:00:56.000Z
2020-03-25T06:07:52.000Z
#include "dragondash\TowerManager.h" using namespace dragondash; dragondash::TowerManager::TowerManager(Vec2 position) { this->lowerSprite = NULL; this->upperSprite = NULL; this->position = position; } dragondash::TowerManager::TowerManager(GameWorld * parent) { // save reference to GameWorld this->gameworld = parent; this->screenSize = parent->screenSize; // initialise variables // this->towers = []; this->towerSpriteSize = Size::ZERO; this->firstTowerIndex = 0; this->lastTowerIndex = 0; } bool dragondash::TowerManager::init() { // record size of the tower's sprite this->towerSpriteSize = SpriteFrameCache::getInstance()->getSpriteFrameByName("opst_02")->getOriginalSize() * this->gameworld->scaleFactor; // create the first pair of towers // they should be two whole screens away from the dragon auto initialPosition = Vec2(this->screenSize.width * 2, this->screenSize.height*0.5); this->firstTowerIndex = 0; this->createTower(initialPosition); // create the remaining towers this->lastTowerIndex = 0; this->createTower(this->getNextTowerPosition()); this->lastTowerIndex = 1; this->createTower(this->getNextTowerPosition()); this->lastTowerIndex = 2; return true; } void dragondash::TowerManager::createTower(Vec2 position) { // create a new tower and add it to the array auto tower = new TowerManager(position); this->towers.pushBack(tower); // create lower tower sprite & add it to GameWorld's batch node tower->lowerSprite = Sprite::createWithSpriteFrameName("opst_02"); tower->lowerSprite->setScale(this->gameworld->scaleFactor); tower->lowerSprite->setPositionX(position.x); tower->lowerSprite->setPositionY(position.y + VERT_GAP_BWN_TOWERS * -0.5 + this->towerSpriteSize.height * -0.5); this->gameworld->spriteBatchNode->addChild(tower->lowerSprite, E_ZORDER::E_LAYER_TOWER); // create upper tower sprite & add it to GameWorld's batch node tower->upperSprite = Sprite::createWithSpriteFrameName("opst_01"); tower->upperSprite->setScale(this->gameworld->scaleFactor); tower->upperSprite->setPositionX(position.x); tower->upperSprite->setPositionY(position.y + VERT_GAP_BWN_TOWERS * 0.5 + this->towerSpriteSize.height * 0.5); this->gameworld->spriteBatchNode->addChild(tower->upperSprite, E_ZORDER::E_LAYER_TOWER); } void dragondash::TowerManager::update() { TowerManager* tower; for (int i = 0; i < this->towers.size(); ++i) { tower = this->towers.at(i); // first update the position of the tower tower->position.x -= MAX_SCROLLING_SPEED; tower->lowerSprite->setPosition(tower->position.x, tower->lowerSprite->getPositionY()); tower->upperSprite->setPosition(tower->position.x, tower->upperSprite->getPositionY()); // if the tower has moved out of the screen, reposition them at the end if (tower->position.x < this->towerSpriteSize.width * -0.5) { this->repositionTower(i); // this tower now becomes the tower at the end this->lastTowerIndex = i; // that means some other tower has become first this->firstTowerIndex = ((i + 1) >= this->towers.size()) ? 0 : (i + 1); } } } void dragondash::TowerManager::repositionTower(int index) { auto tower = this->towers.at(index); // update tower's position and sprites tower->position = this->getNextTowerPosition(); tower->lowerSprite->setPosition(tower->position.x, tower->position.y + VERT_GAP_BWN_TOWERS * -0.5 + this->towerSpriteSize.height * -0.5); tower->upperSprite->setPosition(tower->position.x, tower->position.y + VERT_GAP_BWN_TOWERS * 0.5 + this->towerSpriteSize.height * 0.5); } Vec2 dragondash::TowerManager::getNextTowerPosition() { // randomly select either above or below last tower bool isAbove = (CCRANDOM_0_1() > 0.5); float offset = CCRANDOM_0_1() * VERT_GAP_BWN_TOWERS * 0.75; offset *= (isAbove) ? 1 : -1; // new position calculated by adding to last tower's position float newPositionX = this->towers.at(this->lastTowerIndex)->position.x + this->screenSize.width * 0.5f; float newPositionY = this->towers.at(this->lastTowerIndex)->position.y + offset; // limit the point to stay within 30-80% of the screen if (newPositionY >= this->screenSize.height * 0.8) { newPositionY -= VERT_GAP_BWN_TOWERS; } else if (newPositionY <= this->screenSize.height * 0.3) { newPositionY += VERT_GAP_BWN_TOWERS; } // return the new tower position return Vec2(newPositionX, newPositionY); } dragondash::TowerManager* dragondash::TowerManager::getFrontTower() { return this->towers.at(this->firstTowerIndex); }
36.495935
140
0.736021
Dotosoft
42343997e5cbaabd2bfbd8b043a5e62720235bc0
3,837
cpp
C++
sysy2riscv/ast_tigger.cpp
Yibo-He/sysyCompiler
fd95b17153b565d9ccb69c296cdcc8be64670b11
[ "MIT" ]
7
2021-06-06T05:26:38.000Z
2021-12-25T08:19:43.000Z
sysy2riscv/ast_tigger.cpp
Yibo-He/sysyCompiler
fd95b17153b565d9ccb69c296cdcc8be64670b11
[ "MIT" ]
null
null
null
sysy2riscv/ast_tigger.cpp
Yibo-He/sysyCompiler
fd95b17153b565d9ccb69c296cdcc8be64670b11
[ "MIT" ]
null
null
null
#include "ast_tigger.hpp" int string2num(const string s){ return atoi(s.c_str()); } string num2string_3(int num){ string ans = to_string(num); return ans; } int op2int(string op){ if(!strcmp(op.c_str(),"+")) return Plus; if(!strcmp(op.c_str(),"-")) return Minus; if(!strcmp(op.c_str(),"*")) return Multi; if(!strcmp(op.c_str(),"/")) return Divi; if(!strcmp(op.c_str(),"%")) return Mod; if(!strcmp(op.c_str(),"!")) return Not; if(!strcmp(op.c_str(),">")) return More; if(!strcmp(op.c_str(),"<")) return Less; if(!strcmp(op.c_str(),">=")) return MorEq; if(!strcmp(op.c_str(),"<=")) return LorEq; if(!strcmp(op.c_str(),"&&")) return And; if(!strcmp(op.c_str(),"||")) return Or; if(!strcmp(op.c_str(),"!=")) return Neq; if(!strcmp(op.c_str(),"==")) return Eq; return -1; } void ProgramAST::generator(){ for(auto i:varDecls) i->generator(); riscvCode.push_back(" "); for(auto i:funDefs) i->generator(); for(auto &i: riscvCode) cout << i << endl; cout << endl; } void GlobalVarDeclAST::generator(){ if(isMalloc){ riscvCode.push_back(" .comm "+ varName +", "+ num +", 4"); }else{ riscvCode.push_back(" .global " + varName); riscvCode.push_back(" .section .sdata"); riscvCode.push_back(" .align 2"); riscvCode.push_back(" .type " + varName + ", @object"); riscvCode.push_back(" .size " + varName + ", 4"); riscvCode.push_back(varName + ":"); riscvCode.push_back(" .word " + num); } } void FunctionDefAST::generator(){ funHead->generator(); exps->generator(); funEnd->generator(); } void FunctionHeaderAST::generator(){ riscvCode.push_back(" .text"); riscvCode.push_back(" .align 2"); riscvCode.push_back(" .global " + funName); riscvCode.push_back(" .type " + funName + ", @function"); riscvCode.push_back(funName + ":"); int STK = (n2 / 4 + 1) * 16; vector<BaseTiggerAST*>::iterator itBegin = dynamic_cast<ExpressionsAST*>(dynamic_cast<FunctionDefAST*>(funDef)->exps)->exp.begin(); vector<BaseTiggerAST*>::iterator itEnd = dynamic_cast<ExpressionsAST*>(dynamic_cast<FunctionDefAST*>(funDef)->exps)->exp.end(); for(itBegin;itBegin!=itEnd;++itBegin){ (*itBegin)->STK = STK; } if(STK<=2047 && STK>=-2048){ riscvCode.push_back(" addi sp, sp, -" + num2string_3(STK)); riscvCode.push_back(" sw ra, " + num2string_3(STK-4) + "(sp)"); }else { riscvCode.push_back(" li s0, " + num2string_3(STK)); riscvCode.push_back(" sub sp, sp, s0"); riscvCode.push_back(" add s0, s0, sp"); riscvCode.push_back(" sw ra, -4(s0)"); } } void ExpressionsAST::generator(){ for(auto i: exp){ i->generator(); } } void FunctionEndAST::generator(){ riscvCode.push_back(" .size " + funName + ", .-" + funName); } void ExpressionAST::generator(){ list<string>::iterator it = riscvAction.begin(); if(!strcmp(it->c_str(), "ret")){ if(STK<=2047 && STK>=-2048){ string tmp; tmp = " lw ra, "+num2string_3(STK-4)+"(sp)"; riscvCode.push_back(tmp); tmp = " addi sp, sp, "+num2string_3(STK); riscvCode.push_back(tmp); tmp = " ret"; riscvCode.push_back(tmp); }else { riscvCode.push_back(" li s0, " + num2string_3(STK)); riscvCode.push_back(" add s0, s0, sp"); riscvCode.push_back(" lw ra, -4(s0)"); riscvCode.push_back(" li s0, " + num2string_3(STK)); riscvCode.push_back(" add sp, sp, s0"); riscvCode.push_back(" ret"); } } else { riscvCode.splice(riscvCode.end(), riscvAction); } }
35.201835
135
0.562419
Yibo-He
4236cbcd2e4cad1781694ca6d2e1c343d97cd435
775
cpp
C++
System/test_Triangle/Triangle1.cpp
Mr-Hunter/Linux
dc222abe4e961a65282d7bc8ac6a301657386ddc
[ "Apache-2.0" ]
2
2018-10-30T08:06:57.000Z
2019-12-12T03:05:58.000Z
System/test_Triangle/Triangle1.cpp
Mr-Hunter/Linux
dc222abe4e961a65282d7bc8ac6a301657386ddc
[ "Apache-2.0" ]
null
null
null
System/test_Triangle/Triangle1.cpp
Mr-Hunter/Linux
dc222abe4e961a65282d7bc8ac6a301657386ddc
[ "Apache-2.0" ]
null
null
null
/************************************************************************* > File Name: Triangle1.cpp > Author: Hunter > Mail: hunter.520@qq.com > Created Time: Tue 02 Apr 2019 11:21:37 PM PDT ************************************************************************/ #include <iostream> #include <stdio.h> using namespace std; int main(int argc, char* argv[]) { int i,j,n=0,a[17]={1},b[17]; while(n<1 || n>16) { printf("请输入杨辉三角形的行数:"); scanf("%d",&n); } for(i=0;i<n;i++) { b[0]=a[0]; for(j=1;j<=i;j++) b[j]=a[j-1]+a[j]; /*每个数是上面两数之和*/ for(j=0;j<=i;j++) /*输出杨辉三角*/ { a[j]=b[j]; /*把算得的新行赋给a,用于打印和下一次计算*/ printf("%5d",a[j]); } printf("\n"); } return 0; }
24.21875
74
0.383226
Mr-Hunter
4236d0f908e7d559293bd761abda432e8267c9c3
4,973
cpp
C++
source/scene/Scene.cpp
freneticmonkey/epsilonc
0fb7c6c4c6342a770e2882bfd67ed34719e79066
[ "MIT" ]
null
null
null
source/scene/Scene.cpp
freneticmonkey/epsilonc
0fb7c6c4c6342a770e2882bfd67ed34719e79066
[ "MIT" ]
null
null
null
source/scene/Scene.cpp
freneticmonkey/epsilonc
0fb7c6c4c6342a770e2882bfd67ed34719e79066
[ "MIT" ]
null
null
null
#include "scene/Scene.h" namespace epsilon { Scene::Ptr Scene::Create(std::string name) { Scene::Ptr newScene = std::make_shared<Scene>(private_struct(), name); newScene->Setup(); return newScene; } Scene::Scene(const private_struct &, std::string sceneName) : name(sceneName) { } Scene::~Scene(void) { Destroy(); } void Scene::Destroy() { if (rootNode != nullptr) { rootNode->OnDestroy(); rootNode = nullptr; } } // Initialise the default values of the scene void Scene::Setup() { // Create a root node for the scene rootNode = SceneNode::Create("root"); // Set the this scene as the current scene rootNode->SetScene(ThisPtr()); // Get the new node's transform as the scene root transform rootTransform = rootNode->GetTransform(); // Attach a node with a camera as the default scene camera SceneNode::Ptr camNode = rootNode->CreateChild("camera_node"); // Set the new camera as the default / active camera SetActiveCamera(camNode->CreateCamera("main_camera")); // Move default camera to a suitable position camNode->transform->SetPosition(0, 1, -10); //camNode->transform->LookAt(Vector3(0, 1, 0)); } bool Scene::operator==(Scene::Ptr other) { return name == other->name; } bool Scene::operator==(std::string otherName) { return name == otherName; } void Scene::Update(float el) { rootTransform->_update(true, false); } void Scene::SetActiveCamera(Camera::Ptr camera) { // Add the camera AddCamera(camera); // Set it as the active camera activeCamera = camera; std::for_each(sceneCameras.begin(), sceneCameras.end(), [](Camera::Ptr camera){ camera->SetActive(false); }); camera->SetActive(true); } void Scene::SetActiveCamera(std::string name) { // Find the camera bool found = false; CameraList::iterator cam = std::find_if(sceneCameras.begin(), sceneCameras.end(), [name](Camera::Ptr camera) { return camera->GetName() == name; }); // if a camera with name 'name' wasn't found if (cam == sceneCameras.end()) { Log("Error setting active camera. Unknown camera: " + name); } else { // Set the found camera as the active camera SetActiveCamera(*cam); } } bool Scene::AddCamera(Camera::Ptr newCamera) { // Find the camera bool added = false; CameraList::iterator it = std::find_if(sceneCameras.begin(), sceneCameras.end(), [&](Camera::Ptr cam){ return cam->GetId() == newCamera->GetId(); }); // if a new camera if (it == sceneCameras.end()) { // keep track of it sceneCameras.push_back(newCamera); added = true; } // Return the result of the add return added; } bool Scene::RemoveCamera(Camera::Ptr camera) { // Find the camera bool found = false; CameraList::iterator it = std::find_if(sceneCameras.begin(), sceneCameras.end(), [&](Camera::Ptr cam){ return cam == camera; }); if (it != sceneCameras.end()) { sceneCameras.erase(it); found = true; } // Return the result return found; } bool Scene::RemoveCamera(std::string name) { // Find the camera bool found = false; CameraList::iterator it = std::find_if(sceneCameras.begin(), sceneCameras.end(), [&](Camera::Ptr cam){ return cam->GetName() == name; }); if (it != sceneCameras.end()) { sceneCameras.erase(it); found = true; } // Return the result return found; } Camera::Ptr Scene::GetCamera(std::string name) { Camera::Ptr foundCam; CameraList::iterator it = std::find_if(sceneCameras.begin(), sceneCameras.end(), [&](Camera::Ptr cam){ return cam->GetName() == name; }); if (it != sceneCameras.end()) { foundCam = (*it); } return foundCam; } bool Scene::AddLight(Light::Ptr light) { bool success = false; LightList::iterator it = std::find_if(sceneLights.begin(), sceneLights.end(), [&](Light::Ptr light){ return light->GetName() == name; }); if (it == sceneLights.end()) { sceneLights.push_back(light); success = true; } return success; } bool Scene::RemoveLight(Light::Ptr light) { bool success = false; LightList::iterator it = std::find_if(sceneLights.begin(), sceneLights.end(), [&](Light::Ptr sLight){ return light == sLight; }); if (it == sceneLights.end()) { sceneLights.erase(it); success = true; } return success; } bool Scene::RemoveLight(std::string name) { bool success = false; LightList::iterator it = std::find_if(sceneLights.begin(), sceneLights.end(), [&](Light::Ptr light){ return light->GetName() == name; }); if (it == sceneLights.end()) { sceneLights.erase(it); success = true; } return success; } Light::Ptr Scene::GetLight(std::string name) { Light::Ptr foundLight; LightList::iterator it = std::find_if(sceneLights.begin(), sceneLights.end(), [&](Light::Ptr light){ return light->GetName() == name; }); if (it != sceneLights.end()) { foundLight = *it; } return foundLight; } }
20.052419
112
0.645285
freneticmonkey
4236f3c151d40f8581667f417cbe6145c80ffa77
2,335
hpp
C++
addons/main/weapons/CfgWeapMG.hpp
johnb432/Weapons-Balance-FOW
9d72a7f5a86b59ed6c651b62a39cc08dd21f694e
[ "MIT" ]
null
null
null
addons/main/weapons/CfgWeapMG.hpp
johnb432/Weapons-Balance-FOW
9d72a7f5a86b59ed6c651b62a39cc08dd21f694e
[ "MIT" ]
null
null
null
addons/main/weapons/CfgWeapMG.hpp
johnb432/Weapons-Balance-FOW
9d72a7f5a86b59ed6c651b62a39cc08dd21f694e
[ "MIT" ]
null
null
null
//https://old.weaponsystems.net/weaponsystem/AA06%20-%20Bren.html class fow_w_bren: fow_rifle_base { ACE_barrelLength = 635; ACE_barrelTwist = 254; ACE_Overheating_allowSwapBarrel = 1; displayName = "Bren Mk.II"; magazineReloadTime = 0; magazineWell[] += {"CBA_303B_BREN"}; class WeaponSlotsInfo: WeaponSlotsInfo { mass = 228.2; }; }; class fow_w_fg42: fow_rifle_base { ACE_barrelLength = 500; ACE_barrelTwist = 240; displayName = "FG 42"; magazineWell[] += {"CBA_792x57_FG42"}; class WeaponSlotsInfo: WeaponSlotsInfo { mass = 93; }; }; class fow_w_m1918a2: fow_rifle_base { ACE_barrelLength = 610; ACE_barrelTwist = 254; displayName = "M1918A2 BAR"; magazineWell[] += {"CBA_3006_BAR"}; }; class fow_w_m1918a2_bak: fow_w_m1918a2 { displayName = "M1918A2 BAR (Bakelite)"; }; class fow_w_m1919: fow_rifle_base { ACE_barrelLength = 610; ACE_barrelTwist = 254; ACE_Overheating_allowSwapBarrel = 1; displayName = "M1919A4"; magazineWell[] += {"CBA_3006_Belt"}; class WeaponSlotsInfo: WeaponSlotsInfo {}; }; class fow_w_m1919a4: fow_w_m1919 { displayName = "M1919A4"; class WeaponSlotsInfo: WeaponSlotsInfo { mass = 310; }; }; class fow_w_m1919a6: fow_w_m1919 { displayName = "M1919A6"; class WeaponSlotsInfo: WeaponSlotsInfo { mass = 330.7; }; }; class fow_w_mg34: fow_rifle_base { ACE_barrelLength = 627; ACE_barrelTwist = 240; ACE_Overheating_allowSwapBarrel = 1; displayName = "MG 34"; magazineReloadTime = 0; magazineWell[] += {"CBA_792x57_LINKS"}; class WeaponSlotsInfo: WeaponSlotsInfo { mass = 264.5; }; }; class fow_w_mg42: fow_rifle_base { ACE_barrelLength = 530; ACE_barrelTwist = 240; ACE_Overheating_allowSwapBarrel = 1; displayName = "MG 42"; magazineReloadTime = 0; magazineWell[] += {"CBA_792x57_LINKS"}; class WeaponSlotsInfo: WeaponSlotsInfo { mass = 254.5; }; }; class fow_w_type99_lmg: fow_rifle_base { ACE_barrelLength = 550; ACE_barrelTwist = 254; ACE_Overheating_allowSwapBarrel = 1; displayName = "Type 99 LMG"; magazineReloadTime = 0; magazineWell[] += {"CBA_77x58_Type99"}; class WeaponSlotsInfo: WeaponSlotsInfo { mass = 299; }; };
25.944444
65
0.667238
johnb432
42370348e04d00d16d863f09edf9807461c0286b
2,982
cpp
C++
src/kmr_behaviortree/plugins/action/plan_manipulator_path.cpp
stoic-roboticist/kmriiwa_ws_devel
582c2477ec29c9eb68bd826c64f2ec1f76feb4a6
[ "Apache-2.0" ]
22
2020-04-06T16:35:33.000Z
2022-03-29T07:47:38.000Z
src/kmr_behaviortree/plugins/action/plan_manipulator_path.cpp
stoic-roboticist/kmriiwa_ws_devel
582c2477ec29c9eb68bd826c64f2ec1f76feb4a6
[ "Apache-2.0" ]
2
2020-09-04T10:09:25.000Z
2021-11-30T20:43:50.000Z
src/kmr_behaviortree/plugins/action/plan_manipulator_path.cpp
stoic-roboticist/kmriiwa_ws_devel
582c2477ec29c9eb68bd826c64f2ec1f76feb4a6
[ "Apache-2.0" ]
10
2020-06-16T08:36:56.000Z
2022-03-29T07:48:11.000Z
// Copyright 2019 Nina Marie Wahl and Charlotte Heggem. // Copyright 2019 Norwegian University of Science and Technology. // // 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 "kmr_behaviortree/bt_action_node.hpp" #include "kmr_msgs/action/plan_to_frame.hpp" #include "trajectory_msgs/msg/joint_trajectory.hpp" #include <geometry_msgs/msg/pose_stamped.hpp> #include <iostream> namespace kmr_behavior_tree { class PlanManipulatorPathAction : public BtActionNode<kmr_msgs::action::PlanToFrame> { public: PlanManipulatorPathAction( const std::string & xml_tag_name, const std::string & action_name, const BT::NodeConfiguration & conf) : BtActionNode<kmr_msgs::action::PlanToFrame>(xml_tag_name, action_name, conf) { } void on_tick() override { if (!getInput("plan_to_frame", plan_to_frame)) { RCLCPP_ERROR(node_->get_logger(),"PlanToFrameAction: frame not provided"); return; } goal_.frame = plan_to_frame; RCLCPP_INFO(node_->get_logger(),"Start planning to %s", plan_to_frame.c_str()); if (plan_to_frame == "object"){ geometry_msgs::msg::PoseStamped pose_msg; getInput("object_pose",pose_msg); goal_.pose = pose_msg; } } BT::NodeStatus on_success() override { setOutput("manipulator_path", result_.result->path); setOutput("move_to_frame", plan_to_frame); return BT::NodeStatus::SUCCESS; } static BT::PortsList providedPorts() { return providedBasicPorts( { BT::InputPort<std::string>("plan_to_frame", "The frame MoveIt should plan to"), BT::InputPort<geometry_msgs::msg::PoseStamped>("object_pose", "Pose of the object manipulator should move to"), BT::OutputPort<trajectory_msgs::msg::JointTrajectory>("manipulator_path", "The path MoveIt has planned for the manipulator"), BT::OutputPort<std::string>("move_to_frame", "Frame we should move to"), }); } private: std::string plan_to_frame; }; } // namespace kmr_behavior_tree //register our custom TreeNodes into the BehaviorTreeFactory #include "behaviortree_cpp_v3/bt_factory.h" BT_REGISTER_NODES(factory) { BT::NodeBuilder builder = [](const std::string & name, const BT::NodeConfiguration & config) { return std::make_unique<kmr_behavior_tree::PlanManipulatorPathAction>( name, "/moveit/frame", config); }; factory.registerBuilder<kmr_behavior_tree::PlanManipulatorPathAction>( "PlanManipulatorPath", builder); }
33.505618
133
0.724346
stoic-roboticist
423765ec487b397f7871841a4b4f5ae931495248
1,882
cpp
C++
src/ColdTowerShopItem.cpp
dgi09/Tower-Defence
2edd53d50c9f913d00de26e7e2bdc5e8b950cc02
[ "BSD-2-Clause" ]
1
2021-07-28T15:24:00.000Z
2021-07-28T15:24:00.000Z
src/ColdTowerShopItem.cpp
dgi09/Tower-Defence
2edd53d50c9f913d00de26e7e2bdc5e8b950cc02
[ "BSD-2-Clause" ]
null
null
null
src/ColdTowerShopItem.cpp
dgi09/Tower-Defence
2edd53d50c9f913d00de26e7e2bdc5e8b950cc02
[ "BSD-2-Clause" ]
null
null
null
#include "ColdTowerShopItem.h" #include "GamePlayMediator.h" #include "ArenaHeap.h" #include <functional> #include "GUISystem.h" #include "TowerCreationTool.h" #include "ToolManager.h" #include "SplashCreationTool.h" ColdTowerShopItem::ColdTowerShopItem(void) { } ColdTowerShopItem::~ColdTowerShopItem(void) { } void ColdTowerShopItem::updateState(PlayerStat & stat) { if(stat.gold < itemCost) { button->loadImageFromFile("Data/ShopImages/coldTurretUnavailable.png"); state = UNACTIVE; } else { button->loadImageFromFile("Data/ShopImages/coldTurret.png"); state = ACTIVE; } button->setWidth(buttonW); button->setHeight(buttonH); } void ColdTowerShopItem::init() { initGUI("Cold Tower","Data/ShopImages/coldTurret.png"); button->subsribeEvent(PRESS,new MemberSubsciber<ColdTowerShopItem>(&ColdTowerShopItem::onClick,this)); tower = ArenaHeap::getPtr()->ColdTowers.New(); tower->init(); } void ColdTowerShopItem::onDestroy() { destroyGUI(); tower->destroy(); tower->removeFromHeap(); } void ColdTowerShopItem::onClick(Widget * sender) { if(state == ACTIVE) { TowerCreationTool * tool = new TowerCreationTool(); tool->setTower(tower->copy()); tool->setTowerCost(itemCost); ToolManager::getPtr()->setActiveTool(tool); } } void ColdTowerShopItem::setDamage(double damage) { tower->setDamageValue(damage); } void ColdTowerShopItem::setAmmoSpeed(int speed) { tower->setAmmoSpeed(speed); } void ColdTowerShopItem::setRange(double range) { tower->setRangeValue(range); } void ColdTowerShopItem::setShootRate(int ms) { tower->setShootRate(ms); } void ColdTowerShopItem::setSlowDuration(int ms) { tower->setSlowingDuration(ms); } void ColdTowerShopItem::setSpeedDecrease(int speedDecrease) { tower->setSpeedDecrease(speedDecrease); } void ColdTowerShopItem::postPropertySet() { ic.init(itemCost,tower); ic.attach(info); }
17.109091
103
0.745484
dgi09
423e648f5f47046258fed6b8938ba99d024c7d8f
3,229
cpp
C++
src/qt/qtbase/examples/widgets/graphicsview/boxes/glextensions.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
src/qt/qtbase/examples/widgets/graphicsview/boxes/glextensions.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/examples/widgets/graphicsview/boxes/glextensions.cpp
power-electro/phantomjs-Gohstdriver-DIY-openshift
a571d301a9658a4c1b524d07e15658b45f8a0579
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the demonstration applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "glextensions.h" #define RESOLVE_GL_FUNC(f) ok &= bool((f = (_gl##f) context->getProcAddress(QLatin1String("gl" #f)))); bool GLExtensionFunctions::resolve(const QGLContext *context) { bool ok = true; RESOLVE_GL_FUNC(GenFramebuffersEXT) RESOLVE_GL_FUNC(GenRenderbuffersEXT) RESOLVE_GL_FUNC(BindRenderbufferEXT) RESOLVE_GL_FUNC(RenderbufferStorageEXT) RESOLVE_GL_FUNC(DeleteFramebuffersEXT) RESOLVE_GL_FUNC(DeleteRenderbuffersEXT) RESOLVE_GL_FUNC(BindFramebufferEXT) RESOLVE_GL_FUNC(FramebufferTexture2DEXT) RESOLVE_GL_FUNC(FramebufferRenderbufferEXT) RESOLVE_GL_FUNC(CheckFramebufferStatusEXT) RESOLVE_GL_FUNC(ActiveTexture) RESOLVE_GL_FUNC(TexImage3D) RESOLVE_GL_FUNC(GenBuffers) RESOLVE_GL_FUNC(BindBuffer) RESOLVE_GL_FUNC(BufferData) RESOLVE_GL_FUNC(DeleteBuffers) RESOLVE_GL_FUNC(MapBuffer) RESOLVE_GL_FUNC(UnmapBuffer) return ok; } bool GLExtensionFunctions::fboSupported() { return GenFramebuffersEXT && GenRenderbuffersEXT && BindRenderbufferEXT && RenderbufferStorageEXT && DeleteFramebuffersEXT && DeleteRenderbuffersEXT && BindFramebufferEXT && FramebufferTexture2DEXT && FramebufferRenderbufferEXT && CheckFramebufferStatusEXT; } bool GLExtensionFunctions::openGL15Supported() { return ActiveTexture && TexImage3D && GenBuffers && BindBuffer && BufferData && DeleteBuffers && MapBuffer && UnmapBuffer; } #undef RESOLVE_GL_FUNC
35.483516
102
0.691855
power-electro
4244cf3519c3f83103e5e498a05f02df486a4631
91
cc
C++
muduo/net/boilerplate.cc
923310233/muduoTest
03c291df5605479ece4fc031ab3dd619c8c8f73a
[ "BSD-3-Clause" ]
null
null
null
muduo/net/boilerplate.cc
923310233/muduoTest
03c291df5605479ece4fc031ab3dd619c8c8f73a
[ "BSD-3-Clause" ]
null
null
null
muduo/net/boilerplate.cc
923310233/muduoTest
03c291df5605479ece4fc031ab3dd619c8c8f73a
[ "BSD-3-Clause" ]
null
null
null
#include "muduo/net/BoilerPlate.h" using namespace muduo; using namespace muduo::net;
10.111111
34
0.747253
923310233
424639e79751125238e05d98a96dd490fced1f81
1,074
cpp
C++
workshop8/IntlPhone.cpp
PavanKamra96/BTP200
516f5ed60452da53d47206caef22423825a3145e
[ "MIT" ]
null
null
null
workshop8/IntlPhone.cpp
PavanKamra96/BTP200
516f5ed60452da53d47206caef22423825a3145e
[ "MIT" ]
null
null
null
workshop8/IntlPhone.cpp
PavanKamra96/BTP200
516f5ed60452da53d47206caef22423825a3145e
[ "MIT" ]
null
null
null
#include <iostream> #include "Phone.h" IntlPhone::IntlPhone(){ country_Code = 0; } IntlPhone::IntlPhone(int regionCode, int areaCode, int localNumber): Phone(areaCode, localNumber) { //ctor if (regionCode >= 1 && regionCode <= 999) { country_Code = regionCode; } else *this = IntlPhone(); } void IntlPhone::display() const { std::cout << country_Code << '-'; Phone::display(); } bool IntlPhone::isValid() const { return country_Code != 0; } std::istream & operator >> (std::istream & is, IntlPhone & p) { int tempRegionCode; int tempAreaCode; int tempLocaleNumber; std::cout << "Country : "; is >> tempRegionCode; if (tempRegionCode >= 1 && tempRegionCode <= 999) { std::cout << "Area Code : "; is >> tempAreaCode; std::cout << "Local No. : "; is >> tempLocaleNumber; } IntlPhone temp(tempRegionCode, tempAreaCode, tempLocaleNumber); p = temp; return is; } std::ostream & operator << (std::ostream & os, const IntlPhone & p) { p.display(); return os; }
21.918367
100
0.608007
PavanKamra96
42465f2891251668ec041517ceea4841891deed4
800
cpp
C++
src/components/src/core/Component.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
6
2021-04-20T10:32:29.000Z
2021-06-05T11:48:56.000Z
src/components/src/core/Component.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
1
2021-05-18T21:00:12.000Z
2021-06-02T07:59:03.000Z
src/components/src/core/Component.cpp
walter-strazak/chimarrao
b4c9f9d726eb5e46d61b33e10b7579cc5512cd09
[ "MIT" ]
3
2020-09-12T08:54:04.000Z
2021-04-17T11:16:36.000Z
#include "Component.h" #include "ComponentOwner.h" namespace components::core { Component::Component(ComponentOwner* ownerInit) : owner{ownerInit} {} void Component::loadDependentComponents() {} void Component::update(utils::DeltaTime, const input::Input&) {} void Component::lateUpdate(utils::DeltaTime, const input::Input&) {} void Component::enable() { enabled = true; } void Component::disable() { enabled = false; } bool Component::isEnabled() const { return enabled; } std::string Component::getOwnerName() const { return owner->getName(); } unsigned int Component::getOwnerId() const { return owner->getId(); } bool Component::shouldBeRemoved() const { return owner->shouldBeRemoved(); } ComponentOwner& Component::getOwner() const { return *owner; } }
16
69
0.70625
walter-strazak
4247f6d342a62cdcce8c0dab9c859a873e016ffa
13,178
cpp
C++
Nacro/SDK/FN_BP_FortExpeditionListItem_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_BP_FortExpeditionListItem_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_BP_FortExpeditionListItem_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Update Bang State // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortAccountItem* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Update_Bang_State(class UFortAccountItem* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Update Bang State"); UBP_FortExpeditionListItem_C_Update_Bang_State_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Success Chance // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Set_Success_Chance(class UFortExpeditionItem* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Success Chance"); UBP_FortExpeditionListItem_C_Set_Success_Chance_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Vehicle Icon // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* Expedition (ConstParm, Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Set_Vehicle_Icon(class UFortExpeditionItem* Expedition) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Vehicle Icon"); UBP_FortExpeditionListItem_C_Set_Vehicle_Icon_Params params; params.Expedition = Expedition; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Expedition Returns Data // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* InputPin (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Set_Expedition_Returns_Data(class UFortExpeditionItem* InputPin) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Expedition Returns Data"); UBP_FortExpeditionListItem_C_Set_Expedition_Returns_Data_Params params; params.InputPin = InputPin; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set In Progress State // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Set_In_Progress_State(class UFortExpeditionItem* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set In Progress State"); UBP_FortExpeditionListItem_C_Set_In_Progress_State_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Remaining Expiration Time // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Set_Remaining_Expiration_Time(class UFortExpeditionItem* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Remaining Expiration Time"); UBP_FortExpeditionListItem_C_Set_Remaining_Expiration_Time_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rarity // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Set_Rarity(class UFortItem* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rarity"); UBP_FortExpeditionListItem_C_Set_Rarity_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rating // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Set_Rating(class UFortExpeditionItem* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rating"); UBP_FortExpeditionListItem_C_Set_Rating_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rewards // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Set_Rewards(class UFortItem* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Rewards"); UBP_FortExpeditionListItem_C_Set_Rewards_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Get Expedition Item Definition // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData) // class UFortExpeditionItemDefinition* Item_Def (Parm, OutParm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Get_Expedition_Item_Definition(class UFortItem* Item, class UFortExpeditionItemDefinition** Item_Def) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Get Expedition Item Definition"); UBP_FortExpeditionListItem_C_Get_Expedition_Item_Definition_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Item_Def != nullptr) *Item_Def = params.Item_Def; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Name // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortItem* Item (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Set_Name(class UFortItem* Item) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Set Name"); UBP_FortExpeditionListItem_C_Set_Name_Params params; params.Item = Item; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Setup Base Item Data // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // class UFortExpeditionItem* Expedition (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::Setup_Base_Item_Data(class UFortExpeditionItem* Expedition) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.Setup Base Item Data"); UBP_FortExpeditionListItem_C_Setup_Base_Item_Data_Params params; params.Expedition = Expedition; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.SetData // (Event, Public, BlueprintCallable, BlueprintEvent) // Parameters: // class UObject** InData (Parm, ZeroConstructor, IsPlainOldData) // class UCommonListView** OwningList (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::SetData(class UObject** InData, class UCommonListView** OwningList) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.SetData"); UBP_FortExpeditionListItem_C_SetData_Params params; params.InData = InData; params.OwningList = OwningList; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnSelected // (Event, Protected, BlueprintEvent) void UBP_FortExpeditionListItem_C::OnSelected() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnSelected"); UBP_FortExpeditionListItem_C_OnSelected_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnItemChanged // (Event, Protected, BlueprintEvent) void UBP_FortExpeditionListItem_C::OnItemChanged() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnItemChanged"); UBP_FortExpeditionListItem_C_OnItemChanged_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnDeselected // (Event, Protected, BlueprintEvent) void UBP_FortExpeditionListItem_C::OnDeselected() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnDeselected"); UBP_FortExpeditionListItem_C_OnDeselected_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature // (BlueprintEvent) // Parameters: // class UWidget* ActiveWidget (Parm, ZeroConstructor, IsPlainOldData) // int ActiveWidgetIndex (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature(class UWidget* ActiveWidget, int ActiveWidgetIndex) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature"); UBP_FortExpeditionListItem_C_BndEvt__InProgressSwitcher_K2Node_ComponentBoundEvent_17_OnActiveWidgetChanged__DelegateSignature_Params params; params.ActiveWidget = ActiveWidget; params.ActiveWidgetIndex = ActiveWidgetIndex; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnHovered // (Event, Protected, BlueprintEvent) void UBP_FortExpeditionListItem_C::OnHovered() { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.OnHovered"); UBP_FortExpeditionListItem_C_OnHovered_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.ExecuteUbergraph_BP_FortExpeditionListItem // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UBP_FortExpeditionListItem_C::ExecuteUbergraph_BP_FortExpeditionListItem(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function BP_FortExpeditionListItem.BP_FortExpeditionListItem_C.ExecuteUbergraph_BP_FortExpeditionListItem"); UBP_FortExpeditionListItem_C_ExecuteUbergraph_BP_FortExpeditionListItem_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
33.277778
213
0.773258
Milxnor
4249a13c522a0727ca53058a12a138656bd75265
3,962
cxx
C++
Google_hashcode/2018/main.cxx
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
Google_hashcode/2018/main.cxx
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
Google_hashcode/2018/main.cxx
mstrechen/cp
ffac439840a71f70580a0ef197e47479e167a0eb
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<random> #include<algorithm> #include<tuple> using namespace std; const int INF = 2000*1000*1000; struct Ride{ int x1, y1; int x2, y2; int l, r; int index; int getLen(int, int, int) const; int getCost(int, int, int) const; }; int Ride::getLen(int x, int y, int t) const{ int first_len = t + max(abs(x1 - x) + abs(y1 - y), l); int second_len = abs(x1 - x2) + abs(y1 - y2); if(first_len + second_len >= r) return INF; return first_len + second_len; } int Ride::getCost(int x, int y, int t) const { int first_len = t + max(abs(x1 - x) + abs(y1 - y), l); int second_len = abs(x1 - x2) + abs(y1 - y2); if(first_len + second_len >= r) return INF; return first_len; } struct City{ int R, C, F, N, B, T; vector<Ride> rides; vector<tuple<int, int, int> > currentPos; vector<vector<int> > finalRides; void calculateRides(); }; void City::calculateRides(){ srand(0); int max_iterations_cnt = 1000*10; while(max_iterations_cnt-- && rides.size()){ int i = rand() % finalRides.size(); auto & currentCar = currentPos[i]; auto get_optimal = [&](const auto & a, const auto & b){ int t1 = a.getCost(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar)); int t2 = b.getCost(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar)); return t1 > t2; }; auto it = max_element(rides.begin(), rides.end(), get_optimal); int tmp = 41; while(it->getLen(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar)) != INF){ finalRides[i].push_back(it->index); currentCar = make_tuple(it->x2, it->y2, it->getLen(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar))); rides.erase(it); if(rides.size() == 0 || tmp-- == 0) break; it = max_element(rides.begin(), rides.end(), get_optimal); } } /* for(int _i = 0; _i < iterations_count; _i++){ int i = UID(gen); auto & currentCar = currentPos[i]; auto it = max_element(rides.begin(), rides.end(), [&](const auto & a, const auto & b){ int t1 = a.getCost(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar)); int t2 = b.getCost(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar)); return t1 < t2;} ); finalRides[i].push_back(it->index); currentCar = {it->y1, it->y2, it->getLen(get<0>(currentCar), get<1>(currentCar), get<2>(currentCar))}; rides.erase(it); } */ } istream & operator >> (istream & in, Ride & toRead){ in >> toRead.x1 >> toRead.y1 >> toRead.x2 >> toRead.y2 >> toRead.l >> toRead.r; return in; } istream & operator >> (istream & in, City & toRead){ in >> toRead.R >> toRead.C >> toRead.F >> toRead.N >> toRead.B >> toRead.T; toRead.rides.resize(toRead.N); toRead.finalRides.resize(toRead.F); toRead.currentPos.assign(toRead.F, tuple<int, int, int>(0, 0, 0)); int j = 0; for(auto & i : toRead.rides){ in >> i; i.index = j; j++; } return in; }; ostream & operator << (ostream & out, const City & toWrite){ for(auto & i : toWrite.finalRides){ cout << i.size(); for(auto & j : i) cout << ' ' << j; cout << '\n'; } return out; } int main(int argc, char ** argv){ int MIA = atoi(argv[1]); ios::sync_with_stdio(false); cin.tie(nullptr); City city; cin >> city; city.calculateRides(); cout << city; return 0; }
25.235669
124
0.513882
mstrechen
424b58ad8420784e1df4081159cab8fabb0cb5d7
1,073
cpp
C++
CodeChef/TSHIRTS.cpp
ggml1/Competitive-Programming
1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79
[ "MIT" ]
null
null
null
CodeChef/TSHIRTS.cpp
ggml1/Competitive-Programming
1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79
[ "MIT" ]
null
null
null
CodeChef/TSHIRTS.cpp
ggml1/Competitive-Programming
1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; const ll mod = 1e9 + 7; const int ms = 123; const int mv = 11; ll dp[ms][1 << mv]; ll ways(int x, ll mask, ll limit, vector<int> shirts[], int n){ if(shirts[x].size() == 0) return ways(x+1, mask, limit, shirts, n); if(mask == limit){ return 1; } if(x >= 101) return 0; if(dp[x][mask] != -1){ return dp[x][mask]; } ll ans = ways(x+1, mask, limit, shirts, n); for(int j = 0, c = shirts[x].size(); j < c; ++j){ if(!(mask & (1 << shirts[x][j]))){ ans += ways(x+1, mask | (1 << shirts[x][j]), limit, shirts, n); ans %= mod; } } return dp[x][mask] = ans; } int main(){ ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--){ int n; cin >> n; cin.ignore(); vector<int> shirts[ms]; for(int i = 0; i < n; ++i){ int x; string k; getline(cin, k); stringstream ss(k); while(ss >> x){ shirts[x].push_back(i); } } memset(dp, -1, sizeof(dp)); cout << ways(0, 0, (1 << n) - 1, shirts, n) << endl; } return 0; }
17.031746
68
0.520969
ggml1
424b68c2de65ac475af42da66f7a935a66b8460f
299
cpp
C++
13_ploymorph/main.cpp
Aaron-labo/Cpp_StudyNotes
afff37736468b26dad87e9b5cda90f1e5f1efb06
[ "Unlicense" ]
1
2021-06-17T11:37:42.000Z
2021-06-17T11:37:42.000Z
13_ploymorph/main.cpp
Aaron-labo/Cpp_StudyNotes
afff37736468b26dad87e9b5cda90f1e5f1efb06
[ "Unlicense" ]
null
null
null
13_ploymorph/main.cpp
Aaron-labo/Cpp_StudyNotes
afff37736468b26dad87e9b5cda90f1e5f1efb06
[ "Unlicense" ]
null
null
null
#include "Circle.h" #include "Rect.h" int main() { Circle c(1, 2, 3); Rect r(10, 20, 30, 40); Shape s(1, 2); s.show(); int input; while (1) { cin >> input; switch (input) { case 1: s = &c;; s->show(); break; case 2: s = &r;; s->show(); break; } } return 0; }
10.678571
24
0.478261
Aaron-labo
424f0a9d20c8f5343f00778ce197924e1945e367
1,178
cpp
C++
Based_Engine/Based_Engine/TextureResource.cpp
Sanmopre/Based_Engine
2a408dc501f6357bde9872e2eef70f67295e0a3a
[ "MIT" ]
null
null
null
Based_Engine/Based_Engine/TextureResource.cpp
Sanmopre/Based_Engine
2a408dc501f6357bde9872e2eef70f67295e0a3a
[ "MIT" ]
null
null
null
Based_Engine/Based_Engine/TextureResource.cpp
Sanmopre/Based_Engine
2a408dc501f6357bde9872e2eef70f67295e0a3a
[ "MIT" ]
null
null
null
#include "TextureResource.h" #include "FileSystem.h" TextureResource::TextureResource(uint uid, const char* assetsFile, const char* libraryFile) : Resource(uid, FileType::IMAGE, assetsFile, libraryFile) { } TextureResource::~TextureResource() { } const Texture TextureResource::GetTexture() const { return texture; } bool TextureResource::LoadInMemory() { texture = TextureLoader::Load(assetsFile.c_str()); if (texture.id != NULL) return true; return false; } bool TextureResource::Unload() { texture = { NULL, NULL, NULL }; return true; } //void Input::ProccesImage(std::string file) //{ // GameObject* object = App->objects->selected; // if (!object) // { // object = App->objects->AddObject(nullptr, App->objects->selected, true, "Plane"); // object->AddMeshComponent("Library/Meshes/plane.monki", file.c_str()); // } // else // { // bool found = false; // for (uint c = 0; c < object->components.size(); c++) // { // if (object->components[c]->AddTexture(file.c_str())) // { // found = true; // break; // } // } // if (!found) // object->AddMeshComponent("Library/Meshes/plane.monki", file.c_str()); // } //}
20.666667
91
0.643463
Sanmopre
4250158ef2b3d006b1cdb28c80860f418155bc23
1,269
cpp
C++
508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/base-types.cpp
NekoSilverFox/CPP
c6797264fceda4a65ac3452acca496e468d1365a
[ "Apache-2.0" ]
5
2020-02-08T20:57:21.000Z
2021-12-23T06:24:41.000Z
508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/base-types.cpp
NekoSilverFox/CPP
c6797264fceda4a65ac3452acca496e468d1365a
[ "Apache-2.0" ]
2
2020-03-02T14:44:55.000Z
2020-11-11T16:25:33.000Z
508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/base-types.cpp
NekoSilverFox/CPP
c6797264fceda4a65ac3452acca496e468d1365a
[ "Apache-2.0" ]
4
2020-09-27T17:30:03.000Z
2022-02-16T09:48:23.000Z
#include "base-types.hpp" #include <ostream> #include <cmath> bool yakovlev::operator==(const point_t & lhs, const point_t & rhs) noexcept { return (lhs.x == rhs.x) && (lhs.y == rhs.y); } bool yakovlev::operator!=(const point_t & lhs, const point_t & rhs) noexcept { return !(lhs == rhs); } std::ostream& yakovlev::operator<<(std::ostream & os, const point_t & point) { return os << '(' << point.x << ", " << point.y << ')'; } namespace { double square(double x) noexcept; } double yakovlev::getDistanceBetweenPoints(const point_t & p1, const point_t & p2) noexcept { return sqrt(square(p1.x - p2.x) + square(p1.y - p2.y)); } bool yakovlev::areOverlapping(const rectangle_t & lhs, const rectangle_t & rhs) noexcept { return (abs(lhs.pos.x - rhs.pos.x) < ((lhs.width + rhs.width) / 2.0)) && (abs(lhs.pos.y - rhs.pos.y) < ((lhs.height + rhs.height) / 2.0)); } bool yakovlev::operator==(const rectangle_t & lhs, const rectangle_t & rhs) noexcept { return (lhs.width == rhs.width) && (lhs.height == rhs.height) && (lhs.pos == rhs.pos); } bool yakovlev::operator!=(const rectangle_t & lhs, const rectangle_t & rhs) noexcept { return !(lhs == rhs); } namespace { double square(double x) noexcept { return x * x; } }
22.660714
90
0.63357
NekoSilverFox
4252acccfbd215a271503823aa57cb38bd306a22
25,064
cc
C++
videoenhan/src/VideoenhanClient.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
videoenhan/src/VideoenhanClient.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
videoenhan/src/VideoenhanClient.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/videoenhan/VideoenhanClient.h> #include <alibabacloud/core/SimpleCredentialsProvider.h> using namespace AlibabaCloud; using namespace AlibabaCloud::Location; using namespace AlibabaCloud::Videoenhan; using namespace AlibabaCloud::Videoenhan::Model; namespace { const std::string SERVICE_NAME = "videoenhan"; } VideoenhanClient::VideoenhanClient(const Credentials &credentials, const ClientConfiguration &configuration) : RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(credentials), configuration) { auto locationClient = std::make_shared<LocationClient>(credentials, configuration); endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "videoenhan"); } VideoenhanClient::VideoenhanClient(const std::shared_ptr<CredentialsProvider>& credentialsProvider, const ClientConfiguration & configuration) : RpcServiceClient(SERVICE_NAME, credentialsProvider, configuration) { auto locationClient = std::make_shared<LocationClient>(credentialsProvider, configuration); endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "videoenhan"); } VideoenhanClient::VideoenhanClient(const std::string & accessKeyId, const std::string & accessKeySecret, const ClientConfiguration & configuration) : RpcServiceClient(SERVICE_NAME, std::make_shared<SimpleCredentialsProvider>(accessKeyId, accessKeySecret), configuration) { auto locationClient = std::make_shared<LocationClient>(accessKeyId, accessKeySecret, configuration); endpointProvider_ = std::make_shared<EndpointProvider>(locationClient, configuration.regionId(), SERVICE_NAME, "videoenhan"); } VideoenhanClient::~VideoenhanClient() {} VideoenhanClient::AbstractEcommerceVideoOutcome VideoenhanClient::abstractEcommerceVideo(const AbstractEcommerceVideoRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return AbstractEcommerceVideoOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return AbstractEcommerceVideoOutcome(AbstractEcommerceVideoResult(outcome.result())); else return AbstractEcommerceVideoOutcome(outcome.error()); } void VideoenhanClient::abstractEcommerceVideoAsync(const AbstractEcommerceVideoRequest& request, const AbstractEcommerceVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, abstractEcommerceVideo(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::AbstractEcommerceVideoOutcomeCallable VideoenhanClient::abstractEcommerceVideoCallable(const AbstractEcommerceVideoRequest &request) const { auto task = std::make_shared<std::packaged_task<AbstractEcommerceVideoOutcome()>>( [this, request]() { return this->abstractEcommerceVideo(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::AbstractFilmVideoOutcome VideoenhanClient::abstractFilmVideo(const AbstractFilmVideoRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return AbstractFilmVideoOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return AbstractFilmVideoOutcome(AbstractFilmVideoResult(outcome.result())); else return AbstractFilmVideoOutcome(outcome.error()); } void VideoenhanClient::abstractFilmVideoAsync(const AbstractFilmVideoRequest& request, const AbstractFilmVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, abstractFilmVideo(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::AbstractFilmVideoOutcomeCallable VideoenhanClient::abstractFilmVideoCallable(const AbstractFilmVideoRequest &request) const { auto task = std::make_shared<std::packaged_task<AbstractFilmVideoOutcome()>>( [this, request]() { return this->abstractFilmVideo(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::AddFaceVideoTemplateOutcome VideoenhanClient::addFaceVideoTemplate(const AddFaceVideoTemplateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return AddFaceVideoTemplateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return AddFaceVideoTemplateOutcome(AddFaceVideoTemplateResult(outcome.result())); else return AddFaceVideoTemplateOutcome(outcome.error()); } void VideoenhanClient::addFaceVideoTemplateAsync(const AddFaceVideoTemplateRequest& request, const AddFaceVideoTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, addFaceVideoTemplate(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::AddFaceVideoTemplateOutcomeCallable VideoenhanClient::addFaceVideoTemplateCallable(const AddFaceVideoTemplateRequest &request) const { auto task = std::make_shared<std::packaged_task<AddFaceVideoTemplateOutcome()>>( [this, request]() { return this->addFaceVideoTemplate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::AdjustVideoColorOutcome VideoenhanClient::adjustVideoColor(const AdjustVideoColorRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return AdjustVideoColorOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return AdjustVideoColorOutcome(AdjustVideoColorResult(outcome.result())); else return AdjustVideoColorOutcome(outcome.error()); } void VideoenhanClient::adjustVideoColorAsync(const AdjustVideoColorRequest& request, const AdjustVideoColorAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, adjustVideoColor(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::AdjustVideoColorOutcomeCallable VideoenhanClient::adjustVideoColorCallable(const AdjustVideoColorRequest &request) const { auto task = std::make_shared<std::packaged_task<AdjustVideoColorOutcome()>>( [this, request]() { return this->adjustVideoColor(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::ChangeVideoSizeOutcome VideoenhanClient::changeVideoSize(const ChangeVideoSizeRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ChangeVideoSizeOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ChangeVideoSizeOutcome(ChangeVideoSizeResult(outcome.result())); else return ChangeVideoSizeOutcome(outcome.error()); } void VideoenhanClient::changeVideoSizeAsync(const ChangeVideoSizeRequest& request, const ChangeVideoSizeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, changeVideoSize(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::ChangeVideoSizeOutcomeCallable VideoenhanClient::changeVideoSizeCallable(const ChangeVideoSizeRequest &request) const { auto task = std::make_shared<std::packaged_task<ChangeVideoSizeOutcome()>>( [this, request]() { return this->changeVideoSize(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::ConvertHdrVideoOutcome VideoenhanClient::convertHdrVideo(const ConvertHdrVideoRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ConvertHdrVideoOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ConvertHdrVideoOutcome(ConvertHdrVideoResult(outcome.result())); else return ConvertHdrVideoOutcome(outcome.error()); } void VideoenhanClient::convertHdrVideoAsync(const ConvertHdrVideoRequest& request, const ConvertHdrVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, convertHdrVideo(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::ConvertHdrVideoOutcomeCallable VideoenhanClient::convertHdrVideoCallable(const ConvertHdrVideoRequest &request) const { auto task = std::make_shared<std::packaged_task<ConvertHdrVideoOutcome()>>( [this, request]() { return this->convertHdrVideo(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::DeleteFaceVideoTemplateOutcome VideoenhanClient::deleteFaceVideoTemplate(const DeleteFaceVideoTemplateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return DeleteFaceVideoTemplateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return DeleteFaceVideoTemplateOutcome(DeleteFaceVideoTemplateResult(outcome.result())); else return DeleteFaceVideoTemplateOutcome(outcome.error()); } void VideoenhanClient::deleteFaceVideoTemplateAsync(const DeleteFaceVideoTemplateRequest& request, const DeleteFaceVideoTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, deleteFaceVideoTemplate(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::DeleteFaceVideoTemplateOutcomeCallable VideoenhanClient::deleteFaceVideoTemplateCallable(const DeleteFaceVideoTemplateRequest &request) const { auto task = std::make_shared<std::packaged_task<DeleteFaceVideoTemplateOutcome()>>( [this, request]() { return this->deleteFaceVideoTemplate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::EnhanceVideoQualityOutcome VideoenhanClient::enhanceVideoQuality(const EnhanceVideoQualityRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return EnhanceVideoQualityOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return EnhanceVideoQualityOutcome(EnhanceVideoQualityResult(outcome.result())); else return EnhanceVideoQualityOutcome(outcome.error()); } void VideoenhanClient::enhanceVideoQualityAsync(const EnhanceVideoQualityRequest& request, const EnhanceVideoQualityAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, enhanceVideoQuality(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::EnhanceVideoQualityOutcomeCallable VideoenhanClient::enhanceVideoQualityCallable(const EnhanceVideoQualityRequest &request) const { auto task = std::make_shared<std::packaged_task<EnhanceVideoQualityOutcome()>>( [this, request]() { return this->enhanceVideoQuality(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::EraseVideoLogoOutcome VideoenhanClient::eraseVideoLogo(const EraseVideoLogoRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return EraseVideoLogoOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return EraseVideoLogoOutcome(EraseVideoLogoResult(outcome.result())); else return EraseVideoLogoOutcome(outcome.error()); } void VideoenhanClient::eraseVideoLogoAsync(const EraseVideoLogoRequest& request, const EraseVideoLogoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, eraseVideoLogo(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::EraseVideoLogoOutcomeCallable VideoenhanClient::eraseVideoLogoCallable(const EraseVideoLogoRequest &request) const { auto task = std::make_shared<std::packaged_task<EraseVideoLogoOutcome()>>( [this, request]() { return this->eraseVideoLogo(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::EraseVideoSubtitlesOutcome VideoenhanClient::eraseVideoSubtitles(const EraseVideoSubtitlesRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return EraseVideoSubtitlesOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return EraseVideoSubtitlesOutcome(EraseVideoSubtitlesResult(outcome.result())); else return EraseVideoSubtitlesOutcome(outcome.error()); } void VideoenhanClient::eraseVideoSubtitlesAsync(const EraseVideoSubtitlesRequest& request, const EraseVideoSubtitlesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, eraseVideoSubtitles(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::EraseVideoSubtitlesOutcomeCallable VideoenhanClient::eraseVideoSubtitlesCallable(const EraseVideoSubtitlesRequest &request) const { auto task = std::make_shared<std::packaged_task<EraseVideoSubtitlesOutcome()>>( [this, request]() { return this->eraseVideoSubtitles(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::GenerateVideoOutcome VideoenhanClient::generateVideo(const GenerateVideoRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return GenerateVideoOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return GenerateVideoOutcome(GenerateVideoResult(outcome.result())); else return GenerateVideoOutcome(outcome.error()); } void VideoenhanClient::generateVideoAsync(const GenerateVideoRequest& request, const GenerateVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, generateVideo(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::GenerateVideoOutcomeCallable VideoenhanClient::generateVideoCallable(const GenerateVideoRequest &request) const { auto task = std::make_shared<std::packaged_task<GenerateVideoOutcome()>>( [this, request]() { return this->generateVideo(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::GetAsyncJobResultOutcome VideoenhanClient::getAsyncJobResult(const GetAsyncJobResultRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return GetAsyncJobResultOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return GetAsyncJobResultOutcome(GetAsyncJobResultResult(outcome.result())); else return GetAsyncJobResultOutcome(outcome.error()); } void VideoenhanClient::getAsyncJobResultAsync(const GetAsyncJobResultRequest& request, const GetAsyncJobResultAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, getAsyncJobResult(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::GetAsyncJobResultOutcomeCallable VideoenhanClient::getAsyncJobResultCallable(const GetAsyncJobResultRequest &request) const { auto task = std::make_shared<std::packaged_task<GetAsyncJobResultOutcome()>>( [this, request]() { return this->getAsyncJobResult(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::InterpolateVideoFrameOutcome VideoenhanClient::interpolateVideoFrame(const InterpolateVideoFrameRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return InterpolateVideoFrameOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return InterpolateVideoFrameOutcome(InterpolateVideoFrameResult(outcome.result())); else return InterpolateVideoFrameOutcome(outcome.error()); } void VideoenhanClient::interpolateVideoFrameAsync(const InterpolateVideoFrameRequest& request, const InterpolateVideoFrameAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, interpolateVideoFrame(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::InterpolateVideoFrameOutcomeCallable VideoenhanClient::interpolateVideoFrameCallable(const InterpolateVideoFrameRequest &request) const { auto task = std::make_shared<std::packaged_task<InterpolateVideoFrameOutcome()>>( [this, request]() { return this->interpolateVideoFrame(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::MergeVideoFaceOutcome VideoenhanClient::mergeVideoFace(const MergeVideoFaceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return MergeVideoFaceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return MergeVideoFaceOutcome(MergeVideoFaceResult(outcome.result())); else return MergeVideoFaceOutcome(outcome.error()); } void VideoenhanClient::mergeVideoFaceAsync(const MergeVideoFaceRequest& request, const MergeVideoFaceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, mergeVideoFace(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::MergeVideoFaceOutcomeCallable VideoenhanClient::mergeVideoFaceCallable(const MergeVideoFaceRequest &request) const { auto task = std::make_shared<std::packaged_task<MergeVideoFaceOutcome()>>( [this, request]() { return this->mergeVideoFace(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::MergeVideoModelFaceOutcome VideoenhanClient::mergeVideoModelFace(const MergeVideoModelFaceRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return MergeVideoModelFaceOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return MergeVideoModelFaceOutcome(MergeVideoModelFaceResult(outcome.result())); else return MergeVideoModelFaceOutcome(outcome.error()); } void VideoenhanClient::mergeVideoModelFaceAsync(const MergeVideoModelFaceRequest& request, const MergeVideoModelFaceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, mergeVideoModelFace(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::MergeVideoModelFaceOutcomeCallable VideoenhanClient::mergeVideoModelFaceCallable(const MergeVideoModelFaceRequest &request) const { auto task = std::make_shared<std::packaged_task<MergeVideoModelFaceOutcome()>>( [this, request]() { return this->mergeVideoModelFace(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::QueryFaceVideoTemplateOutcome VideoenhanClient::queryFaceVideoTemplate(const QueryFaceVideoTemplateRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return QueryFaceVideoTemplateOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return QueryFaceVideoTemplateOutcome(QueryFaceVideoTemplateResult(outcome.result())); else return QueryFaceVideoTemplateOutcome(outcome.error()); } void VideoenhanClient::queryFaceVideoTemplateAsync(const QueryFaceVideoTemplateRequest& request, const QueryFaceVideoTemplateAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, queryFaceVideoTemplate(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::QueryFaceVideoTemplateOutcomeCallable VideoenhanClient::queryFaceVideoTemplateCallable(const QueryFaceVideoTemplateRequest &request) const { auto task = std::make_shared<std::packaged_task<QueryFaceVideoTemplateOutcome()>>( [this, request]() { return this->queryFaceVideoTemplate(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::SuperResolveVideoOutcome VideoenhanClient::superResolveVideo(const SuperResolveVideoRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return SuperResolveVideoOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return SuperResolveVideoOutcome(SuperResolveVideoResult(outcome.result())); else return SuperResolveVideoOutcome(outcome.error()); } void VideoenhanClient::superResolveVideoAsync(const SuperResolveVideoRequest& request, const SuperResolveVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, superResolveVideo(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::SuperResolveVideoOutcomeCallable VideoenhanClient::superResolveVideoCallable(const SuperResolveVideoRequest &request) const { auto task = std::make_shared<std::packaged_task<SuperResolveVideoOutcome()>>( [this, request]() { return this->superResolveVideo(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); } VideoenhanClient::ToneSdrVideoOutcome VideoenhanClient::toneSdrVideo(const ToneSdrVideoRequest &request) const { auto endpointOutcome = endpointProvider_->getEndpoint(); if (!endpointOutcome.isSuccess()) return ToneSdrVideoOutcome(endpointOutcome.error()); auto outcome = makeRequest(endpointOutcome.result(), request); if (outcome.isSuccess()) return ToneSdrVideoOutcome(ToneSdrVideoResult(outcome.result())); else return ToneSdrVideoOutcome(outcome.error()); } void VideoenhanClient::toneSdrVideoAsync(const ToneSdrVideoRequest& request, const ToneSdrVideoAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context) const { auto fn = [this, request, handler, context]() { handler(this, request, toneSdrVideo(request), context); }; asyncExecute(new Runnable(fn)); } VideoenhanClient::ToneSdrVideoOutcomeCallable VideoenhanClient::toneSdrVideoCallable(const ToneSdrVideoRequest &request) const { auto task = std::make_shared<std::packaged_task<ToneSdrVideoOutcome()>>( [this, request]() { return this->toneSdrVideo(request); }); asyncExecute(new Runnable([task]() { (*task)(); })); return task->get_future(); }
35.703704
214
0.787464
aliyun
4252b1138e785857031adf5a59146588d37796ea
5,448
cc
C++
chromeos/components/string_matching/prefix_matcher.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chromeos/components/string_matching/prefix_matcher.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chromeos/components/string_matching/prefix_matcher.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2020 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 "chromeos/components/string_matching/prefix_matcher.h" #include "base/check.h" #include "base/macros.h" #include "chromeos/components/string_matching/tokenized_string.h" #include "chromeos/components/string_matching/tokenized_string_char_iterator.h" namespace chromeos { namespace string_matching { namespace { // The factors below are applied when the current char of query matches // the current char of the text to be matched. Different factors are chosen // based on where the match happens. kIsPrefixMultiplier is used when the // matched portion is a prefix of both the query and the text, which implies // that the matched chars are at the same position in query and text. This is // the most preferred case thus it has the highest score. When the current char // of the query and the text does not match, the algorithm moves to the next // token in the text and try to match from there. kIsFrontOfWordMultipler will // be used if the first char of the token matches the current char of the query. // Otherwise, the match is considered as weak and kIsWeakHitMultiplier is // used. // Examples: // Suppose the text to be matched is 'Google Chrome'. // Query 'go' would yield kIsPrefixMultiplier for each char. // Query 'gc' would use kIsPrefixMultiplier for 'g' and // kIsFrontOfWordMultipler for 'c'. // Query 'ch' would use kIsFrontOfWordMultipler for 'c' and // kIsWeakHitMultiplier for 'h'. const double kIsPrefixMultiplier = 1.0; const double kIsFrontOfWordMultipler = 0.8; const double kIsWeakHitMultiplier = 0.6; // A relevance score that represents no match. const double kNoMatchScore = 0.0; } // namespace PrefixMatcher::PrefixMatcher(const TokenizedString& query, const TokenizedString& text) : query_iter_(query), text_iter_(text), current_match_(gfx::Range::InvalidRange()), current_relevance_(kNoMatchScore) {} bool PrefixMatcher::Match() { while (!RunMatch()) { // No match found and no more states to try. Bail out. if (states_.empty()) { current_relevance_ = kNoMatchScore; current_hits_.clear(); return false; } PopState(); // Skip restored match to try other possibilities. AdvanceToNextTextToken(); } if (current_match_.IsValid()) current_hits_.push_back(current_match_); return true; } PrefixMatcher::State::State() : relevance(kNoMatchScore) {} PrefixMatcher::State::~State() = default; PrefixMatcher::State::State(double relevance, const gfx::Range& current_match, const Hits& hits, const TokenizedStringCharIterator& query_iter, const TokenizedStringCharIterator& text_iter) : relevance(relevance), current_match(current_match), hits(hits.begin(), hits.end()), query_iter_state(query_iter.GetState()), text_iter_state(text_iter.GetState()) {} PrefixMatcher::State::State(const PrefixMatcher::State& state) = default; bool PrefixMatcher::RunMatch() { bool have_match_already = false; while (!query_iter_.end() && !text_iter_.end()) { if (query_iter_.Get() == text_iter_.Get()) { PushState(); if (query_iter_.GetArrayPos() == text_iter_.GetArrayPos()) current_relevance_ += kIsPrefixMultiplier; else if (text_iter_.IsFirstCharOfToken()) current_relevance_ += kIsFrontOfWordMultipler; else current_relevance_ += kIsWeakHitMultiplier; if (!current_match_.IsValid()) current_match_.set_start(text_iter_.GetArrayPos()); current_match_.set_end(text_iter_.GetArrayPos() + text_iter_.GetCharSize()); query_iter_.NextChar(); text_iter_.NextChar(); have_match_already = true; } else { // There are two possibilities here: // 1. Need to AdvanceToNextTextToken() after having at least a match in // current token (e.g. match the first character of the token) and the // next character doesn't match. // 2. Need to AdvanceToNextTextToken() because there is no match in // current token. // If there is no match in current token and we already have match (in // previous tokens) before, a token is skipped and we consider this as no // match. if (text_iter_.IsFirstCharOfToken() && have_match_already) return false; AdvanceToNextTextToken(); } } return query_iter_.end(); } void PrefixMatcher::AdvanceToNextTextToken() { if (current_match_.IsValid()) { current_hits_.push_back(current_match_); current_match_ = gfx::Range::InvalidRange(); } text_iter_.NextToken(); } void PrefixMatcher::PushState() { states_.push_back(State(current_relevance_, current_match_, current_hits_, query_iter_, text_iter_)); } void PrefixMatcher::PopState() { DCHECK(!states_.empty()); State& last_match = states_.back(); current_relevance_ = last_match.relevance; current_match_ = last_match.current_match; current_hits_.swap(last_match.hits); query_iter_.SetState(last_match.query_iter_state); text_iter_.SetState(last_match.text_iter_state); states_.pop_back(); } } // namespace string_matching } // namespace chromeos
35.607843
80
0.699523
mghgroup
425a0925749b56a4129bb1aa0bb244bc4080c218
2,543
cc
C++
src/app-framework/LookupHandler.cc
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
1
2022-03-30T20:16:43.000Z
2022-03-30T20:16:43.000Z
src/app-framework/LookupHandler.cc
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
null
null
null
src/app-framework/LookupHandler.cc
taless474/plexil1
0da24f0330404c41a695ea367bb760fb9c7ee8dd
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2006-2021, Universities Space Research Association (USRA). * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Universities Space Research Association nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY USRA ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL USRA 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. */ // // Default methods for LookupHandler // #include "LookupHandler.hh" #include "AdapterExecInterface.hh" #include "Debug.hh" #include "LookupReceiver.hh" #include "State.hh" namespace PLEXIL { bool LookupHandler::initialize() { return true; } void LookupHandler::lookupNow(const State &state, LookupReceiver * /* rcvr */) { debugMsg("LookupHandler:defaultLookupNow", ' ' << state); } void LookupHandler::setThresholds(const State &state, Real hi, Real lo) { debugMsg("LookupHandler:defaultSetThresholds", ' ' << state << " (Real) " << hi << "," << lo); } void LookupHandler::setThresholds(const State &state, Integer hi, Integer lo) { debugMsg("LookupHandler:defaultSetThresholds", ' ' << state << " (Integer) " << hi << "," << lo); } void LookupHandler::clearThresholds(const State &state) { debugMsg("LookupHandler:defaultClearThresholds", ' ' << state); } }
36.855072
80
0.714117
taless474
425b96f71cb7f3ec403821d7c11418ca6bf893b4
2,999
hpp
C++
include/libtorrent/aux_/websocket_tracker_connection.hpp
redchief/libtorrent
42917790b1606b5ea0cf5385fde44536c7040a27
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
include/libtorrent/aux_/websocket_tracker_connection.hpp
redchief/libtorrent
42917790b1606b5ea0cf5385fde44536c7040a27
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
include/libtorrent/aux_/websocket_tracker_connection.hpp
redchief/libtorrent
42917790b1606b5ea0cf5385fde44536c7040a27
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2019 Paul-Louis Ageneau Copyright (c) 2020, Paul-Louis Ageneau All rights reserved. You may use, distribute and modify this code under the terms of the BSD license, see LICENSE file. */ #ifndef TORRENT_WEBSOCKET_TRACKER_CONNECTION_HPP_INCLUDED #define TORRENT_WEBSOCKET_TRACKER_CONNECTION_HPP_INCLUDED #include "libtorrent/config.hpp" #if TORRENT_USE_RTC #include "libtorrent/aux_/rtc_signaling.hpp" // for rtc_offer and rtc_answer #include "libtorrent/aux_/websocket_stream.hpp" #include "libtorrent/error_code.hpp" #include "libtorrent/io_context.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/aux_/resolver_interface.hpp" #include "libtorrent/aux_/tracker_manager.hpp" // for tracker_connection #include "libtorrent/aux_/ssl.hpp" #include <boost/beast/core/flat_buffer.hpp> #include <map> #include <memory> #include <queue> #include <tuple> #include <variant> #include <optional> namespace libtorrent::aux { struct tracker_answer { sha1_hash info_hash; peer_id pid; aux::rtc_answer answer; }; struct TORRENT_EXTRA_EXPORT websocket_tracker_connection : tracker_connection { friend class tracker_manager; websocket_tracker_connection( io_context& ios , tracker_manager& man , tracker_request const& req , std::weak_ptr<request_callback> cb); ~websocket_tracker_connection() override = default; void start() override; void close() override; bool is_started() const; bool is_open() const; void queue_request(tracker_request req, std::weak_ptr<request_callback> cb); void queue_answer(tracker_answer ans); private: std::shared_ptr<websocket_tracker_connection> shared_from_this() { return std::static_pointer_cast<websocket_tracker_connection>( tracker_connection::shared_from_this()); } void send_pending(); void do_send(tracker_request const& req); void do_send(tracker_answer const& ans); void do_read(); void on_timeout(error_code const& ec) override; void on_connect(error_code const& ec); void on_read(error_code ec, std::size_t bytes_read); void on_write(error_code const& ec, std::size_t bytes_written); void fail(operation_t op, error_code const& ec); io_context& m_io_context; ssl::context m_ssl_context; std::shared_ptr<aux::websocket_stream> m_websocket; boost::beast::flat_buffer m_read_buffer; std::string m_write_data; using tracker_message = std::variant<tracker_request, tracker_answer>; std::queue<std::tuple<tracker_message, std::weak_ptr<request_callback>>> m_pending; std::map<sha1_hash, std::weak_ptr<request_callback>> m_callbacks; bool m_sending = false; }; struct websocket_tracker_response { sha1_hash info_hash; std::optional<tracker_response> resp; std::optional<aux::rtc_offer> offer; std::optional<aux::rtc_answer> answer; }; TORRENT_EXTRA_EXPORT std::variant<websocket_tracker_response, std::string> parse_websocket_tracker_response(span<char const> message, error_code &ec); } #endif // TORRENT_USE_RTC #endif // TORRENT_WEBSOCKET_TRACKER_CONNECTION_HPP_INCLUDED
27.263636
84
0.791931
redchief
425cb4ef757c75bd9497830c265e4ba465955905
1,577
cpp
C++
ch3/useEigen/hw.cpp
MrCocoaCat/slambook
1eb2c3b081c6f668f342ae8d3fa536748bedc77d
[ "MIT" ]
3
2018-02-13T05:39:05.000Z
2019-06-15T17:35:25.000Z
ch3/useEigen/hw.cpp
MrCocoaCat/slambook
1eb2c3b081c6f668f342ae8d3fa536748bedc77d
[ "MIT" ]
null
null
null
ch3/useEigen/hw.cpp
MrCocoaCat/slambook
1eb2c3b081c6f668f342ae8d3fa536748bedc77d
[ "MIT" ]
1
2018-12-21T13:59:20.000Z
2018-12-21T13:59:20.000Z
// // Created by liyubo on 12/15/17. // #include <iostream> using namespace std; #include <ctime> // Eigen 部分 #include <Eigen/Core> // 稠密矩阵的代数运算(逆,特征值等) #include <Eigen/Dense> #include"hw.h" #define MATRIX_SIZE 50 void homework() { //作业 Eigen::MatrixXd matrix_A; matrix_A = Eigen::MatrixXd::Random( 100, 100 ); Eigen::MatrixXd matrix_b; matrix_b = Eigen::MatrixXd::Random( 100, 1 ); Eigen::MatrixXd x; // cout << matrix_A << endl; // cout << matrix_b << endl; x = matrix_A.llt().solve(matrix_b); //llt Cholesky来解方程 /*******************时间比较*********************/ clock_t time_stt = clock(); x = matrix_A.colPivHouseholderQr().solve(matrix_b); //利用QR分解求解方程 cout <<"time use in Qr decomposition is " <<1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<"ms" << endl; time_stt = clock(); x = matrix_A.fullPivLu().solve(matrix_b); //LU cout <<"time use in fullPivLu is " <<1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<"ms" << endl; time_stt = clock(); x = matrix_A.inverse()*matrix_b;; //利用求逆来解方程 cout <<"time use in normal inverse is " <<1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<"ms" << endl; time_stt = clock(); x = matrix_A.llt().solve(matrix_b); //llt Cholesky来解方程 cout <<"time use in llt(Cholesky) is " <<1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<"ms" << endl; time_stt = clock(); x = matrix_A.ldlt().solve(matrix_b); //ldlt cout <<"time use in ldlt is " <<1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC <<"ms"<< endl; }
28.672727
114
0.608751
MrCocoaCat
425d2a724c3d5b91385c065199075392ac4744c4
57,201
cpp
C++
net/snmp/subagent/snmpevnt/evntagnt/snmptrlg.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/snmp/subagent/snmpevnt/evntagnt/snmptrlg.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/snmp/subagent/snmpevnt/evntagnt/snmptrlg.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1994 Microsoft Corporation Module Name: SNMPTRLG.CPP Abstract: This module is the tracing and logging routines for the SNMP Event Log Extension Agent DLL. Author: Randy G. Braze (Braze Computing Services) Created 7 February 1996 Revision History: --*/ extern "C" { #include <windows.h> // windows definitions #include <stdio.h> // standard I/O functions #include <stdlib.h> // standard library definitions #include <stdarg.h> // variable length arguments stuff #include <string.h> // string declarations #include <time.h> // time declarations #include <snmp.h> // snmp definitions #include "snmpelea.h" // global dll definitions #include "snmptrlg.h" // module specific definitions #include "snmpelmg.h" // message definitions } VOID TraceWrite( IN CONST BOOL fDoFormat, // flag for message formatting IN CONST BOOL fDoTime, // flag for date/time prefixing IN CONST LPSTR szFormat, // trace message to write IN OPTIONAL ... // other printf type operands ) /*++ Routine Description: TraceWrite will write information provided to the trace file. Optionally, it will prepend the date and timestamp to the information. If requested, printf type arguments can be passed and they will be substituted just as printf builds the message text. Sometimes this routine is called from WriteTrace and sometimes it is called from other functions that need to generate a trace file record. When called from WriteTrace, no formatting is done on the buffer (WriteTrace has already performed the required formatting). When called from other functions, the message text may or may not require formatting, as specified by the calling function. Arguments: fDoFormat - TRUE or FALSE, indicating if the message text provided requires formatting as a printf type function. fDoTime - TRUE or FALSE, indicating if the date/timestamp should be added to the beginning of the message text. szFormat - NULL terminated string containing the message text to be written to the trace file. If fDoFormat is true, then this text will be in the format of a printf statement and will contain substitution parameters strings and variable names to be substituted will follow. ... - Optional parameters that are used to complete the printf type statement. These are variables that are substituted for strings specified in szFormat. These parameters will only be specified and processed if fDoFormat is TRUE. Return Value: None --*/ { static CHAR szBuffer[LOG_BUF_SIZE]; static FILE *FFile; static SYSTEMTIME NowTime; va_list arglist; // don't even attempt to open the trace file if // the name is "" if (szTraceFileName[0] == TEXT('\0')) return; FFile = fopen(szTraceFileName,"a"); // open trace file in append mode if ( FFile != NULL ) // if file opened okay { if ( fDoTime ) // are we adding time? { GetLocalTime(&NowTime); // yep, get it fprintf(FFile, "%02i/%02i/%02i %02i:%02i:%02i ", NowTime.wMonth, NowTime.wDay, NowTime.wYear, NowTime.wHour, NowTime.wMinute, NowTime.wSecond); // file printf to add date/time } if ( fDoFormat ) // if we need to format the buffer { szBuffer[LOG_BUF_SIZE-1] = 0; va_start(arglist, szFormat); _vsnprintf(szBuffer, LOG_BUF_SIZE-1, szFormat, arglist); // perform substitution va_end(arglist); fwrite(szBuffer, strlen(szBuffer), 1, FFile); // write data to the trace file } else // if no formatting required { fwrite(szFormat, strlen(szFormat), 1, FFile); // write message to the trace file } fflush(FFile); // flush buffers first fclose(FFile); // close the trace file } } // end TraceWrite function VOID LoadMsgDLL( IN VOID ) /*++ Routine Description: LoadMsgDLL is called to load the SNMPELMG.DLL module which contains the message and format information for all messages in the SNMP extension agent DLL. It is necessary to call this routine only in the event that an event log record cannot be written. If this situation occurs, then the DLL will be loaded in an attempt to call FormatMessage and write this same information to the trace file. This routine is called only once and only if the event log write fails. Arguments: None Return Value: None --*/ { TCHAR szXMsgModuleName[MAX_PATH+1]; // space for DLL message module DWORD nFile = sizeof(szXMsgModuleName)-sizeof(TCHAR); // max size for DLL message module name in bytes DWORD dwType; // type of message module name DWORD status; // status from registry calls DWORD cbExpand; // byte count for REG_EXPAND_SZ parameters HKEY hkResult; // handle to registry information // ensure null terminated string szXMsgModuleName[MAX_PATH] = 0; if ( (status = RegOpenKeyEx( // open the registry to read the name HKEY_LOCAL_MACHINE, // of the message module DLL EVENTLOG_SERVICE, 0, KEY_READ, &hkResult) ) != ERROR_SUCCESS) { TraceWrite(TRUE, TRUE, // if we can't find it "LoadMessageDLL: Unable to open EventLog service registry key; RegOpenKeyEx returned %lu\n", status); // write trace event record hMsgModule = (HMODULE) NULL; // set handle null return; // return } else { if ( (status = RegQueryValueEx( // look up module name hkResult, // handle to registry key EXTENSION_MSG_MODULE, // key to look up 0, // ignored &dwType, // address to return type value (LPBYTE) szXMsgModuleName, // where to return message module name &nFile) ) != ERROR_SUCCESS) // size of message module name field { TraceWrite(TRUE, TRUE, // if we can't find it "LoadMessageDLL: Unable to open EventMessageFile registry key; RegQueryValueEx returned %lu\n", status); // write trace event record hMsgModule = (HMODULE) NULL; // set handle null RegCloseKey(hkResult); // close the registry key return; // return } RegCloseKey(hkResult); // close the registry key cbExpand = ExpandEnvironmentStrings( // expand the DLL name szXMsgModuleName, // unexpanded DLL name szelMsgModuleName, // expanded DLL name MAX_PATH+1); // max size of expanded DLL name in TCHARs if (cbExpand == 0 || cbExpand > MAX_PATH+1) // if it didn't expand correctly { TraceWrite(TRUE, TRUE, // didn't have enough space "LoadMessageDLL: Unable to expand message module %s; expanded size required is %lu bytes\n", szXMsgModuleName, cbExpand); // log error message hMsgModule = (HMODULE) NULL; // set handle null return; // and exit } if ( (hMsgModule = (HMODULE) LoadLibraryEx(szelMsgModuleName, NULL, LOAD_LIBRARY_AS_DATAFILE) ) // load the message module name == (HMODULE) NULL ) // if module didn't load { TraceWrite(TRUE, TRUE, // can't load message dll "LoadMessageDLL: Unable to load message module %s; LoadLibraryEx returned %lu\n", szelMsgModuleName, GetLastError() ); // log error message } } return; // exit routine } VOID FormatTrace( IN CONST NTSTATUS nMsg, // message number to format IN CONST LPVOID lpArguments // strings to insert ) /*++ Routine Description: FormatTrace will write the message text specified by nMsg to the trace file. If supplied, the substitution arguments supplied by lpArguments will be inserted in the message. FormatMessage is called to format the message text and insert the substitution arguments into the text. The text of the message is loaded from the SNMPELMG.DLL message module as specified in the Eventlog\Application\Snmpelea registry entry under the key of EventMessageFile. This information is read, the file name is expanded and the message module is loaded. If the message cannot be formatted, then a record is written to the trace file indicating the problem. Arguments: nMsg - This is the message number in SNMPELMG.H in NTSTATUS format that is to be written. lpArguments - This is a pointer to an array of strings that will be substituted in the message text specified. If this value is NULL, there are no substitution values to insert. Return Value: None --*/ { static DWORD nBytes; // return value from FormatMessage static LPTSTR lpBuffer = NULL; // temporary message buffer if ( !fMsgModule ) { // if we don't have dll loaded yet fMsgModule = TRUE; // indicate we've looked now LoadMsgDLL(); // load the DLL } if ( hMsgModule ) { nBytes = FormatMessage( // see if we can format the message FORMAT_MESSAGE_ALLOCATE_BUFFER | // let api build buffer FORMAT_MESSAGE_ARGUMENT_ARRAY | // indicate an array of string inserts FORMAT_MESSAGE_FROM_HMODULE, // look thru message DLL (LPVOID) hMsgModule, // handle to message module nMsg, // message number to get (ULONG) NULL, // specify no language (LPTSTR) &lpBuffer, // address for buffer pointer 80, // minimum space to allocate (va_list* )lpArguments); // address of array of pointers if (nBytes == 0) { // format is not okay TraceWrite(TRUE, TRUE, "FormatTrace: Error formatting message number %08X is %lu\n", nMsg, GetLastError() ); // trace the problem } else { // format is okay TraceWrite(FALSE, TRUE, lpBuffer); // log the message in the trace file } // LocalFree ignores NULL parameter if ( LocalFree(lpBuffer) != NULL ) { // free buffer storage TraceWrite(TRUE, TRUE, "FormatTrace: Error freeing FormatMessage buffer is %lu\n", GetLastError() ); } lpBuffer = NULL; } else { TraceWrite(TRUE, TRUE, "FormatTrace: Unable to format message number %08X; message DLL handle is null.\n", nMsg); // trace the problem } return; // exit routine } USHORT MessageType( IN CONST NTSTATUS nMsg ) /*++ Routine Description: MessageType is used to return the severity type of an NTSTATUS formatted message number. This information is needed to log the appropriate event log information when writing a record to the system event log. Acceptable message types are defined in NTELFAPI.H. Arguments: nMsg - This is the message number in SNMPELMG.H in NTSTATUS format that is to be analyzed. Return Value: Unsigned short integer containing the message severity as described in NTELFAPI.H. If no message type is matched, the default of informational is returned. --*/ { switch ((ULONG) nMsg >> 30) { // get message type case (SNMPELEA_SUCCESS) : return(EVENTLOG_SUCCESS); // success message case (SNMPELEA_INFORMATIONAL) : return(EVENTLOG_INFORMATION_TYPE); // informational message case (SNMPELEA_WARNING) : return(EVENTLOG_WARNING_TYPE); // warning message case (SNMPELEA_ERROR) : return(EVENTLOG_ERROR_TYPE); // error message default: return(EVENTLOG_INFORMATION_TYPE); // default to informational } } VOID WriteLog( IN NTSTATUS nMsgNumber ) /*++ Routine Description: WriteLog is called to write message text to the system event log. This is a C++ overloaded function. In case a log record cannot be written to the system event log, TraceWrite is called to write the appropriate message text to the trace file. Arguments: nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format that is to be written to the event log. Return Value: None --*/ { static USHORT wLogType; // to hold event log type static BOOL fReportEvent; // return flag from report event if (hWriteEvent != NULL) // if we have previous log access ability { wLogType = MessageType(nMsgNumber); // get message type fReportEvent = ReportEvent( // write message hWriteEvent, // handle to log file wLogType, // message type 0, // message category nMsgNumber, // message number NULL, // user sid 0, // number of strings 0, // data length 0, // pointer to string array (PVOID) NULL); // data address if ( !fReportEvent ) // did the event log okay? { // not if we get here..... TraceWrite(TRUE, TRUE, // show error in trace file "WriteLog: Error writing to system event log is %lu\n", GetLastError() ); FormatTrace(nMsgNumber, NULL); // format trace information } } else // if we can't write to event log { TraceWrite(FALSE, TRUE, // show error in trace file "WriteLog: Unable to write to system event log; handle is null\n"); FormatTrace(nMsgNumber, NULL); // format trace information } return; // exit the function } VOID WriteLog( IN NTSTATUS nMsgNumber, // message number to log IN DWORD dwCode // code to pass to message ) /*++ Routine Description: WriteLog is called to write message text to the system event log. This is a C++ overloaded function. In case a log record cannot be written to the system event log, TraceWrite is called to write the appropriate message text to the trace file. Arguments: nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format that is to be written to the event log. dwCode - This is a double word code that is to be converted to a string and substituted appropriately in the message text. Return Value: None --*/ { static USHORT wLogType; // to hold event log type static TCHAR *lpszEventString[1]; // array of strings to pass to event logger static BOOL fReportEvent; // return flag from report event lpszEventString[0] = new TCHAR[34]; // allocate space for string conversion if (hWriteEvent != NULL) // if we have previous log access ability { if ( lpszEventString[0] != (TCHAR *) NULL ) // if storage allocated { wLogType = MessageType(nMsgNumber); // get message type _ultoa(dwCode, lpszEventString[0], 10); // convert to string fReportEvent = ReportEvent( // write message hWriteEvent, // handle to log file wLogType, // message type 0, // message category nMsgNumber, // message number NULL, // user sid 1, // number of strings 0, // data length (const char **) lpszEventString, // pointer to string array NULL); // data address if ( !fReportEvent ) // did the event log okay? { // not if we get here..... TraceWrite(TRUE, TRUE, // write trace file record "WriteLog: Error writing to system event log is %lu\n", GetLastError() ); FormatTrace(nMsgNumber, lpszEventString); // format trace information } } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } else // if we can't write to system log { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Unable to write to system event log; handle is null\n"); if ( lpszEventString[0] != (TCHAR *) NULL ) // if storage allocated { _ultoa(dwCode, lpszEventString[0], 10); // convert to string FormatTrace(nMsgNumber, lpszEventString); // format trace information } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } delete [] lpszEventString[0]; // free storage return; // exit function } VOID WriteLog( IN NTSTATUS nMsgNumber, IN DWORD dwCode1, IN DWORD dwCode2 ) /*++ Routine Description: WriteLog is called to write message text to the system event log. This is a C++ overloaded function. In case a log record cannot be written to the system event log, TraceWrite is called to write the appropriate message text to the trace file. Arguments: nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format that is to be written to the event log. dwCode1 - This is a double word code that is to be converted to a string and substituted appropriately in the message text. dwCode2 - This is a double word code that is to be converted to a string and substituted appropriately in the message text. Return Value: None --*/ { static USHORT wLogType; // to hold event log type static TCHAR *lpszEventString[2]; // array of strings to pass to event logger static BOOL fReportEvent; // return flag from report event lpszEventString[0] = new TCHAR[34]; // allocate space for string conversion lpszEventString[1] = new TCHAR[34]; // allocate space for string conversion if (hWriteEvent != NULL) // if we have previous log access ability { if ( (lpszEventString[0] != (TCHAR *) NULL) && (lpszEventString[1] != (TCHAR *) NULL) ) // if storage allocated { wLogType = MessageType(nMsgNumber); // get message type _ultoa(dwCode1, lpszEventString[0], 10); // convert to string _ultoa(dwCode2, lpszEventString[1], 10); // convert to string fReportEvent = ReportEvent( // write message hWriteEvent, // handle to log file wLogType, // message type 0, // message category nMsgNumber, // message number NULL, // user sid 2, // number of strings 0, // data length (const char **) lpszEventString, // pointer to string array NULL); // data address if ( !fReportEvent ) // did the event log okay? { // not if we get here..... TraceWrite(TRUE, TRUE, // write a trace file entry "WriteLog: Error writing to system event log is %lu\n", GetLastError() ); FormatTrace(nMsgNumber, lpszEventString); // format trace information } } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } else // if we can't write to system log { TraceWrite(FALSE, TRUE, // write trace file entry "WriteLog: Unable to write to system event log; handle is null\n"); if ( (lpszEventString[0] != (TCHAR *) NULL) && (lpszEventString[1] != (TCHAR *) NULL) ) // if storage allocated { _ultoa(dwCode1, lpszEventString[0], 10); // convert to string _ultoa(dwCode2, lpszEventString[1], 10); // convert to string FormatTrace(nMsgNumber, lpszEventString); // format trace information } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } delete [] lpszEventString[0]; // free storage delete [] lpszEventString[1]; // free storage return; // exit function } VOID WriteLog( IN NTSTATUS nMsgNumber, IN DWORD dwCode1, IN LPTSTR lpszText1, IN LPTSTR lpszText2, IN DWORD dwCode2 ) /*++ Routine Description: WriteLog is called to write message text to the system event log. This is a C++ overloaded function. In case a log record cannot be written to the system event log, TraceWrite is called to write the appropriate message text to the trace file. Arguments: nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format that is to be written to the event log. dwCode1 - This is a double word code that is to be converted to a string and substituted appropriately in the message text. lpszText1 - This contains a string parameter that is to be substituted into the message text. lpszText2 - This contains a string parameter that is to be substituted into the message text. dwCode2 - This is a double word code that is to be converted to a string and substituted appropriately in the message text. Return Value: None --*/ { static USHORT wLogType; // to hold event log type static TCHAR *lpszEventString[4]; // array of strings to pass to event logger static BOOL fReportEvent; // return flag from report event lpszEventString[0] = new TCHAR[34]; // allocate space for string conversion lpszEventString[1] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion lpszEventString[2] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion lpszEventString[3] = new TCHAR[34]; // allocate space for string conversion if (hWriteEvent != NULL) // if we have previous log access ability { if ( (lpszEventString[0] != (TCHAR *) NULL) && (lpszEventString[1] != (TCHAR *) NULL) && (lpszEventString[2] != (TCHAR *) NULL) && (lpszEventString[3] != (TCHAR *) NULL) ) // if storage allocated { // ensures null terminated strings lpszEventString[1][MAX_PATH] = 0; lpszEventString[2][MAX_PATH] = 0; wLogType = MessageType(nMsgNumber); // get message type _ultoa(dwCode1, lpszEventString[0], 10); // convert to string strncpy(lpszEventString[1],lpszText1,MAX_PATH); // copy the string strncpy(lpszEventString[2],lpszText2,MAX_PATH); // copy the string _ultoa(dwCode2, lpszEventString[3], 10); // convert to string fReportEvent = ReportEvent( // write message hWriteEvent, // handle to log file wLogType, // message type 0, // message category nMsgNumber, // message number NULL, // user sid 4, // number of strings 0, // data length (const char **) lpszEventString, // pointer to string array NULL); // data address if ( !fReportEvent ) // did the event log okay? { // not if we get here..... TraceWrite(TRUE, TRUE, // write trace file record "WriteLog: Error writing to system event log is %lu\n", GetLastError() ); FormatTrace(nMsgNumber, lpszEventString); // format trace information } } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } else // if we can't write to system log { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Unable to write to system event log; handle is null\n"); if ( (lpszEventString[0] != (TCHAR *) NULL) && (lpszEventString[1] != (TCHAR *) NULL) && (lpszEventString[2] != (TCHAR *) NULL) && (lpszEventString[3] != (TCHAR *) NULL) ) // if storage allocated { // ensures null terminated strings lpszEventString[1][MAX_PATH] = 0; lpszEventString[2][MAX_PATH] = 0; _ultoa(dwCode1, lpszEventString[0], 10); // convert to string strncpy(lpszEventString[1],lpszText1,MAX_PATH); // copy the string strncpy(lpszEventString[2],lpszText2,MAX_PATH); // copy the string _ultoa(dwCode2, lpszEventString[3], 10); // convert to string FormatTrace(nMsgNumber, lpszEventString); // format trace information } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } delete [] lpszEventString[0]; // free storage delete [] lpszEventString[1]; // free storage delete [] lpszEventString[2]; // free storage delete [] lpszEventString[3]; // free storage return; // exit function } VOID WriteLog( IN NTSTATUS nMsgNumber, IN DWORD dwCode1, IN LPTSTR lpszText, IN DWORD dwCode2, IN DWORD dwCode3 ) /*++ Routine Description: WriteLog is called to write message text to the system event log. This is a C++ overloaded function. In case a log record cannot be written to the system event log, TraceWrite is called to write the appropriate message text to the trace file. Arguments: nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format that is to be written to the event log. dwCode1 - This is a double word code that is to be converted to a string and substituted appropriately in the message text. lpszText - This contains a string parameter that is to be substituted into the message text. dwCode2 - This is a double word code that is to be converted to a string and substituted appropriately in the message text. dwCode3 - This is a double word code that is to be converted to a string and substituted appropriately in the message text. Return Value: None --*/ { static USHORT wLogType; // to hold event log type static TCHAR *lpszEventString[4]; // array of strings to pass to event logger static BOOL fReportEvent; // return flag from report event lpszEventString[0] = new TCHAR[34]; // allocate space for string conversion lpszEventString[1] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion lpszEventString[2] = new TCHAR[34]; // allocate space for string conversion lpszEventString[3] = new TCHAR[34]; // allocate space for string conversion if (hWriteEvent != NULL) // if we have previous log access ability { if ( (lpszEventString[0] != (TCHAR *) NULL) && (lpszEventString[1] != (TCHAR *) NULL) && (lpszEventString[2] != (TCHAR *) NULL) && (lpszEventString[3] != (TCHAR *) NULL) ) // if storage allocated { lpszEventString[1][MAX_PATH] = 0; // ensures null terminated string wLogType = MessageType(nMsgNumber); // get message type _ultoa(dwCode1, lpszEventString[0], 10); // convert to string strncpy(lpszEventString[1],lpszText,MAX_PATH); // copy the string _ultoa(dwCode2, lpszEventString[2], 10); // convert to string _ultoa(dwCode3, lpszEventString[3], 10); // convert to string fReportEvent = ReportEvent( // write message hWriteEvent, // handle to log file wLogType, // message type 0, // message category nMsgNumber, // message number NULL, // user sid 4, // number of strings 0, // data length (const char **) lpszEventString, // pointer to string array NULL); // data address if ( !fReportEvent ) // did the event log okay? { // not if we get here..... TraceWrite(TRUE, TRUE, // write trace file record "WriteLog: Error writing to system event log is %lu\n", GetLastError() ); FormatTrace(nMsgNumber, lpszEventString); // format trace information } } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } else // if we can't write to system log { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Unable to write to system event log; handle is null\n"); if ( (lpszEventString[0] != (TCHAR *) NULL) && (lpszEventString[1] != (TCHAR *) NULL) && (lpszEventString[2] != (TCHAR *) NULL) && (lpszEventString[3] != (TCHAR *) NULL) ) // if storage allocated { lpszEventString[1][MAX_PATH] = 0; // ensures null terminated string _ultoa(dwCode1, lpszEventString[0], 10); // convert to string strncpy(lpszEventString[1],lpszText,MAX_PATH); // copy the string _ultoa(dwCode2, lpszEventString[2], 10); // convert to string _ultoa(dwCode3, lpszEventString[3], 10); // convert to string FormatTrace(nMsgNumber, lpszEventString); // format trace information } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } delete [] lpszEventString[0]; // free storage delete [] lpszEventString[1]; // free storage delete [] lpszEventString[2]; // free storage delete [] lpszEventString[3]; // free storage return; // exit the function } VOID WriteLog( IN NTSTATUS nMsgNumber, IN LPTSTR lpszText, IN DWORD dwCode1, IN DWORD dwCode2 ) /*++ Routine Description: WriteLog is called to write message text to the system event log. This is a C++ overloaded function. In case a log record cannot be written to the system event log, TraceWrite is called to write the appropriate message text to the trace file. Arguments: nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format that is to be written to the event log. lpszText - This contains a string parameter that is to be substituted into the message text. dwCode1 - This is a double word code that is to be converted to a string and substituted appropriately in the message text. dwCode2 - This is a double word code that is to be converted to a string and substituted appropriately in the message text. Return Value: None --*/ { static USHORT wLogType; // to hold event log type static TCHAR *lpszEventString[3]; // array of strings to pass to event logger static BOOL fReportEvent; // return flag from report event lpszEventString[0] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion lpszEventString[1] = new TCHAR[34]; // allocate space for string conversion lpszEventString[2] = new TCHAR[34]; // allocate space for string conversion if (hWriteEvent != NULL) // if we have previous log access ability { if ( (lpszEventString[0] != (TCHAR *) NULL) && (lpszEventString[1] != (TCHAR *) NULL) && (lpszEventString[2] != (TCHAR *) NULL) ) // if storage allocated { lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string wLogType = MessageType(nMsgNumber); // get message type strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string _ultoa(dwCode1, lpszEventString[1], 10); // convert to string _ultoa(dwCode2, lpszEventString[2], 10); // convert to string fReportEvent = ReportEvent( // write message hWriteEvent, // handle to log file wLogType, // message type 0, // message category nMsgNumber, // message number NULL, // user sid 3, // number of strings 0, // data length (const char **) lpszEventString, // pointer to string array NULL); // data address if ( !fReportEvent ) // did the event log okay? { // not if we get here..... TraceWrite(TRUE, TRUE, // write trace file record "WriteLog: Error writing to system event log is %lu\n", GetLastError() ); FormatTrace(nMsgNumber, lpszEventString); // format trace information } } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } else // if we can't write to system log { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Unable to write to system event log; handle is null\n"); if ( (lpszEventString[0] != (TCHAR *) NULL) && (lpszEventString[1] != (TCHAR *) NULL) && (lpszEventString[2] != (TCHAR *) NULL) ) // if storage allocated { lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string _ultoa(dwCode1, lpszEventString[1], 10); // convert to string _ultoa(dwCode2, lpszEventString[2], 10); // convert to string FormatTrace(nMsgNumber, lpszEventString); // format trace information } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace file record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } delete [] lpszEventString[0]; // free storage delete [] lpszEventString[1]; // free storage delete [] lpszEventString[2]; // free storage return; // exit the function } VOID WriteLog( IN NTSTATUS nMsgNumber, IN LPTSTR lpszText, IN DWORD dwCode ) /*++ Routine Description: WriteLog is called to write message text to the system event log. This is a C++ overloaded function. In case a log record cannot be written to the system event log, TraceWrite is called to write the appropriate message text to the trace file. Arguments: nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format that is to be written to the event log. lpszText - This contains a string parameter that is to be substituted into the message text. dwCode - This is a double word code that is to be converted to a string and substituted appropriately in the message text. Return Value: None --*/ { static USHORT wLogType; // to hold event log type static TCHAR *lpszEventString[2]; // array of strings to pass to event logger static BOOL fReportEvent; // return flag from report event lpszEventString[0] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion lpszEventString[1] = new TCHAR[34]; // allocate space for string conversion if (hWriteEvent != NULL) // if we have previous log access ability { if ( (lpszEventString[0] != (TCHAR *) NULL) && (lpszEventString[1] != (TCHAR *) NULL) ) // if storage allocated { lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string wLogType = MessageType(nMsgNumber); // get message type strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string _ultoa(dwCode, lpszEventString[1], 10); // convert to string fReportEvent = ReportEvent( // write message hWriteEvent, // handle to log file wLogType, // message type 0, // message category nMsgNumber, // message number NULL, // user sid 2, // number of strings 0, // data length (const char **) lpszEventString, // pointer to string array NULL); // data address if ( !fReportEvent ) // did the event log okay? { // not if we get here..... TraceWrite(TRUE, TRUE, // write trace record "WriteLog: Error writing to system event log is %lu\n", GetLastError() ); FormatTrace(nMsgNumber, lpszEventString); // format trace information } } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } else // if we can't write to system log { TraceWrite(FALSE, TRUE, // write trace record "WriteLog: Unable to write to system event log; handle is null\n"); if ( (lpszEventString[0] != (TCHAR *) NULL) && (lpszEventString[1] != (TCHAR *) NULL) ) // if storage allocated { lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string _ultoa(dwCode, lpszEventString[1], 10); // convert to string FormatTrace(nMsgNumber, lpszEventString); // format trace information } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } delete [] lpszEventString[0]; // free storage delete [] lpszEventString[1]; // free storage return; // exit function } VOID WriteLog( IN NTSTATUS nMsgNumber, IN LPTSTR lpszText ) /*++ Routine Description: WriteLog is called to write message text to the system event log. This is a C++ overloaded function. In case a log record cannot be written to the system event log, TraceWrite is called to write the appropriate message text to the trace file. Arguments: nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format that is to be written to the event log. lpszText - This contains a string parameter that is to be substituted into the message text. Return Value: None --*/ { static USHORT wLogType; // to hold event log type static TCHAR *lpszEventString[1]; // array of strings to pass to event logger static BOOL fReportEvent; // return flag from report event lpszEventString[0] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion if (hWriteEvent != NULL) // if we have previous log access ability { if ( lpszEventString[0] != (TCHAR *) NULL ) // if storage allocated { lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string wLogType = MessageType(nMsgNumber); // get message type strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string fReportEvent = ReportEvent( // write message hWriteEvent, // handle to log file wLogType, // message type 0, // message category nMsgNumber, // message number NULL, // user sid 1, // number of strings 0, // data length (const char **) lpszEventString, // pointer to string array NULL); // data address if ( !fReportEvent ) // did the event log okay? { // not if we get here..... TraceWrite(TRUE, TRUE, // write trace file record "WriteLog: Error writing to system event log is %lu\n", GetLastError() ); FormatTrace(nMsgNumber, lpszEventString); // format trace information } } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } else // if we can't write to system log { TraceWrite(FALSE, TRUE, // write trace record "WriteLog: Unable to write to system event log; handle is null\n"); if ( lpszEventString[0] != (TCHAR *) NULL ) // if storage allocated { lpszEventString[0][MAX_PATH] = 0; // ensures null terminated string strncpy(lpszEventString[0],lpszText,MAX_PATH); // copy the string FormatTrace(nMsgNumber, lpszEventString); // format trace information } else { TraceWrite(FALSE, TRUE, // write trace record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } delete [] lpszEventString[0]; // free storage return; // exit function } VOID WriteLog( IN NTSTATUS nMsgNumber, IN LPCTSTR lpszText1, IN LPCTSTR lpszText2 ) /*++ Routine Description: WriteLog is called to write message text to the system event log. This is a C++ overloaded function. In case a log record cannot be written to the system event log, TraceWrite is called to write the appropriate message text to the trace file. Arguments: nMsgNumber - This is the message number in SNMPELMG.H in NTSTATUS format that is to be written to the event log. lpszText - This contains a string parameter that is to be substituted into the message text. Return Value: None --*/ { static USHORT wLogType; // to hold event log type static TCHAR *lpszEventString[2]; // array of strings to pass to event logger static BOOL fReportEvent; // return flag from report event lpszEventString[0] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion lpszEventString[1] = new TCHAR[MAX_PATH+1]; // allocate space for string conversion if (hWriteEvent != NULL) // if we have previous log access ability { if ( (lpszEventString[0] != (TCHAR *) NULL ) && (lpszEventString[1] != (TCHAR *) NULL ) ) // if storage allocated { // ensures null terminated strings lpszEventString[0][MAX_PATH] = 0; lpszEventString[1][MAX_PATH] = 0; wLogType = MessageType(nMsgNumber); // get message type strncpy(lpszEventString[0],lpszText1,MAX_PATH); // copy the string strncpy(lpszEventString[1],lpszText2,MAX_PATH); // copy the string fReportEvent = ReportEvent( // write message hWriteEvent, // handle to log file wLogType, // message type 0, // message category nMsgNumber, // message number NULL, // user sid 2, // number of strings 0, // data length (const char **) lpszEventString, // pointer to string array NULL); // data address if ( !fReportEvent ) // did the event log okay? { // not if we get here..... TraceWrite(TRUE, TRUE, // write trace file record "WriteLog: Error writing to system event log is %lu\n", GetLastError() ); FormatTrace(nMsgNumber, lpszEventString); // format trace information } } else // if we can't allocate memory { TraceWrite(FALSE, TRUE, // write trace record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } else // if we can't write to system log { TraceWrite(FALSE, TRUE, // write trace record "WriteLog: Unable to write to system event log; handle is null\n"); if ( (lpszEventString[0] != (TCHAR *) NULL) && // if storage allocated (lpszEventString[1] != (TCHAR *) NULL ) ) { // ensures null terminated strings lpszEventString[0][MAX_PATH] = 0; lpszEventString[1][MAX_PATH] = 0; strncpy(lpszEventString[0],lpszText1,MAX_PATH); // copy the string strncpy(lpszEventString[1],lpszText2,MAX_PATH); // copy the string FormatTrace(nMsgNumber, lpszEventString); // format trace information } else { TraceWrite(FALSE, TRUE, // write trace record "WriteLog: Error allocating memory for system event log write\n"); FormatTrace(nMsgNumber, NULL); // format trace information } } delete [] lpszEventString[0]; // free storage delete [] lpszEventString[1]; // free storage return; // exit function } extern "C" { VOID WriteTrace( IN CONST UINT nLevel, // level of trace message IN CONST LPSTR szFormat, // trace message to write IN ... // other printf type operands ) /*++ Routine Description: WriteTrace is called to write the requested trace information to the trace file specified in the configuration registry. The key to the trace file name is \SOFTWARE\Microsoft\SNMP_EVENTS\EventLog\Parameters\TraceFile. The registry information is only read for the first time WriteTrace is called. The TraceLevel parameter is also used to determine if the level of this message is part of a group of messages being traced. If the level of this message is greater than or equal the TraceLevel parameter, then this message will be sent to the file, otherwise the message is ignored. Arguments: nLevel - This is the trace level of the message being logged. szFormat - This is the string text of the message to write to the trace file. This string is in the format of printf strings and will be formatted accordingly. Return Value: None --*/ { static CHAR szBuffer[LOG_BUF_SIZE]; static TCHAR szFile[MAX_PATH+1]; static DWORD nFile = sizeof(szFile)-sizeof(TCHAR); // size in bytes for RegQueryValueEx static DWORD dwLevel; static DWORD dwType; static DWORD nLvl = sizeof(DWORD); static DWORD status; static HKEY hkResult; static DWORD cbExpand; va_list arglist; if ( !fTraceFileName ) // if we haven't yet read registry { szFile[MAX_PATH] = 0; fTraceFileName = TRUE; // set flag to not open registry info again if ( (status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, EXTENSION_PARM, 0, KEY_READ, &hkResult) ) != ERROR_SUCCESS) { WriteLog(SNMPELEA_NO_REGISTRY_PARAMETERS,status); // write log/trace event record } else { if ( (status = RegQueryValueEx( // look up trace file name hkResult, EXTENSION_TRACE_FILE, 0, &dwType, (LPBYTE) szFile, &nFile) ) == ERROR_SUCCESS) { if (dwType != REG_SZ) // we have a bad value. { WriteLog(SNMPELEA_REGISTRY_TRACE_FILE_PARAMETER_TYPE, szTraceFileName); // write log/trace event record } else strncpy(szTraceFileName, szFile,MAX_PATH); } else { WriteLog(SNMPELEA_NO_REGISTRY_TRACE_FILE_PARAMETER,szTraceFileName); // write log/trace event record } if ( (status = RegQueryValueEx( // look up trace level hkResult, EXTENSION_TRACE_LEVEL, 0, &dwType, (LPBYTE) &dwLevel, &nLvl) ) == ERROR_SUCCESS) { if (dwType == REG_DWORD) nTraceLevel = dwLevel; // copy registry trace level else WriteLog(SNMPELEA_REGISTRY_TRACE_LEVEL_PARAMETER_TYPE, nTraceLevel); // write log/trace event record } else { WriteLog(SNMPELEA_NO_REGISTRY_TRACE_LEVEL_PARAMETER,nTraceLevel); // write log/trace event record } status = RegCloseKey(hkResult); } // end else registry lookup successful } // end Trace information registry processing // return if we are not supposed to trace this message if ( nLevel < nTraceLevel ) // are we tracing this message { return; // nope, just exit } // if the value could not be read from the registry (we still have the default value) // then we have no file name, so return. if (szTraceFileName[0] == TEXT('\0')) return; szBuffer[LOG_BUF_SIZE-1] = 0; va_start(arglist, szFormat); _vsnprintf(szBuffer, LOG_BUF_SIZE-1, szFormat, arglist); va_end(arglist); if (nLevel == MAXDWORD) { TraceWrite(FALSE, FALSE, szBuffer); } else { TraceWrite(FALSE, TRUE, szBuffer); } } }
39.098428
138
0.542665
npocmaka
425f7cffba510b1b9021dcb5f89123bd5c20110c
72
cpp
C++
utils/globals.cpp
RapidsAtHKUST/ContinuousSubgraphMatching
f786d19561c8ae13cc7aa2af6e4d41a52aa2aba5
[ "MIT" ]
null
null
null
utils/globals.cpp
RapidsAtHKUST/ContinuousSubgraphMatching
f786d19561c8ae13cc7aa2af6e4d41a52aa2aba5
[ "MIT" ]
null
null
null
utils/globals.cpp
RapidsAtHKUST/ContinuousSubgraphMatching
f786d19561c8ae13cc7aa2af6e4d41a52aa2aba5
[ "MIT" ]
null
null
null
#include "utils/globals.h" std::atomic<bool> reach_time_limit = false;
18
43
0.75
RapidsAtHKUST
425f925acdc49fd521e74e7d0237aea88e107117
470
hpp
C++
Results.hpp
h-g-s/ddtree
4941baf6d66374f5a7c3b7eadd994c2ff8ae55f4
[ "MIT" ]
1
2019-11-30T14:48:40.000Z
2019-11-30T14:48:40.000Z
Results.hpp
h-g-s/ddtree
4941baf6d66374f5a7c3b7eadd994c2ff8ae55f4
[ "MIT" ]
null
null
null
Results.hpp
h-g-s/ddtree
4941baf6d66374f5a7c3b7eadd994c2ff8ae55f4
[ "MIT" ]
null
null
null
/* * Results.hpp * * Created on: 27 de fev de 2019 * Author: haroldo */ #ifndef RESULTS_HPP_ #define RESULTS_HPP_ #include <string> #include <vector> #include "InstanceSet.hpp" class Results { public: Results( const InstanceSet &_iset, const char *resFile ); const std::vector< std::string > &algorithms() const; virtual ~Results (); private: const InstanceSet &iset_; std::vector< std::string > algs_; }; #endif /* RESULTS_HPP_ */
15.666667
61
0.659574
h-g-s
42659843db1fe95995440df1b137db6d97ff4dfe
16,470
cpp
C++
Windows Pin/Windows Pin.cpp
barty32/windows-pin
d89fb0352c5934c403efcfb6518979717920876c
[ "MIT" ]
null
null
null
Windows Pin/Windows Pin.cpp
barty32/windows-pin
d89fb0352c5934c403efcfb6518979717920876c
[ "MIT" ]
null
null
null
Windows Pin/Windows Pin.cpp
barty32/windows-pin
d89fb0352c5934c403efcfb6518979717920876c
[ "MIT" ]
null
null
null
// Windows Pin.cpp : Defines the entry point for the application. // #include "Windows Pin.h" #include "PinDll.h" bool g_bPinning = false; HCURSOR g_hPinCursor = NULL; std::list<HWND> g_pinnedWnds; // Global Variables: HINSTANCE hInst; HWND hWndMain; const UINT WM_TASKBARCREATED = RegisterWindowMessageW(L"TaskbarCreated"); HHOOK hHook = NULL; int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow){ UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); hInst = hInstance; g_hPinCursor = LoadCursorW(hInst, MAKEINTRESOURCEW(IDI_PIN_CURSOR)); // Register main window class (hidden) WNDCLASSEXW wcex = {0}; wcex.cbSize = sizeof(WNDCLASSEXW); wcex.lpfnWndProc = WndProc; wcex.hInstance = hInstance; wcex.lpszClassName = L"WindowsPinWndClass"; if(!RegisterClassExW(&wcex)){ ErrorHandler(L"Class registration failed", GetLastError()); return false; } hWndMain = CreateWindowExW(WS_EX_LAYERED, L"WindowsPinWndClass", L"Windows Pin", WS_POPUP, 0, 0, 0, 0, 0, 0, hInstance, 0); if(!hWndMain){ ErrorHandler(L"Window creation failed", GetLastError()); return false; } NOTIFYICONDATAW* nid = CreateTrayIcon(hWndMain); if(!Shell_NotifyIconW(NIM_ADD, (PNOTIFYICONDATAW)GetPropW(hWndMain, L"trayIcon"))){ ErrorHandler(L"Tray icon creation failed", GetLastError()); return false; } // Prepare tray popup menu HMENU hPopMenu = CreatePopupMenu(); InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_ABOUT, L"About"); InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_PIN, L"Pin a window"); InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_UNPIN, L"Unpin all pinned windows"); InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_SEPARATOR, 0, NULL); InsertMenuW(hPopMenu, 0xFFFFFFFF, MF_BYPOSITION | MF_STRING, IDM_EXIT, L"Exit"); SetPropW(hWndMain, L"hPopMenu", hPopMenu); // Inject DLL to all 32-bit processes hHook = SetWindowsHookExW(WH_GETMESSAGE, ExportHookProc, GetModuleHandleW(L"PinDll32"), 0); if(!hHook){ ErrorHandler(L"32-bit hooking failed", GetLastError()); return false; } HANDLE currentProcess = nullptr; if(Is64BitWindows()){ STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); currentProcess = OpenProcess(SYNCHRONIZE, TRUE, GetCurrentProcessId()); std::wstring cmd = L"Inject64.exe --handle " + std::to_wstring((int)currentProcess); // Start the child process. if(!CreateProcessW(nullptr, (LPWSTR)cmd.data(), NULL, // Process handle not inheritable NULL, // Thread handle not inheritable TRUE, // Handle inheritance 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi) // Pointer to PROCESS_INFORMATION structure ){ ErrorHandler(L"64-bit hook execution failed", GetLastError()); return false; } WaitForSingleObject(pi.hProcess, 500); DWORD dwExitCode; GetExitCodeProcess(pi.hProcess, &dwExitCode); if(dwExitCode != STILL_ACTIVE && dwExitCode > 0){ ErrorHandler(L"64-bit hook error", dwExitCode); return false; } CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } MSG msg; while(GetMessageW(&msg, NULL, 0, 0)){ TranslateMessage(&msg); DispatchMessageW(&msg); } delete nid; DestroyMenu(hPopMenu); if(currentProcess){ CloseHandle(currentProcess); } //UnhookWindowsHookEx(hook); return (int)msg.wParam; } //LRESULT CALLBACK LowLevelMouseProc( // _In_ int nCode, // _In_ WPARAM wParam, // _In_ LPARAM lParam //){ // static bool bCaptured = false; // if(nCode >= HC_ACTION){ // LPMSLLHOOKSTRUCT mss = (LPMSLLHOOKSTRUCT)lParam; // if(g_bPinning){ // switch(wParam){ // case WM_LBUTTONDOWN: // if(!bCaptured){ // //CallNextHookEx(NULL, nCode, WM_LBUTTONDOWN, lParam); // //DefWindowProcW(hWndMain, WM_LBUTTONDOWN, 0, MAKELPARAM(mss->pt.x, mss->pt.y)); // //SetCursorPos(mss->pt.x, mss->pt.y); // SetCursor(g_hPinCursor); // SetCapture(hWndMain); // bCaptured = true; // return false; // } // //case WM_LBUTTONDOWN: // //case WM_MOUSEMOVE: // //SetCursorPos(100, 100); // // //SetCapture(hWndMain); // //return true; // // } // } // } // return CallNextHookEx(NULL, nCode, wParam, lParam); //} bool StartPin(HWND hWnd){ g_bPinning = true; POINT pos; GetCursorPos(&pos); // Hacky solution to set mouse capture without clicking SetWindowPos(hWnd, HWND_TOPMOST, pos.x - 10, pos.y - 10, 20, 20, SWP_SHOWWINDOW); SetLayeredWindowAttributes(hWnd, RGB(255, 0, 0), 200, LWA_COLORKEY | LWA_ALPHA); mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0); SetCursor(LoadCursorW(hInst, MAKEINTRESOURCEW(IDI_PIN_CURSOR))); SetCapture(hWnd); SetWindowPos(hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_HIDEWINDOW); return true; } bool EndPin(){ g_bPinning = false; // Determine the window that lies underneath the mouse cursor. POINT pt; GetCursorPos(&pt); HWND hWnd = FindParent(WindowFromPoint(pt)); ReleaseCapture(); InvalidateRect(NULL, NULL, FALSE); if(CheckWindowValidity(hWnd)){ //WCHAR title[120]; //GetWindowTextW(hWnd, title, 120); //WCHAR result[200]; //_snwprintf_s(result, 200, L"Handle: 0x%08X\nTitle: %s", (int)hWnd, title); //MessageBoxW(NULL, result, L"Info", MB_ICONINFORMATION); PinWindow(hWnd); return true; } return false; } bool MovePin(){ static HWND lastWnd = NULL; POINT pt; GetCursorPos(&pt); // Determine the window that lies underneath the mouse cursor. HWND hWnd = FindParent(WindowFromPoint(pt)); if(lastWnd == hWnd){ return false; } // If there was a previously found window, we must instruct it to refresh itself. if(lastWnd){ InvalidateRect(NULL, NULL, TRUE); UpdateWindow(lastWnd); RedrawWindow(lastWnd, NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN); } // Indicate that this found window is now the current found window. lastWnd = hWnd; // Check first for validity. if(CheckWindowValidity(hWnd)){ return HighlightWindow(hWnd); } return false; } bool HighlightWindow(HWND hWnd){ HDC hdcScreen = GetWindowDC(NULL); if(!hdcScreen){ TRACE(L"Highligt window failed - HDC is null"); return false; } RECT rcWnd; if(FAILED(DwmGetWindowAttribute(hWnd, DWMWA_EXTENDED_FRAME_BOUNDS, &rcWnd, sizeof(rcWnd)))){ //TRACE(L"Highligt window failed - GetWindowAttr failed"); GetWindowRect(hWnd, &rcWnd); } HPEN hPen = CreatePen(PS_SOLID, 10, RGB(255, 0, 0)); HGDIOBJ oldBrush = SelectObject(hdcScreen, GetStockObject(HOLLOW_BRUSH)); HGDIOBJ oldPen = SelectObject(hdcScreen, hPen); Rectangle(hdcScreen, rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom); // Cleanup SelectObject(hdcScreen, oldBrush); SelectObject(hdcScreen, oldPen); DeleteObject(hPen); ReleaseDC(NULL, hdcScreen); return true; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam){ if(message == WM_TASKBARCREATED){ Shell_NotifyIconW(NIM_ADD, (PNOTIFYICONDATAW)GetPropW(hWnd, L"trayIcon")); } switch(message){ case WM_COMMAND: // Parse the menu selections: switch(LOWORD(wParam)){ case IDM_PIN: //PinActiveWindow(hWnd); StartPin(hWnd); break; case IDM_UNPIN: for(auto wnd : g_pinnedWnds){ UnpinWindow(wnd); } g_pinnedWnds.clear(); break; case IDM_ABOUT: return DialogBoxParamW(hInst, MAKEINTRESOURCEW(IDD_ABOUTBOX), hWnd, About, 0); case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } break; case WM_LBUTTONUP: if(g_bPinning){ EndPin(); return false; } break; case WM_MOUSEMOVE: if(g_bPinning){ MovePin(); return false; } break; case WM_USER_SHELLICON: switch(LOWORD(lParam)){ case WM_RBUTTONUP: { POINT lpClickPoint; UINT uFlag = MF_BYPOSITION | MF_STRING; GetCursorPos(&lpClickPoint); TrackPopupMenu((HMENU)GetPropW(hWnd, L"hPopMenu"), TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_BOTTOMALIGN, lpClickPoint.x, lpClickPoint.y, 0, hWnd, NULL); return true; } case WM_LBUTTONUP: StartPin(hWnd); return false; } break; case WM_DESTROY: UnhookWindowsHookEx(hHook); Shell_NotifyIconW(NIM_DELETE, (PNOTIFYICONDATAW)GetPropW(hWnd, L"trayIcon")); PostQuitMessage(0); break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } return DefWindowProcW(hWnd, message, wParam, lParam); } bool PinWindow(HWND hWnd){ LONG dwExStyle = GetWindowLongW(hWnd, GWL_EXSTYLE); dwExStyle |= WS_EX_TOPMOST; SetWindowLongW(hWnd, GWL_EXSTYLE, dwExStyle); SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOREDRAW | SWP_NOREPOSITION | SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_SHOWWINDOW); g_pinnedWnds.push_back(hWnd); return true; } bool UnpinWindow(HWND hWnd){ LONG dwExStyle = GetWindowLongW(hWnd, GWL_EXSTYLE); dwExStyle &= ~WS_EX_TOPMOST; SetWindowLongW(hWnd, GWL_EXSTYLE, dwExStyle); SetWindowPos(hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOREDRAW | SWP_NOREPOSITION | SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_SHOWWINDOW); return true; } NOTIFYICONDATAW* CreateTrayIcon(HWND hWnd){ // Create tray icon NOTIFYICONDATAW* nidApp = new NOTIFYICONDATAW; if(!nidApp) return nullptr; nidApp->cbSize = sizeof(NOTIFYICONDATAW); nidApp->hWnd = hWnd; //handle of the window which will process this app. messages nidApp->uID = IDI_WINDOWSPIN; //ID of the icon that will appear in the system tray nidApp->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; nidApp->hIcon = LoadIconW(hInst, MAKEINTRESOURCEW(IDI_WINDOWSPIN)); nidApp->uCallbackMessage = WM_USER_SHELLICON; LoadStringW(hInst, IDS_APPTOOLTIP, nidApp->szTip, _countof(nidApp->szTip)); SetPropW(hWnd, L"trayIcon", nidApp); return nidApp; } bool CheckWindowValidity(HWND hWnd){ if(!hWnd || !IsWindow(hWnd) || hWnd == GetShellWindow() || hWnd == FindWindowW(L"Shell_TrayWnd", NULL)){ return false; } return true; } HWND FindParent(HWND hWnd){ DWORD dwStyle = GetWindowLongW(hWnd, GWL_STYLE); if(dwStyle & WS_CHILD){ return FindParent(GetParent(hWnd)); } return hWnd; } bool Is64BitWindows(){ #if defined(_WIN64) return true; // 64-bit programs run only on Win64 #elif defined(_WIN32) // 32-bit programs run on both 32-bit and 64-bit Windows, so must sniff BOOL f64 = FALSE; return IsWow64Process(GetCurrentProcess(), &f64) && f64; #else return false; // Win64 does not support Win16 #endif } void ErrorHandler(LPCWSTR errMsg, DWORD errCode, DWORD dwType){ std::wstring msg(errMsg); if(errCode){ msg.append(L"\nError code: " + std::to_wstring(errCode)); } MessageBoxW(NULL, msg.c_str(), L"Windows Pin - Error", dwType | MB_OK); } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam){ UNREFERENCED_PARAMETER(lParam); switch (message){ case WM_INITDIALOG: return true; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL){ EndDialog(hDlg, LOWORD(wParam)); return true; } break; } return false; } //void PinActiveWindow(HWND hWndApp){ // HWND hwndWindow = GetWindow(GetDesktopWindow(), GW_HWNDFIRST);// GetForegroundWindow(); // LONG dwExStyle = GetWindowLongPtrW(hwndWindow, GWL_EXSTYLE); // HWND hInsertAfter = NULL; // if(dwExStyle & WS_EX_TOPMOST){ // dwExStyle &= ~WS_EX_TOPMOST; // hInsertAfter = HWND_NOTOPMOST; // ModifyMenuW((HMENU)GetPropW(hWndApp, L"hPopMenu"), IDM_PIN, MF_BYCOMMAND, IDM_PIN, L"Pin current window"); // } // else{ // dwExStyle |= WS_EX_TOPMOST; // hInsertAfter = HWND_TOPMOST; // ModifyMenuW((HMENU)GetPropW(hWndApp, L"hPopMenu"), IDM_PIN, MF_BYCOMMAND, IDM_PIN, L"Unpin current window"); // } // SetWindowLongPtrW(hwndWindow, GWL_EXSTYLE, dwExStyle); // SetWindowPos(hwndWindow, hInsertAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOREDRAW | SWP_NOREPOSITION | SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_SHOWWINDOW); //} //---------------------------------------------------------------------------------------------InitInstance //BOOL InitInstance(HINSTANCE hInstance){ // obtain msghook library functions /*HINSTANCE g_hInstLib = LoadLibraryW(L"WindowPinDll.dll"); if(g_hInstLib == NULL){ return FALSE; } pfnSetMsgHook = (SetMsgHookT)GetProcAddress(g_hInstLib, "SetMsgHook"); if(NULL == pfnSetMsgHook){ FreeLibrary(g_hInstLib); return FALSE; } pfnUnsetMsgHook = (UnsetMsgHookT)GetProcAddress(g_hInstLib, "UnsetMsgHook"); if(NULL == pfnUnsetMsgHook){ FreeLibrary(g_hInstLib); return FALSE; } pfnSetMsgHook();*/ //(SetMsgHookT)GetProcAddress(g_hInstLib, "SetMsgHook"); //hHook = SetWindowsHookExW(WH_CALLWNDPROC, /*(HOOKPROC)*/HookProc/*GetProcAddress(g_hInstLib, "HookProc")*/, g_hInstLib/*GetModuleHandleW(L"WindowPinDll.dll")*/, 0); //if(hHook == NULL){ // int error = GetLastError(); //} //hHook64 = SetWindowsHookExW(WH_CALLWNDPROC, (HOOKPROC)HookProc, GetModuleHandleW(L"WindowPinDll64"), 0); //hHookCbt = SetWindowsHookExW(WH_CBT, (HOOKPROC)/*CBTProc*/GetProcAddress(g_hInstLib, "CBTProc"), g_hInstLib/*GetModuleHandleW(L"WindowPinDll.dll")*/, 0); //bPump = TRUE; //MSG msg; //while(bPump){ // // Keep pumping... // PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE); // TranslateMessage(&msg); // DispatchMessageW(&msg); // Sleep(10); //} //int error = GetLastError(); //WinExec("notepad.exe", 1); //} /* bool HighlightWindow(HWND hWndIn){ HWND hWnd = hWndIn;//FindParent(hWndIn); //OutputDebugStringW(std::format(L"Highlighting current window {}\n", (int)hWndIn).c_str()); HDC hdcScreen = GetWindowDC(NULL); if(!hdcScreen){ ErrorHandler(L"DC is null", GetLastError()); return false; } RECT rcWnd; //GetWindowRect(hWnd, &rcWnd); DwmGetWindowAttribute(hWnd, DWMWA_EXTENDED_FRAME_BOUNDS, &rcWnd, sizeof(rcWnd)); //RECT rcScreen = {0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)}; //int scrW = GetSystemMetrics(SM_CXSCREEN); //int scrH = GetSystemMetrics(SM_CYSCREEN); //RedrawWindow(GetDesktopWindow(), NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN); //if(bRefresh){ // InvalidateRect(NULL, NULL, false); //} //WCHAR ss[100]; //GetWindowTextW(hWnd, ss, 100); //HDC tempDC = CreateCompatibleDC(NULL); //BitBlt(tempDC, 0, 0, rcWnd.right - rcWnd.left, rcWnd.bottom - rcWnd.top, hdc, ) //ExcludeClipRect(hdc, rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom); //HDC tmpDC = CreateCompatibleDC(g_hdcScreen); //HBITMAP hBmp = CreateCompatibleBitmap(tmpDC, scrW, scrH); //SelectObject(tmpDC, hBmp); //BitBlt(tmpDC, 0, 0, scrW, scrH, g_hdcScreen, 0, 0, SRCCOPY); //FillRect(tmpDC, &rcWnd, (HBRUSH)CreateSolidBrush(RGB(255, 255, 255))); //FillRect(tmpDC, &rcWnd, (HBRUSH)GetStockObject(HOLLOW_BRUSH)); HGDIOBJ oldBrush = SelectObject(hdcScreen, GetStockObject(HOLLOW_BRUSH)); HGDIOBJ oldPen = SelectObject(hdcScreen, CreatePen(PS_SOLID, 10, RGB(255, 0, 0))); ////Rectangle(hdc, 0, 0, scrW, scrH); Rectangle(hdcScreen, rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom); //InvalidateRect(hWnd, NULL, FALSE); //FillRect(hdc, &rcWnd, (HBRUSH)GetStockObject(HOLLOW_BRUSH)); //SelectObject(hdc, ) //FillRect(hdc, &rcScreen, ); //BLENDFUNCTION bf = {0}; //bf.SourceConstantAlpha = 200; //bf.AlphaFormat = AC_SRC_ALPHA; //if(!AlphaBlend(hdc, 0, 0, scrW, scrH, tmpDC, 0, 0, scrW, scrH, bf)){ // OutputDebugStringW(L"AplhaBlend failed"); //} //TransparentBlt(hdcScreen, 0, 0, scrW, scrH, tmpDC, 0, 0, scrW, scrH, RGB(255, 255, 255)); SelectObject(hdcScreen, oldBrush); SelectObject(hdcScreen, oldPen); ReleaseDC(NULL, hdcScreen); return true; } */ // Create snapshot of current screen //int sw = GetSystemMetrics(SM_CXSCREEN); //int sy = GetSystemMetrics(SM_CYSCREEN); //HDC hdc = GetWindowDC(NULL); //g_hdcScreen = CreateCompatibleDC(hdc); //HBITMAP hBmp = CreateCompatibleBitmap(hdc, sw, sy); //SelectObject(g_hdcScreen, hBmp); //BitBlt(g_hdcScreen, 0, 0, sw, sy, hdc, 0, 0, SRCCOPY); //ReleaseDC(NULL, hdc); //case WM_PAINT: //{ // PAINTSTRUCT ps; // HDC hdc = BeginPaint(hWnd, &ps); // RECT rc; // GetWindowRect(hWnd, &rc); // FillRect(hdc, &rc, (HBRUSH)GetStockObject(BLACK_BRUSH)); // EndPaint(hWnd, &ps); // return false; //}
29.253996
167
0.702975
barty32
4266219ebae7d643ef0606185beb79535329e25e
54
cpp
C++
source/framework/algorithm/src/local_operation/cos.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
2
2021-02-26T22:45:56.000Z
2021-05-02T10:28:48.000Z
source/framework/algorithm/src/local_operation/cos.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
131
2020-10-27T13:09:16.000Z
2022-03-29T10:24:26.000Z
source/framework/algorithm/src/local_operation/cos.cpp
computationalgeography/lue
71993169bae67a9863d7bd7646d207405dc6f767
[ "MIT" ]
null
null
null
#include "lue/framework/algorithm/definition/cos.hpp"
27
53
0.814815
computationalgeography
4267171e4f2224965ac76a9a6d9575f74ce643b2
1,640
cpp
C++
Source/SHOOTACUBE/Accessories/Gun/Ammo.cpp
marvkey/SHOOTACUBE
b98665dec593d2a5b33b66bcb1ebb5a4b896b23f
[ "Apache-2.0" ]
null
null
null
Source/SHOOTACUBE/Accessories/Gun/Ammo.cpp
marvkey/SHOOTACUBE
b98665dec593d2a5b33b66bcb1ebb5a4b896b23f
[ "Apache-2.0" ]
null
null
null
Source/SHOOTACUBE/Accessories/Gun/Ammo.cpp
marvkey/SHOOTACUBE
b98665dec593d2a5b33b66bcb1ebb5a4b896b23f
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Ammo.h" #include "SHOOTACUBE/Player/Player1.h" #include "Components/BoxComponent.h" AAmmo::AAmmo(){} void AAmmo::BeginPlay(){ Super::BeginPlay(); Collider->OnComponentBeginOverlap.AddDynamic(this,&AAmmo::OnOverlapBegin); if(AmmoTypeToBeSpawned==AmmoType::SmallAmmo){ AmmoToBeSpawned =FMath::RandRange(10,50); } else if(AmmoTypeToBeSpawned==AmmoType::MediumAmmo){ AmmoToBeSpawned =FMath::RandRange(10,50); } else{ AmmoToBeSpawned =FMath::RandRange(1,3); } } void AAmmo::Tick(float DeltaSeconds){ Super::Tick(DeltaSeconds); } AmmoType AAmmo::GetAmmoTypeToBeSpawned(){ return AmmoTypeToBeSpawned; } void AAmmo::OnOverlapBegin(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp,int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult){ if(OtherActor && OtherActor != this){ GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, TEXT("Overlap Begin")); if(OtherActor->IsA(APlayer1::StaticClass())){ APlayer1 * FirstPlayer =Cast<APlayer1>(OtherActor); if(FirstPlayer->bIsAi == true){return;} if(this->AmmoTypeToBeSpawned ==AmmoType::SmallAmmo){ FirstPlayer->SmallBulletsAmmo+=AmmoToBeSpawned; }else if(AmmoTypeToBeSpawned ==AmmoType::MediumAmmo){ FirstPlayer->MediumBulletAmmo+=AmmoToBeSpawned; }else{ FirstPlayer->RocketLuncherBulletAmmo+=AmmoToBeSpawned; } this->Destroy(); } } }
37.272727
185
0.679268
marvkey
4269de30fa7cfb72d6b42b76f5231eb530d0a6ee
12,518
cpp
C++
src/samples/aiff/aiff.cpp
eriser/hivetrekkr
bac051e587fb53fc47bbd18066059c2c402b5720
[ "BSD-2-Clause" ]
1
2018-10-22T11:32:30.000Z
2018-10-22T11:32:30.000Z
src/samples/aiff/aiff.cpp
eriser/hivetrekkr
bac051e587fb53fc47bbd18066059c2c402b5720
[ "BSD-2-Clause" ]
null
null
null
src/samples/aiff/aiff.cpp
eriser/hivetrekkr
bac051e587fb53fc47bbd18066059c2c402b5720
[ "BSD-2-Clause" ]
1
2019-03-05T15:39:57.000Z
2019-03-05T15:39:57.000Z
// ------------------------------------------------------ // Protrekkr // Based on Juan Antonio Arguelles Rius's NoiseTrekker. // // Copyright (C) 2008-2014 Franck Charlet. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL FRANCK CHARLET OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. // ------------------------------------------------------ // TODO: add support for AIFC // ------------------------------------------------------ // Includes #include "include/aiff.h" AIFFFile::AIFFFile() { file = NULL; Base_Note = 0; SustainLoop.PlayMode = NoLooping; Use_Floats = 0; Loop_Start = 0; Loop_End = 0; } AIFFFile::~AIFFFile() { Close(); } unsigned long AIFFFile::FourCC(const char *ChunkName) { long retbuf = 0x20202020; // four spaces (padding) char *p = ((char *) &retbuf); // Remember, this is Intel format! // The first character goes in the LSB for (int i = 0; i < 4 && ChunkName[i]; i++) { *p++ = ChunkName[i]; } return retbuf; } // ------------------------------------------------------ // Look for a chunk inside the file // Return it's length (with file pointing to it's data) or 0 int AIFFFile::SeekChunk(const char *ChunkName) { int Chunk; int Chunk_To_Find_Lo; int Chunk_To_Find = FourCC(ChunkName); int i; int size; i = 0; Chunk_To_Find_Lo = tolower(Chunk_To_Find & 0xff); Chunk_To_Find_Lo |= tolower((Chunk_To_Find >> 8) & 0xff) << 8; Chunk_To_Find_Lo |= tolower((Chunk_To_Find >> 16) & 0xff) << 16; Chunk_To_Find_Lo |= tolower((Chunk_To_Find >> 24) & 0xff) << 24; Seek(i); while(!feof(file)) { Chunk = 0; Seek(i); Read(&Chunk, 4); if(Chunk == Chunk_To_Find || Chunk == Chunk_To_Find_Lo) { Read(&size, 4); return(Mot_Swap_32(size)); } // Skip the data part to speed up the process if(Chunk == SoundDataID) { Read(&size, 4); size = Mot_Swap_32(size); i += size + 4 + 4 - 1; } i++; } return(0); } int AIFFFile::Open(const char *Filename) { int chunk_size; int Padding; int Phony_Byte; short Phony_Short; file = fopen(Filename, "rb"); if(file) { // Those compression schemes are not supported chunk_size = SeekChunk("ALAW"); if(chunk_size) return 0; chunk_size = SeekChunk("ULAW"); if(chunk_size) return 0; chunk_size = SeekChunk("G722"); if(chunk_size) return 0; chunk_size = SeekChunk("G726"); if(chunk_size) return 0; chunk_size = SeekChunk("G728"); if(chunk_size) return 0; chunk_size = SeekChunk("GSM "); if(chunk_size) return 0; chunk_size = SeekChunk("COMM"); if(chunk_size) { Read(&CommDat.numChannels, sizeof(short)); CommDat.numChannels = Mot_Swap_16(CommDat.numChannels); Read(&CommDat.numSampleFrames, sizeof(unsigned long)); CommDat.numSampleFrames = Mot_Swap_32(CommDat.numSampleFrames); Read(&CommDat.sampleSize, sizeof(short)); CommDat.sampleSize = Mot_Swap_16(CommDat.sampleSize); chunk_size = SeekChunk("INST"); // (Not mandatory) if(chunk_size) { Read(&Base_Note, sizeof(char)); Read(&Phony_Byte, sizeof(char)); // detune Read(&Phony_Byte, sizeof(char)); // lowNote Read(&Phony_Byte, sizeof(char)); // highNote Read(&Phony_Byte, sizeof(char)); // lowVelocity Read(&Phony_Byte, sizeof(char)); // highVelocity Read(&Phony_Short, sizeof(short)); // gain Read(&SustainLoop, sizeof(Loop)); // sustainLoop SustainLoop.PlayMode = Mot_Swap_16(SustainLoop.PlayMode); SustainLoop.beginLoop = Mot_Swap_16(SustainLoop.beginLoop); SustainLoop.endLoop = Mot_Swap_16(SustainLoop.endLoop); if(SustainLoop.beginLoop < SustainLoop.endLoop) { // Find loop points Loop_Start = Get_Marker(SustainLoop.beginLoop); Loop_End = Get_Marker(SustainLoop.endLoop); // Messed up data if(Loop_Start >= Loop_End) { SustainLoop.PlayMode = NoLooping; } } else { // Doc specifies that begin must be smaller // otherwise there's no loop SustainLoop.PlayMode = NoLooping; } } chunk_size = SeekChunk("FL32"); if(chunk_size) Use_Floats = 1; chunk_size = SeekChunk("FL64"); if(chunk_size) Use_Floats = 1; chunk_size = SeekChunk("SSND"); if(chunk_size) { // Dummy reads Read(&Padding, sizeof(unsigned long)); Read(&Block_Size, sizeof(unsigned long)); Seek(CurrentFilePosition() + Padding); // File pos now points on waveform data return 1; } } } return 0; } long AIFFFile::CurrentFilePosition() { return ftell(file); } int AIFFFile::Seek(long offset) { fflush(file); if(fseek(file, offset, SEEK_SET)) { return(0); } else { return(1); } } int AIFFFile::Read(void *Data, unsigned NumBytes) { return fread(Data, NumBytes, 1, file); } void AIFFFile::Close() { if(file) fclose(file); file = NULL; } int AIFFFile::BitsPerSample() { return CommDat.sampleSize; } int AIFFFile::NumChannels() { return CommDat.numChannels; } unsigned long AIFFFile::LoopStart() { return Loop_Start; } unsigned long AIFFFile::LoopEnd() { return Loop_End; } unsigned long AIFFFile::NumSamples() { return CommDat.numSampleFrames; } int AIFFFile::BaseNote() { return Base_Note; } int AIFFFile::LoopType() { return SustainLoop.PlayMode; } int AIFFFile::ReadMonoSample(short *Sample) { int retcode; float y; double y64; unsigned long int_y; Uint64 int_y64; switch(CommDat.sampleSize) { case 8: unsigned char x; retcode = Read(&x, 1); *Sample = (short(x) << 8); break; case 12: case 16: retcode = Read(Sample, 2); *Sample = Mot_Swap_16(*Sample); break; case 24: int_y = 0; retcode = Read(&int_y, 3); int_y = Mot_Swap_32(int_y); *Sample = (short) (int_y / 65536); break; case 32: retcode = Read(&int_y, 4); int_y = Mot_Swap_32(int_y); if(Use_Floats) { IntToFloat((int *) &y, int_y); *Sample = (short) (y * 32767.0f); } else { *Sample = (short) (int_y / 65536); } break; case 64: retcode = Read(&int_y64, 8); int_y64 = Mot_Swap_64(int_y64); Int64ToDouble((Uint64 *) &y64, int_y64); *Sample = (short) (y64 * 32767.0); break; default: retcode = 0; } return retcode; } int AIFFFile::ReadStereoSample(short *L, short *R) { int retcode = 0; unsigned char x[2]; short y[2]; float z[2]; double z64[2]; long int_z[2]; Uint64 int_z64[2]; switch(CommDat.sampleSize) { case 8: retcode = Read(x, 2); *L = (short (x[0]) << 8); *R = (short (x[1]) << 8); break; case 12: case 16: retcode = Read(y, 4); y[0] = Mot_Swap_16(y[0]); y[1] = Mot_Swap_16(y[1]); *L = short(y[0]); *R = short(y[1]); break; case 24: int_z[0] = 0; int_z[1] = 0; retcode = Read(&int_z[0], 3); retcode = Read(&int_z[1], 3); int_z[0] = Mot_Swap_32(int_z[0]); int_z[1] = Mot_Swap_32(int_z[1]); *L = (short) (int_z[0] / 65536); *R = (short) (int_z[1] / 65536); break; case 32: retcode = Read(int_z, 8); int_z[0] = Mot_Swap_32(int_z[0]); int_z[1] = Mot_Swap_32(int_z[1]); if(Use_Floats) { IntToFloat((int *) &z[0], int_z[0]); IntToFloat((int *) &z[1], int_z[1]); *L = (short) (z[0] * 32767.0f); *R = (short) (z[1] * 32767.0f); } else { *L = (short) (int_z[0] / 65536); *R = (short) (int_z[1] / 65536); } break; case 64: retcode = Read(int_z64, 16); int_z64[0] = Mot_Swap_64(int_z64[0]); int_z64[1] = Mot_Swap_64(int_z64[1]); Int64ToDouble((Uint64 *) &z64[0], int_z64[0]); Int64ToDouble((Uint64 *) &z64[1], int_z64[1]); *L = (short) (z64[0] * 32767.0); *R = (short) (z64[1] * 32767.0); break; default: retcode = 0; } return retcode; } int AIFFFile::Get_Marker(int Marker_Id) { unsigned char string_size; int i; int chunk_size = SeekChunk("MARK"); if(chunk_size) { Read(&Markers.numMarkers, sizeof(unsigned short)); Markers.numMarkers = Mot_Swap_16(Markers.numMarkers); for(i = 0 ; i < Markers.numMarkers; i++) { Read(&CurMarker.id, sizeof(unsigned short)); CurMarker.id = Mot_Swap_16(CurMarker.id); Read(&CurMarker.position, sizeof(unsigned long)); CurMarker.position = Mot_Swap_32(CurMarker.position); if(CurMarker.id == Marker_Id) { return(CurMarker.position); } else { Read(&string_size, sizeof(unsigned char)); string_size++; Seek(CurrentFilePosition() + string_size); } } // Couldn't find the specified marker so disable everything SustainLoop.PlayMode = NoLooping; return(-1); } else { // Everything is broken so disable looping SustainLoop.PlayMode = NoLooping; return(-1); } } void AIFFFile::IntToFloat(int *Dest, int Source) { *Dest = Source; } void AIFFFile::Int64ToDouble(Uint64 *Dest, Uint64 Source) { *Dest = Source; }
28.067265
81
0.506071
eriser
426c13fd0ff5d057eb38130136cf45fe3043ea2c
6,174
hpp
C++
inference-engine/thirdparty/mkl-dnn/src/cpu/jit_avx512_core_x8s8s32x_1x1_deconvolution.hpp
zhoub/dldt
e42c01cf6e1d3aefa55e2c5df91f1054daddc575
[ "Apache-2.0" ]
52
2019-12-11T14:33:19.000Z
2021-09-24T14:09:54.000Z
inference-engine/thirdparty/mkl-dnn/src/cpu/jit_avx512_core_x8s8s32x_1x1_deconvolution.hpp
zhoub/dldt
e42c01cf6e1d3aefa55e2c5df91f1054daddc575
[ "Apache-2.0" ]
13
2019-12-12T04:15:23.000Z
2021-09-06T01:16:04.000Z
inference-engine/thirdparty/mkl-dnn/src/cpu/jit_avx512_core_x8s8s32x_1x1_deconvolution.hpp
zhoub/dldt
e42c01cf6e1d3aefa55e2c5df91f1054daddc575
[ "Apache-2.0" ]
15
2019-12-12T00:58:07.000Z
2021-09-15T09:37:39.000Z
/******************************************************************************* * Copyright 2018 Intel Corporation * * 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. *******************************************************************************/ #ifndef CPU_JIT_AVX512_CORE_X8S8S32X_1X1_DECONVOLUTION_HPP #define CPU_JIT_AVX512_CORE_X8S8S32X_1X1_DECONVOLUTION_HPP #include "c_types_map.hpp" #include "cpu_deconvolution_pd.hpp" #include "cpu_engine.hpp" #include "cpu_reducer.hpp" #include "mkldnn_thread.hpp" #include "utils.hpp" #include "cpu_convolution_pd.hpp" #include "type_helpers.hpp" #include "primitive_iterator.hpp" #include "jit_uni_1x1_conv_utils.hpp" #include "jit_avx512_core_x8s8s32x_1x1_convolution.hpp" namespace mkldnn { namespace impl { namespace cpu { template <impl::data_type_t src_type, impl::data_type_t dst_type> struct jit_avx512_core_x8s8s32x_1x1_deconvolution_fwd_t : public cpu_primitive_t { struct pd_t : public cpu_deconvolution_fwd_pd_t { pd_t(engine_t *engine, const deconvolution_desc_t *adesc, const primitive_attr_t *attr, const deconvolution_fwd_pd_t *hint_fwd_pd) : cpu_deconvolution_fwd_pd_t(engine, adesc, attr, hint_fwd_pd) , conv_pd_(nullptr) {} pd_t(const pd_t &other) : cpu_deconvolution_fwd_pd_t(other) , conv_pd_(other.conv_pd_->clone()) , conv_supports_bias_(other.conv_supports_bias_) {} ~pd_t() { delete conv_pd_; } DECLARE_DECONVOLUTION_PD_T( jit_avx512_core_x8s8s32x_1x1_deconvolution_fwd_t<src_type, dst_type>); status_t init_convolution() { convolution_desc_t cd; status_t status; auto dd = this->desc(); status = conv_desc_init(&cd, prop_kind::forward_training, alg_kind::convolution_direct, &(dd->src_desc), &(dd->weights_desc), &(dd->bias_desc), &(dd->dst_desc), dd->strides, dd->dilates, dd->padding[0], dd->padding[1], dd->padding_kind); if (status == status::success) { status = mkldnn_primitive_desc::create< typename mkldnn::impl::cpu:: jit_avx512_core_x8s8s32x_1x1_convolution_fwd_t<src_type, dst_type>::pd_t>(&conv_pd_, (op_desc_t *)&cd, &(this->attr_), this->engine_, nullptr); } if (status == status::success) { status = set_default_params(); } return status; }; virtual status_t init() override { using namespace prop_kind; status_t status; assert(this->engine()->kind() == engine_kind::cpu); bool ok = true && utils::one_of(this->desc()->prop_kind, prop_kind::forward_training, prop_kind::forward_inference) && this->desc()->alg_kind == alg_kind::deconvolution_direct && !this->has_zero_dim_memory() && this->desc()->src_desc.data_type == src_type && this->desc()->dst_desc.data_type == dst_type && this->desc()->weights_desc.data_type == data_type::s8 && IMPLICATION(this->with_bias(), utils::one_of(this->desc()->bias_desc.data_type, data_type::f32, data_type::s32, data_type::s8, data_type::u8)) && this->desc()->accum_data_type == data_type::s32; if (ok) status = init_convolution(); else status = status::unimplemented; return status; } protected: virtual status_t set_default_params() { using namespace memory_format; auto conv_1x1_pd_ = static_cast<typename mkldnn::impl::cpu:: jit_avx512_core_x8s8s32x_1x1_convolution_fwd_t<src_type, dst_type>::pd_t *>(conv_pd_); CHECK(this->src_pd_.set_format( conv_1x1_pd_->src_pd()->desc()->format)); CHECK(this->dst_pd_.set_format( conv_1x1_pd_->dst_pd()->desc()->format)); CHECK(this->weights_pd_.set_format( conv_1x1_pd_->weights_pd()->desc()->format)); if (this->with_bias()) CHECK(this->bias_pd_.set_format( conv_1x1_pd_->weights_pd(1)->desc()->format)); return status::success; } primitive_desc_t *conv_pd_; bool conv_supports_bias_; }; jit_avx512_core_x8s8s32x_1x1_deconvolution_fwd_t(const pd_t *apd, const input_vector &inputs, const output_vector &outputs) : cpu_primitive_t(apd, inputs, outputs), conv_p_(nullptr) {} ~jit_avx512_core_x8s8s32x_1x1_deconvolution_fwd_t() { delete this->conv_p_; } virtual void execute(event_t *e) const { switch (pd()->desc()->prop_kind) { case prop_kind::forward_training: case prop_kind::forward_inference: (conv_p_)->execute(e); break; default: assert(!"invalid prop_kind"); } e->set_state(event_t::ready); } private: const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); } primitive_t *conv_p_; }; } } } #endif /* CPU_JIT_AVX512_CORE_X8S8S32X_1X1_DECONVOLUTION_HPP */
37.877301
88
0.573858
zhoub
426d393697ce31c2e9966196878a5b2b0785e8d7
693
cpp
C++
HOL6/unified/main.cpp
sudopluto/GPUClassS19
6bc0ff715b0c2082e46fd77d33fe1cf8486b09f4
[ "MIT" ]
null
null
null
HOL6/unified/main.cpp
sudopluto/GPUClassS19
6bc0ff715b0c2082e46fd77d33fe1cf8486b09f4
[ "MIT" ]
null
null
null
HOL6/unified/main.cpp
sudopluto/GPUClassS19
6bc0ff715b0c2082e46fd77d33fe1cf8486b09f4
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> void initialize (int N, float *a, float *b, float *c){ for (int i = 0; i < N; i++){ if (i < N){ c[i] = 0; a[i] = 1 + i; b[i] = 1 - i; } } } void addVectors (int N, float *a, float *b, float *c){ for (int i = 0; i < N; i++){ if (i < N){ c[i] = a[i] + b[i]; } } } int main (int argc, char **argv){ if (argc != 2) exit (1); int N = atoi(argv[1]); float *a, *b, *c; a = (float *) malloc(N*sizeof(float)); b = (float *) malloc(N*sizeof(float)); c = (float *) malloc(N*sizeof(float)); initialize(N,a,b,c); addVectors(N,a,b,c); for (int i = 0; i < 5; i++) { printf("%f\n", c[i]); } free(a); free(b); free(c); }
15.75
54
0.486291
sudopluto
426d9e182fd082858b230aa1f5cd48f10aac8725
3,192
cc
C++
modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc
minstrelsy/webrtc-official
cfe75c12ee04d17e7898ebc0a8ad1051b6627e53
[ "BSD-3-Clause" ]
305
2020-03-31T14:12:50.000Z
2022-03-19T16:45:49.000Z
modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc
daixy111040536/webrtc
7abfc990c00ab35090fff285fcf635d1d7892433
[ "BSD-3-Clause" ]
23
2020-04-29T11:41:23.000Z
2021-09-07T02:07:57.000Z
modules/congestion_controller/goog_cc/congestion_window_pushback_controller_unittest.cc
daixy111040536/webrtc
7abfc990c00ab35090fff285fcf635d1d7892433
[ "BSD-3-Clause" ]
122
2020-04-17T11:38:56.000Z
2022-03-25T15:48:42.000Z
/* * Copyright (c) 2018 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/congestion_controller/goog_cc/congestion_window_pushback_controller.h" #include <memory> #include "api/transport/field_trial_based_config.h" #include "test/field_trial.h" #include "test/gmock.h" #include "test/gtest.h" using ::testing::_; namespace webrtc { namespace test { class CongestionWindowPushbackControllerTest : public ::testing::Test { public: CongestionWindowPushbackControllerTest() { cwnd_controller_.reset( new CongestionWindowPushbackController(&field_trial_config_)); } protected: FieldTrialBasedConfig field_trial_config_; std::unique_ptr<CongestionWindowPushbackController> cwnd_controller_; }; TEST_F(CongestionWindowPushbackControllerTest, FullCongestionWindow) { cwnd_controller_->UpdateOutstandingData(100000); cwnd_controller_->SetDataWindow(DataSize::bytes(50000)); uint32_t bitrate_bps = 80000; bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps); EXPECT_EQ(72000u, bitrate_bps); cwnd_controller_->SetDataWindow(DataSize::bytes(50000)); bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps); EXPECT_EQ(static_cast<uint32_t>(72000 * 0.9 * 0.9), bitrate_bps); } TEST_F(CongestionWindowPushbackControllerTest, NormalCongestionWindow) { cwnd_controller_->UpdateOutstandingData(199999); cwnd_controller_->SetDataWindow(DataSize::bytes(200000)); uint32_t bitrate_bps = 80000; bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps); EXPECT_EQ(80000u, bitrate_bps); } TEST_F(CongestionWindowPushbackControllerTest, LowBitrate) { cwnd_controller_->UpdateOutstandingData(100000); cwnd_controller_->SetDataWindow(DataSize::bytes(50000)); uint32_t bitrate_bps = 35000; bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps); EXPECT_EQ(static_cast<uint32_t>(35000 * 0.9), bitrate_bps); cwnd_controller_->SetDataWindow(DataSize::bytes(20000)); bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps); EXPECT_EQ(30000u, bitrate_bps); } TEST_F(CongestionWindowPushbackControllerTest, NoPushbackOnDataWindowUnset) { cwnd_controller_->UpdateOutstandingData(1e8); // Large number uint32_t bitrate_bps = 80000; bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps); EXPECT_EQ(80000u, bitrate_bps); } TEST_F(CongestionWindowPushbackControllerTest, PushbackOnInititialDataWindow) { test::ScopedFieldTrials trials("WebRTC-CongestionWindow/InitWin:100000/"); cwnd_controller_.reset( new CongestionWindowPushbackController(&field_trial_config_)); cwnd_controller_->UpdateOutstandingData(1e8); // Large number uint32_t bitrate_bps = 80000; bitrate_bps = cwnd_controller_->UpdateTargetBitrate(bitrate_bps); EXPECT_GT(80000u, bitrate_bps); } } // namespace test } // namespace webrtc
33.957447
88
0.794486
minstrelsy
f11737a8bdf71e8e728cc3403ef9cde13391f555
3,515
cpp
C++
gfx/region_pixman.cpp
clarfonthey/laf
305592194e3d89dfe6d16648bf84576a2f7b05a5
[ "MIT" ]
186
2017-04-25T12:13:05.000Z
2022-03-30T08:06:47.000Z
gfx/region_pixman.cpp
clarfonthey/laf
305592194e3d89dfe6d16648bf84576a2f7b05a5
[ "MIT" ]
34
2016-12-20T16:33:31.000Z
2022-03-29T21:07:52.000Z
gfx/region_pixman.cpp
clarfonthey/laf
305592194e3d89dfe6d16648bf84576a2f7b05a5
[ "MIT" ]
47
2016-12-19T17:23:46.000Z
2022-03-30T19:45:55.000Z
// LAF Gfx Library // Copyright (C) 2001-2015 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "pixman.h" #include "base/debug.h" #include "gfx/point.h" #include "gfx/region.h" #include <cstdio> #include <cstdlib> #include <cstring> namespace gfx { inline Rect to_rect(const pixman_box32& extends) { return Rect( extends.x1, extends.y1, extends.x2 - extends.x1, extends.y2 - extends.y1); } Region::Region() { pixman_region32_init(&m_region); } Region::Region(const Region& copy) { pixman_region32_init(&m_region); pixman_region32_copy(&m_region, &copy.m_region); } Region::Region(const Rect& rect) { if (!rect.isEmpty()) pixman_region32_init_rect(&m_region, rect.x, rect.y, rect.w, rect.h); else pixman_region32_init(&m_region); } Region::~Region() { pixman_region32_fini(&m_region); } Region& Region::operator=(const Rect& rect) { if (!rect.isEmpty()) { pixman_box32 box = { rect.x, rect.y, rect.x2(), rect.y2() }; pixman_region32_reset(&m_region, &box); } else pixman_region32_clear(&m_region); return *this; } Region& Region::operator=(const Region& copy) { pixman_region32_copy(&m_region, &copy.m_region); return *this; } Region::iterator Region::begin() { iterator it; it.m_ptr = pixman_region32_rectangles(&m_region, NULL); return it; } Region::iterator Region::end() { iterator it; it.m_ptr = pixman_region32_rectangles(&m_region, NULL) + size(); return it; } Region::const_iterator Region::begin() const { const_iterator it; it.m_ptr = pixman_region32_rectangles(&m_region, NULL); return it; } Region::const_iterator Region::end() const { const_iterator it; it.m_ptr = pixman_region32_rectangles(&m_region, NULL) + size(); return it; } bool Region::isEmpty() const { return (pixman_region32_not_empty(&m_region) ? false: true); } bool Region::isRect() const { return (size() == 1); } bool Region::isComplex() const { return (size() > 1); } std::size_t Region::size() const { return pixman_region32_n_rects(&m_region); } Rect Region::bounds() const { return to_rect(*pixman_region32_extents(&m_region)); } void Region::clear() { pixman_region32_clear(&m_region); } void Region::offset(int dx, int dy) { pixman_region32_translate(&m_region, dx, dy); } void Region::offset(const PointT<int>& delta) { pixman_region32_translate(&m_region, delta.x, delta.y); } Region& Region::createIntersection(const Region& a, const Region& b) { pixman_region32_intersect(&m_region, &a.m_region, &b.m_region); return *this; } Region& Region::createUnion(const Region& a, const Region& b) { pixman_region32_union(&m_region, &a.m_region, &b.m_region); return *this; } Region& Region::createSubtraction(const Region& a, const Region& b) { pixman_region32_subtract(&m_region, &a.m_region, &b.m_region); return *this; } bool Region::contains(const PointT<int>& pt) const { return pixman_region32_contains_point(&m_region, pt.x, pt.y, NULL) ? true: false; } Region::Overlap Region::contains(const Rect& rect) const { static_assert( int(Out) == int(PIXMAN_REGION_OUT) && int(In) == int(PIXMAN_REGION_IN) && int(Part) == int(PIXMAN_REGION_PART), "Pixman constants have changed"); pixman_box32 box = { rect.x, rect.y, rect.x2(), rect.y2() }; return (Region::Overlap)pixman_region32_contains_rectangle(&m_region, &box); } } // namespace gfx
20.085714
83
0.702703
clarfonthey
f119ccfb9176845b806213b365af93a316cf0fff
6,870
cpp
C++
frameworks/entity/plugins/wheels/dmzEntityPluginWheels.cpp
shillcock/dmz
02174b45089e12cd7f0840d5259a00403cd1ccff
[ "MIT" ]
2
2015-11-05T03:03:40.000Z
2016-02-03T21:50:40.000Z
frameworks/entity/plugins/wheels/dmzEntityPluginWheels.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
frameworks/entity/plugins/wheels/dmzEntityPluginWheels.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
#include <dmzEntityConsts.h> #include "dmzEntityPluginWheels.h" #include <dmzObjectAttributeMasks.h> #include <dmzObjectConsts.h> #include <dmzObjectModule.h> #include <dmzRuntimeConfig.h> #include <dmzRuntimeConfigToTypesBase.h> #include <dmzRuntimePluginFactoryLinkSymbol.h> #include <dmzRuntimePluginInfo.h> #include <dmzRuntimeObjectType.h> #include <dmzTypesMatrix.h> #include <dmzTypesVector.h> /*! \class dmz::EntityPluginWheels \ingroup Entity \brief Articulates an object's wheels based on velocity. \details \code <dmz> <runtime> <object-type name="Type"> <wheels pairs="Int32" radius="Float64" root="String" modifier="Float64"/> </object-type> </runtime> </dmz> \endcode Wheels are defined on a ObjectType basis. - pairs: Number of wheel pairs. Defaults to 0. - radius: Wheel radius in meters. Defaults to 0.25. - root: Root of the wheel attribute name. Defaults to dmz::EntityWheelRootName. - modifier: Defaults to 1.0 */ //! \cond dmz::EntityPluginWheels::EntityPluginWheels (const PluginInfo &Info, Config &local) : Plugin (Info), TimeSlice (Info), ObjectObserverUtil (Info, local), _log (Info), _defs (Info), _defaultAttr (0) { _init (local); } dmz::EntityPluginWheels::~EntityPluginWheels () { _wheelTable.empty (); _objTable.empty (); } // Plugin Interface void dmz::EntityPluginWheels::update_plugin_state ( const PluginStateEnum State, const UInt32 Level) { if (State == PluginStateInit) { } else if (State == PluginStateStart) { } else if (State == PluginStateStop) { } else if (State == PluginStateShutdown) { } } void dmz::EntityPluginWheels::discover_plugin ( const PluginDiscoverEnum Mode, const Plugin *PluginPtr) { if (Mode == PluginDiscoverAdd) { } else if (Mode == PluginDiscoverRemove) { } } // Time Slice Interface void dmz::EntityPluginWheels::update_time_slice (const Float64 DeltaTime) { ObjectModule *module = get_object_module (); if (module) { HashTableHandleIterator it; ObjectStruct *os (0); while (_objTable.get_next (it, os)) { Matrix ori; Vector vel; module->lookup_velocity (os->Object, _defaultAttr, vel); module->lookup_orientation (os->Object, _defaultAttr, ori); Float64 speed = vel.magnitude (); if (!is_zero64 (speed)) { Vector dir (0.0, 0.0, -1.0); ori.transform_vector (dir); if (dir.get_angle (vel) > HalfPi64) { speed = -speed; } const Float64 Distance = speed * DeltaTime; WheelStruct *wheel (os->wheels); while (wheel) { Float64 value (0.0); module->lookup_scalar (os->Object, wheel->Attr, value); value -= (Distance * wheel->InvertRadius * wheel->Mod); value = normalize_angle (value); module->store_scalar (os->Object, wheel->Attr, value); wheel = wheel->next; } } } } } // Object Observer Interface void dmz::EntityPluginWheels::create_object ( const UUID &Identity, const Handle ObjectHandle, const ObjectType &Type, const ObjectLocalityEnum Locality) { WheelStruct *ws = _lookup_wheels_def (Type); if (ws) { ObjectStruct *os = new ObjectStruct (ObjectHandle, ws); if (os && !_objTable.store (ObjectHandle, os)) { delete os; os = 0; } } } void dmz::EntityPluginWheels::destroy_object ( const UUID &Identity, const Handle ObjectHandle) { ObjectStruct *os = _objTable.remove (ObjectHandle); if (os) { delete os; os = 0; } } dmz::EntityPluginWheels::WheelStruct * dmz::EntityPluginWheels::_lookup_wheels_def (const ObjectType &Type) { WheelStruct *result (0); ObjectType current (Type); while (!result && current) { result = _wheelTable.lookup (current.get_handle ()); if (!result) { result = _create_wheels_def (current); } current.become_parent (); } return result; } namespace { static const dmz::UInt32 FlipRight = 0x01; static const dmz::UInt32 FlipLeft = 0x02; }; dmz::EntityPluginWheels::WheelStruct * dmz::EntityPluginWheels::_create_wheels_def (const ObjectType &Type) { WheelStruct *result (0); Config wheels; if (Type.get_config ().lookup_all_config_merged ("wheels", wheels)) { UInt32 flip (0); const Float64 Radius = config_to_float64 ("radius", wheels, 0.25); const Float64 Mod = config_to_float64 ("modifier", wheels, 1.0); const String Root = config_to_string ("root", wheels, EntityWheelRootName); const Int32 Pairs = config_to_int32 ("pairs", wheels, 0); const String FlipString = config_to_string ("reverse", wheels, "none"); if (FlipString == "left") { flip = FlipLeft; } else if (FlipString == "right") { flip = FlipRight; } else if ((FlipString == "both") || (FlipString == "all")) { flip = FlipLeft | FlipRight; } else if (FlipString == "none") { flip = 0; } if (Radius > 0.0) { const Float64 InvertRadius = 1.0 / Radius; if (Pairs > 0) { for (Int32 ix = 1; ix <= Pairs; ix++) { Handle attr = _defs.create_named_handle ( create_wheel_attribute_name (Root, EntityWheelLeft, ix)); WheelStruct *ws = new WheelStruct ( attr, InvertRadius, Mod * (flip & FlipLeft ? -1.0 : 1.0)); if (ws) { ws->next = result; result = ws; } attr = _defs.create_named_handle ( create_wheel_attribute_name (Root, EntityWheelRight, ix)); ws = new WheelStruct ( attr, InvertRadius, Mod * (flip & FlipRight ? -1.0 : 1.0)); if (ws) { ws->next = result; result = ws; } } } else { _log.error << "Must have at least one wheel pair in type: " << Type.get_name () << endl; } } else { _log.error << "Radius of wheel of type: " << Type.get_name () << " is less than or equal to zero: " << Radius << endl; } } return result; } void dmz::EntityPluginWheels::_init (Config &local) { _defaultAttr = _defs.create_named_handle (ObjectAttributeDefaultName); activate_default_object_attribute (ObjectCreateMask | ObjectDestroyMask); } //! \endcond extern "C" { DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin * create_dmzEntityPluginWheels ( const dmz::PluginInfo &Info, dmz::Config &local, dmz::Config &global) { return new dmz::EntityPluginWheels (Info, local); } };
22.82392
85
0.604658
shillcock
f11edf0045a11ad72e3bb5d8fd84b19f5e9060ea
977
cpp
C++
Engine/src/Traceability/Logger.cpp
LinMAD/Nibble
65a8d12810335d832512812740f86bd8df14feb0
[ "MIT" ]
null
null
null
Engine/src/Traceability/Logger.cpp
LinMAD/Nibble
65a8d12810335d832512812740f86bd8df14feb0
[ "MIT" ]
null
null
null
Engine/src/Traceability/Logger.cpp
LinMAD/Nibble
65a8d12810335d832512812740f86bd8df14feb0
[ "MIT" ]
null
null
null
#include "pch.h" #include "Logger.h" #include "spdlog/sinks/stdout_color_sinks.h" namespace Nibble { std::shared_ptr<spdlog::logger> Logger::s_CoreLogger; std::shared_ptr<spdlog::logger> Logger::s_ClientLogger; Logger::Logger() { } Logger::~Logger() { } void Logger::Init() { // https://github.com/gabime/spdlog/wiki/3.-Custom-formatting // %^ - Start color range (can be used only once) // %$ - End color range (for example %^[+++]%$ %v) (can be used only once) // %T - ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S // %l - The log level of the message // %v - The actual text to log ("debug", "info", etc) spdlog::set_pattern("%^[%l]|%T| %n: %v"); s_CoreLogger = spdlog::stdout_color_mt("Nibble"); s_ClientLogger = spdlog::stdout_color_mt("Application"); // TODO Add log level config loading s_CoreLogger->set_level(spdlog::level::trace); s_ClientLogger->set_level(spdlog::level::trace); } }
28.735294
77
0.64176
LinMAD
f121c81e2a556a26ce7c1dbda509bdc8ae36dcc9
1,344
hpp
C++
src/sensors/interface.hpp
Hyp-ed/hyped-2022
9cac4632b660f569629cf0ad4048787f6017905d
[ "Apache-2.0" ]
9
2021-07-31T16:22:24.000Z
2022-01-19T18:14:31.000Z
src/sensors/interface.hpp
Hyp-ed/hyped-2022
9cac4632b660f569629cf0ad4048787f6017905d
[ "Apache-2.0" ]
91
2021-07-29T18:21:30.000Z
2022-03-31T20:44:55.000Z
src/sensors/interface.hpp
Hyp-ed/hyped-2022
9cac4632b660f569629cf0ad4048787f6017905d
[ "Apache-2.0" ]
null
null
null
#pragma once #include <string> #include <data/data.hpp> namespace hyped { using data::BatteryData; using data::ImuData; using data::NavigationVector; using data::StripeCounter; using data::TemperatureData; namespace sensors { class SensorInterface { public: /** * @brief Check if sensor is responding, i.e. connected to the system * @return true - if sensor is online */ virtual bool isOnline() = 0; }; class ImuInterface : public SensorInterface { public: /** * @brief Get IMU data * @param imu - output pointer to be filled by this sensor */ virtual void getData(ImuData *imu) = 0; }; class GpioInterface : public SensorInterface { public: /** * @brief Get GPIO data * @param stripe_counter - output pointer */ virtual void getData(StripeCounter *stripe_counter) = 0; }; class BMSInterface : public SensorInterface { public: /** * @brief Get Battery data * @param battery - output pointer to be filled by this sensor */ virtual void getData(BatteryData *battery) = 0; }; class TemperatureInterface { public: /** * @brief not a thread, checks temperature */ virtual void run() = 0; /** * @brief returns int representation of temperature * @return int temperature degrees C */ virtual int getData() = 0; }; } // namespace sensors } // namespace hyped
19.764706
71
0.680804
Hyp-ed
f1221f59c63a06cf4df50f1e2769796ba5ba222c
332
cpp
C++
Plugins/InstancedPlugin/Source/InstancedPlugin/Private/Components/Operations/IPOperationAlignBase.cpp
redcatbox/Instanced
347790e8ade0c6e6fb9b742afc78c764414ed36a
[ "MIT" ]
1
2022-02-03T17:10:29.000Z
2022-02-03T17:10:29.000Z
Plugins/InstancedPlugin/Source/InstancedPlugin/Private/Components/Operations/IPOperationAlignBase.cpp
redcatbox/Instanced
347790e8ade0c6e6fb9b742afc78c764414ed36a
[ "MIT" ]
null
null
null
Plugins/InstancedPlugin/Source/InstancedPlugin/Private/Components/Operations/IPOperationAlignBase.cpp
redcatbox/Instanced
347790e8ade0c6e6fb9b742afc78c764414ed36a
[ "MIT" ]
null
null
null
// redbox, 2021 #include "Components/Operations/IPOperationAlignBase.h" UIPOperationAlignBase::UIPOperationAlignBase() { #if WITH_EDITORONLY_DATA bInstancesNumEditCondition = false; bAlignToSurface = false; OffsetInTraceDirection = 0.f; bReverse = false; bTraceComplex = false; bIgnoreSelf = true; DrawTime = 5.f; #endif }
19.529412
55
0.777108
redcatbox
f1226e2ec401b0be3b8b0af702bb3de980341b25
725
cpp
C++
dmoj/dmopc/2014/contest-2/deforestation.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
dmoj/dmopc/2014/contest-2/deforestation.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
dmoj/dmopc/2014/contest-2/deforestation.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <iostream> #include <vector> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } int main() { use_io_optimizations(); unsigned int trees; cin >> trees; vector<unsigned int> prefix_sums(trees + 1); for (unsigned int i {1}; i <= trees; ++i) { unsigned int mass; cin >> mass; prefix_sums[i] = prefix_sums[i - 1] + mass; } unsigned int queries; cin >> queries; for (unsigned int i {0}; i < queries; ++i) { unsigned int from; unsigned int to; cin >> from >> to; cout << prefix_sums[to + 1] - prefix_sums[from] << '\n'; } return 0; }
16.477273
64
0.56
Rkhoiwal
f124100905a0dd50b377e341d084a768cc278f82
1,151
cpp
C++
cref/10_enums.cpp
admantium-sg/learning-cpp
cc827a8d7eabceac32069bb7f5a64b3c0fe488f4
[ "BSD-3-Clause" ]
null
null
null
cref/10_enums.cpp
admantium-sg/learning-cpp
cc827a8d7eabceac32069bb7f5a64b3c0fe488f4
[ "BSD-3-Clause" ]
null
null
null
cref/10_enums.cpp
admantium-sg/learning-cpp
cc827a8d7eabceac32069bb7f5a64b3c0fe488f4
[ "BSD-3-Clause" ]
null
null
null
/* * --------------------------------------- * Copyright (c) Sebastian Günther 2021 | * | * devcon@admantium.com | * | * SPDX-License-Identifier: BSD-3-Clause | * --------------------------------------- */ #include <stdio.h> #include <stdexcept> #include <iostream> #include <cstddef> using namespace std; enum class Color { Red, Blue, Green }; class ColorFactory{ public: static int getInstances() { return instances;} static Color makeColor(Color c) { ColorFactory::instances++; return c;} static int instances; }; int ColorFactory::instances = 0; int main(int argc, char* argv[]) { cout << "Number of args: " << argc << endl; for (int i=0; i < argc; i++) { cout << "Arg " << i << ": " << argv[i] << endl; } ColorFactory paint; Color r = paint.makeColor(Color::Red); Color g = paint.makeColor(Color::Green); cout << "Number of paints " << ColorFactory::getInstances() << endl; if (r == Color::Red) {cout << "Beautifull Red" << endl;} // if (r == 0) {cout << "Beautifull Red";} //throws error }
24.489362
75
0.519548
admantium-sg
f12445216f388fed4e59651814fdd8bac1bae6e2
3,016
cpp
C++
src/fuel.cpp
BonJovi1/Bullet-the-Blue-Sky
9ebf41fc85ccf9f8e2880acdafc6dfffd8a0268f
[ "WTFPL" ]
null
null
null
src/fuel.cpp
BonJovi1/Bullet-the-Blue-Sky
9ebf41fc85ccf9f8e2880acdafc6dfffd8a0268f
[ "WTFPL" ]
null
null
null
src/fuel.cpp
BonJovi1/Bullet-the-Blue-Sky
9ebf41fc85ccf9f8e2880acdafc6dfffd8a0268f
[ "WTFPL" ]
null
null
null
#include "ball.h" #include "main.h" Fuel::Fuel(float x, float y, float z, color_t color) { this->position = glm::vec3(x, y, z); this->rotation = 0; this->kill = 0; this->fuel_box.height = 15; this->fuel_box.width = 15; this->fuel_box.depth = 15; this->fuel_box.x = x; this->fuel_box.y = y; this->fuel_box.z = z; // speed = 1; // Our vertices. Three consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. // A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices static const GLfloat vertex_buffer_data_sq[] = { -15.0f,-15.0f,-15.0f, // triangle 1 : begin -15.0f,-15.0f, 15.0f, -15.0f, 15.0f, 15.0f, // triangle 1 : end 15.0f, 15.0f,-15.0f, // triangle 2 : begin -15.0f,-15.0f,-15.0f, -15.0f, 15.0f,-15.0f, // triangle 2 : end 15.0f,-15.0f, 15.0f, -15.0f,-15.0f,-15.0f, 15.0f,-15.0f,-15.0f, 15.0f, 15.0f,-15.0f, 15.0f,-15.0f,-15.0f, -15.0f,-15.0f,-15.0f, -15.0f,-15.0f,-15.0f, -15.0f, 15.0f, 15.0f, -15.0f, 15.0f,-15.0f, 15.0f,-15.0f, 15.0f, -15.0f,-15.0f, 15.0f, -15.0f,-15.0f,-15.0f, -15.0f, 15.0f, 15.0f, -15.0f,-15.0f, 15.0f, 15.0f,-15.0f, 15.0f, 15.0f, 15.0f, 15.0f, 15.0f,-15.0f,-15.0f, 15.0f, 15.0f,-15.0f, 15.0f,-15.0f,-15.0f, 15.0f, 15.0f, 15.0f, 15.0f,-15.0f, 15.0f, 15.0f, 15.0f, 15.0f, 15.0f, 15.0f,-15.0f, -15.0f, 15.0f,-15.0f, 15.0f, 15.0f, 15.0f, -15.0f, 15.0f,-15.0f, -15.0f, 15.0f, 15.0f, 15.0f, 15.0f, 15.0f, -15.0f, 15.0f, 15.0f, 15.0f,-15.0f, 15.0f }; // Our vertices. Three consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. // A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices this->object = create3DObject(GL_TRIANGLES, 12*3, vertex_buffer_data_sq, color, GL_FILL); } void Fuel::draw(glm::mat4 VP) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(1, 0, 0)); // No need as coords centered at 0, 0, 0 of cube arouund which we waant to rotate // rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0)); Matrices.model *= (translate * rotate); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->object); } void Fuel::set_position(float x, float y) { this->position = glm::vec3(x, y, 0); } void Fuel::tick() { // this->rotation += speed; // this->position.x -= speed; this->position.y -= 0.6; this->fuel_box.x = this->position.x; this->fuel_box.y = this->position.y; this->fuel_box.z = this->position.z; }
34.272727
107
0.556698
BonJovi1
f1292ef8610d84e7d6c789af02652b45f680a893
573
cpp
C++
1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp
arpangoswami/LeetcodeSolutions
17a2450cacf0020c2626023012a5a354c8fee5da
[ "MIT" ]
null
null
null
1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp
arpangoswami/LeetcodeSolutions
17a2450cacf0020c2626023012a5a354c8fee5da
[ "MIT" ]
null
null
null
1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/1438-longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit.cpp
arpangoswami/LeetcodeSolutions
17a2450cacf0020c2626023012a5a354c8fee5da
[ "MIT" ]
null
null
null
class Solution { public: int longestSubarray(vector<int>& nums, int limit) { int left = 0; int n = nums.size(); multiset<int> windowElements; int ans = 1; for(int i=0;i<n;i++){ windowElements.insert(nums[i]); while(left <= i && (*windowElements.rbegin() - *windowElements.begin()) > limit){ auto it = windowElements.find(nums[left]); windowElements.erase(it); left++; } ans = max(ans,i-left+1); } return ans; } };
30.157895
93
0.490401
arpangoswami
f12ad4de9a7ae79ebaa583594bdcce5ade49214d
10,437
cc
C++
hookflash-core/webRTC/webRTC_ios/src/modules/video_coding/codecs/test/videoprocessor.cc
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
1
2020-02-19T09:55:55.000Z
2020-02-19T09:55:55.000Z
hookflash-core/webRTC/webRTC_ios/src/modules/video_coding/codecs/test/videoprocessor.cc
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
null
null
null
hookflash-core/webRTC/webRTC_ios/src/modules/video_coding/codecs/test/videoprocessor.cc
ilin-in/OP
bf3e87d90008e2a4106ee70360fbe15b0d694e77
[ "Unlicense" ]
null
null
null
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/video_coding/codecs/test/videoprocessor.h" #include <cassert> #include <cstring> #include <limits> #include "system_wrappers/interface/cpu_info.h" namespace webrtc { namespace test { VideoProcessorImpl::VideoProcessorImpl(webrtc::VideoEncoder* encoder, webrtc::VideoDecoder* decoder, FrameReader* frame_reader, FrameWriter* frame_writer, PacketManipulator* packet_manipulator, const TestConfig& config, Stats* stats) : encoder_(encoder), decoder_(decoder), frame_reader_(frame_reader), frame_writer_(frame_writer), packet_manipulator_(packet_manipulator), config_(config), stats_(stats), encode_callback_(NULL), decode_callback_(NULL), source_buffer_(NULL), first_key_frame_has_been_excluded_(false), last_frame_missing_(false), initialized_(false) { assert(encoder); assert(decoder); assert(frame_reader); assert(frame_writer); assert(packet_manipulator); assert(stats); } bool VideoProcessorImpl::Init() { // Calculate a factor used for bit rate calculations: bit_rate_factor_ = config_.codec_settings->maxFramerate * 0.001 * 8; // bits int frame_length_in_bytes = frame_reader_->FrameLength(); // Initialize data structures used by the encoder/decoder APIs source_buffer_ = new WebRtc_UWord8[frame_length_in_bytes]; last_successful_frame_buffer_ = new WebRtc_UWord8[frame_length_in_bytes]; // Set fixed properties common for all frames: source_frame_._width = config_.codec_settings->width; source_frame_._height = config_.codec_settings->height; source_frame_._length = frame_length_in_bytes; source_frame_._size = frame_length_in_bytes; // Setup required callbacks for the encoder/decoder: encode_callback_ = new VideoProcessorEncodeCompleteCallback(this); decode_callback_ = new VideoProcessorDecodeCompleteCallback(this); WebRtc_Word32 register_result = encoder_->RegisterEncodeCompleteCallback(encode_callback_); if (register_result != WEBRTC_VIDEO_CODEC_OK) { fprintf(stderr, "Failed to register encode complete callback, return code: " "%d\n", register_result); return false; } register_result = decoder_->RegisterDecodeCompleteCallback(decode_callback_); if (register_result != WEBRTC_VIDEO_CODEC_OK) { fprintf(stderr, "Failed to register decode complete callback, return code: " "%d\n", register_result); return false; } // Init the encoder and decoder WebRtc_UWord32 nbr_of_cores = 1; if (!config_.use_single_core) { nbr_of_cores = CpuInfo::DetectNumberOfCores(); } WebRtc_Word32 init_result = encoder_->InitEncode(config_.codec_settings, nbr_of_cores, config_.networking_config.max_payload_size_in_bytes); if (init_result != WEBRTC_VIDEO_CODEC_OK) { fprintf(stderr, "Failed to initialize VideoEncoder, return code: %d\n", init_result); return false; } init_result = decoder_->InitDecode(config_.codec_settings, nbr_of_cores); if (init_result != WEBRTC_VIDEO_CODEC_OK) { fprintf(stderr, "Failed to initialize VideoDecoder, return code: %d\n", init_result); return false; } if (config_.verbose) { printf("Video Processor:\n"); printf(" #CPU cores used : %d\n", nbr_of_cores); printf(" Total # of frames: %d\n", frame_reader_->NumberOfFrames()); printf(" Codec settings:\n"); printf(" Start bitrate : %d kbps\n", config_.codec_settings->startBitrate); printf(" Width : %d\n", config_.codec_settings->width); printf(" Height : %d\n", config_.codec_settings->height); } initialized_ = true; return true; } VideoProcessorImpl::~VideoProcessorImpl() { delete[] source_buffer_; delete[] last_successful_frame_buffer_; encoder_->RegisterEncodeCompleteCallback(NULL); delete encode_callback_; decoder_->RegisterDecodeCompleteCallback(NULL); delete decode_callback_; } bool VideoProcessorImpl::ProcessFrame(int frame_number) { assert(frame_number >=0); if (!initialized_) { fprintf(stderr, "Attempting to use uninitialized VideoProcessor!\n"); return false; } if (frame_reader_->ReadFrame(source_buffer_)) { // point the source frame buffer to the newly read frame data: source_frame_._buffer = source_buffer_; // Ensure we have a new statistics data object we can fill: FrameStatistic& stat = stats_->NewFrame(frame_number); encode_start_ = TickTime::Now(); // Use the frame number as "timestamp" to identify frames source_frame_._timeStamp = frame_number; // Decide if we're going to force a keyframe: VideoFrameType frame_type = kDeltaFrame; if (config_.keyframe_interval > 0 && frame_number % config_.keyframe_interval == 0) { frame_type = kKeyFrame; } WebRtc_Word32 encode_result = encoder_->Encode(source_frame_, NULL, frame_type); if (encode_result != WEBRTC_VIDEO_CODEC_OK) { fprintf(stderr, "Failed to encode frame %d, return code: %d\n", frame_number, encode_result); } stat.encode_return_code = encode_result; return true; } else { return false; // we've reached the last frame } } void VideoProcessorImpl::FrameEncoded(EncodedImage* encoded_image) { TickTime encode_stop = TickTime::Now(); int frame_number = encoded_image->_timeStamp; FrameStatistic& stat = stats_->stats_[frame_number]; stat.encode_time_in_us = GetElapsedTimeMicroseconds(encode_start_, encode_stop); stat.encoding_successful = true; stat.encoded_frame_length_in_bytes = encoded_image->_length; stat.frame_number = encoded_image->_timeStamp; stat.frame_type = encoded_image->_frameType; stat.bit_rate_in_kbps = encoded_image->_length * bit_rate_factor_; stat.total_packets = encoded_image->_length / config_.networking_config.packet_size_in_bytes + 1; // Perform packet loss if criteria is fullfilled: bool exclude_this_frame = false; // Only keyframes can be excluded if (encoded_image->_frameType == kKeyFrame) { switch (config_.exclude_frame_types) { case kExcludeOnlyFirstKeyFrame: if (!first_key_frame_has_been_excluded_) { first_key_frame_has_been_excluded_ = true; exclude_this_frame = true; } break; case kExcludeAllKeyFrames: exclude_this_frame = true; break; default: assert(false); } } if (!exclude_this_frame) { stat.packets_dropped = packet_manipulator_->ManipulatePackets(encoded_image); } // Keep track of if frames are lost due to packet loss so we can tell // this to the encoder (this is handled by the RTP logic in the full stack) decode_start_ = TickTime::Now(); // TODO(kjellander): Pass fragmentation header to the decoder when // CL 172001 has been submitted and PacketManipulator supports this. WebRtc_Word32 decode_result = decoder_->Decode(*encoded_image, last_frame_missing_, NULL); stat.decode_return_code = decode_result; if (decode_result != WEBRTC_VIDEO_CODEC_OK) { // Write the last successful frame the output file to avoid getting it out // of sync with the source file for SSIM and PSNR comparisons: frame_writer_->WriteFrame(last_successful_frame_buffer_); } // save status for losses so we can inform the decoder for the next frame: last_frame_missing_ = encoded_image->_length == 0; } void VideoProcessorImpl::FrameDecoded(const RawImage& image) { TickTime decode_stop = TickTime::Now(); int frame_number = image._timeStamp; // Report stats FrameStatistic& stat = stats_->stats_[frame_number]; stat.decode_time_in_us = GetElapsedTimeMicroseconds(decode_start_, decode_stop); stat.decoding_successful = true; // Update our copy of the last successful frame: memcpy(last_successful_frame_buffer_, image._buffer, image._length); bool write_success = frame_writer_->WriteFrame(image._buffer); if (!write_success) { fprintf(stderr, "Failed to write frame %d to disk!", frame_number); } } int VideoProcessorImpl::GetElapsedTimeMicroseconds( const webrtc::TickTime& start, const webrtc::TickTime& stop) { WebRtc_UWord64 encode_time = (stop - start).Microseconds(); assert(encode_time < static_cast<unsigned int>(std::numeric_limits<int>::max())); return static_cast<int>(encode_time); } const char* ExcludeFrameTypesToStr(ExcludeFrameTypes e) { switch (e) { case kExcludeOnlyFirstKeyFrame: return "ExcludeOnlyFirstKeyFrame"; case kExcludeAllKeyFrames: return "ExcludeAllKeyFrames"; default: assert(false); return "Unknown"; } } const char* VideoCodecTypeToStr(webrtc::VideoCodecType e) { switch (e) { case kVideoCodecVP8: return "VP8"; case kVideoCodecI420: return "I420"; case kVideoCodecRED: return "RED"; case kVideoCodecULPFEC: return "ULPFEC"; case kVideoCodecUnknown: return "Unknown"; default: assert(false); return "Unknown"; } } // Callbacks WebRtc_Word32 VideoProcessorImpl::VideoProcessorEncodeCompleteCallback::Encoded( EncodedImage& encoded_image, const webrtc::CodecSpecificInfo* codec_specific_info, const webrtc::RTPFragmentationHeader* fragmentation) { video_processor_->FrameEncoded(&encoded_image); // forward to parent class return 0; } WebRtc_Word32 VideoProcessorImpl::VideoProcessorDecodeCompleteCallback::Decoded( RawImage& image) { video_processor_->FrameDecoded(image); // forward to parent class return 0; } } // namespace test } // namespace webrtc
36.239583
80
0.696465
ilin-in
f12b3726fca9bd6e160b866808b266980538cc88
3,681
cpp
C++
Source/Framework/Core/GameComponentContainer.cpp
gabr1e11/cornerstone
bc696e22af350b867219ef3ac99840b3e8a3f20a
[ "MIT" ]
null
null
null
Source/Framework/Core/GameComponentContainer.cpp
gabr1e11/cornerstone
bc696e22af350b867219ef3ac99840b3e8a3f20a
[ "MIT" ]
null
null
null
Source/Framework/Core/GameComponentContainer.cpp
gabr1e11/cornerstone
bc696e22af350b867219ef3ac99840b3e8a3f20a
[ "MIT" ]
null
null
null
// // GameComponentContainer.cpp // // @author Roberto Cano // #include "GameComponentContainer.hpp" using namespace Framework; using namespace Framework::Core; using namespace Framework::Types; void GameComponentContainer::addComponent(Types::GameComponent::PtrType component) { const ComponentId& componentId = component->getComponentId(); const InstanceId& instanceId = component->getInstanceId(); _notStartedComponents.push(component); // Dependency injection Types::GameObject::PtrType gameObjectPtr = shared_from_this(); component->_setOwner(gameObjectPtr); // Map by Instance Id auto insertionIter = _componentsMapByInstanceId.insert(std::pair<InstanceId, Types::GameComponent::PtrType>(instanceId, std::move(component))); assert(insertionIter.second); // Map by Component Id auto componentsMapIter = _componentsMapByComponentId.find(componentId); if (componentsMapIter != _componentsMapByComponentId.end()) { componentsMapIter->second.emplace(instanceId); } else { _componentsMapByComponentId.emplace(componentId, std::set<InstanceId>{instanceId}); } } bool GameComponentContainer::removeComponent(const Core::GameComponent& component) { const InstanceId& instanceId = component.getInstanceId(); return removeComponent(instanceId); } bool GameComponentContainer::removeComponent(const InstanceId& instanceId) { bool retValue = true; auto findIter = _componentsMapByInstanceId.find(instanceId); if (findIter == _componentsMapByInstanceId.end()) { return false; } const GameComponent& component = *(findIter->second); const ComponentId& componentId = component.getComponentId(); // Map by Component Id auto componentsMapIter = _componentsMapByComponentId.find(componentId); if (componentsMapIter != _componentsMapByComponentId.end()) { componentsMapIter->second.erase(instanceId); } else { retValue = false; } // Map by Instance Id _componentsMapByInstanceId.erase(findIter); return retValue; } bool GameComponentContainer::hasComponent(const Core::GameComponent& component) const { const InstanceId& instanceId = component.getInstanceId(); return hasComponent(instanceId); } bool GameComponentContainer::hasComponents(const ComponentId& componentId) const { auto componentsMapIter = _componentsMapByComponentId.find(componentId); return componentsMapIter != _componentsMapByComponentId.end(); } bool GameComponentContainer::hasComponent(const InstanceId& instanceId) const { auto instancesMapIter = _componentsMapByInstanceId.find(instanceId); return instancesMapIter != _componentsMapByInstanceId.end(); } const std::set<InstanceId>& GameComponentContainer::getComponentsIds(const ComponentId& componentId) const { auto componentsMapIter = _componentsMapByComponentId.find(componentId); assert(componentsMapIter != _componentsMapByComponentId.end()); return componentsMapIter->second; } void GameComponentContainer::internalInit() { for (auto& componentPair : _componentsMapByInstanceId) { componentPair.second->init(); } } void GameComponentContainer::internalStart() { for (auto& componentPair : _componentsMapByInstanceId) { componentPair.second->start(); } } void GameComponentContainer::internalUpdate(float dt) { for (auto& componentPair : _componentsMapByInstanceId) { componentPair.second->update(dt); } } void GameComponentContainer::updateNotStarted() { if (_notStartedComponents.empty()) { return; } while (!_notStartedComponents.empty()) { Types::GameComponent::WeakPtrType gameComponentWPtr = _notStartedComponents.front(); _notStartedComponents.pop(); if (auto gameComponent = gameComponentWPtr.lock()) { gameComponent->internalStart(); } } }
25.741259
144
0.784569
gabr1e11
f12d0977ce64856eef91ed814818316579c52041
1,013
cpp
C++
code/baseline-system/src/sensors/sensor_random.cpp
jo-jstrm/rime-data-streaming-iot
8caf549868c6f5ebacb201cb21be9ae5b641ee0b
[ "MIT" ]
null
null
null
code/baseline-system/src/sensors/sensor_random.cpp
jo-jstrm/rime-data-streaming-iot
8caf549868c6f5ebacb201cb21be9ae5b641ee0b
[ "MIT" ]
1
2021-08-16T09:19:17.000Z
2021-08-16T09:19:17.000Z
code/baseline-system/src/sensors/sensor_random.cpp
jo-jstrm/rime-data-streaming-iot
8caf549868c6f5ebacb201cb21be9ae5b641ee0b
[ "MIT" ]
null
null
null
#include "sensor_random.hpp" #include <random> #include <chrono> #include <utility> #include "results.hpp" using namespace caf; using namespace std; using namespace std::chrono; using read = atom_constant<atom("read")>; using state = atom_constant<atom("state")>; behavior random_sensor(stateful_actor<sensor_state>* self, string name) { self->state.name = name; return { // RETURN: (string sensor_name, double sensor reading) [=](read) { double sensor_reading; system_clock::time_point begin = system_clock::now(); system_clock::duration dur; mt19937 gen; uniform_real_distribution<double> dist(0, 100); //seed the generator dur = system_clock::now() - begin; gen.seed(dur.count()); sensor_reading = dist(gen); return value(sensor_reading); }, /*-------------------------------Testing------------------------------*/ [=](state) { return self->state.name; } }; }
24.707317
76
0.586377
jo-jstrm
f132ed9ead1956efad145f4b362f7737812a27b8
6,264
cpp
C++
qttools/src/assistant/3rdparty/clucene/src/CLucene/index/FieldInfos.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qttools/src/assistant/3rdparty/clucene/src/CLucene/index/FieldInfos.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qttools/src/assistant/3rdparty/clucene/src/CLucene/index/FieldInfos.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team * * Distributable under the terms of either the Apache License (Version 2.0) or * the GNU Lesser General Public License, as specified in the COPYING file. * * Changes are Copyright (C) 2015 The Qt Company Ltd. */ #include "CLucene/StdHeader.h" #include "FieldInfos.h" #include "CLucene/store/Directory.h" #include "CLucene/document/Document.h" #include "CLucene/document/Field.h" #include "CLucene/util/VoidMap.h" #include "CLucene/util/Misc.h" #include "CLucene/util/StringIntern.h" CL_NS_USE(store) CL_NS_USE(document) CL_NS_USE(util) CL_NS_DEF(index) FieldInfo::FieldInfo(const TCHAR* _fieldName, bool _isIndexed, int32_t _fieldNumber, bool _storeTermVector, bool _storeOffsetWithTermVector, bool _storePositionWithTermVector, bool _omitNorms) : name(CLStringIntern::intern(_fieldName CL_FILELINE)) , isIndexed(_isIndexed) , number(_fieldNumber) , storeTermVector(_storeTermVector) , storeOffsetWithTermVector(_storeOffsetWithTermVector) , storePositionWithTermVector(_storeTermVector) , omitNorms(_omitNorms) { } FieldInfo::~FieldInfo() { CL_NS(util)::CLStringIntern::unintern(name); } // #pragma mark -- FieldInfos FieldInfos::FieldInfos() : byName(false, false) , byNumber(true) { } FieldInfos::~FieldInfos() { byName.clear(); byNumber.clear(); } FieldInfos::FieldInfos(Directory* d, const QString& name) : byName(false, false) , byNumber(true) { IndexInput* input = d->openInput(name); try { read(input); } _CLFINALLY ( input->close(); _CLDELETE(input); ); } void FieldInfos::add(const Document* doc) { DocumentFieldEnumeration* fields = doc->fields(); Field* field; while (fields->hasMoreElements()) { field = fields->nextElement(); add(field->name(), field->isIndexed(), field->isTermVectorStored()); } _CLDELETE(fields); } void FieldInfos::add(const TCHAR* name, bool isIndexed, bool storeTermVector, bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool omitNorms) { FieldInfo* fi = fieldInfo(name); if (fi == NULL) { addInternal(name, isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms); } else { if (fi->isIndexed != isIndexed) { // once indexed, always index fi->isIndexed = true; } if (fi->storeTermVector != storeTermVector) { // once vector, always vector fi->storeTermVector = true; } if (fi->storePositionWithTermVector != storePositionWithTermVector) { // once vector, always vector fi->storePositionWithTermVector = true; } if (fi->storeOffsetWithTermVector != storeOffsetWithTermVector) { // once vector, always vector fi->storeOffsetWithTermVector = true; } if (fi->omitNorms != omitNorms) { // once norms are stored, always store fi->omitNorms = false; } } } void FieldInfos::add(const TCHAR** names, bool isIndexed, bool storeTermVectors, bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool omitNorms) { int32_t i=0; while (names[i] != NULL) { add(names[i], isIndexed, storeTermVectors, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms); ++i; } } int32_t FieldInfos::fieldNumber(const TCHAR* fieldName) const { FieldInfo* fi = fieldInfo(fieldName); return (fi != NULL) ? fi->number : -1; } FieldInfo* FieldInfos::fieldInfo(const TCHAR* fieldName) const { return byName.get(fieldName); } const TCHAR* FieldInfos::fieldName(const int32_t fieldNumber) const { FieldInfo* fi = fieldInfo(fieldNumber); return (fi == NULL) ? LUCENE_BLANK_STRING : fi->name; } FieldInfo* FieldInfos::fieldInfo(const int32_t fieldNumber) const { if (fieldNumber < 0 || (size_t)fieldNumber >= byNumber.size()) return NULL; return byNumber[fieldNumber]; } int32_t FieldInfos::size() const { return byNumber.size(); } void FieldInfos::write(Directory* d, const QString& name) const { IndexOutput* output = d->createOutput(name); try { write(output); } _CLFINALLY ( output->close(); _CLDELETE(output); ); } void FieldInfos::write(IndexOutput* output) const { output->writeVInt(size()); FieldInfo* fi; uint8_t bits; for (int32_t i = 0; i < size(); ++i) { fi = fieldInfo(i); bits = 0x0; if (fi->isIndexed) bits |= IS_INDEXED; if (fi->storeTermVector) bits |= STORE_TERMVECTOR; if (fi->storePositionWithTermVector) bits |= STORE_POSITIONS_WITH_TERMVECTOR; if (fi->storeOffsetWithTermVector) bits |= STORE_OFFSET_WITH_TERMVECTOR; if (fi->omitNorms) bits |= OMIT_NORMS; output->writeString(fi->name, _tcslen(fi->name)); output->writeByte(bits); } } void FieldInfos::read(IndexInput* input) { int32_t size = input->readVInt(); for (int32_t i = 0; i < size; ++i) { // we could read name into a string buffer, but we can't be sure what // the maximum field length will be. TCHAR* name = input->readString(); uint8_t bits = input->readByte(); bool isIndexed = (bits & IS_INDEXED) != 0; bool storeTermVector = (bits & STORE_TERMVECTOR) != 0; bool storePositionsWithTermVector = (bits & STORE_POSITIONS_WITH_TERMVECTOR) != 0; bool storeOffsetWithTermVector = (bits & STORE_OFFSET_WITH_TERMVECTOR) != 0; bool omitNorms = (bits & OMIT_NORMS) != 0; addInternal(name, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms); _CLDELETE_CARRAY(name); } } void FieldInfos::addInternal(const TCHAR* name, bool isIndexed, bool storeTermVector, bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool omitNorms) { FieldInfo* fi = _CLNEW FieldInfo(name, isIndexed, byNumber.size(), storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms); byNumber.push_back(fi); byName.put(fi->name, fi); } bool FieldInfos::hasVectors() const { for (int32_t i = 0; i < size(); i++) { if (fieldInfo(i)->storeTermVector) return true; } return false; } CL_NS_END
26.43038
85
0.685983
wgnet
f133409731a3a8155fbf3128a4b1e316847324c6
240
cpp
C++
src/trap_instances/SegmentLdr.cpp
DavidLudwig/executor
eddb527850af639b3ffe314e05d92a083ba47af6
[ "MIT" ]
2
2019-09-16T15:51:39.000Z
2020-03-04T08:47:42.000Z
src/trap_instances/SegmentLdr.cpp
probonopd/executor
0fb82c09109ec27ae8707f07690f7325ee0f98e0
[ "MIT" ]
null
null
null
src/trap_instances/SegmentLdr.cpp
probonopd/executor
0fb82c09109ec27ae8707f07690f7325ee0f98e0
[ "MIT" ]
null
null
null
#define INSTANTIATE_TRAPS_SegmentLdr #include <SegmentLdr.h> // Function for preventing the linker from considering the static constructors in this module unused namespace Executor { namespace ReferenceTraps { void SegmentLdr() {} } }
24
100
0.791667
DavidLudwig
f1368c3c646265606a2f4ca855cf81b325293b08
269
cpp
C++
cpp_algs/bst/test_new.cpp
vitalir2/AlgorithmsCpp
f9a1b7a0b51c6f122ff600008d2c0ef72a26502f
[ "MIT" ]
null
null
null
cpp_algs/bst/test_new.cpp
vitalir2/AlgorithmsCpp
f9a1b7a0b51c6f122ff600008d2c0ef72a26502f
[ "MIT" ]
null
null
null
cpp_algs/bst/test_new.cpp
vitalir2/AlgorithmsCpp
f9a1b7a0b51c6f122ff600008d2c0ef72a26502f
[ "MIT" ]
null
null
null
#include <iostream> void f(double* n) { n = new double(4); } void g(double* n) { delete n; } int main() { double* x = new double(5); f(x); std::cout << *x << std::endl; g(x); std::cout << *x << std::endl; int* m = nullptr; delete m; return 0; }
12.227273
31
0.520446
vitalir2
f136c9e05ffcde42149c9d9ba3a27c2ddca3539c
774
cpp
C++
2021_March/30.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
17
2018-08-23T08:53:56.000Z
2021-04-17T00:06:13.000Z
2021_March/30.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
2021_March/30.cpp
zzz0906/LeetCode
cd0b4a4fd03d0dff585c9ef349984eba1922ece0
[ "MIT" ]
null
null
null
class Solution { public: int maxEnvelopes(vector<vector<int>>& envelopes) { if (envelopes.empty() || envelopes[0].size() == 0) return 0; int res = 1, n = envelopes.size(); vector<int> dp(n,1); sort(envelopes.begin(), envelopes.end()); for (int i = 1; i < n; i++){ for (int j = 0; j < i; ++j) if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) { dp[i] = max(dp[i], dp[j] + 1); } res = max(res,dp[i]); } return res; // if (envelopes[i][0] > envelopes[i-1][0] && envelopes[i][1] > envelopes[i-1][1]) // dp[i] = dp[i-1] + 1; // else // dp[i] = dp[i-1]; } };
36.857143
94
0.425065
zzz0906
f13712f5a4d5b34c049fdc782a7bbe51a4e909a6
9,958
cpp
C++
src/websocket/frame_websocket.cpp
hl4/da4qi4
9dfb8902427d40b392977b4fd706048ce3ee8828
[ "Apache-2.0" ]
166
2019-04-15T03:19:31.000Z
2022-03-26T05:41:12.000Z
src/websocket/frame_websocket.cpp
YangKefan/da4qi4
9dfb8902427d40b392977b4fd706048ce3ee8828
[ "Apache-2.0" ]
9
2019-07-18T06:09:59.000Z
2021-01-27T04:19:04.000Z
src/websocket/frame_websocket.cpp
YangKefan/da4qi4
9dfb8902427d40b392977b4fd706048ce3ee8828
[ "Apache-2.0" ]
43
2019-07-03T05:41:57.000Z
2022-02-24T14:16:09.000Z
#include "daqi/websocket/frame_websocket.hpp" #include <cstring> namespace da4qi4 { namespace Websocket { std::string FrameBuilder::Build(char const* data, size_t len) { std::string buffer; size_t externded_payload_len = (len <= 125 ? 0 : (len <= 65535 ? 2 : 8)); size_t mask_key_len = ((len && _frame_header.MASK) ? 4 : 0); auto frame_size = static_cast<size_t>(2 + externded_payload_len + mask_key_len + len); buffer.resize(frame_size); uint8_t* ptr = reinterpret_cast<uint8_t*>(buffer.data()); uint64_t offset = 0; ptr[0] |= _frame_header.FIN; ptr[0] |= _frame_header.OPCODE; if (len) { ptr[1] |= _frame_header.MASK; } ++offset; if (len <= 125) { ptr[offset++] |= static_cast<unsigned char>(len); } else if (len <= 65535) { ptr[offset++] |= 126; ptr[offset++] = static_cast<unsigned char>((len >> 8) & 0xFF); ptr[offset++] = len & 0xFF; } else { ptr[offset++] |= 127; ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 56) & 0xff)); ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 48) & 0xff)); ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 40) & 0xff)); ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 32) & 0xff)); ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 24) & 0xff)); ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 16) & 0xff)); ptr[offset++] = static_cast<unsigned char>(((static_cast<uint64_t>(len) >> 8) & 0xff)); ptr[offset++] = static_cast<unsigned char>((static_cast<uint64_t>(len) & 0xff)); } if (!len || !data) { return buffer; } if (_frame_header.MASK) { int mask_key = static_cast<int>(_frame_header.MASKING_KEY); ptr[offset++] = static_cast<unsigned char>(((mask_key >> 24) & 0xff)); ptr[offset++] = static_cast<unsigned char>(((mask_key >> 16) & 0xff)); ptr[offset++] = static_cast<unsigned char>(((mask_key >> 8) & 0xff)); ptr[offset++] = static_cast<unsigned char>(((mask_key) & 0xff)); unsigned char* mask = ptr + offset - 4; for (uint32_t i = 0; i < len; ++i) { ptr[offset++] = static_cast<uint8_t>(data[i] ^ mask[i % 4]); } } else { std::copy(data, data + len, reinterpret_cast<char*>(ptr + offset)); offset += len; } assert(offset == frame_size); return buffer; } void FrameParser::reset() { _parser_step = e_fixed_header; _masking_key_pos = 0; _payload_len_offset = 0; _payload.clear(); memset(&_frame_header, 0, sizeof(_frame_header)); } void FrameParser::move_reset(FrameParser&& parser) { if (&parser == this) { return; } _parser_step = parser._parser_step; _payload_len_offset = parser._payload_len_offset; _masking_key_pos = parser._masking_key_pos; _payload = std::move(parser._payload); _frame_header = std::move(parser._frame_header); _msb_cb = std::move(parser._msb_cb); } uint32_t FrameParser::parse_fixed_header(const char* data) { const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data); memset(&_frame_header, 0, sizeof(_frame_header)); _payload_len_offset = 0; _frame_header.FIN = ptr[0] & 0xf0; _frame_header.RSV1 = ptr[0] & 0x40; _frame_header.RSV2 = ptr[0] & 0x20; _frame_header.RSV3 = ptr[0] & 0x10; _frame_header.OPCODE = static_cast<FrameType>(ptr[0] & 0x0f); _parser_step = e_payload_len; return 1U; } uint32_t FrameParser::parse_payload_len(const char* data) { const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data); _frame_header.MASK = ptr[0] & 0x80; _frame_header.PAYLOAD_LEN = ptr[0] & (0x7f); if (_frame_header.PAYLOAD_LEN <= 125) { _frame_header.PAYLOAD_REALY_LEN = _frame_header.PAYLOAD_LEN; if (_frame_header.MASK) { _parser_step = e_masking_key; } else { _parser_step = e_payload_data; } } else if (_frame_header.PAYLOAD_LEN > 125) { _parser_step = e_extened_payload_len; } if (_frame_header.PAYLOAD_LEN == 0) { assert(_msb_cb); _msb_cb("", _frame_header.OPCODE, !!_frame_header.FIN); reset(); } return 1U; } uint32_t FrameParser::parse_extened_payload_len(const char* data, uint32_t len) { uint32_t offset = 0; const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data); if (_frame_header.PAYLOAD_LEN == 126) { //Extended payload length is 16bit! uint32_t min_len = std::min<uint32_t> (2 - _payload_len_offset, len - offset); memcpy(&_frame_header.EXT_PAYLOAD_LEN_16, ptr + offset, min_len); offset += min_len; _payload_len_offset += min_len; if (_payload_len_offset == 2) { decode_extened_payload_len(); } } else if (_frame_header.PAYLOAD_LEN == 127) { //Extended payload length is 64bit! auto min_len = std::min<uint32_t>(8 - _payload_len_offset, len - offset); memcpy(&_frame_header.EXT_PAYLOAD_LEN_64, ptr + offset, static_cast<size_t>(min_len)); offset += min_len; _payload_len_offset += min_len; if (_payload_len_offset == 8) { decode_extened_payload_len(); } } return offset; } void FrameParser::decode_extened_payload_len() { if (_frame_header.PAYLOAD_LEN == 126) { uint16_t tmp = _frame_header.EXT_PAYLOAD_LEN_16; uint8_t* buffer_ = reinterpret_cast<uint8_t*>(&tmp); _frame_header.PAYLOAD_REALY_LEN = static_cast<uint64_t>( (static_cast<uint16_t>(buffer_[0]) << 8) | static_cast<uint16_t>(buffer_[1])); } else if (_frame_header.PAYLOAD_LEN == 127) { uint64_t tmp = _frame_header.EXT_PAYLOAD_LEN_64; uint8_t* buffer_ = reinterpret_cast<uint8_t*>(&tmp); _frame_header.PAYLOAD_REALY_LEN = (static_cast<uint64_t>(buffer_[0]) << 56) | (static_cast<uint64_t>(buffer_[1]) << 48) | (static_cast<uint64_t>(buffer_[2]) << 40) | (static_cast<uint64_t>(buffer_[3]) << 32) | (static_cast<uint64_t>(buffer_[4]) << 24) | (static_cast<uint64_t>(buffer_[5]) << 16) | (static_cast<uint64_t>(buffer_[6]) << 8) | static_cast<uint64_t>(buffer_[7]); } if (_frame_header.MASK) { _parser_step = e_masking_key; } else { _parser_step = e_payload_data; } } uint32_t FrameParser::parse_masking_key(const char* data, uint32_t len) { const uint8_t* ptr = reinterpret_cast<const uint8_t*>(data); auto min = std::min<uint32_t>(4 - _masking_key_pos, len); if (_parser_step == e_masking_key) { memcpy(&_frame_header.MASKING_KEY, ptr, static_cast<size_t>(min)); _masking_key_pos += min; if (_masking_key_pos == 4) { _parser_step = e_payload_data; } } return min; } uint32_t FrameParser::parse_payload(const char* data, uint32_t len) { if (_payload.empty() && _frame_header.PAYLOAD_REALY_LEN > 0) { _payload.reserve(static_cast<size_t>(_frame_header.PAYLOAD_REALY_LEN)); } auto remain = static_cast<uint32_t>(_frame_header.PAYLOAD_REALY_LEN) - static_cast<uint32_t>(_payload.size()); auto min_len = std::min<uint32_t>(remain, len); if (_frame_header.MASK) { unsigned char* mask = reinterpret_cast<unsigned char*>(&_frame_header.MASKING_KEY); for (size_t i = 0; i < min_len; i++) { _payload.push_back(static_cast<char>(data[i] ^ mask[i % 4])); } } else { _payload.append(data, min_len); } if (_payload.size() == _frame_header.PAYLOAD_REALY_LEN) { assert(_msb_cb); _msb_cb(std::move(_payload), _frame_header.OPCODE, !!_frame_header.FIN); reset(); } return min_len; } std::pair<bool, std::string> FrameParser::Parse(void const* data, uint32_t len) { assert(data != nullptr && len > 0); uint32_t offset = 0; uint32_t remain_len = len; try { do { if (_parser_step == e_fixed_header && remain_len) { offset += parse_fixed_header(static_cast<char const*>(data) + offset); remain_len = len - offset; } if (_parser_step == e_payload_len && remain_len) { offset += parse_payload_len(static_cast<char const*>(data) + offset); remain_len = len - offset; } if (_parser_step == e_extened_payload_len && remain_len) { offset += parse_extened_payload_len(static_cast<char const*>(data) + offset, remain_len); remain_len = len - offset; } if (_parser_step == e_masking_key && remain_len) { offset += parse_masking_key(static_cast<char const*>(data) + offset, remain_len); remain_len = len - offset; } if (_parser_step == e_payload_data && remain_len) { offset += parse_payload(static_cast<char const*>(data) + offset, remain_len); remain_len = len - offset; } } while (offset < len); } catch (std::exception const& e) { return {false, e.what()}; } catch (...) { return {false, "unknown exception."}; } return {true, ""}; } } // namespace Websocket } // namespace da4qi4
28.37037
114
0.586463
hl4
f137c5d4c66f20fd9810d8e5203c0a323e4e585e
2,893
cpp
C++
lib/src/agents/proximity_sensor.cpp
eidelen/maf
759b4b4a21962de8ec53dd198bc5bf66c19ee017
[ "MIT" ]
null
null
null
lib/src/agents/proximity_sensor.cpp
eidelen/maf
759b4b4a21962de8ec53dd198bc5bf66c19ee017
[ "MIT" ]
null
null
null
lib/src/agents/proximity_sensor.cpp
eidelen/maf
759b4b4a21962de8ec53dd198bc5bf66c19ee017
[ "MIT" ]
null
null
null
/**************************************************************************** ** Copyright (c) 2021 Adrian Schneider ** ** Permission is hereby granted, free of charge, to any person obtaining a ** copy of this software and associated documentation files (the "Software"), ** to deal in the Software without restriction, including without limitation ** the rights to use, copy, modify, merge, publish, distribute, sublicense, ** and/or sell copies of the Software, and to permit persons to whom the ** Software is furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in ** all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ** FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ** DEALINGS IN THE SOFTWARE. ** *****************************************************************************/ #include "proximity_sensor.h" std::shared_ptr<ProximitySensor> ProximitySensor::createProxSensor(unsigned int id, double range) { return std::shared_ptr<ProximitySensor>(new ProximitySensor(id, range)); } ProximitySensor::ProximitySensor(unsigned int id, double range): Agent::Agent(id), m_range(range) { } ProximitySensor::~ProximitySensor() { } void ProximitySensor::update(double time) { // update first sub agents updateSubAgents(time); assert(hasEnvironment()); // update agents in range m_agentsInRange.clear(); EnvironmentInterface::DistanceQueue q = m_environment.lock()->getAgentDistancesToAllOtherAgents(id()); while(!q.empty()) { const auto& d = q.top(); // if target is not on ignore list and target is in range if( d.dist < m_range ) { if( m_ignoreAgentIds.find(d.targetId) == m_ignoreAgentIds.end() ) { m_agentsInRange.push_back(d); } q.pop(); } else { // DistanceQueue is ordered -> next agent is out of range too break; } } performMove(time); } AgentType ProximitySensor::type() const { return AgentType::EProxSensor; } double ProximitySensor::range() const { return m_range; } void ProximitySensor::setRange(double newRange) { m_range = newRange; } std::vector<EnvironmentInterface::Distance> ProximitySensor::getAgentsInSensorRange() const { return m_agentsInRange; } void ProximitySensor::addIgnoreAgentId(unsigned int agentId) { m_ignoreAgentIds.insert(agentId); }
28.93
106
0.663671
eidelen
f137ef2add0af378ea99b08270988355bd06f43b
212
cpp
C++
TestProject/Source/TestProject/TestProject.cpp
1Gokul/TestProject
e732c65440537252bd02b9b527ac9a084f4ce44c
[ "MIT" ]
3
2020-07-06T19:46:42.000Z
2021-12-06T11:23:17.000Z
TestProject/Source/TestProject/TestProject.cpp
1Gokul/TestProject
e732c65440537252bd02b9b527ac9a084f4ce44c
[ "MIT" ]
null
null
null
TestProject/Source/TestProject/TestProject.cpp
1Gokul/TestProject
e732c65440537252bd02b9b527ac9a084f4ce44c
[ "MIT" ]
1
2021-12-06T11:23:48.000Z
2021-12-06T11:23:48.000Z
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "TestProject.h" #include "Modules/ModuleManager.h" IMPLEMENT_PRIMARY_GAME_MODULE(FDefaultGameModuleImpl, TestProject, "TestProject");
30.285714
83
0.783019
1Gokul
f138a7c9b24826789f4657efba62850bfafede9b
3,047
cpp
C++
go/runtime/cgosymbolizer/symbolizer.cpp
searKing/golang
b386053582e223fc1f4c4ab3c2d73ab423cefef2
[ "MIT" ]
37
2019-11-19T15:42:09.000Z
2022-03-27T07:55:42.000Z
go/runtime/cgosymbolizer/symbolizer.cpp
searKing/golang
b386053582e223fc1f4c4ab3c2d73ab423cefef2
[ "MIT" ]
5
2020-10-28T06:55:54.000Z
2021-06-19T05:25:46.000Z
go/runtime/cgosymbolizer/symbolizer.cpp
searKing/golang
b386053582e223fc1f4c4ab3c2d73ab423cefef2
[ "MIT" ]
8
2019-12-17T05:56:18.000Z
2021-08-17T20:36:41.000Z
// Copyright 2021 The searKing Author. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include "symbolizer.h" #include <stdint.h> #include <string.h> #include <sys/types.h> #include <boost/stacktrace/frame.hpp> #include <boost/stacktrace/stacktrace.hpp> #include "traceback.h" static int append_pc_info_to_symbolizer_list(cgoSymbolizerArg* arg); static int append_entry_to_symbolizer_list(cgoSymbolizerArg* arg); // For the details of how this is called see runtime.SetCgoTraceback. void cgoSymbolizer(cgoSymbolizerArg* arg) { cgoSymbolizerMore* more = arg->data; if (more != NULL) { arg->file = more->file; arg->lineno = more->lineno; arg->func = more->func; // set non-zero if more info for this PC arg->more = more->more != NULL; arg->data = more->more; // If returning the last file/line, we can set the // entry point field. if (!arg->more) { // no more info append_entry_to_symbolizer_list(arg); } return; } arg->file = NULL; arg->lineno = 0; arg->func = NULL; arg->more = 0; if (arg->pc == 0) { return; } append_pc_info_to_symbolizer_list(arg); // If returning only one file/line, we can set the entry point field. if (!arg->more) { append_entry_to_symbolizer_list(arg); } } void prepare_syminfo(const boost::stacktrace::detail::native_frame_ptr_t addr, std::string& file, std::size_t& line, std::string& func) { auto frame = boost::stacktrace::frame(addr); file = frame.source_file(); line = frame.source_line(); func = frame.name(); if (!func.empty()) { func = boost::core::demangle(func.c_str()); } else { func = boost::stacktrace::detail::to_hex_array(addr).data(); } if (file.empty() || file.find_first_of("?") == 0) { boost::stacktrace::detail::location_from_symbol loc(addr); if (!loc.empty()) { file = loc.name(); } } } static int append_pc_info_to_symbolizer_list(cgoSymbolizerArg* arg) { std::string file; std::size_t line = 0; std::string func; prepare_syminfo(boost::stacktrace::frame::native_frame_ptr_t(arg->pc), file, line, func); // init head with current stack if (arg->file == NULL) { arg->file = strdup(file.c_str()); arg->lineno = line; arg->func = strdup(func.c_str()); return 0; } cgoSymbolizerMore* more = (cgoSymbolizerMore*)malloc(sizeof(*more)); if (more == NULL) { return 1; } // append current stack to the tail more->more = NULL; more->file = strdup(file.c_str()); more->lineno = line; more->func = strdup(func.c_str()); cgoSymbolizerMore** pp = NULL; for (pp = &arg->data; *pp != NULL; pp = &(*pp)->more) { } *pp = more; arg->more = 1; return 0; } static int append_entry_to_symbolizer_list(cgoSymbolizerArg* arg) { auto frame = boost::stacktrace::frame( boost::stacktrace::frame::native_frame_ptr_t(arg->pc)); arg->entry = (uintptr_t)strdup(frame.name().c_str()); return 0; }
27.954128
79
0.653758
searKing
f13ca70aaf155bb98e21ed8269ff4fbac2b742b0
1,187
cpp
C++
src/BabylonImGui/src/inspector/components/sceneexplorer/entities/transform_node_tree_item_component.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
277
2017-05-18T08:27:10.000Z
2022-03-26T01:31:37.000Z
src/BabylonImGui/src/inspector/components/sceneexplorer/entities/transform_node_tree_item_component.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
77
2017-09-03T15:35:02.000Z
2022-03-28T18:47:20.000Z
src/BabylonImGui/src/inspector/components/sceneexplorer/entities/transform_node_tree_item_component.cpp
sacceus/BabylonCpp
94669cf7cbe3214ec6e905cbf249fa0c9daf6222
[ "Apache-2.0" ]
37
2017-03-30T03:36:24.000Z
2022-01-28T08:28:36.000Z
#include <babylon/inspector/components/sceneexplorer/entities/transform_node_tree_item_component.h> #include <babylon/inspector/components/sceneexplorer/tree_item_label_component.h> #include <babylon/meshes/transform_node.h> #include <babylon/misc/string_tools.h> #include <imgui_utils/imgui_utils.h> namespace BABYLON { TransformNodeTreeItemComponent::TransformNodeTreeItemComponent( const ITransformNodeTreeItemComponentProps& iProps) : props{iProps} { const auto& transformNode = props.transformNode; sprintf(label, "%s", transformNode->name.c_str()); // Set the entity info entityInfo.uniqueId = transformNode->uniqueId; const auto className = transformNode->getClassName(); if (StringTools::contains(className, "TransformNode")) { entityInfo.type = EntityType::TransformNode; } else if (StringTools::contains(className, "Mesh")) { entityInfo.type = EntityType::Mesh; } } TransformNodeTreeItemComponent::~TransformNodeTreeItemComponent() = default; void TransformNodeTreeItemComponent::render() { // TransformNode tree item label TreeItemLabelComponent::render(label, faCodeBranch, ImGui::cornflowerblue); } } // end of namespace BABYLON
31.236842
99
0.781803
sacceus
f13ca97b2f05ebd5a61231499adceea695401023
7,774
cpp
C++
unique_paths.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
unique_paths.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
unique_paths.cpp
artureganyan/algorithms
98cd0048162b3cb1c79712a884261cd3fe31063c
[ "MIT" ]
null
null
null
// Problem: https://leetcode.com/problems/unique-paths/ #include <vector> #include "utils.h" namespace unique_paths { // Note: All solutions return int as required by the initial problem, but // 32-bit signed integer can hold the result for at most the 17x18 grid. // The straightforward solution, recursively counting paths from the start // cell to the target class Solution1 { public: // Time: O(C(n + m, m)), Space: O(n + m), Recursion depth < n + m // n - number of rows, m - number of columns, // C(n + m, m) - binomial coefficient (n + m)! / (m! * n!) // // Note: Time complexity is estimated by the number of paths, which is // the binomial coefficient as shown in the Solution3. Space complexity // depends on the recursion depth, which is determined by the path // length n + m - 1. // int run(int rows_count, int cols_count) { if (rows_count <= 0 || cols_count <= 0) return 0; if (rows_count == 1 || cols_count == 1) return 1; // Go right + go down return run(rows_count, cols_count - 1) + run(rows_count - 1, cols_count); } }; // Non-recursive solution, counting paths from the target cell to the start class Solution2 { public: // Time: O(n * m), Space: O(n * m), n - number of rows, m - number of columns // // Note: It calculates all cells, but 1) we need only the (0, 0), 2) the // results are symmetrical: count(n, m) == count(m, n). So it could be // optimized. // int run(int rows_count, int cols_count) { if (rows_count <= 0 || cols_count <= 0) return 0; // Idea: // Count paths in reverse order, moving the start from the target cell to (0, 0): // 1. Put the start to the target cell (t = rows_count - 1, l = cols_count - 1). // Then there is only 1 path, i.e. the cell itself. // 2. Go to the outer rectangle, which top-left corner is (t - 1, l - 1) if this // is a square. // 3. Calculate counts for the top and left borders of the outer rectangle. For // each cell (r, c), the count is a sum of counts for (r + 1, c) and (r, c + 1), // because we can step only right or down. // 4. Repeat 2 and 3 until we reach (0, 0). // // 0 0 0 0 0 0 6 3 1 // 0 0 0 -> 0 2 1 -> 3 2 1 // 0 0 1 0 1 1 1 1 1 // Allocate one more row and column with zeros to avoid excessive range checks std::vector<std::vector<int>> count(rows_count + 1, std::vector<int>(cols_count + 1, 0)); // Start from the target cell int t = rows_count - 1; int l = cols_count - 1; int b = t; int r = l; count[t][l] = 1; do { // Go up and left. If not possible, decrease the right/bottom border // because everything at the right/bottom is already counted. if (t > 0) { t -= 1; } else { r = l - 1; } if (l > 0) { l -= 1; } else { b = t - 1; } // Count top border of the outer rectangle for (int ci = r, ri = t; ci > l; ci--) { calculateCount(count, ri, ci); } // Count left border of the outer rectangle for (int ri = b, ci = l; ri > t; ri--) { calculateCount(count, ri, ci); } // Count top-left corner of the outer rectangle calculateCount(count, t, l); } while (t != 0 || l != 0); return count[0][0]; } private: inline void calculateCount(std::vector<std::vector<int>>& count, int r, int c) const { int& cell = count[r][c]; cell += count[r + 1][c]; cell += count[r][c + 1]; } }; // This solution just calculates the binomial coefficient class Solution3 { public: // Time: O(n - m), Space: O(1), n - number of rows, m - number of columns // // Warning: This implementation uses floating-point calculation and produces // rounding error for large grids (e.g. test for 15x18 returned 1 path less // than expected). // int run(int rows_count, int cols_count) { // Idea: // If we look at the numbers of paths from each cell to the right-bottom // corner, we may notice that they are binomial coefficients // C(n, m) = n! / (m! * (n - m)!), written by diagonals: // // Numbers of paths. n n, excluding // They are C(n, m). trivial cases // // 70 35 15 5 1 8 7 6 5 4 8 7 6 5 * // 35 20 10 4 1 7 6 5 4 3 7 6 5 4 * // 15 10 6 3 1 6 5 4 3 2 6 5 4 3 * // 5 4 3 2 1 5 4 3 2 1 5 4 3 2 * // 1 1 1 1 1 4 3 2 1 1 * * * * * // // For all cells except the right and bottom borders (which correspond // to trivial cases nx1 and 1xn): // n = (rows_count - 1) + (cols_count - 1) // m = (cols_count - 1) // // Finally, to reduce the number of multiplications, we can simplify // C(n, m) to ((m+1) * (m+2) * ... * n) / (n - m)! and swap rows_count // and cols_count if rows_count > cols_count (the result is the same, // but both the dividend and divisor are lesser). if (rows_count <= 0 || cols_count <= 0) return 0; if (rows_count == 1 || cols_count == 1) return 1; if (rows_count > cols_count) std::swap(rows_count, cols_count); // Calculate C(n, m) = n! / (m! * (n - m)!) // n, m const int n = rows_count - 1 + cols_count - 1; const int m = cols_count - 1; // n! / m! = (m + 1) * (m + 2) * ... * n double nf_div_mf = 1; for (int i = m + 1; i <= n; i++) nf_div_mf *= i; // (n - m)! double n_minus_m_f = 1; for (int i = 2; i <= (n - m); i++) n_minus_m_f *= i; // C(n, m) const double C_n_m = nf_div_mf / n_minus_m_f; return static_cast<int>(C_n_m); } }; template <typename Solution> void test(bool large_grid = false) { auto test_symmetrical = [](int rows_count, int cols_count, int expected) { if (Solution().run(rows_count, cols_count) != expected) return false; if (rows_count != cols_count) { if (Solution().run(cols_count, rows_count) != expected) return false; } return true; }; ASSERT( test_symmetrical(-1, -1, 0) ); ASSERT( test_symmetrical(-1, 0, 0) ); ASSERT( test_symmetrical(-1, 1, 0) ); ASSERT( test_symmetrical(0, 0, 0) ); ASSERT( test_symmetrical(1, 0, 0) ); ASSERT( test_symmetrical(1, 1, 1) ); ASSERT( test_symmetrical(1, 2, 1) ); ASSERT( test_symmetrical(1, 3, 1) ); ASSERT( test_symmetrical(2, 2, 2) ); ASSERT( test_symmetrical(2, 3, 3) ); ASSERT( test_symmetrical(2, 4, 4) ); ASSERT( test_symmetrical(2, 5, 5) ); ASSERT( test_symmetrical(3, 3, 6) ); ASSERT( test_symmetrical(3, 4, 10) ); ASSERT( test_symmetrical(3, 5, 15) ); ASSERT( test_symmetrical(4, 4, 20) ); ASSERT( test_symmetrical(4, 5, 35) ); ASSERT( test_symmetrical(5, 5, 70) ); ASSERT( test_symmetrical(10, 10, 48620) ); if (large_grid) ASSERT( test_symmetrical(17, 18, 1166803110) ); } int main() { // Do not test large grid because of time complexity test<Solution1>(); test<Solution2>(true); // Do not test large grid because of rounding error test<Solution3>(); return 0; } }
32.123967
97
0.531515
artureganyan
f13e6e63b73ef115d8ca7a445339307d0a7f6eca
176,331
cpp
C++
GCG_Source.build/module.django.utils._os.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
GCG_Source.build/module.django.utils._os.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
GCG_Source.build/module.django.utils._os.cpp
Pckool/GCG
cee786d04ea30f3995e910bca82635f442b2a6a8
[ "MIT" ]
null
null
null
/* Generated code for Python source for module 'django.utils._os' * created by Nuitka version 0.5.28.2 * * This code is in part copyright 2017 Kay Hayen. * * 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 "nuitka/prelude.h" #include "__helpers.h" /* The _module_django$utils$_os is a Python object pointer of module type. */ /* Note: For full compatibility with CPython, every module variable access * needs to go through it except for cases where the module cannot possibly * have changed in the mean time. */ PyObject *module_django$utils$_os; PyDictObject *moduledict_django$utils$_os; /* The module constants used, if any. */ extern PyObject *const_str_plain_force_text; static PyObject *const_str_digest_a2f4bfb7897945f1cc69848924f0cb55; extern PyObject *const_str_plain_remove; extern PyObject *const_str_plain_PY2; extern PyObject *const_str_plain_ModuleSpec; extern PyObject *const_str_plain___spec__; extern PyObject *const_str_plain___package__; extern PyObject *const_str_plain_sys; extern PyObject *const_tuple_str_plain_SuspiciousFileOperation_tuple; extern PyObject *const_str_plain_decode; extern PyObject *const_str_plain_unicode_literals; extern PyObject *const_str_plain_nt; extern PyObject *const_str_plain_sep; static PyObject *const_str_digest_02c3b3e14ee51a74c880c9a2312b4dc8; extern PyObject *const_str_plain_text_type; static PyObject *const_str_plain_final_path; extern PyObject *const_tuple_str_plain_path_tuple; static PyObject *const_str_plain_symlink_path; static PyObject *const_str_digest_e029ae267a3a9a3ffb4d22037d50a89e; extern PyObject *const_dict_empty; extern PyObject *const_str_digest_842dfd4744c6e20ce39943a1591eb59d; extern PyObject *const_str_plain___file__; static PyObject *const_str_digest_e333b5c27f64858ace2064722679d143; extern PyObject *const_str_digest_e3393b2e61653c3df2c7d436c253bbee; static PyObject *const_tuple_d68c618138c0feb94dce5f32faa81863_tuple; extern PyObject *const_tuple_str_plain_force_text_tuple; extern PyObject *const_str_digest_e399ba4554180f37de594a6743234f17; extern PyObject *const_int_0; extern PyObject *const_str_plain_path; extern PyObject *const_str_angle_listcontraction; extern PyObject *const_str_plain_safe_join; extern PyObject *const_str_plain_encode; static PyObject *const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple; extern PyObject *const_str_plain_six; extern PyObject *const_str_plain_p; extern PyObject *const_str_plain_tempfile; extern PyObject *const_str_plain_abspathu; static PyObject *const_str_digest_b3b92bc7aa9804266ff219682e3d0112; static PyObject *const_str_plain_mkdtemp; extern PyObject *const_str_plain_normpath; extern PyObject *const_str_plain_abspath; static PyObject *const_str_plain_rmdir; static PyObject *const_str_digest_7099b288cddfaaccfbbcfd3d0cceafa5; extern PyObject *const_str_plain_normcase; static PyObject *const_str_plain_getdefaultencoding; static PyObject *const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple; extern PyObject *const_str_digest_dfb6e1abbed3113ee07234fdc458a320; static PyObject *const_str_digest_d92a79f74db4468ebeba34a6c933cb11; extern PyObject *const_tuple_str_plain_six_tuple; extern PyObject *const_str_plain_os; static PyObject *const_str_digest_5c892843b642786d8376f7cd7a9ec574; static PyObject *const_str_plain_getfilesystemencoding; static PyObject *const_str_plain_symlink; extern PyObject *const_str_plain_original; extern PyObject *const_tuple_empty; extern PyObject *const_str_plain_getcwdu; extern PyObject *const_str_plain_SuspiciousFileOperation; extern PyObject *const_str_digest_467c9722f19d9d40d148689532cdc0b1; extern PyObject *const_str_plain_base; extern PyObject *const_str_plain_tmpdir; extern PyObject *const_str_plain_upath; extern PyObject *const_str_plain_npath; extern PyObject *const_str_plain_paths; static PyObject *const_str_plain_base_path; extern PyObject *const_str_plain_makedirs; static PyObject *const_str_plain_original_path; extern PyObject *const_str_plain___loader__; extern PyObject *const_str_plain_format; extern PyObject *const_str_plain_join; extern PyObject *const_str_plain_name; static PyObject *const_str_plain_symlinks_supported; extern PyObject *const_str_plain_startswith; static PyObject *const_str_plain_supported; extern PyObject *const_str_plain_dirname; static PyObject *const_str_plain_fs_encoding; static PyObject *const_tuple_str_plain_p_str_plain_paths_tuple; extern PyObject *const_str_plain_PY3; extern PyObject *const_str_plain___doc__; extern PyObject *const_str_plain___cached__; static PyObject *const_str_plain_isabs; static PyObject *module_filename_obj; static bool constants_created = false; static void createModuleConstants( void ) { const_str_digest_a2f4bfb7897945f1cc69848924f0cb55 = UNSTREAM_STRING( &constant_bin[ 1141471 ], 19, 0 ); const_str_digest_02c3b3e14ee51a74c880c9a2312b4dc8 = UNSTREAM_STRING( &constant_bin[ 1141490 ], 257, 0 ); const_str_plain_final_path = UNSTREAM_STRING( &constant_bin[ 1141747 ], 10, 1 ); const_str_plain_symlink_path = UNSTREAM_STRING( &constant_bin[ 1141757 ], 12, 1 ); const_str_digest_e029ae267a3a9a3ffb4d22037d50a89e = UNSTREAM_STRING( &constant_bin[ 1141769 ], 39, 0 ); const_str_digest_e333b5c27f64858ace2064722679d143 = UNSTREAM_STRING( &constant_bin[ 1141808 ], 71, 0 ); const_tuple_d68c618138c0feb94dce5f32faa81863_tuple = PyTuple_New( 4 ); PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 0, const_str_plain_tmpdir ); Py_INCREF( const_str_plain_tmpdir ); const_str_plain_original_path = UNSTREAM_STRING( &constant_bin[ 1141879 ], 13, 1 ); PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 1, const_str_plain_original_path ); Py_INCREF( const_str_plain_original_path ); PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 2, const_str_plain_symlink_path ); Py_INCREF( const_str_plain_symlink_path ); const_str_plain_supported = UNSTREAM_STRING( &constant_bin[ 1262 ], 9, 1 ); PyTuple_SET_ITEM( const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 3, const_str_plain_supported ); Py_INCREF( const_str_plain_supported ); const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple = PyTuple_New( 4 ); PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 0, const_str_plain_base ); Py_INCREF( const_str_plain_base ); PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 1, const_str_plain_paths ); Py_INCREF( const_str_plain_paths ); PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 2, const_str_plain_final_path ); Py_INCREF( const_str_plain_final_path ); const_str_plain_base_path = UNSTREAM_STRING( &constant_bin[ 1141892 ], 9, 1 ); PyTuple_SET_ITEM( const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 3, const_str_plain_base_path ); Py_INCREF( const_str_plain_base_path ); const_str_digest_b3b92bc7aa9804266ff219682e3d0112 = UNSTREAM_STRING( &constant_bin[ 1141901 ], 183, 0 ); const_str_plain_mkdtemp = UNSTREAM_STRING( &constant_bin[ 1142084 ], 7, 1 ); const_str_plain_rmdir = UNSTREAM_STRING( &constant_bin[ 1142091 ], 5, 1 ); const_str_digest_7099b288cddfaaccfbbcfd3d0cceafa5 = UNSTREAM_STRING( &constant_bin[ 1142096 ], 25, 0 ); const_str_plain_getdefaultencoding = UNSTREAM_STRING( &constant_bin[ 1142121 ], 18, 1 ); const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple = PyTuple_New( 7 ); PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 0, const_str_plain_abspath ); Py_INCREF( const_str_plain_abspath ); PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 1, const_str_plain_dirname ); Py_INCREF( const_str_plain_dirname ); const_str_plain_isabs = UNSTREAM_STRING( &constant_bin[ 1142139 ], 5, 1 ); PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 2, const_str_plain_isabs ); Py_INCREF( const_str_plain_isabs ); PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 3, const_str_plain_join ); Py_INCREF( const_str_plain_join ); PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 4, const_str_plain_normcase ); Py_INCREF( const_str_plain_normcase ); PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 5, const_str_plain_normpath ); Py_INCREF( const_str_plain_normpath ); PyTuple_SET_ITEM( const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple, 6, const_str_plain_sep ); Py_INCREF( const_str_plain_sep ); const_str_digest_d92a79f74db4468ebeba34a6c933cb11 = UNSTREAM_STRING( &constant_bin[ 1142144 ], 213, 0 ); const_str_digest_5c892843b642786d8376f7cd7a9ec574 = UNSTREAM_STRING( &constant_bin[ 1142357 ], 98, 0 ); const_str_plain_getfilesystemencoding = UNSTREAM_STRING( &constant_bin[ 1142455 ], 21, 1 ); const_str_plain_symlink = UNSTREAM_STRING( &constant_bin[ 1141757 ], 7, 1 ); const_str_plain_symlinks_supported = UNSTREAM_STRING( &constant_bin[ 1142476 ], 18, 1 ); const_str_plain_fs_encoding = UNSTREAM_STRING( &constant_bin[ 1142494 ], 11, 1 ); const_tuple_str_plain_p_str_plain_paths_tuple = PyTuple_New( 2 ); PyTuple_SET_ITEM( const_tuple_str_plain_p_str_plain_paths_tuple, 0, const_str_plain_p ); Py_INCREF( const_str_plain_p ); PyTuple_SET_ITEM( const_tuple_str_plain_p_str_plain_paths_tuple, 1, const_str_plain_paths ); Py_INCREF( const_str_plain_paths ); constants_created = true; } #ifndef __NUITKA_NO_ASSERT__ void checkModuleConstants_django$utils$_os( void ) { // The module may not have been used at all. if (constants_created == false) return; } #endif // The module code objects. static PyCodeObject *codeobj_f795cf1a4736e33c5a5152c4aef12ba3; static PyCodeObject *codeobj_e3f2225c4277cee0cd5878c353c5494a; static PyCodeObject *codeobj_8338c887cffee3f6624948b93fdb5cad; static PyCodeObject *codeobj_f5eb817954879f203f472ef76832ad97; static PyCodeObject *codeobj_519eab41ce47fa2590f6a99ccc08067a; static PyCodeObject *codeobj_7f1d67953d1486ada0ef5501b0312cae; static PyCodeObject *codeobj_786e20e096923522b138dc8044ece5a9; static void createModuleCodeObjects(void) { module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_a2f4bfb7897945f1cc69848924f0cb55 ); codeobj_f795cf1a4736e33c5a5152c4aef12ba3 = MAKE_CODEOBJ( module_filename_obj, const_str_angle_listcontraction, 63, const_tuple_str_plain_p_str_plain_paths_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_e3f2225c4277cee0cd5878c353c5494a = MAKE_CODEOBJ( module_filename_obj, const_str_digest_7099b288cddfaaccfbbcfd3d0cceafa5, 1, const_tuple_empty, 0, 0, CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_8338c887cffee3f6624948b93fdb5cad = MAKE_CODEOBJ( module_filename_obj, const_str_plain_abspathu, 24, const_tuple_str_plain_path_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_f5eb817954879f203f472ef76832ad97 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_npath, 44, const_tuple_str_plain_path_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_519eab41ce47fa2590f6a99ccc08067a = MAKE_CODEOBJ( module_filename_obj, const_str_plain_safe_join, 54, const_tuple_099e64e46bf53bd54ca59e200c24ee37_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_VARARGS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_7f1d67953d1486ada0ef5501b0312cae = MAKE_CODEOBJ( module_filename_obj, const_str_plain_symlinks_supported, 82, const_tuple_d68c618138c0feb94dce5f32faa81863_tuple, 0, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); codeobj_786e20e096923522b138dc8044ece5a9 = MAKE_CODEOBJ( module_filename_obj, const_str_plain_upath, 35, const_tuple_str_plain_path_tuple, 1, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS ); } // The module function declarations. NUITKA_CROSS_MODULE PyObject *impl___internal__$$$function_12_complex_call_helper_pos_star_list( PyObject **python_pars ); static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_1_abspathu( ); static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_2_upath( ); static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_3_npath( ); static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_4_safe_join( ); static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_5_symlinks_supported( ); // The module function definitions. static PyObject *impl_django$utils$_os$$$function_1_abspathu( struct Nuitka_FunctionObject const *self, PyObject **python_pars ) { // Preserve error status for checks #ifndef __NUITKA_NO_ASSERT__ NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED(); #endif // Local variable declarations. PyObject *par_path = python_pars[ 0 ]; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_args_element_name_3; PyObject *tmp_args_element_name_4; PyObject *tmp_assign_source_1; PyObject *tmp_called_instance_1; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; PyObject *tmp_called_name_3; int tmp_cond_truth_1; PyObject *tmp_cond_value_1; PyObject *tmp_return_value; static struct Nuitka_FrameObject *cache_frame_8338c887cffee3f6624948b93fdb5cad = NULL; struct Nuitka_FrameObject *frame_8338c887cffee3f6624948b93fdb5cad; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; tmp_return_value = NULL; // Actual function code. // Tried code: MAKE_OR_REUSE_FRAME( cache_frame_8338c887cffee3f6624948b93fdb5cad, codeobj_8338c887cffee3f6624948b93fdb5cad, module_django$utils$_os, sizeof(void *) ); frame_8338c887cffee3f6624948b93fdb5cad = cache_frame_8338c887cffee3f6624948b93fdb5cad; // Push the new frame as the currently active one. pushFrameStack( frame_8338c887cffee3f6624948b93fdb5cad ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_8338c887cffee3f6624948b93fdb5cad ) == 2 ); // Frame stack // Framed code: tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_isabs ); if (unlikely( tmp_called_name_1 == NULL )) { tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_isabs ); } if ( tmp_called_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "isabs" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 30; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_args_element_name_1 = par_path; CHECK_OBJECT( tmp_args_element_name_1 ); frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 30; { PyObject *call_args[] = { tmp_args_element_name_1 }; tmp_cond_value_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args ); } if ( tmp_cond_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 30; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_cond_value_1 ); exception_lineno = 30; type_description_1 = "o"; goto frame_exception_exit_1; } Py_DECREF( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == 1 ) { goto branch_no_1; } else { goto branch_yes_1; } branch_yes_1:; tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_join ); if (unlikely( tmp_called_name_2 == NULL )) { tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_join ); } if ( tmp_called_name_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "join" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 31; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os ); if (unlikely( tmp_called_instance_1 == NULL )) { tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os ); } if ( tmp_called_instance_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 31; type_description_1 = "o"; goto frame_exception_exit_1; } frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 31; tmp_args_element_name_2 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_getcwdu ); if ( tmp_args_element_name_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 31; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_args_element_name_3 = par_path; if ( tmp_args_element_name_3 == NULL ) { Py_DECREF( tmp_args_element_name_2 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 31; type_description_1 = "o"; goto frame_exception_exit_1; } frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 31; { PyObject *call_args[] = { tmp_args_element_name_2, tmp_args_element_name_3 }; tmp_assign_source_1 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_2, call_args ); } Py_DECREF( tmp_args_element_name_2 ); if ( tmp_assign_source_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 31; type_description_1 = "o"; goto frame_exception_exit_1; } { PyObject *old = par_path; par_path = tmp_assign_source_1; Py_XDECREF( old ); } branch_no_1:; tmp_called_name_3 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normpath ); if (unlikely( tmp_called_name_3 == NULL )) { tmp_called_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normpath ); } if ( tmp_called_name_3 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normpath" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 32; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_args_element_name_4 = par_path; if ( tmp_args_element_name_4 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 32; type_description_1 = "o"; goto frame_exception_exit_1; } frame_8338c887cffee3f6624948b93fdb5cad->m_frame.f_lineno = 32; { PyObject *call_args[] = { tmp_args_element_name_4 }; tmp_return_value = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, call_args ); } if ( tmp_return_value == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 32; type_description_1 = "o"; goto frame_exception_exit_1; } goto frame_return_exit_1; #if 0 RESTORE_FRAME_EXCEPTION( frame_8338c887cffee3f6624948b93fdb5cad ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_1; frame_return_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_8338c887cffee3f6624948b93fdb5cad ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_8338c887cffee3f6624948b93fdb5cad ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_8338c887cffee3f6624948b93fdb5cad, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_8338c887cffee3f6624948b93fdb5cad->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_8338c887cffee3f6624948b93fdb5cad, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_8338c887cffee3f6624948b93fdb5cad, type_description_1, par_path ); // Release cached frame. if ( frame_8338c887cffee3f6624948b93fdb5cad == cache_frame_8338c887cffee3f6624948b93fdb5cad ) { Py_DECREF( frame_8338c887cffee3f6624948b93fdb5cad ); } cache_frame_8338c887cffee3f6624948b93fdb5cad = NULL; assertFrameObject( frame_8338c887cffee3f6624948b93fdb5cad ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto try_except_handler_1; frame_no_exception_1:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_1_abspathu ); return NULL; // Return handler code: try_return_handler_1:; Py_XDECREF( par_path ); par_path = NULL; goto function_return_exit; // Exception handler code: try_except_handler_1:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( par_path ); par_path = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto function_exception_exit; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_1_abspathu ); return NULL; function_exception_exit: assert( exception_type ); RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return NULL; function_return_exit: CHECK_OBJECT( tmp_return_value ); assert( had_error || !ERROR_OCCURRED() ); return tmp_return_value; } static PyObject *impl_django$utils$_os$$$function_2_upath( struct Nuitka_FunctionObject const *self, PyObject **python_pars ) { // Preserve error status for checks #ifndef __NUITKA_NO_ASSERT__ NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED(); #endif // Local variable declarations. PyObject *par_path = python_pars[ 0 ]; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; int tmp_and_left_truth_1; PyObject *tmp_and_left_value_1; PyObject *tmp_and_right_value_1; PyObject *tmp_args_element_name_1; PyObject *tmp_called_name_1; int tmp_cond_truth_1; PyObject *tmp_cond_value_1; PyObject *tmp_isinstance_cls_1; PyObject *tmp_isinstance_inst_1; PyObject *tmp_operand_name_1; PyObject *tmp_return_value; PyObject *tmp_source_name_1; PyObject *tmp_source_name_2; PyObject *tmp_source_name_3; static struct Nuitka_FrameObject *cache_frame_786e20e096923522b138dc8044ece5a9 = NULL; struct Nuitka_FrameObject *frame_786e20e096923522b138dc8044ece5a9; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; tmp_return_value = NULL; // Actual function code. // Tried code: MAKE_OR_REUSE_FRAME( cache_frame_786e20e096923522b138dc8044ece5a9, codeobj_786e20e096923522b138dc8044ece5a9, module_django$utils$_os, sizeof(void *) ); frame_786e20e096923522b138dc8044ece5a9 = cache_frame_786e20e096923522b138dc8044ece5a9; // Push the new frame as the currently active one. pushFrameStack( frame_786e20e096923522b138dc8044ece5a9 ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_786e20e096923522b138dc8044ece5a9 ) == 2 ); // Frame stack // Framed code: tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six ); if (unlikely( tmp_source_name_1 == NULL )) { tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six ); } if ( tmp_source_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 39; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_and_left_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_PY2 ); if ( tmp_and_left_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 39; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_and_left_truth_1 = CHECK_IF_TRUE( tmp_and_left_value_1 ); if ( tmp_and_left_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_and_left_value_1 ); exception_lineno = 39; type_description_1 = "o"; goto frame_exception_exit_1; } if ( tmp_and_left_truth_1 == 1 ) { goto and_right_1; } else { goto and_left_1; } and_right_1:; Py_DECREF( tmp_and_left_value_1 ); tmp_isinstance_inst_1 = par_path; if ( tmp_isinstance_inst_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 39; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six ); if (unlikely( tmp_source_name_2 == NULL )) { tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six ); } if ( tmp_source_name_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 39; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_isinstance_cls_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_text_type ); if ( tmp_isinstance_cls_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 39; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_operand_name_1 = BUILTIN_ISINSTANCE( tmp_isinstance_inst_1, tmp_isinstance_cls_1 ); Py_DECREF( tmp_isinstance_cls_1 ); if ( tmp_operand_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 39; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_and_right_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_1 ); if ( tmp_and_right_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 39; type_description_1 = "o"; goto frame_exception_exit_1; } Py_INCREF( tmp_and_right_value_1 ); tmp_cond_value_1 = tmp_and_right_value_1; goto and_end_1; and_left_1:; tmp_cond_value_1 = tmp_and_left_value_1; and_end_1:; tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_cond_value_1 ); exception_lineno = 39; type_description_1 = "o"; goto frame_exception_exit_1; } Py_DECREF( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == 1 ) { goto branch_yes_1; } else { goto branch_no_1; } branch_yes_1:; tmp_source_name_3 = par_path; if ( tmp_source_name_3 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 40; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_decode ); if ( tmp_called_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 40; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_args_element_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_fs_encoding ); if (unlikely( tmp_args_element_name_1 == NULL )) { tmp_args_element_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_fs_encoding ); } if ( tmp_args_element_name_1 == NULL ) { Py_DECREF( tmp_called_name_1 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "fs_encoding" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 40; type_description_1 = "o"; goto frame_exception_exit_1; } frame_786e20e096923522b138dc8044ece5a9->m_frame.f_lineno = 40; { PyObject *call_args[] = { tmp_args_element_name_1 }; tmp_return_value = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args ); } Py_DECREF( tmp_called_name_1 ); if ( tmp_return_value == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 40; type_description_1 = "o"; goto frame_exception_exit_1; } goto frame_return_exit_1; branch_no_1:; tmp_return_value = par_path; if ( tmp_return_value == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 41; type_description_1 = "o"; goto frame_exception_exit_1; } Py_INCREF( tmp_return_value ); goto frame_return_exit_1; #if 0 RESTORE_FRAME_EXCEPTION( frame_786e20e096923522b138dc8044ece5a9 ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_1; frame_return_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_786e20e096923522b138dc8044ece5a9 ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_786e20e096923522b138dc8044ece5a9 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_786e20e096923522b138dc8044ece5a9, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_786e20e096923522b138dc8044ece5a9->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_786e20e096923522b138dc8044ece5a9, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_786e20e096923522b138dc8044ece5a9, type_description_1, par_path ); // Release cached frame. if ( frame_786e20e096923522b138dc8044ece5a9 == cache_frame_786e20e096923522b138dc8044ece5a9 ) { Py_DECREF( frame_786e20e096923522b138dc8044ece5a9 ); } cache_frame_786e20e096923522b138dc8044ece5a9 = NULL; assertFrameObject( frame_786e20e096923522b138dc8044ece5a9 ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto try_except_handler_1; frame_no_exception_1:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_2_upath ); return NULL; // Return handler code: try_return_handler_1:; Py_XDECREF( par_path ); par_path = NULL; goto function_return_exit; // Exception handler code: try_except_handler_1:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( par_path ); par_path = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto function_exception_exit; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_2_upath ); return NULL; function_exception_exit: assert( exception_type ); RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return NULL; function_return_exit: CHECK_OBJECT( tmp_return_value ); assert( had_error || !ERROR_OCCURRED() ); return tmp_return_value; } static PyObject *impl_django$utils$_os$$$function_3_npath( struct Nuitka_FunctionObject const *self, PyObject **python_pars ) { // Preserve error status for checks #ifndef __NUITKA_NO_ASSERT__ NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED(); #endif // Local variable declarations. PyObject *par_path = python_pars[ 0 ]; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; int tmp_and_left_truth_1; PyObject *tmp_and_left_value_1; PyObject *tmp_and_right_value_1; PyObject *tmp_args_element_name_1; PyObject *tmp_called_name_1; int tmp_cond_truth_1; PyObject *tmp_cond_value_1; PyObject *tmp_isinstance_cls_1; PyObject *tmp_isinstance_inst_1; PyObject *tmp_operand_name_1; PyObject *tmp_return_value; PyObject *tmp_source_name_1; PyObject *tmp_source_name_2; static struct Nuitka_FrameObject *cache_frame_f5eb817954879f203f472ef76832ad97 = NULL; struct Nuitka_FrameObject *frame_f5eb817954879f203f472ef76832ad97; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; tmp_return_value = NULL; // Actual function code. // Tried code: MAKE_OR_REUSE_FRAME( cache_frame_f5eb817954879f203f472ef76832ad97, codeobj_f5eb817954879f203f472ef76832ad97, module_django$utils$_os, sizeof(void *) ); frame_f5eb817954879f203f472ef76832ad97 = cache_frame_f5eb817954879f203f472ef76832ad97; // Push the new frame as the currently active one. pushFrameStack( frame_f5eb817954879f203f472ef76832ad97 ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_f5eb817954879f203f472ef76832ad97 ) == 2 ); // Frame stack // Framed code: tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six ); if (unlikely( tmp_source_name_1 == NULL )) { tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six ); } if ( tmp_source_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 49; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_and_left_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_PY2 ); if ( tmp_and_left_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 49; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_and_left_truth_1 = CHECK_IF_TRUE( tmp_and_left_value_1 ); if ( tmp_and_left_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_and_left_value_1 ); exception_lineno = 49; type_description_1 = "o"; goto frame_exception_exit_1; } if ( tmp_and_left_truth_1 == 1 ) { goto and_right_1; } else { goto and_left_1; } and_right_1:; Py_DECREF( tmp_and_left_value_1 ); tmp_isinstance_inst_1 = par_path; if ( tmp_isinstance_inst_1 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 49; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_isinstance_cls_1 = (PyObject *)&PyBytes_Type; tmp_operand_name_1 = BUILTIN_ISINSTANCE( tmp_isinstance_inst_1, tmp_isinstance_cls_1 ); if ( tmp_operand_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 49; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_and_right_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_1 ); if ( tmp_and_right_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 49; type_description_1 = "o"; goto frame_exception_exit_1; } Py_INCREF( tmp_and_right_value_1 ); tmp_cond_value_1 = tmp_and_right_value_1; goto and_end_1; and_left_1:; tmp_cond_value_1 = tmp_and_left_value_1; and_end_1:; tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_cond_value_1 ); exception_lineno = 49; type_description_1 = "o"; goto frame_exception_exit_1; } Py_DECREF( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == 1 ) { goto branch_yes_1; } else { goto branch_no_1; } branch_yes_1:; tmp_source_name_2 = par_path; if ( tmp_source_name_2 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 50; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_encode ); if ( tmp_called_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 50; type_description_1 = "o"; goto frame_exception_exit_1; } tmp_args_element_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_fs_encoding ); if (unlikely( tmp_args_element_name_1 == NULL )) { tmp_args_element_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_fs_encoding ); } if ( tmp_args_element_name_1 == NULL ) { Py_DECREF( tmp_called_name_1 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "fs_encoding" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 50; type_description_1 = "o"; goto frame_exception_exit_1; } frame_f5eb817954879f203f472ef76832ad97->m_frame.f_lineno = 50; { PyObject *call_args[] = { tmp_args_element_name_1 }; tmp_return_value = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args ); } Py_DECREF( tmp_called_name_1 ); if ( tmp_return_value == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 50; type_description_1 = "o"; goto frame_exception_exit_1; } goto frame_return_exit_1; branch_no_1:; tmp_return_value = par_path; if ( tmp_return_value == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 51; type_description_1 = "o"; goto frame_exception_exit_1; } Py_INCREF( tmp_return_value ); goto frame_return_exit_1; #if 0 RESTORE_FRAME_EXCEPTION( frame_f5eb817954879f203f472ef76832ad97 ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_1; frame_return_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_f5eb817954879f203f472ef76832ad97 ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_f5eb817954879f203f472ef76832ad97 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_f5eb817954879f203f472ef76832ad97, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_f5eb817954879f203f472ef76832ad97->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_f5eb817954879f203f472ef76832ad97, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_f5eb817954879f203f472ef76832ad97, type_description_1, par_path ); // Release cached frame. if ( frame_f5eb817954879f203f472ef76832ad97 == cache_frame_f5eb817954879f203f472ef76832ad97 ) { Py_DECREF( frame_f5eb817954879f203f472ef76832ad97 ); } cache_frame_f5eb817954879f203f472ef76832ad97 = NULL; assertFrameObject( frame_f5eb817954879f203f472ef76832ad97 ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto try_except_handler_1; frame_no_exception_1:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_3_npath ); return NULL; // Return handler code: try_return_handler_1:; Py_XDECREF( par_path ); par_path = NULL; goto function_return_exit; // Exception handler code: try_except_handler_1:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( par_path ); par_path = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto function_exception_exit; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_3_npath ); return NULL; function_exception_exit: assert( exception_type ); RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return NULL; function_return_exit: CHECK_OBJECT( tmp_return_value ); assert( had_error || !ERROR_OCCURRED() ); return tmp_return_value; } static PyObject *impl_django$utils$_os$$$function_4_safe_join( struct Nuitka_FunctionObject const *self, PyObject **python_pars ) { // Preserve error status for checks #ifndef __NUITKA_NO_ASSERT__ NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED(); #endif // Local variable declarations. PyObject *par_base = python_pars[ 0 ]; PyObject *par_paths = python_pars[ 1 ]; PyObject *var_final_path = NULL; PyObject *var_base_path = NULL; PyObject *outline_0_var_p = NULL; PyObject *tmp_listcontraction_1__$0 = NULL; PyObject *tmp_listcontraction_1__contraction = NULL; PyObject *tmp_listcontraction_1__iter_value_0 = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *exception_keeper_type_2; PyObject *exception_keeper_value_2; PyTracebackObject *exception_keeper_tb_2; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2; PyObject *exception_keeper_type_3; PyObject *exception_keeper_value_3; PyTracebackObject *exception_keeper_tb_3; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3; int tmp_and_left_truth_1; int tmp_and_left_truth_2; PyObject *tmp_and_left_value_1; PyObject *tmp_and_left_value_2; PyObject *tmp_and_right_value_1; PyObject *tmp_and_right_value_2; PyObject *tmp_append_list_1; PyObject *tmp_append_value_1; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_args_element_name_3; PyObject *tmp_args_element_name_4; PyObject *tmp_args_element_name_5; PyObject *tmp_args_element_name_6; PyObject *tmp_args_element_name_7; PyObject *tmp_args_element_name_8; PyObject *tmp_args_element_name_9; PyObject *tmp_args_element_name_10; PyObject *tmp_args_element_name_11; PyObject *tmp_args_element_name_12; PyObject *tmp_args_element_name_13; PyObject *tmp_args_element_name_14; PyObject *tmp_args_element_name_15; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_assign_source_6; PyObject *tmp_assign_source_7; PyObject *tmp_assign_source_8; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; PyObject *tmp_called_name_3; PyObject *tmp_called_name_4; PyObject *tmp_called_name_5; PyObject *tmp_called_name_6; PyObject *tmp_called_name_7; PyObject *tmp_called_name_8; PyObject *tmp_called_name_9; PyObject *tmp_called_name_10; PyObject *tmp_called_name_11; PyObject *tmp_called_name_12; PyObject *tmp_called_name_13; PyObject *tmp_called_name_14; PyObject *tmp_compexpr_left_1; PyObject *tmp_compexpr_left_2; PyObject *tmp_compexpr_right_1; PyObject *tmp_compexpr_right_2; int tmp_cond_truth_1; PyObject *tmp_cond_value_1; PyObject *tmp_dircall_arg1_1; PyObject *tmp_dircall_arg2_1; PyObject *tmp_dircall_arg3_1; PyObject *tmp_iter_arg_1; PyObject *tmp_left_name_1; PyObject *tmp_next_source_1; PyObject *tmp_operand_name_1; PyObject *tmp_outline_return_value_1; PyObject *tmp_raise_type_1; int tmp_res; PyObject *tmp_return_value; PyObject *tmp_right_name_1; PyObject *tmp_source_name_1; PyObject *tmp_source_name_2; PyObject *tmp_tuple_element_1; static struct Nuitka_FrameObject *cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2 = NULL; struct Nuitka_FrameObject *frame_f795cf1a4736e33c5a5152c4aef12ba3_2; static struct Nuitka_FrameObject *cache_frame_519eab41ce47fa2590f6a99ccc08067a = NULL; struct Nuitka_FrameObject *frame_519eab41ce47fa2590f6a99ccc08067a; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; NUITKA_MAY_BE_UNUSED char const *type_description_2 = NULL; tmp_return_value = NULL; tmp_outline_return_value_1 = NULL; // Actual function code. // Tried code: MAKE_OR_REUSE_FRAME( cache_frame_519eab41ce47fa2590f6a99ccc08067a, codeobj_519eab41ce47fa2590f6a99ccc08067a, module_django$utils$_os, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) ); frame_519eab41ce47fa2590f6a99ccc08067a = cache_frame_519eab41ce47fa2590f6a99ccc08067a; // Push the new frame as the currently active one. pushFrameStack( frame_519eab41ce47fa2590f6a99ccc08067a ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_519eab41ce47fa2590f6a99ccc08067a ) == 2 ); // Frame stack // Framed code: tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_force_text ); if (unlikely( tmp_called_name_1 == NULL )) { tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_force_text ); } if ( tmp_called_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "force_text" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 62; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_1 = par_base; CHECK_OBJECT( tmp_args_element_name_1 ); frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 62; { PyObject *call_args[] = { tmp_args_element_name_1 }; tmp_assign_source_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_1, call_args ); } if ( tmp_assign_source_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 62; type_description_1 = "oooo"; goto frame_exception_exit_1; } { PyObject *old = par_base; par_base = tmp_assign_source_1; Py_XDECREF( old ); } // Tried code: tmp_iter_arg_1 = par_paths; if ( tmp_iter_arg_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "free variable '%s' referenced before assignment in enclosing scope", "paths" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 63; type_description_1 = "oooo"; goto try_except_handler_2; } tmp_assign_source_3 = MAKE_ITERATOR( tmp_iter_arg_1 ); if ( tmp_assign_source_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 63; type_description_1 = "oooo"; goto try_except_handler_2; } assert( tmp_listcontraction_1__$0 == NULL ); tmp_listcontraction_1__$0 = tmp_assign_source_3; tmp_assign_source_4 = PyList_New( 0 ); assert( tmp_listcontraction_1__contraction == NULL ); tmp_listcontraction_1__contraction = tmp_assign_source_4; MAKE_OR_REUSE_FRAME( cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2, codeobj_f795cf1a4736e33c5a5152c4aef12ba3, module_django$utils$_os, sizeof(void *)+sizeof(void *) ); frame_f795cf1a4736e33c5a5152c4aef12ba3_2 = cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2; // Push the new frame as the currently active one. pushFrameStack( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 ) == 2 ); // Frame stack // Framed code: // Tried code: loop_start_1:; tmp_next_source_1 = tmp_listcontraction_1__$0; CHECK_OBJECT( tmp_next_source_1 ); tmp_assign_source_5 = ITERATOR_NEXT( tmp_next_source_1 ); if ( tmp_assign_source_5 == NULL ) { if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() ) { goto loop_end_1; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); type_description_2 = "oo"; exception_lineno = 63; goto try_except_handler_3; } } { PyObject *old = tmp_listcontraction_1__iter_value_0; tmp_listcontraction_1__iter_value_0 = tmp_assign_source_5; Py_XDECREF( old ); } tmp_assign_source_6 = tmp_listcontraction_1__iter_value_0; CHECK_OBJECT( tmp_assign_source_6 ); { PyObject *old = outline_0_var_p; outline_0_var_p = tmp_assign_source_6; Py_INCREF( outline_0_var_p ); Py_XDECREF( old ); } tmp_append_list_1 = tmp_listcontraction_1__contraction; CHECK_OBJECT( tmp_append_list_1 ); tmp_called_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_force_text ); if (unlikely( tmp_called_name_2 == NULL )) { tmp_called_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_force_text ); } if ( tmp_called_name_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "force_text" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 63; type_description_2 = "oo"; goto try_except_handler_3; } tmp_args_element_name_2 = outline_0_var_p; CHECK_OBJECT( tmp_args_element_name_2 ); frame_f795cf1a4736e33c5a5152c4aef12ba3_2->m_frame.f_lineno = 63; { PyObject *call_args[] = { tmp_args_element_name_2 }; tmp_append_value_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_2, call_args ); } if ( tmp_append_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 63; type_description_2 = "oo"; goto try_except_handler_3; } assert( PyList_Check( tmp_append_list_1 ) ); tmp_res = PyList_Append( tmp_append_list_1, tmp_append_value_1 ); Py_DECREF( tmp_append_value_1 ); if ( tmp_res == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 63; type_description_2 = "oo"; goto try_except_handler_3; } if ( CONSIDER_THREADING() == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 63; type_description_2 = "oo"; goto try_except_handler_3; } goto loop_start_1; loop_end_1:; tmp_outline_return_value_1 = tmp_listcontraction_1__contraction; CHECK_OBJECT( tmp_outline_return_value_1 ); Py_INCREF( tmp_outline_return_value_1 ); goto try_return_handler_3; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join ); return NULL; // Return handler code: try_return_handler_3:; Py_XDECREF( tmp_listcontraction_1__$0 ); tmp_listcontraction_1__$0 = NULL; Py_XDECREF( tmp_listcontraction_1__contraction ); tmp_listcontraction_1__contraction = NULL; Py_XDECREF( tmp_listcontraction_1__iter_value_0 ); tmp_listcontraction_1__iter_value_0 = NULL; goto frame_return_exit_2; // Exception handler code: try_except_handler_3:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_listcontraction_1__$0 ); tmp_listcontraction_1__$0 = NULL; Py_XDECREF( tmp_listcontraction_1__contraction ); tmp_listcontraction_1__contraction = NULL; Py_XDECREF( tmp_listcontraction_1__iter_value_0 ); tmp_listcontraction_1__iter_value_0 = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto frame_exception_exit_2; // End of try: #if 0 RESTORE_FRAME_EXCEPTION( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_1; frame_return_exit_2:; #if 0 RESTORE_FRAME_EXCEPTION( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_2; frame_exception_exit_2:; #if 0 RESTORE_FRAME_EXCEPTION( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_f795cf1a4736e33c5a5152c4aef12ba3_2, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_f795cf1a4736e33c5a5152c4aef12ba3_2->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_f795cf1a4736e33c5a5152c4aef12ba3_2, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_f795cf1a4736e33c5a5152c4aef12ba3_2, type_description_2, outline_0_var_p, par_paths ); // Release cached frame. if ( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 == cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2 ) { Py_DECREF( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 ); } cache_frame_f795cf1a4736e33c5a5152c4aef12ba3_2 = NULL; assertFrameObject( frame_f795cf1a4736e33c5a5152c4aef12ba3_2 ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto nested_frame_exit_1; frame_no_exception_1:; goto skip_nested_handling_1; nested_frame_exit_1:; type_description_1 = "oooo"; goto try_except_handler_2; skip_nested_handling_1:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join ); return NULL; // Return handler code: try_return_handler_2:; Py_XDECREF( outline_0_var_p ); outline_0_var_p = NULL; goto outline_result_1; // Exception handler code: try_except_handler_2:; exception_keeper_type_2 = exception_type; exception_keeper_value_2 = exception_value; exception_keeper_tb_2 = exception_tb; exception_keeper_lineno_2 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( outline_0_var_p ); outline_0_var_p = NULL; // Re-raise. exception_type = exception_keeper_type_2; exception_value = exception_keeper_value_2; exception_tb = exception_keeper_tb_2; exception_lineno = exception_keeper_lineno_2; goto outline_exception_1; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join ); return NULL; outline_exception_1:; exception_lineno = 63; goto frame_exception_exit_1; outline_result_1:; tmp_assign_source_2 = tmp_outline_return_value_1; { PyObject *old = par_paths; par_paths = tmp_assign_source_2; Py_XDECREF( old ); } tmp_called_name_3 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu ); if (unlikely( tmp_called_name_3 == NULL )) { tmp_called_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_abspathu ); } if ( tmp_called_name_3 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "abspathu" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 64; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_dircall_arg1_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_join ); if (unlikely( tmp_dircall_arg1_1 == NULL )) { tmp_dircall_arg1_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_join ); } if ( tmp_dircall_arg1_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "join" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 64; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_dircall_arg2_1 = PyTuple_New( 1 ); tmp_tuple_element_1 = par_base; if ( tmp_tuple_element_1 == NULL ) { Py_DECREF( tmp_dircall_arg2_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 64; type_description_1 = "oooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_dircall_arg2_1, 0, tmp_tuple_element_1 ); tmp_dircall_arg3_1 = par_paths; CHECK_OBJECT( tmp_dircall_arg3_1 ); Py_INCREF( tmp_dircall_arg1_1 ); Py_INCREF( tmp_dircall_arg3_1 ); { PyObject *dir_call_args[] = {tmp_dircall_arg1_1, tmp_dircall_arg2_1, tmp_dircall_arg3_1}; tmp_args_element_name_3 = impl___internal__$$$function_12_complex_call_helper_pos_star_list( dir_call_args ); } if ( tmp_args_element_name_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 64; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 64; { PyObject *call_args[] = { tmp_args_element_name_3 }; tmp_assign_source_7 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, call_args ); } Py_DECREF( tmp_args_element_name_3 ); if ( tmp_assign_source_7 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 64; type_description_1 = "oooo"; goto frame_exception_exit_1; } assert( var_final_path == NULL ); var_final_path = tmp_assign_source_7; tmp_called_name_4 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu ); if (unlikely( tmp_called_name_4 == NULL )) { tmp_called_name_4 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_abspathu ); } if ( tmp_called_name_4 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "abspathu" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 65; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_4 = par_base; if ( tmp_args_element_name_4 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 65; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 65; { PyObject *call_args[] = { tmp_args_element_name_4 }; tmp_assign_source_8 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_4, call_args ); } if ( tmp_assign_source_8 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 65; type_description_1 = "oooo"; goto frame_exception_exit_1; } assert( var_base_path == NULL ); var_base_path = tmp_assign_source_8; tmp_called_name_6 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase ); if (unlikely( tmp_called_name_6 == NULL )) { tmp_called_name_6 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase ); } if ( tmp_called_name_6 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 73; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_5 = var_final_path; if ( tmp_args_element_name_5 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 73; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 73; { PyObject *call_args[] = { tmp_args_element_name_5 }; tmp_source_name_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_6, call_args ); } if ( tmp_source_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 73; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_called_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_startswith ); Py_DECREF( tmp_source_name_1 ); if ( tmp_called_name_5 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 73; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_called_name_7 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase ); if (unlikely( tmp_called_name_7 == NULL )) { tmp_called_name_7 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase ); } if ( tmp_called_name_7 == NULL ) { Py_DECREF( tmp_called_name_5 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 73; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_left_name_1 = var_base_path; if ( tmp_left_name_1 == NULL ) { Py_DECREF( tmp_called_name_5 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 73; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_right_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sep ); if (unlikely( tmp_right_name_1 == NULL )) { tmp_right_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_sep ); } if ( tmp_right_name_1 == NULL ) { Py_DECREF( tmp_called_name_5 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "sep" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 73; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_7 = BINARY_OPERATION_ADD( tmp_left_name_1, tmp_right_name_1 ); if ( tmp_args_element_name_7 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_called_name_5 ); exception_lineno = 73; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 73; { PyObject *call_args[] = { tmp_args_element_name_7 }; tmp_args_element_name_6 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_7, call_args ); } Py_DECREF( tmp_args_element_name_7 ); if ( tmp_args_element_name_6 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_called_name_5 ); exception_lineno = 73; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 73; { PyObject *call_args[] = { tmp_args_element_name_6 }; tmp_operand_name_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_5, call_args ); } Py_DECREF( tmp_called_name_5 ); Py_DECREF( tmp_args_element_name_6 ); if ( tmp_operand_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 73; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_and_left_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_1 ); Py_DECREF( tmp_operand_name_1 ); if ( tmp_and_left_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 73; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_and_left_truth_1 = CHECK_IF_TRUE( tmp_and_left_value_1 ); if ( tmp_and_left_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } if ( tmp_and_left_truth_1 == 1 ) { goto and_right_1; } else { goto and_left_1; } and_right_1:; tmp_called_name_8 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase ); if (unlikely( tmp_called_name_8 == NULL )) { tmp_called_name_8 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase ); } if ( tmp_called_name_8 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 74; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_8 = var_final_path; if ( tmp_args_element_name_8 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 74; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 74; { PyObject *call_args[] = { tmp_args_element_name_8 }; tmp_compexpr_left_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_8, call_args ); } if ( tmp_compexpr_left_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 74; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_called_name_9 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase ); if (unlikely( tmp_called_name_9 == NULL )) { tmp_called_name_9 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase ); } if ( tmp_called_name_9 == NULL ) { Py_DECREF( tmp_compexpr_left_1 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 74; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_9 = var_base_path; if ( tmp_args_element_name_9 == NULL ) { Py_DECREF( tmp_compexpr_left_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 74; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 74; { PyObject *call_args[] = { tmp_args_element_name_9 }; tmp_compexpr_right_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_9, call_args ); } if ( tmp_compexpr_right_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_compexpr_left_1 ); exception_lineno = 74; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_and_left_value_2 = RICH_COMPARE_NE( tmp_compexpr_left_1, tmp_compexpr_right_1 ); Py_DECREF( tmp_compexpr_left_1 ); Py_DECREF( tmp_compexpr_right_1 ); if ( tmp_and_left_value_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 74; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_and_left_truth_2 = CHECK_IF_TRUE( tmp_and_left_value_2 ); if ( tmp_and_left_truth_2 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_and_left_value_2 ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } if ( tmp_and_left_truth_2 == 1 ) { goto and_right_2; } else { goto and_left_2; } and_right_2:; Py_DECREF( tmp_and_left_value_2 ); tmp_called_name_10 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_dirname ); if (unlikely( tmp_called_name_10 == NULL )) { tmp_called_name_10 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_dirname ); } if ( tmp_called_name_10 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "dirname" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_called_name_11 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase ); if (unlikely( tmp_called_name_11 == NULL )) { tmp_called_name_11 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase ); } if ( tmp_called_name_11 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_11 = var_base_path; if ( tmp_args_element_name_11 == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 75; { PyObject *call_args[] = { tmp_args_element_name_11 }; tmp_args_element_name_10 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_11, call_args ); } if ( tmp_args_element_name_10 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 75; { PyObject *call_args[] = { tmp_args_element_name_10 }; tmp_compexpr_left_2 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_10, call_args ); } Py_DECREF( tmp_args_element_name_10 ); if ( tmp_compexpr_left_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_called_name_12 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase ); if (unlikely( tmp_called_name_12 == NULL )) { tmp_called_name_12 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_normcase ); } if ( tmp_called_name_12 == NULL ) { Py_DECREF( tmp_compexpr_left_2 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "normcase" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_12 = var_base_path; if ( tmp_args_element_name_12 == NULL ) { Py_DECREF( tmp_compexpr_left_2 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 75; { PyObject *call_args[] = { tmp_args_element_name_12 }; tmp_compexpr_right_2 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_12, call_args ); } if ( tmp_compexpr_right_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_compexpr_left_2 ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_and_right_value_2 = RICH_COMPARE_NE( tmp_compexpr_left_2, tmp_compexpr_right_2 ); Py_DECREF( tmp_compexpr_left_2 ); Py_DECREF( tmp_compexpr_right_2 ); if ( tmp_and_right_value_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_and_right_value_1 = tmp_and_right_value_2; goto and_end_2; and_left_2:; tmp_and_right_value_1 = tmp_and_left_value_2; and_end_2:; tmp_cond_value_1 = tmp_and_right_value_1; goto and_end_1; and_left_1:; Py_INCREF( tmp_and_left_value_1 ); tmp_cond_value_1 = tmp_and_left_value_1; and_end_1:; tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_cond_value_1 ); exception_lineno = 75; type_description_1 = "oooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == 1 ) { goto branch_yes_1; } else { goto branch_no_1; } branch_yes_1:; tmp_called_name_13 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_SuspiciousFileOperation ); if (unlikely( tmp_called_name_13 == NULL )) { tmp_called_name_13 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_SuspiciousFileOperation ); } if ( tmp_called_name_13 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "SuspiciousFileOperation" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 76; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_source_name_2 = const_str_digest_e333b5c27f64858ace2064722679d143; tmp_called_name_14 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_format ); assert( tmp_called_name_14 != NULL ); tmp_args_element_name_14 = var_final_path; if ( tmp_args_element_name_14 == NULL ) { Py_DECREF( tmp_called_name_14 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 78; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_15 = var_base_path; if ( tmp_args_element_name_15 == NULL ) { Py_DECREF( tmp_called_name_14 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "base_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 78; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 77; { PyObject *call_args[] = { tmp_args_element_name_14, tmp_args_element_name_15 }; tmp_args_element_name_13 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_14, call_args ); } Py_DECREF( tmp_called_name_14 ); if ( tmp_args_element_name_13 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 77; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_519eab41ce47fa2590f6a99ccc08067a->m_frame.f_lineno = 76; { PyObject *call_args[] = { tmp_args_element_name_13 }; tmp_raise_type_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_13, call_args ); } Py_DECREF( tmp_args_element_name_13 ); if ( tmp_raise_type_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 76; type_description_1 = "oooo"; goto frame_exception_exit_1; } exception_type = tmp_raise_type_1; exception_lineno = 76; RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb ); type_description_1 = "oooo"; goto frame_exception_exit_1; branch_no_1:; tmp_return_value = var_final_path; if ( tmp_return_value == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "final_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 79; type_description_1 = "oooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_return_value ); goto frame_return_exit_1; #if 0 RESTORE_FRAME_EXCEPTION( frame_519eab41ce47fa2590f6a99ccc08067a ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_2; frame_return_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_519eab41ce47fa2590f6a99ccc08067a ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_519eab41ce47fa2590f6a99ccc08067a ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_519eab41ce47fa2590f6a99ccc08067a, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_519eab41ce47fa2590f6a99ccc08067a->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_519eab41ce47fa2590f6a99ccc08067a, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_519eab41ce47fa2590f6a99ccc08067a, type_description_1, par_base, par_paths, var_final_path, var_base_path ); // Release cached frame. if ( frame_519eab41ce47fa2590f6a99ccc08067a == cache_frame_519eab41ce47fa2590f6a99ccc08067a ) { Py_DECREF( frame_519eab41ce47fa2590f6a99ccc08067a ); } cache_frame_519eab41ce47fa2590f6a99ccc08067a = NULL; assertFrameObject( frame_519eab41ce47fa2590f6a99ccc08067a ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto try_except_handler_1; frame_no_exception_2:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join ); return NULL; // Return handler code: try_return_handler_1:; Py_XDECREF( par_base ); par_base = NULL; Py_XDECREF( par_paths ); par_paths = NULL; Py_XDECREF( var_final_path ); var_final_path = NULL; Py_XDECREF( var_base_path ); var_base_path = NULL; goto function_return_exit; // Exception handler code: try_except_handler_1:; exception_keeper_type_3 = exception_type; exception_keeper_value_3 = exception_value; exception_keeper_tb_3 = exception_tb; exception_keeper_lineno_3 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( par_base ); par_base = NULL; Py_XDECREF( par_paths ); par_paths = NULL; Py_XDECREF( var_final_path ); var_final_path = NULL; Py_XDECREF( var_base_path ); var_base_path = NULL; // Re-raise. exception_type = exception_keeper_type_3; exception_value = exception_keeper_value_3; exception_tb = exception_keeper_tb_3; exception_lineno = exception_keeper_lineno_3; goto function_exception_exit; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_4_safe_join ); return NULL; function_exception_exit: assert( exception_type ); RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return NULL; function_return_exit: CHECK_OBJECT( tmp_return_value ); assert( had_error || !ERROR_OCCURRED() ); return tmp_return_value; } static PyObject *impl_django$utils$_os$$$function_5_symlinks_supported( struct Nuitka_FunctionObject const *self, PyObject **python_pars ) { // Preserve error status for checks #ifndef __NUITKA_NO_ASSERT__ NUITKA_MAY_BE_UNUSED bool had_error = ERROR_OCCURRED(); #endif // Local variable declarations. PyObject *var_tmpdir = NULL; PyObject *var_original_path = NULL; PyObject *var_symlink_path = NULL; PyObject *var_supported = NULL; PyObject *tmp_try_except_1__unhandled_indicator = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *exception_keeper_type_2; PyObject *exception_keeper_value_2; PyTracebackObject *exception_keeper_tb_2; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2; PyObject *exception_keeper_type_3; PyObject *exception_keeper_value_3; PyTracebackObject *exception_keeper_tb_3; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3; PyObject *exception_keeper_type_4; PyObject *exception_keeper_value_4; PyTracebackObject *exception_keeper_tb_4; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_4; PyObject *exception_keeper_type_5; PyObject *exception_keeper_value_5; PyTracebackObject *exception_keeper_tb_5; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_5; PyObject *exception_keeper_type_6; PyObject *exception_keeper_value_6; PyTracebackObject *exception_keeper_tb_6; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_6; PyObject *exception_preserved_type_1; PyObject *exception_preserved_value_1; PyTracebackObject *exception_preserved_tb_1; PyObject *exception_preserved_type_2; PyObject *exception_preserved_value_2; PyTracebackObject *exception_preserved_tb_2; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_args_element_name_3; PyObject *tmp_args_element_name_4; PyObject *tmp_args_element_name_5; PyObject *tmp_args_element_name_6; PyObject *tmp_args_element_name_7; PyObject *tmp_args_element_name_8; PyObject *tmp_args_element_name_9; PyObject *tmp_args_element_name_10; PyObject *tmp_args_element_name_11; PyObject *tmp_args_element_name_12; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_assign_source_6; PyObject *tmp_assign_source_7; PyObject *tmp_called_instance_1; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; PyObject *tmp_called_name_3; PyObject *tmp_called_name_4; PyObject *tmp_called_name_5; PyObject *tmp_called_name_6; PyObject *tmp_called_name_7; PyObject *tmp_called_name_8; PyObject *tmp_called_name_9; PyObject *tmp_compare_left_1; PyObject *tmp_compare_left_2; PyObject *tmp_compare_right_1; PyObject *tmp_compare_right_2; int tmp_exc_match_exception_match_1; bool tmp_is_1; bool tmp_result; PyObject *tmp_return_value; PyObject *tmp_source_name_1; PyObject *tmp_source_name_2; PyObject *tmp_source_name_3; PyObject *tmp_source_name_4; PyObject *tmp_source_name_5; PyObject *tmp_source_name_6; PyObject *tmp_source_name_7; PyObject *tmp_source_name_8; PyObject *tmp_source_name_9; PyObject *tmp_source_name_10; PyObject *tmp_source_name_11; PyObject *tmp_tuple_element_1; NUITKA_MAY_BE_UNUSED PyObject *tmp_unused; static struct Nuitka_FrameObject *cache_frame_7f1d67953d1486ada0ef5501b0312cae = NULL; struct Nuitka_FrameObject *frame_7f1d67953d1486ada0ef5501b0312cae; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; tmp_return_value = NULL; // Actual function code. // Tried code: MAKE_OR_REUSE_FRAME( cache_frame_7f1d67953d1486ada0ef5501b0312cae, codeobj_7f1d67953d1486ada0ef5501b0312cae, module_django$utils$_os, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) ); frame_7f1d67953d1486ada0ef5501b0312cae = cache_frame_7f1d67953d1486ada0ef5501b0312cae; // Push the new frame as the currently active one. pushFrameStack( frame_7f1d67953d1486ada0ef5501b0312cae ); // Mark the frame object as in use, ref count 1 will be up for reuse. assert( Py_REFCNT( frame_7f1d67953d1486ada0ef5501b0312cae ) == 2 ); // Frame stack // Framed code: tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_tempfile ); if (unlikely( tmp_called_instance_1 == NULL )) { tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_tempfile ); } if ( tmp_called_instance_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "tempfile" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 88; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 88; tmp_assign_source_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_mkdtemp ); if ( tmp_assign_source_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 88; type_description_1 = "oooo"; goto frame_exception_exit_1; } assert( var_tmpdir == NULL ); var_tmpdir = tmp_assign_source_1; tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os ); if (unlikely( tmp_source_name_2 == NULL )) { tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os ); } if ( tmp_source_name_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 89; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_source_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_path ); if ( tmp_source_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 89; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_join ); Py_DECREF( tmp_source_name_1 ); if ( tmp_called_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 89; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_1 = var_tmpdir; if ( tmp_args_element_name_1 == NULL ) { Py_DECREF( tmp_called_name_1 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 89; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_2 = const_str_plain_original; frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 89; { PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 }; tmp_assign_source_2 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args ); } Py_DECREF( tmp_called_name_1 ); if ( tmp_assign_source_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 89; type_description_1 = "oooo"; goto frame_exception_exit_1; } assert( var_original_path == NULL ); var_original_path = tmp_assign_source_2; tmp_source_name_4 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os ); if (unlikely( tmp_source_name_4 == NULL )) { tmp_source_name_4 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os ); } if ( tmp_source_name_4 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 90; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_source_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_path ); if ( tmp_source_name_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 90; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_join ); Py_DECREF( tmp_source_name_3 ); if ( tmp_called_name_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 90; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_3 = var_tmpdir; if ( tmp_args_element_name_3 == NULL ) { Py_DECREF( tmp_called_name_2 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 90; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_4 = const_str_plain_symlink; frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 90; { PyObject *call_args[] = { tmp_args_element_name_3, tmp_args_element_name_4 }; tmp_assign_source_3 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_2, call_args ); } Py_DECREF( tmp_called_name_2 ); if ( tmp_assign_source_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 90; type_description_1 = "oooo"; goto frame_exception_exit_1; } assert( var_symlink_path == NULL ); var_symlink_path = tmp_assign_source_3; tmp_source_name_5 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os ); if (unlikely( tmp_source_name_5 == NULL )) { tmp_source_name_5 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os ); } if ( tmp_source_name_5 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 91; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_5, const_str_plain_makedirs ); if ( tmp_called_name_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 91; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_5 = var_original_path; if ( tmp_args_element_name_5 == NULL ) { Py_DECREF( tmp_called_name_3 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 91; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 91; { PyObject *call_args[] = { tmp_args_element_name_5 }; tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, call_args ); } Py_DECREF( tmp_called_name_3 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 91; type_description_1 = "oooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_unused ); tmp_assign_source_4 = Py_True; assert( tmp_try_except_1__unhandled_indicator == NULL ); Py_INCREF( tmp_assign_source_4 ); tmp_try_except_1__unhandled_indicator = tmp_assign_source_4; // Tried code: // Tried code: // Tried code: tmp_source_name_6 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os ); if (unlikely( tmp_source_name_6 == NULL )) { tmp_source_name_6 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os ); } if ( tmp_source_name_6 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 93; type_description_1 = "oooo"; goto try_except_handler_4; } tmp_called_name_4 = LOOKUP_ATTRIBUTE( tmp_source_name_6, const_str_plain_symlink ); if ( tmp_called_name_4 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 93; type_description_1 = "oooo"; goto try_except_handler_4; } tmp_args_element_name_6 = var_original_path; if ( tmp_args_element_name_6 == NULL ) { Py_DECREF( tmp_called_name_4 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 93; type_description_1 = "oooo"; goto try_except_handler_4; } tmp_args_element_name_7 = var_symlink_path; if ( tmp_args_element_name_7 == NULL ) { Py_DECREF( tmp_called_name_4 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "symlink_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 93; type_description_1 = "oooo"; goto try_except_handler_4; } frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 93; { PyObject *call_args[] = { tmp_args_element_name_6, tmp_args_element_name_7 }; tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_4, call_args ); } Py_DECREF( tmp_called_name_4 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 93; type_description_1 = "oooo"; goto try_except_handler_4; } Py_DECREF( tmp_unused ); tmp_assign_source_5 = Py_True; assert( var_supported == NULL ); Py_INCREF( tmp_assign_source_5 ); var_supported = tmp_assign_source_5; goto try_end_1; // Exception handler code: try_except_handler_4:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; tmp_assign_source_6 = Py_False; { PyObject *old = tmp_try_except_1__unhandled_indicator; tmp_try_except_1__unhandled_indicator = tmp_assign_source_6; Py_INCREF( tmp_try_except_1__unhandled_indicator ); Py_XDECREF( old ); } // Preserve existing published exception. exception_preserved_type_1 = PyThreadState_GET()->exc_type; Py_XINCREF( exception_preserved_type_1 ); exception_preserved_value_1 = PyThreadState_GET()->exc_value; Py_XINCREF( exception_preserved_value_1 ); exception_preserved_tb_1 = (PyTracebackObject *)PyThreadState_GET()->exc_traceback; Py_XINCREF( exception_preserved_tb_1 ); if ( exception_keeper_tb_1 == NULL ) { exception_keeper_tb_1 = MAKE_TRACEBACK( frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_1 ); } else if ( exception_keeper_lineno_1 != 0 ) { exception_keeper_tb_1 = ADD_TRACEBACK( exception_keeper_tb_1, frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_1 ); } NORMALIZE_EXCEPTION( &exception_keeper_type_1, &exception_keeper_value_1, &exception_keeper_tb_1 ); PyException_SetTraceback( exception_keeper_value_1, (PyObject *)exception_keeper_tb_1 ); PUBLISH_EXCEPTION( &exception_keeper_type_1, &exception_keeper_value_1, &exception_keeper_tb_1 ); // Tried code: tmp_compare_left_1 = PyThreadState_GET()->exc_type; tmp_compare_right_1 = PyTuple_New( 3 ); tmp_tuple_element_1 = PyExc_OSError; Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_compare_right_1, 0, tmp_tuple_element_1 ); tmp_tuple_element_1 = PyExc_NotImplementedError; Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_compare_right_1, 1, tmp_tuple_element_1 ); tmp_tuple_element_1 = PyExc_AttributeError; Py_INCREF( tmp_tuple_element_1 ); PyTuple_SET_ITEM( tmp_compare_right_1, 2, tmp_tuple_element_1 ); tmp_exc_match_exception_match_1 = EXCEPTION_MATCH_BOOL( tmp_compare_left_1, tmp_compare_right_1 ); if ( tmp_exc_match_exception_match_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_compare_right_1 ); exception_lineno = 95; type_description_1 = "oooo"; goto try_except_handler_5; } Py_DECREF( tmp_compare_right_1 ); if ( tmp_exc_match_exception_match_1 == 1 ) { goto branch_yes_1; } else { goto branch_no_1; } branch_yes_1:; tmp_assign_source_7 = Py_False; assert( var_supported == NULL ); Py_INCREF( tmp_assign_source_7 ); var_supported = tmp_assign_source_7; goto branch_end_1; branch_no_1:; tmp_result = RERAISE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); if (unlikely( tmp_result == false )) { exception_lineno = 92; } if (exception_tb && exception_tb->tb_frame == &frame_7f1d67953d1486ada0ef5501b0312cae->m_frame) frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = exception_tb->tb_lineno; type_description_1 = "oooo"; goto try_except_handler_5; branch_end_1:; goto try_end_2; // Exception handler code: try_except_handler_5:; exception_keeper_type_2 = exception_type; exception_keeper_value_2 = exception_value; exception_keeper_tb_2 = exception_tb; exception_keeper_lineno_2 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; // Restore previous exception. SET_CURRENT_EXCEPTION( exception_preserved_type_1, exception_preserved_value_1, exception_preserved_tb_1 ); // Re-raise. exception_type = exception_keeper_type_2; exception_value = exception_keeper_value_2; exception_tb = exception_keeper_tb_2; exception_lineno = exception_keeper_lineno_2; goto try_except_handler_3; // End of try: try_end_2:; // Restore previous exception. SET_CURRENT_EXCEPTION( exception_preserved_type_1, exception_preserved_value_1, exception_preserved_tb_1 ); goto try_end_1; // exception handler codes exits in all cases NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported ); return NULL; // End of try: try_end_1:; tmp_compare_left_2 = tmp_try_except_1__unhandled_indicator; CHECK_OBJECT( tmp_compare_left_2 ); tmp_compare_right_2 = Py_True; tmp_is_1 = ( tmp_compare_left_2 == tmp_compare_right_2 ); if ( tmp_is_1 ) { goto branch_yes_2; } else { goto branch_no_2; } branch_yes_2:; tmp_source_name_7 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os ); if (unlikely( tmp_source_name_7 == NULL )) { tmp_source_name_7 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os ); } if ( tmp_source_name_7 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 98; type_description_1 = "oooo"; goto try_except_handler_3; } tmp_called_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_7, const_str_plain_remove ); if ( tmp_called_name_5 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 98; type_description_1 = "oooo"; goto try_except_handler_3; } tmp_args_element_name_8 = var_symlink_path; if ( tmp_args_element_name_8 == NULL ) { Py_DECREF( tmp_called_name_5 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "symlink_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 98; type_description_1 = "oooo"; goto try_except_handler_3; } frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 98; { PyObject *call_args[] = { tmp_args_element_name_8 }; tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_5, call_args ); } Py_DECREF( tmp_called_name_5 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 98; type_description_1 = "oooo"; goto try_except_handler_3; } Py_DECREF( tmp_unused ); branch_no_2:; goto try_end_3; // Exception handler code: try_except_handler_3:; exception_keeper_type_3 = exception_type; exception_keeper_value_3 = exception_value; exception_keeper_tb_3 = exception_tb; exception_keeper_lineno_3 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_try_except_1__unhandled_indicator ); tmp_try_except_1__unhandled_indicator = NULL; // Re-raise. exception_type = exception_keeper_type_3; exception_value = exception_keeper_value_3; exception_tb = exception_keeper_tb_3; exception_lineno = exception_keeper_lineno_3; goto try_except_handler_2; // End of try: try_end_3:; goto try_end_4; // Exception handler code: try_except_handler_2:; exception_keeper_type_4 = exception_type; exception_keeper_value_4 = exception_value; exception_keeper_tb_4 = exception_tb; exception_keeper_lineno_4 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; // Preserve existing published exception. exception_preserved_type_2 = PyThreadState_GET()->exc_type; Py_XINCREF( exception_preserved_type_2 ); exception_preserved_value_2 = PyThreadState_GET()->exc_value; Py_XINCREF( exception_preserved_value_2 ); exception_preserved_tb_2 = (PyTracebackObject *)PyThreadState_GET()->exc_traceback; Py_XINCREF( exception_preserved_tb_2 ); if ( exception_keeper_tb_4 == NULL ) { exception_keeper_tb_4 = MAKE_TRACEBACK( frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_4 ); } else if ( exception_keeper_lineno_4 != 0 ) { exception_keeper_tb_4 = ADD_TRACEBACK( exception_keeper_tb_4, frame_7f1d67953d1486ada0ef5501b0312cae, exception_keeper_lineno_4 ); } NORMALIZE_EXCEPTION( &exception_keeper_type_4, &exception_keeper_value_4, &exception_keeper_tb_4 ); PyException_SetTraceback( exception_keeper_value_4, (PyObject *)exception_keeper_tb_4 ); PUBLISH_EXCEPTION( &exception_keeper_type_4, &exception_keeper_value_4, &exception_keeper_tb_4 ); // Tried code: tmp_source_name_8 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os ); if (unlikely( tmp_source_name_8 == NULL )) { tmp_source_name_8 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os ); } if ( tmp_source_name_8 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 100; type_description_1 = "oooo"; goto try_except_handler_6; } tmp_called_name_6 = LOOKUP_ATTRIBUTE( tmp_source_name_8, const_str_plain_rmdir ); if ( tmp_called_name_6 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 100; type_description_1 = "oooo"; goto try_except_handler_6; } tmp_args_element_name_9 = var_original_path; if ( tmp_args_element_name_9 == NULL ) { Py_DECREF( tmp_called_name_6 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 100; type_description_1 = "oooo"; goto try_except_handler_6; } frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 100; { PyObject *call_args[] = { tmp_args_element_name_9 }; tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_6, call_args ); } Py_DECREF( tmp_called_name_6 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 100; type_description_1 = "oooo"; goto try_except_handler_6; } Py_DECREF( tmp_unused ); tmp_source_name_9 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os ); if (unlikely( tmp_source_name_9 == NULL )) { tmp_source_name_9 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os ); } if ( tmp_source_name_9 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 101; type_description_1 = "oooo"; goto try_except_handler_6; } tmp_called_name_7 = LOOKUP_ATTRIBUTE( tmp_source_name_9, const_str_plain_rmdir ); if ( tmp_called_name_7 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 101; type_description_1 = "oooo"; goto try_except_handler_6; } tmp_args_element_name_10 = var_tmpdir; if ( tmp_args_element_name_10 == NULL ) { Py_DECREF( tmp_called_name_7 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 101; type_description_1 = "oooo"; goto try_except_handler_6; } frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 101; { PyObject *call_args[] = { tmp_args_element_name_10 }; tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_7, call_args ); } Py_DECREF( tmp_called_name_7 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 101; type_description_1 = "oooo"; goto try_except_handler_6; } Py_DECREF( tmp_unused ); tmp_return_value = var_supported; if ( tmp_return_value == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "supported" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 102; type_description_1 = "oooo"; goto try_except_handler_6; } Py_INCREF( tmp_return_value ); goto try_return_handler_6; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported ); return NULL; // Return handler code: try_return_handler_6:; // Restore previous exception. SET_CURRENT_EXCEPTION( exception_preserved_type_2, exception_preserved_value_2, exception_preserved_tb_2 ); goto frame_return_exit_1; // Exception handler code: try_except_handler_6:; exception_keeper_type_5 = exception_type; exception_keeper_value_5 = exception_value; exception_keeper_tb_5 = exception_tb; exception_keeper_lineno_5 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; // Restore previous exception. SET_CURRENT_EXCEPTION( exception_preserved_type_2, exception_preserved_value_2, exception_preserved_tb_2 ); // Re-raise. exception_type = exception_keeper_type_5; exception_value = exception_keeper_value_5; exception_tb = exception_keeper_tb_5; exception_lineno = exception_keeper_lineno_5; goto frame_exception_exit_1; // End of try: // End of try: try_end_4:; Py_XDECREF( tmp_try_except_1__unhandled_indicator ); tmp_try_except_1__unhandled_indicator = NULL; tmp_source_name_10 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os ); if (unlikely( tmp_source_name_10 == NULL )) { tmp_source_name_10 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os ); } if ( tmp_source_name_10 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 100; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_called_name_8 = LOOKUP_ATTRIBUTE( tmp_source_name_10, const_str_plain_rmdir ); if ( tmp_called_name_8 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 100; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_11 = var_original_path; if ( tmp_args_element_name_11 == NULL ) { Py_DECREF( tmp_called_name_8 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_path" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 100; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 100; { PyObject *call_args[] = { tmp_args_element_name_11 }; tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_8, call_args ); } Py_DECREF( tmp_called_name_8 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 100; type_description_1 = "oooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_unused ); tmp_source_name_11 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os ); if (unlikely( tmp_source_name_11 == NULL )) { tmp_source_name_11 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os ); } if ( tmp_source_name_11 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 101; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_called_name_9 = LOOKUP_ATTRIBUTE( tmp_source_name_11, const_str_plain_rmdir ); if ( tmp_called_name_9 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 101; type_description_1 = "oooo"; goto frame_exception_exit_1; } tmp_args_element_name_12 = var_tmpdir; if ( tmp_args_element_name_12 == NULL ) { Py_DECREF( tmp_called_name_9 ); exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "tmpdir" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 101; type_description_1 = "oooo"; goto frame_exception_exit_1; } frame_7f1d67953d1486ada0ef5501b0312cae->m_frame.f_lineno = 101; { PyObject *call_args[] = { tmp_args_element_name_12 }; tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_9, call_args ); } Py_DECREF( tmp_called_name_9 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 101; type_description_1 = "oooo"; goto frame_exception_exit_1; } Py_DECREF( tmp_unused ); tmp_return_value = var_supported; if ( tmp_return_value == NULL ) { exception_type = PyExc_UnboundLocalError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "supported" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 102; type_description_1 = "oooo"; goto frame_exception_exit_1; } Py_INCREF( tmp_return_value ); goto frame_return_exit_1; #if 1 RESTORE_FRAME_EXCEPTION( frame_7f1d67953d1486ada0ef5501b0312cae ); #endif // Put the previous frame back on top. popFrameStack(); goto frame_no_exception_1; frame_return_exit_1:; #if 1 RESTORE_FRAME_EXCEPTION( frame_7f1d67953d1486ada0ef5501b0312cae ); #endif // Put the previous frame back on top. popFrameStack(); goto try_return_handler_1; frame_exception_exit_1:; #if 1 RESTORE_FRAME_EXCEPTION( frame_7f1d67953d1486ada0ef5501b0312cae ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_7f1d67953d1486ada0ef5501b0312cae, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_7f1d67953d1486ada0ef5501b0312cae->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_7f1d67953d1486ada0ef5501b0312cae, exception_lineno ); } // Attachs locals to frame if any. Nuitka_Frame_AttachLocals( (struct Nuitka_FrameObject *)frame_7f1d67953d1486ada0ef5501b0312cae, type_description_1, var_tmpdir, var_original_path, var_symlink_path, var_supported ); // Release cached frame. if ( frame_7f1d67953d1486ada0ef5501b0312cae == cache_frame_7f1d67953d1486ada0ef5501b0312cae ) { Py_DECREF( frame_7f1d67953d1486ada0ef5501b0312cae ); } cache_frame_7f1d67953d1486ada0ef5501b0312cae = NULL; assertFrameObject( frame_7f1d67953d1486ada0ef5501b0312cae ); // Put the previous frame back on top. popFrameStack(); // Return the error. goto try_except_handler_1; frame_no_exception_1:; // tried codes exits in all cases NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported ); return NULL; // Return handler code: try_return_handler_1:; Py_XDECREF( var_tmpdir ); var_tmpdir = NULL; Py_XDECREF( var_original_path ); var_original_path = NULL; Py_XDECREF( var_symlink_path ); var_symlink_path = NULL; Py_XDECREF( var_supported ); var_supported = NULL; goto function_return_exit; // Exception handler code: try_except_handler_1:; exception_keeper_type_6 = exception_type; exception_keeper_value_6 = exception_value; exception_keeper_tb_6 = exception_tb; exception_keeper_lineno_6 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( var_tmpdir ); var_tmpdir = NULL; Py_XDECREF( var_original_path ); var_original_path = NULL; Py_XDECREF( var_symlink_path ); var_symlink_path = NULL; Py_XDECREF( var_supported ); var_supported = NULL; // Re-raise. exception_type = exception_keeper_type_6; exception_value = exception_keeper_value_6; exception_tb = exception_keeper_tb_6; exception_lineno = exception_keeper_lineno_6; goto function_exception_exit; // End of try: // Return statement must have exited already. NUITKA_CANNOT_GET_HERE( django$utils$_os$$$function_5_symlinks_supported ); return NULL; function_exception_exit: assert( exception_type ); RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return NULL; function_return_exit: CHECK_OBJECT( tmp_return_value ); assert( had_error || !ERROR_OCCURRED() ); return tmp_return_value; } static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_1_abspathu( ) { struct Nuitka_FunctionObject *result = Nuitka_Function_New( impl_django$utils$_os$$$function_1_abspathu, const_str_plain_abspathu, #if PYTHON_VERSION >= 330 NULL, #endif codeobj_8338c887cffee3f6624948b93fdb5cad, NULL, #if PYTHON_VERSION >= 300 NULL, const_dict_empty, #endif module_django$utils$_os, const_str_digest_d92a79f74db4468ebeba34a6c933cb11, 0 ); return (PyObject *)result; } static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_2_upath( ) { struct Nuitka_FunctionObject *result = Nuitka_Function_New( impl_django$utils$_os$$$function_2_upath, const_str_plain_upath, #if PYTHON_VERSION >= 330 NULL, #endif codeobj_786e20e096923522b138dc8044ece5a9, NULL, #if PYTHON_VERSION >= 300 NULL, const_dict_empty, #endif module_django$utils$_os, const_str_digest_e029ae267a3a9a3ffb4d22037d50a89e, 0 ); return (PyObject *)result; } static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_3_npath( ) { struct Nuitka_FunctionObject *result = Nuitka_Function_New( impl_django$utils$_os$$$function_3_npath, const_str_plain_npath, #if PYTHON_VERSION >= 330 NULL, #endif codeobj_f5eb817954879f203f472ef76832ad97, NULL, #if PYTHON_VERSION >= 300 NULL, const_dict_empty, #endif module_django$utils$_os, const_str_digest_5c892843b642786d8376f7cd7a9ec574, 0 ); return (PyObject *)result; } static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_4_safe_join( ) { struct Nuitka_FunctionObject *result = Nuitka_Function_New( impl_django$utils$_os$$$function_4_safe_join, const_str_plain_safe_join, #if PYTHON_VERSION >= 330 NULL, #endif codeobj_519eab41ce47fa2590f6a99ccc08067a, NULL, #if PYTHON_VERSION >= 300 NULL, const_dict_empty, #endif module_django$utils$_os, const_str_digest_02c3b3e14ee51a74c880c9a2312b4dc8, 0 ); return (PyObject *)result; } static PyObject *MAKE_FUNCTION_django$utils$_os$$$function_5_symlinks_supported( ) { struct Nuitka_FunctionObject *result = Nuitka_Function_New( impl_django$utils$_os$$$function_5_symlinks_supported, const_str_plain_symlinks_supported, #if PYTHON_VERSION >= 330 NULL, #endif codeobj_7f1d67953d1486ada0ef5501b0312cae, NULL, #if PYTHON_VERSION >= 300 NULL, const_dict_empty, #endif module_django$utils$_os, const_str_digest_b3b92bc7aa9804266ff219682e3d0112, 0 ); return (PyObject *)result; } #if PYTHON_VERSION >= 300 static struct PyModuleDef mdef_django$utils$_os = { PyModuleDef_HEAD_INIT, "django.utils._os", /* m_name */ NULL, /* m_doc */ -1, /* m_size */ NULL, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif #if PYTHON_VERSION >= 300 extern PyObject *metapath_based_loader; #endif #if PYTHON_VERSION >= 330 extern PyObject *const_str_plain___loader__; #endif extern void _initCompiledCellType(); extern void _initCompiledGeneratorType(); extern void _initCompiledFunctionType(); extern void _initCompiledMethodType(); extern void _initCompiledFrameType(); #if PYTHON_VERSION >= 350 extern void _initCompiledCoroutineTypes(); #endif #if PYTHON_VERSION >= 360 extern void _initCompiledAsyncgenTypes(); #endif // The exported interface to CPython. On import of the module, this function // gets called. It has to have an exact function name, in cases it's a shared // library export. This is hidden behind the MOD_INIT_DECL. MOD_INIT_DECL( django$utils$_os ) { #if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300 static bool _init_done = false; // Modules might be imported repeatedly, which is to be ignored. if ( _init_done ) { return MOD_RETURN_VALUE( module_django$utils$_os ); } else { _init_done = true; } #endif #ifdef _NUITKA_MODULE // In case of a stand alone extension module, need to call initialization // the init here because that's the first and only time we are going to get // called here. // Initialize the constant values used. _initBuiltinModule(); createGlobalConstants(); /* Initialize the compiled types of Nuitka. */ _initCompiledCellType(); _initCompiledGeneratorType(); _initCompiledFunctionType(); _initCompiledMethodType(); _initCompiledFrameType(); #if PYTHON_VERSION >= 350 _initCompiledCoroutineTypes(); #endif #if PYTHON_VERSION >= 360 _initCompiledAsyncgenTypes(); #endif #if PYTHON_VERSION < 300 _initSlotCompare(); #endif #if PYTHON_VERSION >= 270 _initSlotIternext(); #endif patchBuiltinModule(); patchTypeComparison(); // Enable meta path based loader if not already done. setupMetaPathBasedLoader(); #if PYTHON_VERSION >= 300 patchInspectModule(); #endif #endif /* The constants only used by this module are created now. */ #ifdef _NUITKA_TRACE puts("django.utils._os: Calling createModuleConstants()."); #endif createModuleConstants(); /* The code objects used by this module are created now. */ #ifdef _NUITKA_TRACE puts("django.utils._os: Calling createModuleCodeObjects()."); #endif createModuleCodeObjects(); // puts( "in initdjango$utils$_os" ); // Create the module object first. There are no methods initially, all are // added dynamically in actual code only. Also no "__doc__" is initially // set at this time, as it could not contain NUL characters this way, they // are instead set in early module code. No "self" for modules, we have no // use for it. #if PYTHON_VERSION < 300 module_django$utils$_os = Py_InitModule4( "django.utils._os", // Module Name NULL, // No methods initially, all are added // dynamically in actual module code only. NULL, // No __doc__ is initially set, as it could // not contain NUL this way, added early in // actual code. NULL, // No self for modules, we don't use it. PYTHON_API_VERSION ); #else module_django$utils$_os = PyModule_Create( &mdef_django$utils$_os ); #endif moduledict_django$utils$_os = MODULE_DICT( module_django$utils$_os ); CHECK_OBJECT( module_django$utils$_os ); // Seems to work for Python2.7 out of the box, but for Python3, the module // doesn't automatically enter "sys.modules", so do it manually. #if PYTHON_VERSION >= 300 { int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_842dfd4744c6e20ce39943a1591eb59d, module_django$utils$_os ); assert( r != -1 ); } #endif // For deep importing of a module we need to have "__builtins__", so we set // it ourselves in the same way than CPython does. Note: This must be done // before the frame object is allocated, or else it may fail. if ( GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___builtins__ ) == NULL ) { PyObject *value = (PyObject *)builtin_module; // Check if main module, not a dict then but the module itself. #if !defined(_NUITKA_EXE) || !0 value = PyModule_GetDict( value ); #endif UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___builtins__, value ); } #if PYTHON_VERSION >= 330 UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader ); #endif // Temp variables if any PyObject *tmp_import_from_1__module = NULL; PyObject *exception_type = NULL; PyObject *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = 0; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *tmp_args_element_name_1; PyObject *tmp_args_element_name_2; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_assign_source_6; PyObject *tmp_assign_source_7; PyObject *tmp_assign_source_8; PyObject *tmp_assign_source_9; PyObject *tmp_assign_source_10; PyObject *tmp_assign_source_11; PyObject *tmp_assign_source_12; PyObject *tmp_assign_source_13; PyObject *tmp_assign_source_14; PyObject *tmp_assign_source_15; PyObject *tmp_assign_source_16; PyObject *tmp_assign_source_17; PyObject *tmp_assign_source_18; PyObject *tmp_assign_source_19; PyObject *tmp_assign_source_20; PyObject *tmp_assign_source_21; PyObject *tmp_assign_source_22; PyObject *tmp_assign_source_23; PyObject *tmp_assign_source_24; PyObject *tmp_assign_source_25; PyObject *tmp_assign_source_26; PyObject *tmp_assign_source_27; PyObject *tmp_assign_source_28; PyObject *tmp_called_instance_1; PyObject *tmp_called_instance_2; PyObject *tmp_called_name_1; PyObject *tmp_compexpr_left_1; PyObject *tmp_compexpr_right_1; int tmp_cond_truth_1; int tmp_cond_truth_2; PyObject *tmp_cond_value_1; PyObject *tmp_cond_value_2; PyObject *tmp_fromlist_name_1; PyObject *tmp_fromlist_name_2; PyObject *tmp_fromlist_name_3; PyObject *tmp_fromlist_name_4; PyObject *tmp_fromlist_name_5; PyObject *tmp_fromlist_name_6; PyObject *tmp_fromlist_name_7; PyObject *tmp_globals_name_1; PyObject *tmp_globals_name_2; PyObject *tmp_globals_name_3; PyObject *tmp_globals_name_4; PyObject *tmp_globals_name_5; PyObject *tmp_globals_name_6; PyObject *tmp_globals_name_7; PyObject *tmp_import_name_from_1; PyObject *tmp_import_name_from_2; PyObject *tmp_import_name_from_3; PyObject *tmp_import_name_from_4; PyObject *tmp_import_name_from_5; PyObject *tmp_import_name_from_6; PyObject *tmp_import_name_from_7; PyObject *tmp_import_name_from_8; PyObject *tmp_import_name_from_9; PyObject *tmp_import_name_from_10; PyObject *tmp_import_name_from_11; PyObject *tmp_level_name_1; PyObject *tmp_level_name_2; PyObject *tmp_level_name_3; PyObject *tmp_level_name_4; PyObject *tmp_level_name_5; PyObject *tmp_level_name_6; PyObject *tmp_level_name_7; PyObject *tmp_locals_name_1; PyObject *tmp_locals_name_2; PyObject *tmp_locals_name_3; PyObject *tmp_locals_name_4; PyObject *tmp_locals_name_5; PyObject *tmp_locals_name_6; PyObject *tmp_locals_name_7; PyObject *tmp_name_name_1; PyObject *tmp_name_name_2; PyObject *tmp_name_name_3; PyObject *tmp_name_name_4; PyObject *tmp_name_name_5; PyObject *tmp_name_name_6; PyObject *tmp_name_name_7; int tmp_or_left_truth_1; int tmp_or_left_truth_2; PyObject *tmp_or_left_value_1; PyObject *tmp_or_left_value_2; PyObject *tmp_or_right_value_1; PyObject *tmp_or_right_value_2; PyObject *tmp_source_name_1; PyObject *tmp_source_name_2; PyObject *tmp_source_name_3; struct Nuitka_FrameObject *frame_e3f2225c4277cee0cd5878c353c5494a; NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL; // Module code. tmp_assign_source_1 = Py_None; UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 ); tmp_assign_source_2 = module_filename_obj; UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 ); tmp_assign_source_3 = metapath_based_loader; UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_3 ); // Frame without reuse. frame_e3f2225c4277cee0cd5878c353c5494a = MAKE_MODULE_FRAME( codeobj_e3f2225c4277cee0cd5878c353c5494a, module_django$utils$_os ); // Push the new frame as the currently active one, and we should be exclusively // owning it. pushFrameStack( frame_e3f2225c4277cee0cd5878c353c5494a ); assert( Py_REFCNT( frame_e3f2225c4277cee0cd5878c353c5494a ) == 2 ); // Framed code: frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 1; { PyObject *module = PyImport_ImportModule("importlib._bootstrap"); if (likely( module != NULL )) { tmp_called_name_1 = PyObject_GetAttr( module, const_str_plain_ModuleSpec ); } else { tmp_called_name_1 = NULL; } } if ( tmp_called_name_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 1; goto frame_exception_exit_1; } tmp_args_element_name_1 = const_str_digest_842dfd4744c6e20ce39943a1591eb59d; tmp_args_element_name_2 = metapath_based_loader; frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 1; { PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 }; tmp_assign_source_4 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args ); } if ( tmp_assign_source_4 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 1; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_4 ); tmp_assign_source_5 = Py_None; UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_5 ); tmp_assign_source_6 = const_str_digest_467c9722f19d9d40d148689532cdc0b1; UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_6 ); frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 1; tmp_import_name_from_1 = PyImport_ImportModule("__future__"); assert( tmp_import_name_from_1 != NULL ); tmp_assign_source_7 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_unicode_literals ); if ( tmp_assign_source_7 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 1; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_unicode_literals, tmp_assign_source_7 ); tmp_name_name_1 = const_str_plain_os; tmp_globals_name_1 = (PyObject *)moduledict_django$utils$_os; tmp_locals_name_1 = Py_None; tmp_fromlist_name_1 = Py_None; tmp_level_name_1 = const_int_0; frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 3; tmp_assign_source_8 = IMPORT_MODULE5( tmp_name_name_1, tmp_globals_name_1, tmp_locals_name_1, tmp_fromlist_name_1, tmp_level_name_1 ); if ( tmp_assign_source_8 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 3; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os, tmp_assign_source_8 ); tmp_name_name_2 = const_str_plain_sys; tmp_globals_name_2 = (PyObject *)moduledict_django$utils$_os; tmp_locals_name_2 = Py_None; tmp_fromlist_name_2 = Py_None; tmp_level_name_2 = const_int_0; frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 4; tmp_assign_source_9 = IMPORT_MODULE5( tmp_name_name_2, tmp_globals_name_2, tmp_locals_name_2, tmp_fromlist_name_2, tmp_level_name_2 ); assert( tmp_assign_source_9 != NULL ); UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sys, tmp_assign_source_9 ); tmp_name_name_3 = const_str_plain_tempfile; tmp_globals_name_3 = (PyObject *)moduledict_django$utils$_os; tmp_locals_name_3 = Py_None; tmp_fromlist_name_3 = Py_None; tmp_level_name_3 = const_int_0; frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 5; tmp_assign_source_10 = IMPORT_MODULE5( tmp_name_name_3, tmp_globals_name_3, tmp_locals_name_3, tmp_fromlist_name_3, tmp_level_name_3 ); if ( tmp_assign_source_10 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 5; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_tempfile, tmp_assign_source_10 ); tmp_name_name_4 = const_str_digest_e399ba4554180f37de594a6743234f17; tmp_globals_name_4 = (PyObject *)moduledict_django$utils$_os; tmp_locals_name_4 = Py_None; tmp_fromlist_name_4 = const_tuple_b212215a1d5bdcf7deec7f4b12b6825d_tuple; tmp_level_name_4 = const_int_0; frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 6; tmp_assign_source_11 = IMPORT_MODULE5( tmp_name_name_4, tmp_globals_name_4, tmp_locals_name_4, tmp_fromlist_name_4, tmp_level_name_4 ); if ( tmp_assign_source_11 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 6; goto frame_exception_exit_1; } assert( tmp_import_from_1__module == NULL ); tmp_import_from_1__module = tmp_assign_source_11; // Tried code: tmp_import_name_from_2 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_2 ); tmp_assign_source_12 = IMPORT_NAME( tmp_import_name_from_2, const_str_plain_abspath ); if ( tmp_assign_source_12 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 6; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspath, tmp_assign_source_12 ); tmp_import_name_from_3 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_3 ); tmp_assign_source_13 = IMPORT_NAME( tmp_import_name_from_3, const_str_plain_dirname ); if ( tmp_assign_source_13 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 6; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_dirname, tmp_assign_source_13 ); tmp_import_name_from_4 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_4 ); tmp_assign_source_14 = IMPORT_NAME( tmp_import_name_from_4, const_str_plain_isabs ); if ( tmp_assign_source_14 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 6; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_isabs, tmp_assign_source_14 ); tmp_import_name_from_5 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_5 ); tmp_assign_source_15 = IMPORT_NAME( tmp_import_name_from_5, const_str_plain_join ); if ( tmp_assign_source_15 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 6; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_join, tmp_assign_source_15 ); tmp_import_name_from_6 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_6 ); tmp_assign_source_16 = IMPORT_NAME( tmp_import_name_from_6, const_str_plain_normcase ); if ( tmp_assign_source_16 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 6; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normcase, tmp_assign_source_16 ); tmp_import_name_from_7 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_7 ); tmp_assign_source_17 = IMPORT_NAME( tmp_import_name_from_7, const_str_plain_normpath ); if ( tmp_assign_source_17 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 6; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_normpath, tmp_assign_source_17 ); tmp_import_name_from_8 = tmp_import_from_1__module; CHECK_OBJECT( tmp_import_name_from_8 ); tmp_assign_source_18 = IMPORT_NAME( tmp_import_name_from_8, const_str_plain_sep ); if ( tmp_assign_source_18 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 6; goto try_except_handler_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sep, tmp_assign_source_18 ); goto try_end_1; // Exception handler code: try_except_handler_1:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = 0; Py_XDECREF( tmp_import_from_1__module ); tmp_import_from_1__module = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto frame_exception_exit_1; // End of try: try_end_1:; Py_XDECREF( tmp_import_from_1__module ); tmp_import_from_1__module = NULL; tmp_name_name_5 = const_str_digest_dfb6e1abbed3113ee07234fdc458a320; tmp_globals_name_5 = (PyObject *)moduledict_django$utils$_os; tmp_locals_name_5 = Py_None; tmp_fromlist_name_5 = const_tuple_str_plain_SuspiciousFileOperation_tuple; tmp_level_name_5 = const_int_0; frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 8; tmp_import_name_from_9 = IMPORT_MODULE5( tmp_name_name_5, tmp_globals_name_5, tmp_locals_name_5, tmp_fromlist_name_5, tmp_level_name_5 ); if ( tmp_import_name_from_9 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 8; goto frame_exception_exit_1; } tmp_assign_source_19 = IMPORT_NAME( tmp_import_name_from_9, const_str_plain_SuspiciousFileOperation ); Py_DECREF( tmp_import_name_from_9 ); if ( tmp_assign_source_19 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 8; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_SuspiciousFileOperation, tmp_assign_source_19 ); tmp_name_name_6 = const_str_digest_467c9722f19d9d40d148689532cdc0b1; tmp_globals_name_6 = (PyObject *)moduledict_django$utils$_os; tmp_locals_name_6 = Py_None; tmp_fromlist_name_6 = const_tuple_str_plain_six_tuple; tmp_level_name_6 = const_int_0; frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 9; tmp_import_name_from_10 = IMPORT_MODULE5( tmp_name_name_6, tmp_globals_name_6, tmp_locals_name_6, tmp_fromlist_name_6, tmp_level_name_6 ); if ( tmp_import_name_from_10 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 9; goto frame_exception_exit_1; } tmp_assign_source_20 = IMPORT_NAME( tmp_import_name_from_10, const_str_plain_six ); Py_DECREF( tmp_import_name_from_10 ); if ( tmp_assign_source_20 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 9; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six, tmp_assign_source_20 ); tmp_name_name_7 = const_str_digest_e3393b2e61653c3df2c7d436c253bbee; tmp_globals_name_7 = (PyObject *)moduledict_django$utils$_os; tmp_locals_name_7 = Py_None; tmp_fromlist_name_7 = const_tuple_str_plain_force_text_tuple; tmp_level_name_7 = const_int_0; frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 10; tmp_import_name_from_11 = IMPORT_MODULE5( tmp_name_name_7, tmp_globals_name_7, tmp_locals_name_7, tmp_fromlist_name_7, tmp_level_name_7 ); if ( tmp_import_name_from_11 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 10; goto frame_exception_exit_1; } tmp_assign_source_21 = IMPORT_NAME( tmp_import_name_from_11, const_str_plain_force_text ); Py_DECREF( tmp_import_name_from_11 ); if ( tmp_assign_source_21 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 10; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_force_text, tmp_assign_source_21 ); tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six ); if (unlikely( tmp_source_name_1 == NULL )) { tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six ); } if ( tmp_source_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 12; goto frame_exception_exit_1; } tmp_cond_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_PY2 ); if ( tmp_cond_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 12; goto frame_exception_exit_1; } tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_cond_value_1 ); exception_lineno = 12; goto frame_exception_exit_1; } Py_DECREF( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == 1 ) { goto branch_yes_1; } else { goto branch_no_1; } branch_yes_1:; tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sys ); if (unlikely( tmp_called_instance_1 == NULL )) { tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_sys ); } if ( tmp_called_instance_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "sys" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 13; goto frame_exception_exit_1; } frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 13; tmp_or_left_value_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_1, const_str_plain_getfilesystemencoding ); if ( tmp_or_left_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 13; goto frame_exception_exit_1; } tmp_or_left_truth_1 = CHECK_IF_TRUE( tmp_or_left_value_1 ); if ( tmp_or_left_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_or_left_value_1 ); exception_lineno = 13; goto frame_exception_exit_1; } if ( tmp_or_left_truth_1 == 1 ) { goto or_left_1; } else { goto or_right_1; } or_right_1:; Py_DECREF( tmp_or_left_value_1 ); tmp_called_instance_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_sys ); if (unlikely( tmp_called_instance_2 == NULL )) { tmp_called_instance_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_sys ); } if ( tmp_called_instance_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "sys" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 13; goto frame_exception_exit_1; } frame_e3f2225c4277cee0cd5878c353c5494a->m_frame.f_lineno = 13; tmp_or_right_value_1 = CALL_METHOD_NO_ARGS( tmp_called_instance_2, const_str_plain_getdefaultencoding ); if ( tmp_or_right_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 13; goto frame_exception_exit_1; } tmp_assign_source_22 = tmp_or_right_value_1; goto or_end_1; or_left_1:; tmp_assign_source_22 = tmp_or_left_value_1; or_end_1:; UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_fs_encoding, tmp_assign_source_22 ); branch_no_1:; tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_six ); if (unlikely( tmp_source_name_2 == NULL )) { tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_six ); } if ( tmp_source_name_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "six" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 21; goto frame_exception_exit_1; } tmp_or_left_value_2 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_PY3 ); if ( tmp_or_left_value_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 21; goto frame_exception_exit_1; } tmp_or_left_truth_2 = CHECK_IF_TRUE( tmp_or_left_value_2 ); if ( tmp_or_left_truth_2 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_or_left_value_2 ); exception_lineno = 21; goto frame_exception_exit_1; } if ( tmp_or_left_truth_2 == 1 ) { goto or_left_2; } else { goto or_right_2; } or_right_2:; Py_DECREF( tmp_or_left_value_2 ); tmp_source_name_3 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_os ); if (unlikely( tmp_source_name_3 == NULL )) { tmp_source_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_os ); } if ( tmp_source_name_3 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "os" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 21; goto frame_exception_exit_1; } tmp_compexpr_left_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_name ); if ( tmp_compexpr_left_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 21; goto frame_exception_exit_1; } tmp_compexpr_right_1 = const_str_plain_nt; tmp_or_right_value_2 = RICH_COMPARE_EQ_NORECURSE( tmp_compexpr_left_1, tmp_compexpr_right_1 ); Py_DECREF( tmp_compexpr_left_1 ); if ( tmp_or_right_value_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 21; goto frame_exception_exit_1; } tmp_cond_value_2 = tmp_or_right_value_2; goto or_end_2; or_left_2:; tmp_cond_value_2 = tmp_or_left_value_2; or_end_2:; tmp_cond_truth_2 = CHECK_IF_TRUE( tmp_cond_value_2 ); if ( tmp_cond_truth_2 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_cond_value_2 ); exception_lineno = 21; goto frame_exception_exit_1; } Py_DECREF( tmp_cond_value_2 ); if ( tmp_cond_truth_2 == 1 ) { goto branch_yes_2; } else { goto branch_no_2; } branch_yes_2:; tmp_assign_source_23 = GET_STRING_DICT_VALUE( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspath ); if (unlikely( tmp_assign_source_23 == NULL )) { tmp_assign_source_23 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_abspath ); } if ( tmp_assign_source_23 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "abspath" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 22; goto frame_exception_exit_1; } UPDATE_STRING_DICT0( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu, tmp_assign_source_23 ); goto branch_end_2; branch_no_2:; tmp_assign_source_24 = MAKE_FUNCTION_django$utils$_os$$$function_1_abspathu( ); UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_abspathu, tmp_assign_source_24 ); branch_end_2:; // Restore frame exception if necessary. #if 0 RESTORE_FRAME_EXCEPTION( frame_e3f2225c4277cee0cd5878c353c5494a ); #endif popFrameStack(); assertFrameObject( frame_e3f2225c4277cee0cd5878c353c5494a ); goto frame_no_exception_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_e3f2225c4277cee0cd5878c353c5494a ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_e3f2225c4277cee0cd5878c353c5494a, exception_lineno ); } else if ( exception_tb->tb_frame != &frame_e3f2225c4277cee0cd5878c353c5494a->m_frame ) { exception_tb = ADD_TRACEBACK( exception_tb, frame_e3f2225c4277cee0cd5878c353c5494a, exception_lineno ); } // Put the previous frame back on top. popFrameStack(); // Return the error. goto module_exception_exit; frame_no_exception_1:; tmp_assign_source_25 = MAKE_FUNCTION_django$utils$_os$$$function_2_upath( ); UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_upath, tmp_assign_source_25 ); tmp_assign_source_26 = MAKE_FUNCTION_django$utils$_os$$$function_3_npath( ); UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_npath, tmp_assign_source_26 ); tmp_assign_source_27 = MAKE_FUNCTION_django$utils$_os$$$function_4_safe_join( ); UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_safe_join, tmp_assign_source_27 ); tmp_assign_source_28 = MAKE_FUNCTION_django$utils$_os$$$function_5_symlinks_supported( ); UPDATE_STRING_DICT1( moduledict_django$utils$_os, (Nuitka_StringObject *)const_str_plain_symlinks_supported, tmp_assign_source_28 ); return MOD_RETURN_VALUE( module_django$utils$_os ); module_exception_exit: RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return MOD_RETURN_VALUE( NULL ); }
33.741102
255
0.714514
Pckool
f13f7aaa59f43d9abf2c92c59d09202cf868232e
1,842
cc
C++
core/paddlefl_mpc/mpc_protocol/network/mesh_network_test.cc
barrierye/PaddleFL
eff6ef28491fa2011686ca3daa4f680e5ef83deb
[ "Apache-2.0" ]
379
2019-09-27T14:26:42.000Z
2022-03-29T14:28:12.000Z
core/paddlefl_mpc/mpc_protocol/network/mesh_network_test.cc
Sprate/PaddleFL
583691acd5db0a7ca331cc9a72415017b18669b8
[ "Apache-2.0" ]
132
2019-10-16T03:22:03.000Z
2022-03-23T08:54:29.000Z
core/paddlefl_mpc/mpc_protocol/network/mesh_network_test.cc
Sprate/PaddleFL
583691acd5db0a7ca331cc9a72415017b18669b8
[ "Apache-2.0" ]
106
2019-09-27T12:47:18.000Z
2022-03-29T09:07:25.000Z
// Copyright (c) 2020 PaddlePaddle Authors. 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 "core/paddlefl_mpc/mpc_protocol/network/mesh_network.h" #include <thread> #include "gtest/gtest.h" namespace paddle { namespace mpc { class NetworkTest : public ::testing::Test { public: std::string _addr; std::string _prefix; std::shared_ptr<gloo::rendezvous::HashStore> _store; MeshNetwork _n0; MeshNetwork _n1; AbstractNetwork *_p0; AbstractNetwork *_p1; NetworkTest() : _addr("127.0.0.1"), _prefix("test_prefix"), _store(std::make_shared<gloo::rendezvous::HashStore>()), _n0(0, _addr, 2, _prefix, _store), _n1(1, _addr, 2, _prefix, _store), _p0(&_n0), _p1(&_n1) {} void SetUp() { std::thread t0([this]() { _n0.init(); }); std::thread t1([this]() { _n1.init(); }); t0.join(); t1.join(); } }; TEST_F(NetworkTest, basic_test) { int buf[2] = {0, 1}; std::thread t0([this, &buf]() { _p0->template send(1, buf[0]); buf[0] = _p0->template recv<int>(1); }); std::thread t1([this, &buf]() { int to_send = buf[1]; buf[1] = _p1->template recv<int>(0); _p1->template send(0, to_send); }); t0.join(); t1.join(); EXPECT_EQ(1, buf[0]); EXPECT_EQ(0, buf[1]); } } // namespace mpc } // namespace paddle
24.891892
77
0.652552
barrierye
f13fc487d8527459ed97e5c7d6f4c59b8252446b
24,584
cpp
C++
Source/Controls/TextEditorPackage/GuiTextCommonInterface.cpp
JamesLinus/GacUI
b16f5919e03d5e24cb1e4509111e12aa28e6b827
[ "MS-PL" ]
1
2019-04-22T09:09:37.000Z
2019-04-22T09:09:37.000Z
Source/Controls/TextEditorPackage/GuiTextCommonInterface.cpp
JamesLinus/GacUI
b16f5919e03d5e24cb1e4509111e12aa28e6b827
[ "MS-PL" ]
null
null
null
Source/Controls/TextEditorPackage/GuiTextCommonInterface.cpp
JamesLinus/GacUI
b16f5919e03d5e24cb1e4509111e12aa28e6b827
[ "MS-PL" ]
null
null
null
#include "GuiTextCommonInterface.h" #include <math.h> namespace vl { namespace presentation { namespace controls { using namespace elements; using namespace elements::text; using namespace compositions; /*********************************************************************** GuiTextBoxCommonInterface::DefaultCallback ***********************************************************************/ GuiTextBoxCommonInterface::DefaultCallback::DefaultCallback(elements::GuiColorizedTextElement* _textElement, compositions::GuiGraphicsComposition* _textComposition) :textElement(_textElement) ,textComposition(_textComposition) { } GuiTextBoxCommonInterface::DefaultCallback::~DefaultCallback() { } TextPos GuiTextBoxCommonInterface::DefaultCallback::GetLeftWord(TextPos pos) { return pos; } TextPos GuiTextBoxCommonInterface::DefaultCallback::GetRightWord(TextPos pos) { return pos; } void GuiTextBoxCommonInterface::DefaultCallback::GetWord(TextPos pos, TextPos& begin, TextPos& end) { begin=pos; end=pos; } vint GuiTextBoxCommonInterface::DefaultCallback::GetPageRows() { return textComposition->GetBounds().Height()/textElement->GetLines().GetRowHeight(); } bool GuiTextBoxCommonInterface::DefaultCallback::BeforeModify(TextPos start, TextPos end, const WString& originalText, WString& inputText) { return true; } /*********************************************************************** GuiTextBoxCommonInterface ***********************************************************************/ void GuiTextBoxCommonInterface::UpdateCaretPoint() { GuiGraphicsHost* host=textComposition->GetRelatedGraphicsHost(); if(host) { Rect caret=textElement->GetLines().GetRectFromTextPos(textElement->GetCaretEnd()); Point view=textElement->GetViewPosition(); vint x=caret.x1-view.x; vint y=caret.y2-view.y; host->SetCaretPoint(Point(x, y), textComposition); } } void GuiTextBoxCommonInterface::Move(TextPos pos, bool shift) { TextPos oldBegin=textElement->GetCaretBegin(); TextPos oldEnd=textElement->GetCaretEnd(); pos=textElement->GetLines().Normalize(pos); if(!shift) { textElement->SetCaretBegin(pos); } textElement->SetCaretEnd(pos); if(textControl) { GuiGraphicsHost* host=textComposition->GetRelatedGraphicsHost(); if(host) { if(host->GetFocusedComposition()==textControl->GetFocusableComposition()) { textElement->SetCaretVisible(true); } } } Rect bounds=textElement->GetLines().GetRectFromTextPos(pos); Rect view=Rect(textElement->GetViewPosition(), textComposition->GetBounds().GetSize()); Point viewPoint=view.LeftTop(); if(view.x2>view.x1 && view.y2>view.y1) { if(bounds.x1<view.x1) { viewPoint.x=bounds.x1; } else if(bounds.x2>view.x2) { viewPoint.x=bounds.x2-view.Width(); } if(bounds.y1<view.y1) { viewPoint.y=bounds.y1; } else if(bounds.y2>view.y2) { viewPoint.y=bounds.y2-view.Height(); } } callback->ScrollToView(viewPoint); UpdateCaretPoint(); TextPos newBegin=textElement->GetCaretBegin(); TextPos newEnd=textElement->GetCaretEnd(); if(oldBegin!=newBegin || oldEnd!=newEnd) { ICommonTextEditCallback::TextCaretChangedStruct arguments; arguments.oldBegin=oldBegin; arguments.oldEnd=oldEnd; arguments.newBegin=newBegin; arguments.newEnd=newEnd; arguments.editVersion=editVersion; for(vint i=0;i<textEditCallbacks.Count();i++) { textEditCallbacks[i]->TextCaretChanged(arguments); } SelectionChanged.Execute(textControl->GetNotifyEventArguments()); } } void GuiTextBoxCommonInterface::Modify(TextPos start, TextPos end, const WString& input, bool asKeyInput) { if(start>end) { TextPos temp=start; start=end; end=temp; } TextPos originalStart=start; TextPos originalEnd=end; WString originalText=textElement->GetLines().GetText(start, end); WString inputText=input; if(callback->BeforeModify(start, end, originalText, inputText)) { { ICommonTextEditCallback::TextEditPreviewStruct arguments; arguments.originalStart=originalStart; arguments.originalEnd=originalEnd; arguments.originalText=originalText; arguments.inputText=inputText; arguments.editVersion=editVersion; arguments.keyInput=asKeyInput; for(vint i=0;i<textEditCallbacks.Count();i++) { textEditCallbacks[i]->TextEditPreview(arguments); } inputText=arguments.inputText; if(originalStart!=arguments.originalStart || originalEnd!=arguments.originalEnd) { originalStart=arguments.originalStart; originalEnd=arguments.originalEnd; originalText=textElement->GetLines().GetText(originalStart, originalEnd); start=originalStart; end=originalEnd; } } SPIN_LOCK(elementModifyLock) { end=textElement->GetLines().Modify(start, end, inputText); } callback->AfterModify(originalStart, originalEnd, originalText, start, end, inputText); editVersion++; { ICommonTextEditCallback::TextEditNotifyStruct arguments; arguments.originalStart=originalStart; arguments.originalEnd=originalEnd; arguments.originalText=originalText; arguments.inputStart=start; arguments.inputEnd=end; arguments.inputText=inputText; arguments.editVersion=editVersion; arguments.keyInput=asKeyInput; for(vint i=0;i<textEditCallbacks.Count();i++) { textEditCallbacks[i]->TextEditNotify(arguments); } } Move(end, false); for(vint i=0;i<textEditCallbacks.Count();i++) { textEditCallbacks[i]->TextEditFinished(editVersion); } textControl->TextChanged.Execute(textControl->GetNotifyEventArguments()); } } bool GuiTextBoxCommonInterface::ProcessKey(vint code, bool shift, bool ctrl) { if(IGuiShortcutKeyItem* item=internalShortcutKeyManager->TryGetShortcut(ctrl, shift, false, code)) { GuiEventArgs arguments; item->Executed.Execute(arguments); return true; } TextPos begin=textElement->GetCaretBegin(); TextPos end=textElement->GetCaretEnd(); switch(code) { case VKEY_ESCAPE: if(autoComplete && autoComplete->IsListOpening() && !shift && !ctrl) { autoComplete->CloseList(); } return true; case VKEY_RETURN: if(autoComplete && autoComplete->IsListOpening() && !shift && !ctrl) { if(autoComplete->ApplySelectedListItem()) { preventEnterDueToAutoComplete=true; return true; } } break; case VKEY_UP: if(autoComplete && autoComplete->IsListOpening() && !shift && !ctrl) { autoComplete->SelectPreviousListItem(); } else { end.row--; Move(end, shift); } return true; case VKEY_DOWN: if(autoComplete && autoComplete->IsListOpening() && !shift && !ctrl) { autoComplete->SelectNextListItem(); } else { end.row++; Move(end, shift); } return true; case VKEY_LEFT: { if(ctrl) { Move(callback->GetLeftWord(end), shift); } else { if(end.column==0) { if(end.row>0) { end.row--; end=textElement->GetLines().Normalize(end); end.column=textElement->GetLines().GetLine(end.row).dataLength; } } else { end.column--; } Move(end, shift); } } return true; case VKEY_RIGHT: { if(ctrl) { Move(callback->GetRightWord(end), shift); } else { if(end.column==textElement->GetLines().GetLine(end.row).dataLength) { if(end.row<textElement->GetLines().GetCount()-1) { end.row++; end.column=0; } } else { end.column++; } Move(end, shift); } } return true; case VKEY_HOME: { if(ctrl) { Move(TextPos(0, 0), shift); } else { end.column=0; Move(end, shift); } } return true; case VKEY_END: { if(ctrl) { end.row=textElement->GetLines().GetCount()-1; } end.column=textElement->GetLines().GetLine(end.row).dataLength; Move(end, shift); } return true; case VKEY_PRIOR: { end.row-=callback->GetPageRows(); Move(end, shift); } return true; case VKEY_NEXT: { end.row+=callback->GetPageRows(); Move(end, shift); } return true; case VKEY_BACK: if(!readonly) { if(ctrl && !shift) { ProcessKey(VKEY_LEFT, true, true); ProcessKey(VKEY_BACK, false, false); } else if(!ctrl && shift) { ProcessKey(VKEY_UP, true, false); ProcessKey(VKEY_BACK, false, false); } else { if(begin==end) { ProcessKey(VKEY_LEFT, true, false); } SetSelectionTextAsKeyInput(L""); } return true; } break; case VKEY_DELETE: if(!readonly) { if(ctrl && !shift) { ProcessKey(VKEY_RIGHT, true, true); ProcessKey(VKEY_DELETE, false, false); } else if(!ctrl && shift) { ProcessKey(VKEY_DOWN, true, false); ProcessKey(VKEY_DELETE, false, false); } else { if(begin==end) { ProcessKey(VKEY_RIGHT, true, false); } SetSelectionTextAsKeyInput(L""); } return true; } break; } return false; } void GuiTextBoxCommonInterface::OnGotFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments) { textElement->SetFocused(true); textElement->SetCaretVisible(true); UpdateCaretPoint(); } void GuiTextBoxCommonInterface::OnLostFocus(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments) { textElement->SetFocused(false); textElement->SetCaretVisible(false); } void GuiTextBoxCommonInterface::OnCaretNotify(compositions::GuiGraphicsComposition* sender, compositions::GuiEventArgs& arguments) { textElement->SetCaretVisible(!textElement->GetCaretVisible()); } void GuiTextBoxCommonInterface::OnLeftButtonDown(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments) { if(textControl->GetVisuallyEnabled() && arguments.compositionSource==arguments.eventSource) { dragging=true; TextPos pos=GetNearestTextPos(Point(arguments.x, arguments.y)); Move(pos, arguments.shift); } } void GuiTextBoxCommonInterface::OnLeftButtonUp(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments) { if(textControl->GetVisuallyEnabled() && arguments.compositionSource==arguments.eventSource) { dragging=false; } } void GuiTextBoxCommonInterface::OnMouseMove(compositions::GuiGraphicsComposition* sender, compositions::GuiMouseEventArgs& arguments) { if(textControl->GetVisuallyEnabled() && arguments.compositionSource==arguments.eventSource) { if(dragging) { TextPos pos=GetNearestTextPos(Point(arguments.x, arguments.y)); Move(pos, true); } } } void GuiTextBoxCommonInterface::OnKeyDown(compositions::GuiGraphicsComposition* sender, compositions::GuiKeyEventArgs& arguments) { if(textControl->GetVisuallyEnabled() && arguments.compositionSource==arguments.eventSource) { if(ProcessKey(arguments.code, arguments.shift, arguments.ctrl)) { arguments.handled=true; } } } void GuiTextBoxCommonInterface::OnCharInput(compositions::GuiGraphicsComposition* sender, compositions::GuiCharEventArgs& arguments) { if(preventEnterDueToAutoComplete) { preventEnterDueToAutoComplete=false; if(arguments.code==VKEY_RETURN) { return; } } if(textControl->GetVisuallyEnabled() && arguments.compositionSource==arguments.eventSource) { if(!readonly && arguments.code!=VKEY_ESCAPE && arguments.code!=VKEY_BACK && !arguments.ctrl) { SetSelectionTextAsKeyInput(WString(arguments.code)); } } } void GuiTextBoxCommonInterface::Install(elements::GuiColorizedTextElement* _textElement, compositions::GuiGraphicsComposition* _textComposition, GuiControl* _textControl) { textElement=_textElement; textComposition=_textComposition; textControl=_textControl; textComposition->SetAssociatedCursor(GetCurrentController()->ResourceService()->GetSystemCursor(INativeCursor::IBeam)); SelectionChanged.SetAssociatedComposition(textControl->GetBoundsComposition()); GuiGraphicsComposition* focusableComposition=textControl->GetFocusableComposition(); focusableComposition->GetEventReceiver()->gotFocus.AttachMethod(this, &GuiTextBoxCommonInterface::OnGotFocus); focusableComposition->GetEventReceiver()->lostFocus.AttachMethod(this, &GuiTextBoxCommonInterface::OnLostFocus); focusableComposition->GetEventReceiver()->caretNotify.AttachMethod(this, &GuiTextBoxCommonInterface::OnCaretNotify); textComposition->GetEventReceiver()->leftButtonDown.AttachMethod(this, &GuiTextBoxCommonInterface::OnLeftButtonDown); textComposition->GetEventReceiver()->leftButtonUp.AttachMethod(this, &GuiTextBoxCommonInterface::OnLeftButtonUp); textComposition->GetEventReceiver()->mouseMove.AttachMethod(this, &GuiTextBoxCommonInterface::OnMouseMove); focusableComposition->GetEventReceiver()->keyDown.AttachMethod(this, &GuiTextBoxCommonInterface::OnKeyDown); focusableComposition->GetEventReceiver()->charInput.AttachMethod(this, &GuiTextBoxCommonInterface::OnCharInput); for(vint i=0;i<textEditCallbacks.Count();i++) { textEditCallbacks[i]->Attach(textElement, elementModifyLock, textComposition ,editVersion); } } GuiTextBoxCommonInterface::ICallback* GuiTextBoxCommonInterface::GetCallback() { return callback; } void GuiTextBoxCommonInterface::SetCallback(ICallback* value) { callback=value; } bool GuiTextBoxCommonInterface::AttachTextEditCallback(Ptr<ICommonTextEditCallback> value) { if(textEditCallbacks.Contains(value.Obj())) { return false; } else { textEditCallbacks.Add(value); if(textElement) { value->Attach(textElement, elementModifyLock, textComposition, editVersion); } return true; } } bool GuiTextBoxCommonInterface::DetachTextEditCallback(Ptr<ICommonTextEditCallback> value) { if(textEditCallbacks.Remove(value.Obj())) { value->Detach(); return true; } else { return false; } } void GuiTextBoxCommonInterface::AddShortcutCommand(vint key, const Func<void()>& eventHandler) { IGuiShortcutKeyItem* item=internalShortcutKeyManager->CreateShortcut(true, false, false, key); item->Executed.AttachLambda([=](GuiGraphicsComposition* sender, GuiEventArgs& arguments) { eventHandler(); }); } elements::GuiColorizedTextElement* GuiTextBoxCommonInterface::GetTextElement() { return textElement; } void GuiTextBoxCommonInterface::UnsafeSetText(const WString& value) { if(textElement) { TextPos end; if(textElement->GetLines().GetCount()>0) { end.row=textElement->GetLines().GetCount()-1; end.column=textElement->GetLines().GetLine(end.row).dataLength; } Modify(TextPos(), end, value, false); } } GuiTextBoxCommonInterface::GuiTextBoxCommonInterface() :textElement(0) ,textComposition(0) ,editVersion(0) ,textControl(0) ,callback(0) ,dragging(false) ,readonly(false) ,preventEnterDueToAutoComplete(false) { undoRedoProcessor=new GuiTextBoxUndoRedoProcessor; AttachTextEditCallback(undoRedoProcessor); internalShortcutKeyManager=new GuiShortcutKeyManager; AddShortcutCommand('Z', Func<bool()>(this, &GuiTextBoxCommonInterface::Undo)); AddShortcutCommand('Y', Func<bool()>(this, &GuiTextBoxCommonInterface::Redo)); AddShortcutCommand('A', Func<void()>(this, &GuiTextBoxCommonInterface::SelectAll)); AddShortcutCommand('X', Func<bool()>(this, &GuiTextBoxCommonInterface::Cut)); AddShortcutCommand('C', Func<bool()>(this, &GuiTextBoxCommonInterface::Copy)); AddShortcutCommand('V', Func<bool()>(this, &GuiTextBoxCommonInterface::Paste)); } GuiTextBoxCommonInterface::~GuiTextBoxCommonInterface() { if(colorizer) { DetachTextEditCallback(colorizer); colorizer=0; } if(undoRedoProcessor) { DetachTextEditCallback(undoRedoProcessor); undoRedoProcessor=0; } for(vint i=0;i<textEditCallbacks.Count();i++) { textEditCallbacks[i]->Detach(); } textEditCallbacks.Clear(); } //================ clipboard operations bool GuiTextBoxCommonInterface::CanCut() { return !readonly && textElement->GetCaretBegin()!=textElement->GetCaretEnd() && textElement->GetPasswordChar()==L'\0'; } bool GuiTextBoxCommonInterface::CanCopy() { return textElement->GetCaretBegin()!=textElement->GetCaretEnd() && textElement->GetPasswordChar()==L'\0'; } bool GuiTextBoxCommonInterface::CanPaste() { return !readonly && GetCurrentController()->ClipboardService()->ContainsText() && textElement->GetPasswordChar()==L'\0'; } bool GuiTextBoxCommonInterface::Cut() { if(CanCut()) { GetCurrentController()->ClipboardService()->SetText(GetSelectionText()); SetSelectionText(L""); return true; } else { return false; } } bool GuiTextBoxCommonInterface::Copy() { if(CanCopy()) { GetCurrentController()->ClipboardService()->SetText(GetSelectionText()); return true; } else { return false; } } bool GuiTextBoxCommonInterface::Paste() { if(CanPaste()) { SetSelectionText(GetCurrentController()->ClipboardService()->GetText()); return true; } else { return false; } } //================ editing control bool GuiTextBoxCommonInterface::GetReadonly() { return readonly; } void GuiTextBoxCommonInterface::SetReadonly(bool value) { readonly=value; } //================ text operations void GuiTextBoxCommonInterface::Select(TextPos begin, TextPos end) { Move(begin, false); Move(end, true); } void GuiTextBoxCommonInterface::SelectAll() { vint row=textElement->GetLines().GetCount()-1; Move(TextPos(0, 0), false); Move(TextPos(row, textElement->GetLines().GetLine(row).dataLength), true); } WString GuiTextBoxCommonInterface::GetSelectionText() { TextPos selectionBegin=textElement->GetCaretBegin()<textElement->GetCaretEnd()?textElement->GetCaretBegin():textElement->GetCaretEnd(); TextPos selectionEnd=textElement->GetCaretBegin()>textElement->GetCaretEnd()?textElement->GetCaretBegin():textElement->GetCaretEnd(); return textElement->GetLines().GetText(selectionBegin, selectionEnd); } void GuiTextBoxCommonInterface::SetSelectionText(const WString& value) { Modify(textElement->GetCaretBegin(), textElement->GetCaretEnd(), value, false); } void GuiTextBoxCommonInterface::SetSelectionTextAsKeyInput(const WString& value) { Modify(textElement->GetCaretBegin(), textElement->GetCaretEnd(), value, true); } WString GuiTextBoxCommonInterface::GetRowText(vint row) { TextPos start=textElement->GetLines().Normalize(TextPos(row, 0)); TextPos end=TextPos(start.row, textElement->GetLines().GetLine(start.row).dataLength); return GetFragmentText(start, end); } WString GuiTextBoxCommonInterface::GetFragmentText(TextPos start, TextPos end) { start=textElement->GetLines().Normalize(start); end=textElement->GetLines().Normalize(end); return textElement->GetLines().GetText(start, end); } TextPos GuiTextBoxCommonInterface::GetCaretBegin() { return textElement->GetCaretBegin(); } TextPos GuiTextBoxCommonInterface::GetCaretEnd() { return textElement->GetCaretEnd(); } TextPos GuiTextBoxCommonInterface::GetCaretSmall() { TextPos c1=GetCaretBegin(); TextPos c2=GetCaretEnd(); return c1<c2?c1:c2; } TextPos GuiTextBoxCommonInterface::GetCaretLarge() { TextPos c1=GetCaretBegin(); TextPos c2=GetCaretEnd(); return c1>c2?c1:c2; } //================ position query vint GuiTextBoxCommonInterface::GetRowWidth(vint row) { return textElement->GetLines().GetRowWidth(row); } vint GuiTextBoxCommonInterface::GetRowHeight() { return textElement->GetLines().GetRowHeight(); } vint GuiTextBoxCommonInterface::GetMaxWidth() { return textElement->GetLines().GetMaxWidth(); } vint GuiTextBoxCommonInterface::GetMaxHeight() { return textElement->GetLines().GetMaxHeight(); } TextPos GuiTextBoxCommonInterface::GetTextPosFromPoint(Point point) { Point view=textElement->GetViewPosition(); return textElement->GetLines().GetTextPosFromPoint(Point(point.x+view.x, point.y+view.y)); } Point GuiTextBoxCommonInterface::GetPointFromTextPos(TextPos pos) { Point view=textElement->GetViewPosition(); Point result=textElement->GetLines().GetPointFromTextPos(pos); return Point(result.x-view.x, result.y-view.y); } Rect GuiTextBoxCommonInterface::GetRectFromTextPos(TextPos pos) { Point view=textElement->GetViewPosition(); Rect result=textElement->GetLines().GetRectFromTextPos(pos); return Rect(Point(result.x1-view.x, result.y1-view.y), result.GetSize()); } TextPos GuiTextBoxCommonInterface::GetNearestTextPos(Point point) { Point viewPosition=textElement->GetViewPosition(); Point mousePosition=Point(point.x+viewPosition.x, point.y+viewPosition.y); TextPos pos=textElement->GetLines().GetTextPosFromPoint(mousePosition); if(pos.column<textElement->GetLines().GetLine(pos.row).dataLength) { Rect rect=textElement->GetLines().GetRectFromTextPos(pos); if(abs((int)(rect.x1-mousePosition.x))>=abs((int)(rect.x2-1-mousePosition.x))) { pos.column++; } } return pos; } //================ colorizing Ptr<GuiTextBoxColorizerBase> GuiTextBoxCommonInterface::GetColorizer() { return colorizer; } void GuiTextBoxCommonInterface::SetColorizer(Ptr<GuiTextBoxColorizerBase> value) { if(colorizer) { DetachTextEditCallback(colorizer); } colorizer=value; if(colorizer) { AttachTextEditCallback(colorizer); GetTextElement()->SetColors(colorizer->GetColors()); } } //================ auto complete Ptr<GuiTextBoxAutoCompleteBase> GuiTextBoxCommonInterface::GetAutoComplete() { return autoComplete; } void GuiTextBoxCommonInterface::SetAutoComplete(Ptr<GuiTextBoxAutoCompleteBase> value) { if(autoComplete) { DetachTextEditCallback(autoComplete); } autoComplete=value; if(autoComplete) { AttachTextEditCallback(autoComplete); } } //================ undo redo control vuint GuiTextBoxCommonInterface::GetEditVersion() { return editVersion; } bool GuiTextBoxCommonInterface::CanUndo() { return !readonly && undoRedoProcessor->CanUndo(); } bool GuiTextBoxCommonInterface::CanRedo() { return !readonly && undoRedoProcessor->CanRedo(); } void GuiTextBoxCommonInterface::ClearUndoRedo() { undoRedoProcessor->ClearUndoRedo(); } bool GuiTextBoxCommonInterface::GetModified() { return undoRedoProcessor->GetModified(); } void GuiTextBoxCommonInterface::NotifyModificationSaved() { undoRedoProcessor->NotifyModificationSaved(); } bool GuiTextBoxCommonInterface::Undo() { if(CanUndo()) { return undoRedoProcessor->Undo(); } else { return false; } } bool GuiTextBoxCommonInterface::Redo() { if(CanRedo()) { return undoRedoProcessor->Redo(); } else { return false; } } } } }
27.164641
173
0.662219
JamesLinus
f1477f3ace2bd40604255b6996713b24abb8a69f
15,362
cpp
C++
hihope_neptune-oh_hid/00_src/v0.1/foundation/distributedschedule/dmsfwk_lite/moduletest/dtbschedmgr_lite/source/tlv_parse_test.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
1
2022-02-15T08:51:55.000Z
2022-02-15T08:51:55.000Z
hihope_neptune-oh_hid/00_src/v0.3/foundation/distributedschedule/dmsfwk_lite/moduletest/dtbschedmgr_lite/source/tlv_parse_test.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
hihope_neptune-oh_hid/00_src/v0.3/foundation/distributedschedule/dmsfwk_lite/moduletest/dtbschedmgr_lite/source/tlv_parse_test.cpp
dawmlight/vendor_oh_fun
bc9fb50920f06cd4c27399f60076f5793043c77d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020 Huawei Device Co., Ltd. * 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 "dmslite_msg_parser.h" #include "dmslite_tlv_common.h" using namespace testing::ext; namespace OHOS { namespace DistributedSchedule { class TlvParseTest : public testing::Test { protected: static void SetUpTestCase() { } static void TearDownTestCase() { } virtual void SetUp() { } virtual void TearDown() { } static void RunTest(const uint8_t *buffer, uint16_t bufferLen, const TlvParseCallback onTlvParseDone, const StartAbilityCallback onStartAbilityDone) { IDmsFeatureCallback dmsFeatureCallback = { .onTlvParseDone = onTlvParseDone, .onStartAbilityDone = onStartAbilityDone }; CommuInterInfo interInfo; interInfo.payloadLength = bufferLen; interInfo.payload = buffer; DmsLiteProcessCommuMsg(&interInfo, &dmsFeatureCallback); } }; /** * @tc.name: NormalPackage_001 * @tc.desc: normal package with small bundle name and ability name * @tc.type: FUNC * @tc.require: SR000ELTHO */ HWTEST_F(TlvParseTest, NormalPackage_001, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0c, 0x4d, 0x61, 0x69, 0x6e, 0x41, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x00, 0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65, 0x79, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { const TlvDmsMsgInfo *msg = reinterpret_cast<const TlvDmsMsgInfo *>(dmsMsg); EXPECT_EQ(errCode, DMS_TLV_SUCCESS); EXPECT_EQ(msg->commandId, 0); EXPECT_EQ(string(msg->calleeBundleName), "com.huawei.launcher"); EXPECT_EQ(string(msg->calleeAbilityName), "MainAbility"); EXPECT_EQ(string(msg->callerSignature), "publickey"); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } /** * @tc.name: NormalPackageWithLongBundleName * @tc.desc: normal package with 255 bytes long(upper boundary) bundle name * @tc.type: FUNC * @tc.require: AR000ENCTK */ HWTEST_F(TlvParseTest, NormalPackage_002, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x82, 0x00, 0x63, 0x6f, 0x6d, 0x2e, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x00, 0x03, 0x0c, 0x4d, 0x61, 0x69, 0x6e, 0x41, 0x62, 0x69, 0x6c, 0x69, 0x74, 0x79, 0x00, 0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65, 0x79, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { const TlvDmsMsgInfo *msg = reinterpret_cast<const TlvDmsMsgInfo *>(dmsMsg); EXPECT_EQ(errCode, DMS_TLV_SUCCESS); std::stringstream ss; ss << "com."; for (int8_t i = 0; i < 4; i++) { ss << "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; } ss << "abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"; ss << ".huawei"; EXPECT_EQ(msg->commandId, 0); EXPECT_EQ(string(msg->calleeBundleName), ss.str()); EXPECT_EQ(string(msg->calleeAbilityName), "MainAbility"); EXPECT_EQ(string(msg->callerSignature), "publickey"); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageOutOfOrder_001 * @tc.desc: abnormal package with node type sequence in disorder * @tc.type: FUNC * @tc.require: AR000ELTIG */ HWTEST_F(TlvParseTest, AbnormalPackageOutOfOrder_001, TestSize.Level0) { uint8_t buffer[] = { 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65, 0x72, 0x01, 0x01, 0x00, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_OUT_OF_ORDER); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageOutOfOrder_002 * @tc.desc: abnormal package with node type sequence in non-continuous order * @tc.type: FUNC * @tc.require: SR000DRR3L */ HWTEST_F(TlvParseTest, AbnormalPackageOutOfOrder_002, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65, 0x72, 0x04, 0x00, 0x04, 0x6d, 0x80, 0xff, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_OUT_OF_ORDER); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadNodeNum_001 * @tc.desc: abnormal package without node * @tc.type: FUNC * @tc.require: AR000E0DGE */ HWTEST_F(TlvParseTest, AbnormalPackageBadNodeNum_001, TestSize.Level0) { uint8_t buffer[] = { }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_LEN); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadNodeNum_002 * @tc.desc: abnormal package with only one mandatory node * @tc.type: FUNC * @tc.require: AR000E0DE5 */ HWTEST_F(TlvParseTest, AbnormalPackageBadNodeNum_002, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_BAD_NODE_NUM); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadNodeNum_003 * @tc.desc: abnormal package with only two mandatory nodes * @tc.type: FUNC * @tc.require: AR000E0DE0 */ HWTEST_F(TlvParseTest, AbnormalPackageBadNodeNum_003, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65, 0x72, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_BAD_NODE_NUM); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadNodeNum_004 * @tc.desc: abnormal package with only three mandatory nodes * @tc.type: FUNC * @tc.require: AR000DSCRF */ HWTEST_F(TlvParseTest, AbnormalPackageBadNodeNum_004, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_BAD_NODE_NUM); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadNodeNum_005 * @tc.desc: abnormal package with an additional node * @tc.type: FUNC * @tc.require: AR000DSCRB */ HWTEST_F(TlvParseTest, AbnormalPackageBadNodeNum_005, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00, 0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65, 0x79, 0x00, 0x05, 0x01, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_BAD_NODE_NUM); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadLength_001 * @tc.desc: abnormal package tlv node without value * @tc.type: FUNC * @tc.require: SR000E0DR9 */ HWTEST_F(TlvParseTest, AbnormalPackageBadLength_001, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_LEN); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadLength_002 * @tc.desc: abnormal package tlv node with zero-size length * @tc.type: FUNC * @tc.require: AR000E0ECR */ HWTEST_F(TlvParseTest, AbnormalPackageBadLength_002, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00, 0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65, 0x79, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_LEN); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadLength_003 * @tc.desc: abnormal package with mismatched buffer size * @tc.type: FUNC * @tc.require: AR000E0DE0 */ HWTEST_F(TlvParseTest, AbnormalPackageBadLength_003, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00, 0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65, 0x79, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_LEN); }; RunTest(buffer, sizeof(buffer) + 1, onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadLength_004 * @tc.desc: abnormal package with mismatched buffer size * @tc.type: FUNC * @tc.require: AR000E0DE0 */ HWTEST_F(TlvParseTest, AbnormalPackageBadLength_004, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00, 0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65, 0x79, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_LEN); }; RunTest(buffer, sizeof(buffer) - 1, onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadLength_005 * @tc.desc: abnormal package with mismatched buffer size * @tc.type: FUNC * @tc.require: AR000E0DE0 */ HWTEST_F(TlvParseTest, AbnormalPackageBadLength_005, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00, 0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65, 0x79, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { bool condition = (errCode == DMS_TLV_ERR_LEN || errCode == DMS_TLV_ERR_BAD_NODE_NUM); EXPECT_EQ(true, condition); }; RunTest(buffer, MAX_DMS_MSG_LENGTH, onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadLength_006 * @tc.desc: abnormal package with mismatched buffer size * @tc.type: FUNC * @tc.require: AR000E0DE0 */ HWTEST_F(TlvParseTest, AbnormalPackageBadLength_006, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65, 0x72, 0x00, 0x03, 0x0d, 0x4d, 0x61, 0x69, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0x00, 0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65, 0x79, 0x00 }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_LEN); }; RunTest(buffer, 0, onTlvParseDone, nullptr); } /** * @tc.name: AbnormalPackageBadSource_001 * @tc.desc: abnormal package string field with no '\0' in the ending * @tc.type: FUNC * @tc.require: AR000E0DE0 */ HWTEST_F(TlvParseTest, AbnormalPackageBadSource_001, TestSize.Level0) { uint8_t buffer[] = { 0x01, 0x01, 0x00, 0x02, 0x14, 0x63, 0x6f, 0x6d, 0x2e, 0x68, 0x75, 0x61, 0x77, 0x65, 0x69, 0x2e, 0x6c, 0x61, 0x75, 0x6e, 0x63, 0x68, 0x65, 0x72, 0xff, 0x03, 0x0d, 0x4d, 0x61, 0x69, 0x6e, 0x41, 0x63, 0x74, 0x69, 0x76, 0x69, 0x74, 0x79, 0xff, 0x04, 0x0a, 0x70, 0x75, 0x62, 0x6C, 0x69, 0x63, 0x6B, 0x65, 0x79, 0xff }; auto onTlvParseDone = [] (int8_t errCode, const void *dmsMsg) { EXPECT_EQ(errCode, DMS_TLV_ERR_BAD_SOURCE); }; RunTest(buffer, sizeof(buffer), onTlvParseDone, nullptr); } } }
35.725581
93
0.648744
dawmlight
f147a63ef44cc2117e7b3f5b5e19f0184f9e3d10
2,186
cpp
C++
src/randact/randomdata.cpp
nicholasjalbert/Thrille
117dbdbe93f81eec9398a75aebc62543498363ac
[ "OLDAP-2.8" ]
2
2015-02-19T13:15:08.000Z
2018-05-30T05:34:15.000Z
src/randact/randomdata.cpp
nicholasjalbert/Thrille
117dbdbe93f81eec9398a75aebc62543498363ac
[ "OLDAP-2.8" ]
null
null
null
src/randact/randomdata.cpp
nicholasjalbert/Thrille
117dbdbe93f81eec9398a75aebc62543498363ac
[ "OLDAP-2.8" ]
null
null
null
#define UNLOCKASSERT #include "randomdata.h" RandomDataTester::RandomDataTester(thrID myself) : RandomActiveTester(myself) { setTestingTargets(); printf("Random Active (Data) Testing started...\n"); printf("iid 1: %p, iid 2: %p\n", target1, target2); } RandomDataTester::RandomDataTester(thrID myself, bool testing) : RandomActiveTester(myself) { printf("TEST: Random Active (Data) Testing started...\n"); target1 = 0; target2 = 0; } RandomDataTester::~RandomDataTester() { if (raceFound) { printf("Data Race Between %p and %p Found!\n", target1, target2); } else { printf("Data Race Between %p and %p Not Reproduced\n", target1, target2); } } bool RandomDataTester::reenableThreadIfLegal(thrID thr) { safe_assert(active_testing_paused[thr]); active_testing_paused[thr] = false; enableThread(thr); return true; } void RandomDataTester::handleMyMemoryRead(thrID myself, void * iid, void * addr) { if (iid == target1 || iid == target2) { ActiveRaceInfo tmp(myself, addr, false); vector<thrID> racers = isRacing(tmp); if (((int) racers.size()) > 0) { raceFound = true; if (log->getPrint()) { printf("Racing access discovered\n"); } enableSpecificActiveTestingPaused(racers); } else { active_testing_paused[myself] = true; active_testing_info[myself] = tmp; disableThread(myself); } } } void RandomDataTester::handleMyMemoryWrite(thrID myself, void * iid, void * addr) { if (iid == target1 || iid == target2) { ActiveRaceInfo tmp(myself, addr, true); vector<thrID> racers = isRacing(tmp); if (((int) racers.size()) > 0) { raceFound = true; if (log->getPrint()) { printf("Racing access discovered\n"); } enableSpecificActiveTestingPaused(racers); } else { active_testing_paused[myself] = true; active_testing_info[myself] = tmp; disableThread(myself); } } }
29.540541
79
0.587374
nicholasjalbert
f149c82d43c60e6684a451990867bad9a9cb791c
866
cpp
C++
InAirState.cpp
thomasvt/stuck
eb590f4218d8eb00199518c8f0c1d3225216d412
[ "MIT" ]
1
2022-03-13T09:02:50.000Z
2022-03-13T09:02:50.000Z
InAirState.cpp
thomasvt/stuck
eb590f4218d8eb00199518c8f0c1d3225216d412
[ "MIT" ]
1
2022-03-13T09:04:33.000Z
2022-03-13T18:56:32.000Z
InAirState.cpp
thomasvt/stuck
eb590f4218d8eb00199518c8f0c1d3225216d412
[ "MIT" ]
null
null
null
#include <InAirState.h> #include <Hero.h> #include "HeroAnimations.h" namespace actors { namespace hero { void InAirState::update(Hero& hero) { if (hero.rigid_body.is_on_floor()) hero.fsm_.change_state(HeroFsm::hero_state::on_floor); if (hero.rigid_body.is_on_ladder() && !hero.rigid_body.is_going_up()) hero.fsm_.change_state(HeroFsm::hero_state::on_ladder); const auto throttle8_x = hero.get_throttle8_x(); hero.rigid_body.set_velocity8_x(throttle8_x); // no inertia, classic feel // bit dirty. can only do this because these animations are only 1 frame. hero.animation_player_.set_animation(hero.rigid_body.is_going_up() ? &animations::hero::jump : &animations::hero::fall); } void InAirState::on_enter(Hero& hero) { hero.rigid_body.is_gravity_enabled = true; } void InAirState::on_exit(Hero& hero) { } } }
26.242424
123
0.720554
thomasvt
f149d8f61c22066d21811d6764bdac4816de4330
5,484
cpp
C++
external/webkit/Source/WebCore/bindings/v8/PageScriptDebugServer.cpp
ghsecuritylab/android_platform_sony_nicki
526381be7808e5202d7865aa10303cb5d249388a
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
Source/WebCore/bindings/v8/PageScriptDebugServer.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
Source/WebCore/bindings/v8/PageScriptDebugServer.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-17T06:02:42.000Z
2018-09-19T10:08:38.000Z
/* * Copyright (c) 2011 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "PageScriptDebugServer.h" #if ENABLE(JAVASCRIPT_DEBUGGER) #include "Frame.h" #include "Page.h" #include "ScriptDebugListener.h" #include "V8Binding.h" #include "V8DOMWindow.h" #include "V8Proxy.h" #include <wtf/OwnPtr.h> #include <wtf/PassOwnPtr.h> #include <wtf/StdLibExtras.h> namespace WebCore { static Frame* retrieveFrame(v8::Handle<v8::Context> context) { if (context.IsEmpty()) return 0; // Test that context has associated global dom window object. v8::Handle<v8::Object> global = context->Global(); if (global.IsEmpty()) return 0; global = V8DOMWrapper::lookupDOMWrapper(V8DOMWindow::GetTemplate(), global); if (global.IsEmpty()) return 0; return V8Proxy::retrieveFrame(context); } PageScriptDebugServer& PageScriptDebugServer::shared() { DEFINE_STATIC_LOCAL(PageScriptDebugServer, server, ()); return server; } PageScriptDebugServer::PageScriptDebugServer() : ScriptDebugServer() , m_pausedPage(0) , m_enabled(true) { } void PageScriptDebugServer::addListener(ScriptDebugListener* listener, Page* page) { if (!m_enabled) return; V8Proxy* proxy = V8Proxy::retrieve(page->mainFrame()); if (!proxy) return; v8::HandleScope scope; v8::Local<v8::Context> debuggerContext = v8::Debug::GetDebugContext(); v8::Context::Scope contextScope(debuggerContext); if (!m_listenersMap.size()) { ensureDebuggerScriptCompiled(); ASSERT(!m_debuggerScript.get()->IsUndefined()); v8::Debug::SetDebugEventListener2(&PageScriptDebugServer::v8DebugEventCallback, v8::External::New(this)); } m_listenersMap.set(page, listener); V8DOMWindowShell* shell = proxy->windowShell(); if (!shell->isContextInitialized()) return; v8::Handle<v8::Context> context = shell->context(); v8::Handle<v8::Function> getScriptsFunction = v8::Local<v8::Function>::Cast(m_debuggerScript.get()->Get(v8::String::New("getScripts"))); v8::Handle<v8::Value> argv[] = { context->GetData() }; v8::Handle<v8::Value> value = getScriptsFunction->Call(m_debuggerScript.get(), 1, argv); if (value.IsEmpty()) return; ASSERT(!value->IsUndefined() && value->IsArray()); v8::Handle<v8::Array> scriptsArray = v8::Handle<v8::Array>::Cast(value); for (unsigned i = 0; i < scriptsArray->Length(); ++i) dispatchDidParseSource(listener, v8::Handle<v8::Object>::Cast(scriptsArray->Get(v8::Integer::New(i)))); } void PageScriptDebugServer::removeListener(ScriptDebugListener* listener, Page* page) { if (!m_listenersMap.contains(page)) return; if (m_pausedPage == page) continueProgram(); m_listenersMap.remove(page); if (m_listenersMap.isEmpty()) v8::Debug::SetDebugEventListener(0); // FIXME: Remove all breakpoints set by the agent. } void PageScriptDebugServer::setClientMessageLoop(PassOwnPtr<ClientMessageLoop> clientMessageLoop) { m_clientMessageLoop = clientMessageLoop; } ScriptDebugListener* PageScriptDebugServer::getDebugListenerForContext(v8::Handle<v8::Context> context) { v8::HandleScope scope; Frame* frame = retrieveFrame(context); if (!frame) return 0; return m_listenersMap.get(frame->page()); } void PageScriptDebugServer::runMessageLoopOnPause(v8::Handle<v8::Context> context) { v8::HandleScope scope; Frame* frame = retrieveFrame(context); m_pausedPage = frame->page(); // Wait for continue or step command. m_clientMessageLoop->run(m_pausedPage); // The listener may have been removed in the nested loop. if (ScriptDebugListener* listener = m_listenersMap.get(m_pausedPage)) listener->didContinue(); m_pausedPage = 0; } void PageScriptDebugServer::quitMessageLoopOnPause() { m_clientMessageLoop->quitNow(); } } // namespace WebCore #endif // ENABLE(JAVASCRIPT_DEBUGGER)
33.036145
140
0.715536
ghsecuritylab
f14b22aad4767d594ef33df2293217cfc40f5233
4,355
cc
C++
video.cc
SolraBizna/teg
05a307f2f3b359f3462cba23e15dbda8d6af66fc
[ "Zlib" ]
null
null
null
video.cc
SolraBizna/teg
05a307f2f3b359f3462cba23e15dbda8d6af66fc
[ "Zlib" ]
null
null
null
video.cc
SolraBizna/teg
05a307f2f3b359f3462cba23e15dbda8d6af66fc
[ "Zlib" ]
null
null
null
#include "video.hh" #include "config.hh" #include "xgl.hh" using namespace Video; const uint32_t Video::uninitialized_context_cookie = 0; uint32_t Video::opengl_context_cookie = uninitialized_context_cookie; #ifndef DEFAULT_WINDOWED_WIDTH #define DEFAULT_WINDOWED_WIDTH 640 #endif #ifndef DEFAULT_WINDOWED_HEIGHT #define DEFAULT_WINDOWED_HEIGHT 480 #endif int32_t Video::fullscreen_width = 0, Video::fullscreen_height = 0; int32_t Video::windowed_width = DEFAULT_WINDOWED_WIDTH, Video::windowed_height = DEFAULT_WINDOWED_HEIGHT; bool Video::fullscreen_mode = true; bool Video::vsync = false; static const char* video_config_file = "Video Configuration.utxt"; static const Config::Element video_config_elements[] = { Config::Element("fullscreen_width", fullscreen_width), Config::Element("fullscreen_height", fullscreen_height), Config::Element("windowed_width", windowed_width), Config::Element("windowed_height", windowed_height), Config::Element("fullscreen_mode", fullscreen_mode), Config::Element("vsync", vsync), }; static SDL_Window* window = NULL; static SDL_GLContext glcontext = NULL; static bool inited = false; static bool window_visible = true, window_minimized = false; void Video::Kill() { if(inited) { SDL_Quit(); inited = false; } } void Video::Init() { if(!inited) { if(SDL_Init(SDL_INIT_VIDEO)) die("Couldn't initialize SDL!"); inited = true; } if(glcontext) SDL_GL_DeleteContext(glcontext); if(window) SDL_DestroyWindow(window); int target_w, target_h; Uint32 flags = SDL_WINDOW_OPENGL; if(fullscreen_mode) { target_w = fullscreen_width; target_h = fullscreen_height; if(target_w == 0 || target_h == 0) flags |= SDL_WINDOW_FULLSCREEN_DESKTOP; else flags |= SDL_WINDOW_FULLSCREEN; } else { target_w = windowed_width; target_h = windowed_height; } do { /* sanity */ if(target_w < 320) target_w = 320; else if(target_h < 240) target_h = 240; window = SDL_CreateWindow(GAME_WINDOW_TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, target_w, target_h, flags); if(window) break; else if(flags & SDL_WINDOW_FULLSCREEN) { fprintf(stderr, "Fullscreen mode %i x %i failed. Trying a window.\n", target_w, target_h); flags &= ~(SDL_WINDOW_FULLSCREEN_DESKTOP); target_w = windowed_width; target_h = windowed_height; } else die("Could not create a window no matter how hard we tried. The last reason SDL gave was: %s", SDL_GetError()); } while(1); /* TODO: set minimized/visible state? */ dprintf("SDL_CreateWindow(..., %i, %i, 0x%x) succeeded.\n", target_w, target_h, flags); glcontext = SDL_GL_CreateContext(window); if(!glcontext) die("Could not create an OpenGL context. The reason SDL gave was: %s", SDL_GetError()); ++opengl_context_cookie; dprintf("OpenGL initialized. Context cookie is %i.\n", opengl_context_cookie); xgl::Initialize(); /* OpenGL context setup */ glPixelStorei(GL_PACK_ALIGNMENT, TEG_PIXEL_PACK); glPixelStorei(GL_UNPACK_ALIGNMENT, TEG_PIXEL_PACK); } void Video::ReadConfig() { Config::Read(video_config_file, video_config_elements, elementcount(video_config_elements)); } void Video::WriteConfig() { Config::Write(video_config_file, video_config_elements, elementcount(video_config_elements)); } uint32_t Video::GetScreenWidth() { int w, h; SDL_GL_GetDrawableSize(window, &w, &h); return w; } uint32_t Video::GetScreenHeight() { int w, h; SDL_GL_GetDrawableSize(window, &w, &h); return h; } double Video::GetAspect() { int w, h; SDL_GL_GetDrawableSize(window, &w, &h); return (double)w / h; } void Video::Swap() { SDL_GL_SwapWindow(window); } bool Video::IsScreenActive() { return window_visible && !window_minimized; } bool Video::HandleEvent(SDL_Event& evt) { switch(evt.type) { case SDL_WINDOWEVENT: switch(evt.window.event) { case SDL_WINDOWEVENT_SHOWN: window_visible = true; break; case SDL_WINDOWEVENT_HIDDEN: window_visible = false; break; case SDL_WINDOWEVENT_MINIMIZED: window_minimized = true; break; case SDL_WINDOWEVENT_RESTORED: window_minimized = false; break; } return true; } return false; }
27.738854
117
0.702181
SolraBizna
f14c2349718a37f8d01d88242163e8662d181f54
14,692
cpp
C++
OgreMain/src/OgreASTCCodec.cpp
resttime/ogre-next
7435e60bd6df422d2fb4c742a493c3f37ef9a7a9
[ "MIT" ]
701
2019-09-08T15:56:41.000Z
2022-03-31T05:51:26.000Z
OgreMain/src/OgreASTCCodec.cpp
resttime/ogre-next
7435e60bd6df422d2fb4c742a493c3f37ef9a7a9
[ "MIT" ]
204
2019-09-01T23:02:32.000Z
2022-03-28T14:58:39.000Z
OgreMain/src/OgreASTCCodec.cpp
resttime/ogre-next
7435e60bd6df422d2fb4c742a493c3f37ef9a7a9
[ "MIT" ]
188
2019-09-05T05:14:46.000Z
2022-03-22T21:51:39.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE-Next (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreRoot.h" #include "OgreRenderSystem.h" #include "OgreASTCCodec.h" #include "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" namespace Ogre { const uint32 ASTC_MAGIC = 0x5CA1AB13; typedef struct { uint8 magic[4]; uint8 blockdim_x; uint8 blockdim_y; uint8 blockdim_z; uint8 xsize[3]; // x-size = xsize[0] + xsize[1] + xsize[2] uint8 ysize[3]; // x-size, y-size and z-size are given in texels; uint8 zsize[3]; // block count is inferred } ASTCHeader; float ASTCCodec::getBitrateForPixelFormat(PixelFormatGpu fmt) { switch (fmt) { case PFG_ASTC_RGBA_UNORM_4X4_LDR: return 8.00; case PFG_ASTC_RGBA_UNORM_5X4_LDR: return 6.40; case PFG_ASTC_RGBA_UNORM_5X5_LDR: return 5.12; case PFG_ASTC_RGBA_UNORM_6X5_LDR: return 4.27; case PFG_ASTC_RGBA_UNORM_6X6_LDR: return 3.56; case PFG_ASTC_RGBA_UNORM_8X5_LDR: return 3.20; case PFG_ASTC_RGBA_UNORM_8X6_LDR: return 2.67; case PFG_ASTC_RGBA_UNORM_8X8_LDR: return 2.00; case PFG_ASTC_RGBA_UNORM_10X5_LDR: return 2.56; case PFG_ASTC_RGBA_UNORM_10X6_LDR: return 2.13; case PFG_ASTC_RGBA_UNORM_10X8_LDR: return 1.60; case PFG_ASTC_RGBA_UNORM_10X10_LDR: return 1.28; case PFG_ASTC_RGBA_UNORM_12X10_LDR: return 1.07; case PFG_ASTC_RGBA_UNORM_12X12_LDR: return 0.89; default: return 0; } } // Utility function to determine 2D block dimensions from a target bitrate. Used for 3D textures. // Taken from astc_toplevel.cpp in ARM's ASTC Evaluation Codec void ASTCCodec::getClosestBlockDim2d(float targetBitrate, int *x, int *y) const { int blockdims[6] = { 4, 5, 6, 8, 10, 12 }; float best_error = 1000; float aspect_of_best = 1; int i, j; // Y dimension for (i = 0; i < 6; i++) { // X dimension for (j = i; j < 6; j++) { // NxN MxN 8x5 10x5 10x6 int is_legal = (j==i) || (j==i+1) || (j==3 && i==1) || (j==4 && i==1) || (j==4 && i==2); if(is_legal) { float bitrate = 128.0f / (blockdims[i] * blockdims[j]); float bitrate_error = fabs(bitrate - targetBitrate); float aspect = (float)blockdims[j] / blockdims[i]; if (bitrate_error < best_error || (bitrate_error == best_error && aspect < aspect_of_best)) { *x = blockdims[j]; *y = blockdims[i]; best_error = bitrate_error; aspect_of_best = aspect; } } } } } // Taken from astc_toplevel.cpp in ARM's ASTC Evaluation Codec void ASTCCodec::getClosestBlockDim3d(float targetBitrate, int *x, int *y, int *z) { int blockdims[4] = { 3, 4, 5, 6 }; float best_error = 1000; float aspect_of_best = 1; int i, j, k; for (i = 0; i < 4; i++) // Z { for (j = i; j < 4; j++) // Y { for (k = j; k < 4; k++) // X { // NxNxN MxNxN MxMxN int is_legal = ((k==j)&&(j==i)) || ((k==j+1)&&(j==i)) || ((k==j)&&(j==i+1)); if(is_legal) { float bitrate = 128.0f / (blockdims[i] * blockdims[j] * blockdims[k]); float bitrate_error = fabs(bitrate - targetBitrate); float aspect = (float)blockdims[k] / blockdims[j] + (float)blockdims[j] / blockdims[i] + (float)blockdims[k] / blockdims[i]; if (bitrate_error < best_error || (bitrate_error == best_error && aspect < aspect_of_best)) { *x = blockdims[k]; *y = blockdims[j]; *z = blockdims[i]; best_error = bitrate_error; aspect_of_best = aspect; } } } } } } size_t ASTCCodec::getMemorySize( uint32 width, uint32 height, uint32 depth, int32 xdim, int32 ydim, PixelFormatGpu fmt ) { float bitrate = getBitrateForPixelFormat(fmt); int32 zdim = 1; if(depth > 1) { getClosestBlockDim3d(bitrate, &xdim, &ydim, &zdim); } int xblocks = (width + xdim - 1) / xdim; int yblocks = (height + ydim - 1) / ydim; int zblocks = (depth + zdim - 1) / zdim; return xblocks * yblocks * zblocks * 16; } //--------------------------------------------------------------------- ASTCCodec* ASTCCodec::msInstance = 0; //--------------------------------------------------------------------- void ASTCCodec::startup() { if (!msInstance) { msInstance = OGRE_NEW ASTCCodec(); Codec::registerCodec(msInstance); } LogManager::getSingleton().logMessage(LML_NORMAL, "ASTC codec registering"); } //--------------------------------------------------------------------- void ASTCCodec::shutdown() { if(msInstance) { Codec::unregisterCodec(msInstance); OGRE_DELETE msInstance; msInstance = 0; } } //--------------------------------------------------------------------- ASTCCodec::ASTCCodec(): mType("astc") { } //--------------------------------------------------------------------- DataStreamPtr ASTCCodec::encode(MemoryDataStreamPtr& input, Codec::CodecDataPtr& pData) const { OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "ASTC encoding not supported", "ASTCCodec::encode" ) ; } //--------------------------------------------------------------------- void ASTCCodec::encodeToFile(MemoryDataStreamPtr& input, const String& outFileName, Codec::CodecDataPtr& pData) const { OGRE_EXCEPT(Exception::ERR_NOT_IMPLEMENTED, "ASTC encoding not supported", "ASTCCodec::encodeToFile" ) ; } //--------------------------------------------------------------------- Codec::DecodeResult ASTCCodec::decode(DataStreamPtr& stream) const { ASTCHeader header; // Read the ASTC header stream->read(&header, sizeof(ASTCHeader)); if( memcmp( &ASTC_MAGIC, &header.magic, sizeof(uint32) ) != 0 ) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "This is not a valid ASTC file!", "ASTCCodec::decode"); } int xdim = header.blockdim_x; int ydim = header.blockdim_y; int zdim = header.blockdim_z; int xsize = header.xsize[0] + 256 * header.xsize[1] + 65536 * header.xsize[2]; int ysize = header.ysize[0] + 256 * header.ysize[1] + 65536 * header.ysize[2]; int zsize = header.zsize[0] + 256 * header.zsize[1] + 65536 * header.zsize[2]; ImageData2 *imgData = OGRE_NEW ImageData2(); imgData->box.width = xsize; imgData->box.height = ysize; imgData->box.depth = zsize; imgData->box.numSlices = 1u; //Always one face, cubemaps are not currently supported imgData->numMipmaps = 1u; // Always 1 mip level per file (ASTC file restriction) if( zsize <= 1 ) imgData->textureType = TextureTypes::Type2D; else imgData->textureType = TextureTypes::Type3D; // For 3D we calculate the bitrate then find the nearest 2D block size. if(zdim > 1) { float bitrate = 128.0f / (xdim * ydim * zdim); getClosestBlockDim2d(bitrate, &xdim, &ydim); } if(xdim == 4) { imgData->format = PFG_ASTC_RGBA_UNORM_4X4_LDR; } else if(xdim == 5) { if(ydim == 4) imgData->format = PFG_ASTC_RGBA_UNORM_5X4_LDR; else if(ydim == 5) imgData->format = PFG_ASTC_RGBA_UNORM_5X5_LDR; } else if(xdim == 6) { if(ydim == 5) imgData->format = PFG_ASTC_RGBA_UNORM_6X5_LDR; else if(ydim == 6) imgData->format = PFG_ASTC_RGBA_UNORM_6X6_LDR; } else if(xdim == 8) { if(ydim == 5) imgData->format = PFG_ASTC_RGBA_UNORM_8X5_LDR; else if(ydim == 6) imgData->format = PFG_ASTC_RGBA_UNORM_8X6_LDR; else if(ydim == 8) imgData->format = PFG_ASTC_RGBA_UNORM_8X8_LDR; } else if(xdim == 10) { if(ydim == 5) imgData->format = PFG_ASTC_RGBA_UNORM_10X5_LDR; else if(ydim == 6) imgData->format = PFG_ASTC_RGBA_UNORM_10X6_LDR; else if(ydim == 8) imgData->format = PFG_ASTC_RGBA_UNORM_10X8_LDR; else if(ydim == 10) imgData->format = PFG_ASTC_RGBA_UNORM_10X10_LDR; } else if(xdim == 12) { if(ydim == 10) imgData->format = PFG_ASTC_RGBA_UNORM_12X10_LDR; else if(ydim == 12) imgData->format = PFG_ASTC_RGBA_UNORM_12X12_LDR; } const uint32 rowAlignment = 4u; // imgData->box.bytesPerPixel = PixelFormatGpuUtils::getBytesPerPixel( imgData->format ); imgData->box.setCompressedPixelFormat( imgData->format ); imgData->box.bytesPerRow = PixelFormatGpuUtils::getSizeBytes( imgData->box.width, 1u, 1u, 1u, imgData->format, rowAlignment ); imgData->box.bytesPerImage = PixelFormatGpuUtils::getSizeBytes( imgData->box.width, imgData->box.height, 1u, 1u, imgData->format, rowAlignment ); const size_t requiredBytes = PixelFormatGpuUtils::calculateSizeBytes( imgData->box.width, imgData->box.height, imgData->box.depth, imgData->box.numSlices, imgData->format, imgData->numMipmaps, rowAlignment ); // Bind output buffer imgData->box.data = OGRE_MALLOC_SIMD( requiredBytes, MEMCATEGORY_RESOURCE ); // Now deal with the data stream->read( imgData->box.data, requiredBytes ); DecodeResult ret; ret.first.reset(); ret.second = CodecDataPtr( imgData ); return ret; } //--------------------------------------------------------------------- String ASTCCodec::getType() const { return mType; } //--------------------------------------------------------------------- void ASTCCodec::flipEndian(void * pData, size_t size, size_t count) const { #if OGRE_ENDIAN == OGRE_ENDIAN_BIG for(unsigned int index = 0; index < count; index++) { flipEndian((void *)((long)pData + (index * size)), size); } #endif } //--------------------------------------------------------------------- void ASTCCodec::flipEndian(void * pData, size_t size) const { #if OGRE_ENDIAN == OGRE_ENDIAN_BIG char swapByte; for(unsigned int byteIndex = 0; byteIndex < size/2; byteIndex++) { swapByte = *(char *)((long)pData + byteIndex); *(char *)((long)pData + byteIndex) = *(char *)((long)pData + size - byteIndex - 1); *(char *)((long)pData + size - byteIndex - 1) = swapByte; } #endif } //--------------------------------------------------------------------- String ASTCCodec::magicNumberToFileExt(const char *magicNumberPtr, size_t maxbytes) const { if (maxbytes >= sizeof(uint32)) { uint32 fileType; memcpy(&fileType, magicNumberPtr, sizeof(uint32)); flipEndian(&fileType, sizeof(uint32), 1); if (ASTC_MAGIC == fileType) return String("astc"); } return BLANKSTRING; } }
37.865979
148
0.487953
resttime
f14ccaa4af8babd8f33583d2a19d07f1d66fe96b
1,409
hh
C++
include/Activia/ActGuiInput.hh
UniversityofWarwick/ACTIVIA
bbd0dfa71337602f94d911fa5101a440e8c16606
[ "BSL-1.0" ]
1
2020-11-04T08:32:23.000Z
2020-11-04T08:32:23.000Z
include/Activia/ActGuiInput.hh
UniversityofWarwick/ACTIVIA
bbd0dfa71337602f94d911fa5101a440e8c16606
[ "BSL-1.0" ]
null
null
null
include/Activia/ActGuiInput.hh
UniversityofWarwick/ACTIVIA
bbd0dfa71337602f94d911fa5101a440e8c16606
[ "BSL-1.0" ]
1
2020-11-04T08:32:30.000Z
2020-11-04T08:32:30.000Z
#ifdef ACT_USE_QT #ifndef ACT_GUI_INPUT_HH #define ACT_GUI_INPUT_HH #include "Activia/ActAbsInput.hh" #include "Activia/ActOutputSelection.hh" #include "Activia/ActGuiWindow.hh" #include <iostream> #include <fstream> #include <string> /// \brief Define the inputs (target, products, spectrum, algorithms) for the code via a GUI class ActGuiInput : public ActAbsInput { public: /// Default constructor ActGuiInput(); /// Constructor ActGuiInput(ActOutputSelection* outputSelection, ActGuiWindow* theGui); /// Destructor virtual ~ActGuiInput(); /// Define the target isotopes virtual void defineTarget(); /// Specify the calculation mode virtual void defineCalcMode(); /// Define the product isotopes virtual void defineNuclides(); /// Define the input beam spectrum virtual void defineSpectrum(); /// Specify the cross-section algorithm virtual void specifyXSecAlgorithm(); /// Define the exposure and decay times for radioactive decay yield calculations virtual void defineTime(); /// Specify the decay yield calculation algorithm virtual void specifyDecayAlgorithm(); /// Define the output file names, format and level of detail. virtual void specifyOutput(); /// Print out the available calculation options. virtual void printOptions(std::ofstream&) {;} protected: private: void printIntro() {;} ActGuiWindow* _theGui; }; #endif #endif
23.483333
92
0.74237
UniversityofWarwick
f14dd9ea676999232cb222f6795a7e021eb553e4
488
cpp
C++
Leetcode/Leaf-Similar Trees.cpp
Lucifermaniraj/Hacktoberfest2021
ec62edfad0d483e4b65874f37c0142d7154adb7b
[ "MIT" ]
null
null
null
Leetcode/Leaf-Similar Trees.cpp
Lucifermaniraj/Hacktoberfest2021
ec62edfad0d483e4b65874f37c0142d7154adb7b
[ "MIT" ]
null
null
null
Leetcode/Leaf-Similar Trees.cpp
Lucifermaniraj/Hacktoberfest2021
ec62edfad0d483e4b65874f37c0142d7154adb7b
[ "MIT" ]
null
null
null
class Solution { public: vector<int> v; bool leafSimilar(TreeNode* root1, TreeNode* root2) { vector<int> v1, v2; leaves(root1, v1); leaves(root2, v2); return v1==v2; } void leaves(TreeNode* root, vector<int>& v) { if(!root) return; if(!root->left && !root->right) v.push_back(root->val); leaves(root->left, v); leaves(root->right, v); } };
21.217391
56
0.471311
Lucifermaniraj
f14f99a466eaf87278065fade561b9f0e0ae7cae
1,097
hpp
C++
libraries/include/Engine/Shader.hpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
3
2015-04-25T22:57:58.000Z
2019-11-05T18:36:31.000Z
libraries/include/Engine/Shader.hpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
1
2016-06-23T15:22:41.000Z
2016-06-23T15:22:41.000Z
libraries/include/Engine/Shader.hpp
kermado/Total-Resistance
debaf40ba3be6590a70c9922e1d1a5e075f4ede3
[ "MIT" ]
null
null
null
#ifndef SHADER_H #define SHADER_H #include <string> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <Engine/NonCopyable.hpp> namespace Engine { class Shader : private NonCopyable { public: /** * Shader types. */ enum Type { VertexShader = GL_VERTEX_SHADER, FragmentShader = GL_FRAGMENT_SHADER }; /** * Constructor. * * @param shaderType Type of shader. */ Shader(Type shaderType); /** * Destructor. */ ~Shader(); /** * Initializes the shader from the specified source code file and * attempts to compile it. * * @param filename Path to the shader source code file. * @return True if shader was initialized successfully. */ bool LoadFromFile(std::string filename); /** * Returns the type of the shader. * * @return Shader type. */ Type GetShaderType() const; /** * Returns the shader object identifier. * * @return Shader ID. */ GLuint GetId() const; private: /** * Shader object identifier. */ GLuint m_id; /** * Shader type. */ Type m_type; }; } #endif
14.824324
67
0.621696
kermado