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
109
| 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
48.5k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
22beb06fd41d6bdf985a1e5f93853dda9cf18408
| 1,781
|
cpp
|
C++
|
Day_90.cpp
|
iamakkkhil/DailyCoding
|
8422ddbcc2a179f3fd449871e2241ad94a845efb
|
[
"MIT"
] | 8
|
2021-02-07T16:31:28.000Z
|
2021-06-11T18:53:23.000Z
|
Day_90.cpp
|
iamakkkhil/DailyCoding
|
8422ddbcc2a179f3fd449871e2241ad94a845efb
|
[
"MIT"
] | null | null | null |
Day_90.cpp
|
iamakkkhil/DailyCoding
|
8422ddbcc2a179f3fd449871e2241ad94a845efb
|
[
"MIT"
] | 1
|
2021-05-25T17:17:58.000Z
|
2021-05-25T17:17:58.000Z
|
/*
DAY 90: Queue using two Stacks.
https://www.geeksforgeeks.org/queue-using-stacks/
QUESTION : Implement a Queue using 2 stacks s1 and s2 .
A Query Q is of 2 Types
(i) 1 x (a query of this type means pushing 'x' into the queue)
(ii) 2 (a query of this type means to pop element from queue and print the poped element)
Example 1:
Input:
5
1 2 1 3 2 1 4 2
Output:
2 3
Explanation:
In the first testcase
1 2 the queue will be {2}
1 3 the queue will be {2 3}
2 poped element will be 2 the queue
will be {3}
1 4 the queue will be {3 4}
2 poped element will be 3.
Example 2:
Input:
4
1 2 2 2 1 4
Output:
2 -1
Explanation:
In the second testcase
1 2 the queue will be {2}
2 poped element will be 2 and
then the queue will be empty
2 the queue is empty and hence -1
1 4 the queue will be {4}.
Expected Time Complexity : O(1) for push() and O(N) for pop() or O(N) for push() and
O(1) for pop()
Expected Auxilliary Space : O(1).
Constraints:
1 <= Q <= 100
1 <= x <= 100
*/
/* The structure of the class is
class StackQueue{
private:
// These are STL stacks ( http://goo.gl/LxlRZQ )
stack<int> s1;
stack<int> s2;
public:
void push(int);
int pop();
}; */
//Function to push an element in queue by using 2 stacks.
void StackQueue :: push(int x)
{
// Your Code
while(!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
s2.push(x);
while(!s2.empty()) {
s1.push(s2.top());
s2.pop();
}
}
//Function to pop an element from queue by using 2 stacks.
int StackQueue :: pop()
{
// Your Code
if (s1.empty()) return -1;
int top_ele = s1.top();
s1.pop();
return top_ele;
}
| 20.011236
| 92
| 0.590118
|
iamakkkhil
|
22bec18cbd71877d96e755c44e00553e11785b18
| 2,178
|
cpp
|
C++
|
oclint-rules/rules/convention/InvertedLogicRule.cpp
|
BGU-AiDnD/oclint
|
484fed44ca0e34532745b3d4f04124cbf5bb42fa
|
[
"BSD-3-Clause"
] | 3,128
|
2015-01-01T06:00:31.000Z
|
2022-03-29T23:43:20.000Z
|
oclint-rules/rules/convention/InvertedLogicRule.cpp
|
BGU-AiDnD/oclint
|
484fed44ca0e34532745b3d4f04124cbf5bb42fa
|
[
"BSD-3-Clause"
] | 432
|
2015-01-03T15:43:08.000Z
|
2022-03-29T02:32:48.000Z
|
oclint-rules/rules/convention/InvertedLogicRule.cpp
|
BGU-AiDnD/oclint
|
484fed44ca0e34532745b3d4f04124cbf5bb42fa
|
[
"BSD-3-Clause"
] | 454
|
2015-01-06T03:11:12.000Z
|
2022-03-22T05:49:38.000Z
|
#include "oclint/AbstractASTVisitorRule.h"
#include "oclint/RuleSet.h"
using namespace std;
using namespace clang;
using namespace oclint;
class InvertedLogicRule : public AbstractASTVisitorRule<InvertedLogicRule>
{
private:
bool isInvertedLogic(Expr *condExpr)
{
BinaryOperator *binaryOperator = dyn_cast_or_null<BinaryOperator>(condExpr);
UnaryOperator *unaryOperator = dyn_cast_or_null<UnaryOperator>(condExpr);
return (binaryOperator && binaryOperator->getOpcode() == BO_NE) ||
(unaryOperator && unaryOperator->getOpcode() == UO_LNot);
}
public:
virtual const string name() const override
{
return "inverted logic";
}
virtual int priority() const override
{
return 3;
}
virtual const string category() const override
{
return "convention";
}
#ifdef DOCGEN
virtual const std::string since() const override
{
return "0.4";
}
virtual const std::string description() const override
{
return "An inverted logic is hard to understand.";
}
virtual const std::string example() const override
{
return R"rst(
.. code-block:: cpp
int example(int a)
{
int i;
if (a != 0) // if (a == 0)
{ // {
i = 1; // i = 0;
} // }
else // else
{ // {
i = 0; // i = 1;
} // }
return !i ? -1 : 1; // return i ? 1 : -1;
}
)rst";
}
#endif
bool VisitIfStmt(IfStmt *ifStmt)
{
if (ifStmt->getElse() && isInvertedLogic(ifStmt->getCond()))
{
addViolation(ifStmt->getCond(), this);
}
return true;
}
bool VisitConditionalOperator(ConditionalOperator *conditionalOperator)
{
if (isInvertedLogic(conditionalOperator->getCond()))
{
addViolation(conditionalOperator->getCond(), this);
}
return true;
}
};
static RuleSet rules(new InvertedLogicRule());
| 23.934066
| 84
| 0.537649
|
BGU-AiDnD
|
42ef672c79b79129801f447209221d49f6662d0a
| 2,263
|
cpp
|
C++
|
src/kpr/TimerTaskManager.cpp
|
hooligan520/rocketmq-clent4cpp-linux
|
2f891c979229dfd78707150fa626ca3822f2d006
|
[
"Apache-2.0"
] | 22
|
2017-02-17T14:28:17.000Z
|
2021-02-25T10:09:04.000Z
|
src/kpr/TimerTaskManager.cpp
|
hooligan520/rocketmq-clent4cpp-linux
|
2f891c979229dfd78707150fa626ca3822f2d006
|
[
"Apache-2.0"
] | 2
|
2017-04-29T05:57:38.000Z
|
2017-11-20T03:49:48.000Z
|
src/kpr/TimerTaskManager.cpp
|
hooligan520/rocketmq-clent4cpp-linux
|
2f891c979229dfd78707150fa626ca3822f2d006
|
[
"Apache-2.0"
] | 10
|
2017-02-08T03:06:57.000Z
|
2020-04-18T01:48:53.000Z
|
/**
* Copyright (C) 2013 kangliqiang ,kangliq@163.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "TimerTaskManager.h"
#include "ThreadPool.h"
#include "ScopedLock.h"
namespace kpr
{
TimerTaskManager::TimerTaskManager()
{
}
TimerTaskManager::~TimerTaskManager()
{
}
int TimerTaskManager::Init(int maxThreadCount, int checklnteval)
{
try
{
m_pThreadPool = new ThreadPool("TimerThreadPool", 5, 5, maxThreadCount);
m_timerThread = new TimerThread("TimerThread", checklnteval);
m_timerThread->Start();
}
catch (...)
{
return -1;
}
return 0;
}
unsigned int TimerTaskManager::RegisterTimer(unsigned int initialDelay, unsigned int elapse, TimerTaskPtr pTask)
{
unsigned int id = m_timerThread->RegisterTimer(initialDelay, elapse, this, true);
kpr::ScopedLock<kpr::Mutex> lock(m_mutex);
m_timerTasks[id] = pTask;
return id;
}
bool TimerTaskManager::UnRegisterTimer(unsigned int timerId)
{
bool ret = m_timerThread->UnRegisterTimer(timerId);
kpr::ScopedLock<kpr::Mutex> lock(m_mutex);
m_timerTasks.erase(timerId);
return ret;
}
bool TimerTaskManager::ResetTimer(unsigned int timerId)
{
return m_timerThread->ResetTimer(timerId);
}
void TimerTaskManager::OnTimeOut(unsigned int timerId)
{
kpr::ScopedLock<kpr::Mutex> lock(m_mutex);
std::map<unsigned int, TimerTaskPtr>::iterator it = m_timerTasks.find(timerId);
if (it != m_timerTasks.end())
{
if (!it->second->IsProcessing())
{
it->second->SetProcessing(true);
m_pThreadPool->AddWork((it->second).ptr());
}
}
}
void TimerTaskManager::Stop()
{
m_timerThread->Stop();
m_timerThread->Join();
m_pThreadPool->Destroy();
}
}
| 24.597826
| 112
| 0.695095
|
hooligan520
|
42f060a507ace5f9dc44c2790a1b9437d42127ed
| 1,626
|
cpp
|
C++
|
src/Gui/Settings/SettingsWidget.cpp
|
AndrzejWoronko/WebPassWare
|
9af0df61a9279f1ffe8561714656265f4bec7939
|
[
"MIT"
] | null | null | null |
src/Gui/Settings/SettingsWidget.cpp
|
AndrzejWoronko/WebPassWare
|
9af0df61a9279f1ffe8561714656265f4bec7939
|
[
"MIT"
] | null | null | null |
src/Gui/Settings/SettingsWidget.cpp
|
AndrzejWoronko/WebPassWare
|
9af0df61a9279f1ffe8561714656265f4bec7939
|
[
"MIT"
] | null | null | null |
#include "SettingsWidget.h"
SettingsWidget::SettingsWidget(QWidget *parent) : QWidget (parent)
{
setGraphicElements();
setGraphicSettings();
setConnections();
}
SettingsWidget::~SettingsWidget()
{
safe_delete(m_look_widget)
safe_delete(m_database_widget)
safe_delete(m_list)
safe_delete(m_layout)
safe_delete(m_splitter)
safe_delete(m_mainLayout)
}
void SettingsWidget::setGraphicElements(QWidget *parent)
{
m_splitter = new CSplitter(QString("SettingsSplitter"), Qt::Horizontal, this);
m_look_widget = new SettingsLookController(parent);
m_database_widget = new SettingsDatabaseViewController(parent);
this->setLayout(m_mainLayout = new CVBoxLayout());
createListWidget();
m_splitter->addWidget(m_list);
m_layout = new QStackedLayout(m_splitter);
m_layout->addWidget(m_look_widget->getView());
m_layout->addWidget(m_database_widget->getView());
m_splitter->setLayout(m_layout);
m_mainLayout->addWidget(m_splitter);
}
void SettingsWidget::setGraphicSettings()
{
m_list->setCurrentRow(0);
}
void SettingsWidget::createListWidget()
{
m_list = new CListWidget(m_splitter);
m_list->addItem(tr("Wygląd"), tr("Ustawienia wyglądu"), ICON("Settings"), QSize(50,50));
m_list->addItem(tr("Baza danych"), tr("Parametry połączenia z bazą danych"), ICON("Database-settings"), QSize(50,50));
m_list->setTabKeyNavigation(true);
//TODO WYMIAR LISTY Z KONFIGURACJI
m_list->setMinimumWidth(200);
}
void SettingsWidget::setConnections()
{
connect(m_list, SIGNAL(currentRowChanged(int)), m_layout, SLOT(setCurrentIndex(int)));
}
| 28.526316
| 122
| 0.735547
|
AndrzejWoronko
|
42f5d1312109441a9d02860cd74c28eed0da86c8
| 2,960
|
hpp
|
C++
|
ComponentFramework/SystemHandlerTemplate.hpp
|
autious/kravall_entity_component_framework
|
a4380ea9135c2ad7aac444c0d52837eb1a43319d
|
[
"MIT"
] | 7
|
2015-06-21T20:23:12.000Z
|
2020-01-04T20:20:56.000Z
|
ComponentFramework/SystemHandlerTemplate.hpp
|
autious/kravall_entity_component_framework
|
a4380ea9135c2ad7aac444c0d52837eb1a43319d
|
[
"MIT"
] | null | null | null |
ComponentFramework/SystemHandlerTemplate.hpp
|
autious/kravall_entity_component_framework
|
a4380ea9135c2ad7aac444c0d52837eb1a43319d
|
[
"MIT"
] | null | null | null |
#ifndef SRC_CORE_COMPONENTFRAMEWORK_SYSTEMHANDLER_H
#define SRC_CORE_COMPONENTFRAMEWORK_SYSTEMHANDLER_H
#include "BaseSystem.hpp"
#include "PVector.hpp"
#include <TemplateUtility/TemplateIndex.hpp>
#include <array>
#include <utility>
#include <vector>
#include <Timer.hpp>
#define GNAME( name ) #name
namespace Core
{
/*!
SystemHandler, stores systems, calls them and handles callbacks from EntityHandler to Systems.
Can be created and called every frame to apply the registered systems transformation on
registered entities
*/
template<typename... Args>
class SystemHandlerTemplate
{
public:
static const int SYSTEM_COUNT = sizeof...(Args);
/*!
Standard constructur, creates systemhandler
*/
SystemHandlerTemplate( )
{
m_systems = {{(new Args())...}};
}
~SystemHandlerTemplate()
{
}
/*!
Returns how many systems were compiled into the systemhandler
*/
int GetSystemCount()
{
return SYSTEM_COUNT;
}
/*!
Main update loop, called every frame to update all systems
*/
void Update( float delta )
{
for( int i = 0; i < SYSTEM_COUNT; i++ )
{
m_timer.Start();
m_systems[i]->Update( delta );
m_timer.Stop();
std::chrono::microseconds diff = m_timer.GetDelta();
m_frameTimes[i] = diff;
}
}
/*!
Intended to be called by EntityHandler when entities are created, modified or removed.
*/
void CallChangedEntity( Entity id, Aspect old_asp, Aspect new_asp )
{
for( int i = 0; i < SYSTEM_COUNT; i++ )
{
m_systems[i]->ChangedEntity( id, old_asp, new_asp );
}
};
/*!
This function primarily exist for testing purposes,
don't use it without thinking about it first.
*/
BaseSystem *GetSystem( int id )
{
return m_systems[id];
}
template <typename System>
System* GetSystem()
{
return reinterpret_cast<System*>(m_systems[Index<System, std::tuple<Args...>>::value]);
}
std::vector<std::pair<const char*,std::chrono::microseconds>> GetFrameTime()
{
std::vector<std::pair<const char*,std::chrono::microseconds>> ar;
for( int i = 0; i < SYSTEM_COUNT; i++ )
{
ar.push_back( std::pair<const char*, std::chrono::microseconds>( m_systems[i]->GetHumanName(), m_frameTimes[i] ) );
}
return ar;
}
private:
std::array<BaseSystem*,SYSTEM_COUNT> m_systems;
std::array<std::chrono::microseconds,SYSTEM_COUNT> m_frameTimes;
HighresTimer m_timer;
};
}
#endif
| 25.517241
| 131
| 0.556757
|
autious
|
42f82baaa8b1c4c175089148c6959535148f32b9
| 228,601
|
cpp
|
C++
|
GCG_Source.build/module.oauthlib.oauth2.rfc6749.grant_types.refresh_token.cpp
|
Pckool/GCG
|
cee786d04ea30f3995e910bca82635f442b2a6a8
|
[
"MIT"
] | null | null | null |
GCG_Source.build/module.oauthlib.oauth2.rfc6749.grant_types.refresh_token.cpp
|
Pckool/GCG
|
cee786d04ea30f3995e910bca82635f442b2a6a8
|
[
"MIT"
] | null | null | null |
GCG_Source.build/module.oauthlib.oauth2.rfc6749.grant_types.refresh_token.cpp
|
Pckool/GCG
|
cee786d04ea30f3995e910bca82635f442b2a6a8
|
[
"MIT"
] | null | null | null |
/* Generated code for Python source for module 'oauthlib.oauth2.rfc6749.grant_types.refresh_token'
* 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_oauthlib$oauth2$rfc6749$grant_types$refresh_token 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_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
PyDictObject *moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
/* The module constants used, if any. */
extern PyObject *const_str_plain_validate_token_request;
extern PyObject *const_str_plain_scopes;
extern PyObject *const_str_plain_headers;
extern PyObject *const_str_plain_metaclass;
extern PyObject *const_tuple_str_plain_errors_str_plain_utils_tuple;
extern PyObject *const_str_plain___spec__;
extern PyObject *const_str_plain_request;
extern PyObject *const_str_plain_getLogger;
static PyObject *const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5;
extern PyObject *const_dict_empty;
extern PyObject *const_str_plain_refresh_token;
static PyObject *const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple;
extern PyObject *const_str_plain___file__;
extern PyObject *const_str_plain_json;
extern PyObject *const_dict_b8647fd2e1f76fc4a4a7d9f73ab075f3;
static PyObject *const_str_plain_original_scopes;
extern PyObject *const_str_plain_client_id;
extern PyObject *const_str_plain_scope;
extern PyObject *const_str_digest_db863ae963136937930c789e9568c079;
extern PyObject *const_str_plain_pre_token;
extern PyObject *const_str_plain_validator;
static PyObject *const_str_digest_012be4d46b429a4aec730cf0f5831f69;
extern PyObject *const_str_plain_utils;
extern PyObject *const_str_plain___doc__;
extern PyObject *const_str_plain_create_token;
extern PyObject *const_str_plain_absolute_import;
extern PyObject *const_str_plain_description;
extern PyObject *const_str_plain_save_token;
static PyObject *const_str_digest_928cbf9bd4fb24f0cb2a442eef2e1a98;
extern PyObject *const_str_digest_1781891970018ef9597f363946d7327b;
extern PyObject *const_str_plain_modifier;
extern PyObject *const_str_plain___package__;
extern PyObject *const_str_plain_validate_grant_type;
extern PyObject *const_str_plain_s;
static PyObject *const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple;
extern PyObject *const_str_angle_genexpr;
extern PyObject *const_str_plain_OAuth2Error;
extern PyObject *const_str_plain___qualname__;
static PyObject *const_str_digest_5c08ddb60a0545fd1e17baf3a6ca1b93;
extern PyObject *const_str_digest_b9c4baf879ebd882d40843df3a4dead7;
static PyObject *const_str_digest_2683d3f8d9f4c4f400b58e6db8957b1b;
extern PyObject *const_str_digest_a97b46010ba2d7a042fbaf3749619f69;
static PyObject *const_str_digest_7d87b8a7beb472784c8f817c5cf003af;
extern PyObject *const_str_plain_all;
extern PyObject *const_str_plain_authenticate_client_id;
extern PyObject *const_str_plain_e;
extern PyObject *const_str_plain_create_token_response;
extern PyObject *const_str_plain_validate_refresh_token;
static PyObject *const_str_digest_db37fe24851f7ebc30f9e552d120d953;
extern PyObject *const_tuple_empty;
extern PyObject *const_str_plain_status_code;
extern PyObject *const_str_plain___loader__;
extern PyObject *const_str_plain_errors;
extern PyObject *const_str_plain_InvalidClientError;
static PyObject *const_str_digest_cb8a1ca4c0d67d12f88e0ed3a0740e39;
extern PyObject *const_tuple_str_plain_RequestValidator_tuple;
extern PyObject *const_str_plain_grant_type;
extern PyObject *const_str_plain_token;
extern PyObject *const_str_plain_ModuleSpec;
extern PyObject *const_str_digest_6d6a615162e89eb148ba9bf8dbfc06d3;
extern PyObject *const_str_plain_scope_to_list;
static PyObject *const_tuple_22acf86284f4127a5583eccb3d24d717_tuple;
extern PyObject *const_str_plain_get_original_scopes;
extern PyObject *const_tuple_str_plain_GrantTypeBase_tuple;
static PyObject *const_str_digest_98c3ffb3273d178290c8022fb1d11588;
extern PyObject *const_str_digest_08fe0cb1e68b13e3e2a5584b97ab8c6f;
extern PyObject *const_str_digest_cd3e142ba7edbf373f9af32f193dc8b0;
extern PyObject *const_int_0;
extern PyObject *const_str_plain_request_validator;
extern PyObject *const_str_plain_dumps;
extern PyObject *const_tuple_none_true_tuple;
extern PyObject *const_str_plain_log;
static PyObject *const_str_digest_6568feb2cea58a2d23fcc0174d2a66c2;
extern PyObject *const_str_plain_GrantTypeBase;
extern PyObject *const_tuple_80aaca258c5d96cc6d36a8af840923ea_tuple;
extern PyObject *const_str_plain_RequestValidator;
extern PyObject *const_str_plain_base;
extern PyObject *const_str_plain_UnsupportedGrantTypeError;
extern PyObject *const_str_plain_post_token;
extern PyObject *const_int_pos_200;
extern PyObject *const_str_plain_InvalidRequestError;
extern PyObject *const_str_digest_12db482c55f456d3fa96605a189c21fd;
static PyObject *const_str_digest_eb1c78d62a3d3030bb88e6017862dd99;
extern PyObject *const_str_plain___cached__;
extern PyObject *const_str_plain_InvalidScopeError;
extern PyObject *const_str_plain___class__;
extern PyObject *const_str_plain___module__;
extern PyObject *const_str_plain_RefreshTokenGrant;
extern PyObject *const_str_plain_debug;
extern PyObject *const_str_plain_unicode_literals;
extern PyObject *const_str_plain_is_within_original_scope;
extern PyObject *const_str_plain_authenticate_client;
extern PyObject *const_int_pos_1;
static PyObject *const_str_digest_0a85429d17cf7c1498bc5d74cde5deef;
static PyObject *const_str_digest_593f75e6de3a53b8e237ecdc0b168189;
extern PyObject *const_str_plain_token_handler;
extern PyObject *const_str_plain_client_authentication_required;
extern PyObject *const_str_plain___prepare__;
extern PyObject *const_str_plain___init__;
extern PyObject *const_str_plain_client;
extern PyObject *const_str_plain_Pragma;
extern PyObject *const_str_digest_8731f29ba21067fcd86e2560f48c09b4;
extern PyObject *const_str_plain_self;
static PyObject *const_str_digest_46e1c89fb94f5988723754dea0b7370c;
extern PyObject *const_str_digest_468773523eb8e0ab1a2621d8a4b4fbf2;
extern PyObject *const_str_plain_kwargs;
static PyObject *const_tuple_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5_tuple;
extern PyObject *const_str_plain_custom_validators;
extern PyObject *const_str_plain_InvalidGrantError;
extern PyObject *const_int_pos_2;
static PyObject *const_str_digest_50648c8293be1086ed1e6a8fd752ea07;
extern PyObject *const_str_plain_logging;
extern PyObject *const_str_empty;
static PyObject *const_str_plain_issue_new_refresh_tokens;
static PyObject *const_str_digest_5cace64d74a86e3d077a283b714130f4;
extern PyObject *const_str_plain__token_modifiers;
static PyObject *module_filename_obj;
static bool constants_created = false;
static void createModuleConstants( void )
{
const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5 = UNSTREAM_STRING( &constant_bin[ 1721206 ], 49, 0 );
const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple = PyTuple_New( 5 );
PyTuple_SET_ITEM( const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 0, const_str_plain_self ); Py_INCREF( const_str_plain_self );
PyTuple_SET_ITEM( const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 1, const_str_plain_request_validator ); Py_INCREF( const_str_plain_request_validator );
const_str_plain_issue_new_refresh_tokens = UNSTREAM_STRING( &constant_bin[ 1721255 ], 24, 1 );
PyTuple_SET_ITEM( const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 2, const_str_plain_issue_new_refresh_tokens ); Py_INCREF( const_str_plain_issue_new_refresh_tokens );
PyTuple_SET_ITEM( const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 3, const_str_plain_kwargs ); Py_INCREF( const_str_plain_kwargs );
PyTuple_SET_ITEM( const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 4, const_str_plain___class__ ); Py_INCREF( const_str_plain___class__ );
const_str_plain_original_scopes = UNSTREAM_STRING( &constant_bin[ 1721279 ], 15, 1 );
const_str_digest_012be4d46b429a4aec730cf0f5831f69 = UNSTREAM_STRING( &constant_bin[ 1721294 ], 104, 0 );
const_str_digest_928cbf9bd4fb24f0cb2a442eef2e1a98 = UNSTREAM_STRING( &constant_bin[ 1721398 ], 40, 0 );
const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple = PyTuple_New( 3 );
PyTuple_SET_ITEM( const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple, 0, const_str_digest_b9c4baf879ebd882d40843df3a4dead7 ); Py_INCREF( const_str_digest_b9c4baf879ebd882d40843df3a4dead7 );
PyTuple_SET_ITEM( const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple, 1, const_str_plain_s ); Py_INCREF( const_str_plain_s );
PyTuple_SET_ITEM( const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple, 2, const_str_plain_original_scopes ); Py_INCREF( const_str_plain_original_scopes );
const_str_digest_5c08ddb60a0545fd1e17baf3a6ca1b93 = UNSTREAM_STRING( &constant_bin[ 1721438 ], 26, 0 );
const_str_digest_2683d3f8d9f4c4f400b58e6db8957b1b = UNSTREAM_STRING( &constant_bin[ 1721464 ], 43, 0 );
const_str_digest_7d87b8a7beb472784c8f817c5cf003af = UNSTREAM_STRING( &constant_bin[ 1721507 ], 36, 0 );
const_str_digest_db37fe24851f7ebc30f9e552d120d953 = UNSTREAM_STRING( &constant_bin[ 1721543 ], 39, 0 );
const_str_digest_cb8a1ca4c0d67d12f88e0ed3a0740e39 = UNSTREAM_STRING( &constant_bin[ 1721582 ], 41, 0 );
const_tuple_22acf86284f4127a5583eccb3d24d717_tuple = PyTuple_New( 4 );
PyTuple_SET_ITEM( const_tuple_22acf86284f4127a5583eccb3d24d717_tuple, 0, const_str_plain_self ); Py_INCREF( const_str_plain_self );
PyTuple_SET_ITEM( const_tuple_22acf86284f4127a5583eccb3d24d717_tuple, 1, const_str_plain_request ); Py_INCREF( const_str_plain_request );
PyTuple_SET_ITEM( const_tuple_22acf86284f4127a5583eccb3d24d717_tuple, 2, const_str_plain_validator ); Py_INCREF( const_str_plain_validator );
PyTuple_SET_ITEM( const_tuple_22acf86284f4127a5583eccb3d24d717_tuple, 3, const_str_plain_original_scopes ); Py_INCREF( const_str_plain_original_scopes );
const_str_digest_98c3ffb3273d178290c8022fb1d11588 = UNSTREAM_STRING( &constant_bin[ 1721623 ], 52, 0 );
const_str_digest_6568feb2cea58a2d23fcc0174d2a66c2 = UNSTREAM_STRING( &constant_bin[ 1721675 ], 32, 0 );
const_str_digest_eb1c78d62a3d3030bb88e6017862dd99 = UNSTREAM_STRING( &constant_bin[ 1721707 ], 42, 0 );
const_str_digest_0a85429d17cf7c1498bc5d74cde5deef = UNSTREAM_STRING( &constant_bin[ 1721749 ], 59, 0 );
const_str_digest_593f75e6de3a53b8e237ecdc0b168189 = UNSTREAM_STRING( &constant_bin[ 1721808 ], 37, 0 );
const_str_digest_46e1c89fb94f5988723754dea0b7370c = UNSTREAM_STRING( &constant_bin[ 1721845 ], 43, 0 );
const_tuple_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5_tuple = PyTuple_New( 1 );
PyTuple_SET_ITEM( const_tuple_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5_tuple, 0, const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5 ); Py_INCREF( const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5 );
const_str_digest_50648c8293be1086ed1e6a8fd752ea07 = UNSTREAM_STRING( &constant_bin[ 1721888 ], 58, 0 );
const_str_digest_5cace64d74a86e3d077a283b714130f4 = UNSTREAM_STRING( &constant_bin[ 1721946 ], 943, 0 );
constants_created = true;
}
#ifndef __NUITKA_NO_ASSERT__
void checkModuleConstants_oauthlib$oauth2$rfc6749$grant_types$refresh_token( void )
{
// The module may not have been used at all.
if (constants_created == false) return;
}
#endif
// The module code objects.
static PyCodeObject *codeobj_d97b4b0e63e7446557f598731ac2685c;
static PyCodeObject *codeobj_fecfc1a1477f82e7708776ac673a0656;
static PyCodeObject *codeobj_b955a297be0011278f93db2870abd52a;
static PyCodeObject *codeobj_4fb8fb5c300d19c3880e6efcc7e0f90c;
static PyCodeObject *codeobj_63747e9cb9a8f20473e6b2eb0348134b;
static void createModuleCodeObjects(void)
{
module_filename_obj = MAKE_RELATIVE_PATH( const_str_digest_98c3ffb3273d178290c8022fb1d11588 );
codeobj_d97b4b0e63e7446557f598731ac2685c = MAKE_CODEOBJ( module_filename_obj, const_str_angle_genexpr, 121, const_tuple_b57fb904a2ca549f355eb6aebf635a97_tuple, 1, 0, CO_GENERATOR | CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_fecfc1a1477f82e7708776ac673a0656 = MAKE_CODEOBJ( module_filename_obj, const_str_digest_50648c8293be1086ed1e6a8fd752ea07, 1, const_tuple_empty, 0, 0, CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_b955a297be0011278f93db2870abd52a = MAKE_CODEOBJ( module_filename_obj, const_str_plain___init__, 25, const_tuple_9ea1b4b7c46ffc93a2b54606eb2d9ffd_tuple, 3, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_VARKEYWORDS | CO_FUTURE_UNICODE_LITERALS );
codeobj_4fb8fb5c300d19c3880e6efcc7e0f90c = MAKE_CODEOBJ( module_filename_obj, const_str_plain_create_token_response, 33, const_tuple_80aaca258c5d96cc6d36a8af840923ea_tuple, 3, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
codeobj_63747e9cb9a8f20473e6b2eb0348134b = MAKE_CODEOBJ( module_filename_obj, const_str_plain_validate_token_request, 74, const_tuple_22acf86284f4127a5583eccb3d24d717_tuple, 2, 0, CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE | CO_FUTURE_UNICODE_LITERALS );
}
// The module function declarations.
#if _NUITKA_EXPERIMENTAL_GENERATOR_GOTO
static PyObject *oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_context( struct Nuitka_GeneratorObject *generator, PyObject *yield_return_value );
#else
static void oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_context( struct Nuitka_GeneratorObject *generator );
#endif
NUITKA_CROSS_MODULE PyObject *impl___internal__$$$function_11_complex_call_helper_pos_keywords_star_dict( PyObject **python_pars );
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__( PyObject *defaults );
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response( );
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request( );
// The module function definitions.
static PyObject *impl_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__( 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_self = python_pars[ 0 ];
PyObject *par_request_validator = python_pars[ 1 ];
PyObject *par_issue_new_refresh_tokens = python_pars[ 2 ];
PyObject *par_kwargs = python_pars[ 3 ];
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_dict_key_1;
PyObject *tmp_dict_value_1;
PyObject *tmp_dircall_arg1_1;
PyObject *tmp_dircall_arg2_1;
PyObject *tmp_dircall_arg3_1;
PyObject *tmp_dircall_arg4_1;
PyObject *tmp_object_name_1;
int tmp_res;
PyObject *tmp_return_value;
PyObject *tmp_source_name_1;
PyObject *tmp_tuple_element_1;
PyObject *tmp_type_name_1;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
static struct Nuitka_FrameObject *cache_frame_b955a297be0011278f93db2870abd52a = NULL;
struct Nuitka_FrameObject *frame_b955a297be0011278f93db2870abd52a;
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_b955a297be0011278f93db2870abd52a, codeobj_b955a297be0011278f93db2870abd52a, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_b955a297be0011278f93db2870abd52a = cache_frame_b955a297be0011278f93db2870abd52a;
// Push the new frame as the currently active one.
pushFrameStack( frame_b955a297be0011278f93db2870abd52a );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_b955a297be0011278f93db2870abd52a ) == 2 ); // Frame stack
// Framed code:
tmp_type_name_1 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_RefreshTokenGrant );
if (unlikely( tmp_type_name_1 == NULL ))
{
tmp_type_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_RefreshTokenGrant );
}
if ( tmp_type_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "RefreshTokenGrant" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 28;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
tmp_object_name_1 = par_self;
CHECK_OBJECT( tmp_object_name_1 );
tmp_source_name_1 = BUILTIN_SUPER( tmp_type_name_1, tmp_object_name_1 );
if ( tmp_source_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 28;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
tmp_dircall_arg1_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain___init__ );
Py_DECREF( tmp_source_name_1 );
if ( tmp_dircall_arg1_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 28;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
tmp_dircall_arg2_1 = PyTuple_New( 1 );
tmp_tuple_element_1 = par_request_validator;
if ( tmp_tuple_element_1 == NULL )
{
Py_DECREF( tmp_dircall_arg1_1 );
Py_DECREF( tmp_dircall_arg2_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request_validator" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 29;
type_description_1 = "ooooN";
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 = _PyDict_NewPresized( 1 );
tmp_dict_key_1 = const_str_plain_issue_new_refresh_tokens;
tmp_dict_value_1 = par_issue_new_refresh_tokens;
if ( tmp_dict_value_1 == NULL )
{
Py_DECREF( tmp_dircall_arg1_1 );
Py_DECREF( tmp_dircall_arg2_1 );
Py_DECREF( tmp_dircall_arg3_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "issue_new_refresh_tokens" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 30;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_dircall_arg3_1, tmp_dict_key_1, tmp_dict_value_1 );
assert( !(tmp_res != 0) );
tmp_dircall_arg4_1 = par_kwargs;
if ( tmp_dircall_arg4_1 == NULL )
{
Py_DECREF( tmp_dircall_arg1_1 );
Py_DECREF( tmp_dircall_arg2_1 );
Py_DECREF( tmp_dircall_arg3_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "kwargs" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 31;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_dircall_arg4_1 );
{
PyObject *dir_call_args[] = {tmp_dircall_arg1_1, tmp_dircall_arg2_1, tmp_dircall_arg3_1, tmp_dircall_arg4_1};
tmp_unused = impl___internal__$$$function_11_complex_call_helper_pos_keywords_star_dict( dir_call_args );
}
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 28;
type_description_1 = "ooooN";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
#if 0
RESTORE_FRAME_EXCEPTION( frame_b955a297be0011278f93db2870abd52a );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_b955a297be0011278f93db2870abd52a );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_b955a297be0011278f93db2870abd52a, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_b955a297be0011278f93db2870abd52a->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_b955a297be0011278f93db2870abd52a, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_b955a297be0011278f93db2870abd52a,
type_description_1,
par_self,
par_request_validator,
par_issue_new_refresh_tokens,
par_kwargs,
NULL
);
// Release cached frame.
if ( frame_b955a297be0011278f93db2870abd52a == cache_frame_b955a297be0011278f93db2870abd52a )
{
Py_DECREF( frame_b955a297be0011278f93db2870abd52a );
}
cache_frame_b955a297be0011278f93db2870abd52a = NULL;
assertFrameObject( frame_b955a297be0011278f93db2870abd52a );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
tmp_return_value = Py_None;
Py_INCREF( tmp_return_value );
goto try_return_handler_1;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__ );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_self );
par_self = NULL;
Py_XDECREF( par_request_validator );
par_request_validator = NULL;
Py_XDECREF( par_issue_new_refresh_tokens );
par_issue_new_refresh_tokens = NULL;
Py_XDECREF( par_kwargs );
par_kwargs = 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_self );
par_self = NULL;
Py_XDECREF( par_request_validator );
par_request_validator = NULL;
Py_XDECREF( par_issue_new_refresh_tokens );
par_issue_new_refresh_tokens = NULL;
Py_XDECREF( par_kwargs );
par_kwargs = 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( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__ );
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_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response( 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_self = python_pars[ 0 ];
PyObject *par_request = python_pars[ 1 ];
PyObject *par_token_handler = python_pars[ 2 ];
PyObject *var_headers = NULL;
PyObject *var_e = NULL;
PyObject *var_token = NULL;
PyObject *var_modifier = NULL;
PyObject *tmp_for_loop_1__for_iterator = NULL;
PyObject *tmp_for_loop_1__iter_value = 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_preserved_type_1;
PyObject *exception_preserved_value_1;
PyTracebackObject *exception_preserved_tb_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_name_1;
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_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_compare_left_1;
PyObject *tmp_compare_right_1;
PyObject *tmp_dict_key_1;
PyObject *tmp_dict_key_2;
PyObject *tmp_dict_value_1;
PyObject *tmp_dict_value_2;
int tmp_exc_match_exception_match_1;
PyObject *tmp_iter_arg_1;
PyObject *tmp_kw_name_1;
PyObject *tmp_next_source_1;
int tmp_res;
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_source_name_12;
PyObject *tmp_source_name_13;
PyObject *tmp_source_name_14;
PyObject *tmp_tuple_element_1;
PyObject *tmp_tuple_element_2;
PyObject *tmp_tuple_element_3;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
static struct Nuitka_FrameObject *cache_frame_4fb8fb5c300d19c3880e6efcc7e0f90c = NULL;
struct Nuitka_FrameObject *frame_4fb8fb5c300d19c3880e6efcc7e0f90c;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
// Actual function code.
tmp_assign_source_1 = PyDict_Copy( const_dict_b8647fd2e1f76fc4a4a7d9f73ab075f3 );
assert( var_headers == NULL );
var_headers = tmp_assign_source_1;
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_4fb8fb5c300d19c3880e6efcc7e0f90c, codeobj_4fb8fb5c300d19c3880e6efcc7e0f90c, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_4fb8fb5c300d19c3880e6efcc7e0f90c = cache_frame_4fb8fb5c300d19c3880e6efcc7e0f90c;
// Push the new frame as the currently active one.
pushFrameStack( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_4fb8fb5c300d19c3880e6efcc7e0f90c ) == 2 ); // Frame stack
// Framed code:
// Tried code:
tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_1 == NULL ))
{
tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 58;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_debug );
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 58;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
tmp_args_element_name_1 = const_str_digest_593f75e6de3a53b8e237ecdc0b168189;
tmp_args_element_name_2 = par_request;
if ( tmp_args_element_name_2 == 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", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 58;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 58;
{
PyObject *call_args[] = { tmp_args_element_name_1, tmp_args_element_name_2 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_1, call_args );
}
Py_DECREF( tmp_called_name_1 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 58;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
Py_DECREF( tmp_unused );
tmp_source_name_2 = par_self;
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 59;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_validate_token_request );
if ( tmp_called_name_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 59;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
tmp_args_element_name_3 = par_request;
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", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 59;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 59;
{
PyObject *call_args[] = { tmp_args_element_name_3 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_2, call_args );
}
Py_DECREF( tmp_called_name_2 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 59;
type_description_1 = "ooooooo";
goto try_except_handler_2;
}
Py_DECREF( tmp_unused );
goto try_end_1;
// Exception handler code:
try_except_handler_2:;
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;
// 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_4fb8fb5c300d19c3880e6efcc7e0f90c, exception_keeper_lineno_1 );
}
else if ( exception_keeper_lineno_1 != 0 )
{
exception_keeper_tb_1 = ADD_TRACEBACK( exception_keeper_tb_1, frame_4fb8fb5c300d19c3880e6efcc7e0f90c, 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_source_name_3 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_3 == NULL ))
{
tmp_source_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_3 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 60;
type_description_1 = "ooooooo";
goto try_except_handler_3;
}
tmp_compare_right_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_OAuth2Error );
if ( tmp_compare_right_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 60;
type_description_1 = "ooooooo";
goto try_except_handler_3;
}
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 = 60;
type_description_1 = "ooooooo";
goto try_except_handler_3;
}
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_2 = PyThreadState_GET()->exc_value;
assert( var_e == NULL );
Py_INCREF( tmp_assign_source_2 );
var_e = tmp_assign_source_2;
// Tried code:
tmp_return_value = PyTuple_New( 3 );
tmp_tuple_element_1 = var_headers;
if ( tmp_tuple_element_1 == NULL )
{
Py_DECREF( tmp_return_value );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "headers" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 61;
type_description_1 = "ooooooo";
goto try_except_handler_4;
}
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_return_value, 0, tmp_tuple_element_1 );
tmp_source_name_4 = var_e;
CHECK_OBJECT( tmp_source_name_4 );
tmp_tuple_element_1 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_json );
if ( tmp_tuple_element_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_return_value );
exception_lineno = 61;
type_description_1 = "ooooooo";
goto try_except_handler_4;
}
PyTuple_SET_ITEM( tmp_return_value, 1, tmp_tuple_element_1 );
tmp_source_name_5 = var_e;
if ( tmp_source_name_5 == NULL )
{
Py_DECREF( tmp_return_value );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "e" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 61;
type_description_1 = "ooooooo";
goto try_except_handler_4;
}
tmp_tuple_element_1 = LOOKUP_ATTRIBUTE( tmp_source_name_5, const_str_plain_status_code );
if ( tmp_tuple_element_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_return_value );
exception_lineno = 61;
type_description_1 = "ooooooo";
goto try_except_handler_4;
}
PyTuple_SET_ITEM( tmp_return_value, 2, tmp_tuple_element_1 );
goto try_return_handler_4;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response );
return NULL;
// Return handler code:
try_return_handler_4:;
Py_XDECREF( var_e );
var_e = NULL;
goto try_return_handler_3;
// Exception handler code:
try_except_handler_4:;
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( var_e );
var_e = 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 try_except_handler_3;
// End of try:
goto branch_end_1;
branch_no_1:;
tmp_result = RERAISE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
if (unlikely( tmp_result == false ))
{
exception_lineno = 57;
}
if (exception_tb && exception_tb->tb_frame == &frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame) frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = exception_tb->tb_lineno;
type_description_1 = "ooooooo";
goto try_except_handler_3;
branch_end_1:;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response );
return NULL;
// Return handler code:
try_return_handler_3:;
// Restore previous exception.
SET_CURRENT_EXCEPTION( exception_preserved_type_1, exception_preserved_value_1, exception_preserved_tb_1 );
goto frame_return_exit_1;
// 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;
// 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_3;
exception_value = exception_keeper_value_3;
exception_tb = exception_keeper_tb_3;
exception_lineno = exception_keeper_lineno_3;
goto frame_exception_exit_1;
// End of try:
// End of try:
try_end_1:;
tmp_source_name_6 = par_token_handler;
if ( tmp_source_name_6 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "token_handler" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 63;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_6, const_str_plain_create_token );
if ( tmp_called_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 63;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_name_1 = PyTuple_New( 1 );
tmp_tuple_element_2 = par_request;
if ( tmp_tuple_element_2 == NULL )
{
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_args_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 63;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_tuple_element_2 );
PyTuple_SET_ITEM( tmp_args_name_1, 0, tmp_tuple_element_2 );
tmp_kw_name_1 = _PyDict_NewPresized( 2 );
tmp_dict_key_1 = const_str_plain_refresh_token;
tmp_source_name_7 = par_self;
if ( tmp_source_name_7 == NULL )
{
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_args_name_1 );
Py_DECREF( tmp_kw_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 64;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_dict_value_1 = LOOKUP_ATTRIBUTE( tmp_source_name_7, const_str_plain_issue_new_refresh_tokens );
if ( tmp_dict_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_args_name_1 );
Py_DECREF( tmp_kw_name_1 );
exception_lineno = 64;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_1, tmp_dict_value_1 );
Py_DECREF( tmp_dict_value_1 );
assert( !(tmp_res != 0) );
tmp_dict_key_2 = const_str_plain_save_token;
tmp_dict_value_2 = Py_False;
tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_2, tmp_dict_value_2 );
assert( !(tmp_res != 0) );
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 63;
tmp_assign_source_3 = CALL_FUNCTION( tmp_called_name_3, tmp_args_name_1, tmp_kw_name_1 );
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_args_name_1 );
Py_DECREF( tmp_kw_name_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 = "ooooooo";
goto frame_exception_exit_1;
}
assert( var_token == NULL );
var_token = tmp_assign_source_3;
tmp_source_name_8 = par_self;
if ( tmp_source_name_8 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 66;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_iter_arg_1 = LOOKUP_ATTRIBUTE( tmp_source_name_8, const_str_plain__token_modifiers );
if ( tmp_iter_arg_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 66;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_assign_source_4 = MAKE_ITERATOR( tmp_iter_arg_1 );
Py_DECREF( tmp_iter_arg_1 );
if ( tmp_assign_source_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 66;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
assert( tmp_for_loop_1__for_iterator == NULL );
tmp_for_loop_1__for_iterator = tmp_assign_source_4;
// Tried code:
loop_start_1:;
tmp_next_source_1 = tmp_for_loop_1__for_iterator;
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_1 = "ooooooo";
exception_lineno = 66;
goto try_except_handler_5;
}
}
{
PyObject *old = tmp_for_loop_1__iter_value;
tmp_for_loop_1__iter_value = tmp_assign_source_5;
Py_XDECREF( old );
}
tmp_assign_source_6 = tmp_for_loop_1__iter_value;
CHECK_OBJECT( tmp_assign_source_6 );
{
PyObject *old = var_modifier;
var_modifier = tmp_assign_source_6;
Py_INCREF( var_modifier );
Py_XDECREF( old );
}
tmp_called_name_4 = var_modifier;
CHECK_OBJECT( tmp_called_name_4 );
tmp_args_element_name_4 = var_token;
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", "token" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 67;
type_description_1 = "ooooooo";
goto try_except_handler_5;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 67;
{
PyObject *call_args[] = { tmp_args_element_name_4 };
tmp_assign_source_7 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_4, call_args );
}
if ( tmp_assign_source_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 67;
type_description_1 = "ooooooo";
goto try_except_handler_5;
}
{
PyObject *old = var_token;
var_token = tmp_assign_source_7;
Py_XDECREF( old );
}
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 66;
type_description_1 = "ooooooo";
goto try_except_handler_5;
}
goto loop_start_1;
loop_end_1:;
goto try_end_2;
// Exception handler code:
try_except_handler_5:;
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;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
// Re-raise.
exception_type = exception_keeper_type_4;
exception_value = exception_keeper_value_4;
exception_tb = exception_keeper_tb_4;
exception_lineno = exception_keeper_lineno_4;
goto frame_exception_exit_1;
// End of try:
try_end_2:;
Py_XDECREF( tmp_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
tmp_source_name_10 = par_self;
if ( tmp_source_name_10 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_source_name_9 = LOOKUP_ATTRIBUTE( tmp_source_name_10, const_str_plain_request_validator );
if ( tmp_source_name_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_called_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_9, const_str_plain_save_token );
Py_DECREF( tmp_source_name_9 );
if ( tmp_called_name_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_5 = var_token;
if ( tmp_args_element_name_5 == 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", "token" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_6 = par_request;
if ( tmp_args_element_name_6 == 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", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 68;
{
PyObject *call_args[] = { tmp_args_element_name_5, tmp_args_element_name_6 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( 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 = 68;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_11 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_11 == NULL ))
{
tmp_source_name_11 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_11 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 70;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_called_name_6 = LOOKUP_ATTRIBUTE( tmp_source_name_11, const_str_plain_debug );
if ( tmp_called_name_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 70;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_7 = const_str_digest_46e1c89fb94f5988723754dea0b7370c;
tmp_source_name_12 = par_request;
if ( tmp_source_name_12 == 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", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 71;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_8 = LOOKUP_ATTRIBUTE( tmp_source_name_12, const_str_plain_client_id );
if ( tmp_args_element_name_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_6 );
exception_lineno = 71;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_source_name_13 = par_request;
if ( tmp_source_name_13 == NULL )
{
Py_DECREF( tmp_called_name_6 );
Py_DECREF( tmp_args_element_name_8 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 71;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_9 = LOOKUP_ATTRIBUTE( tmp_source_name_13, const_str_plain_client );
if ( tmp_args_element_name_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_6 );
Py_DECREF( tmp_args_element_name_8 );
exception_lineno = 71;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_10 = var_token;
if ( tmp_args_element_name_10 == NULL )
{
Py_DECREF( tmp_called_name_6 );
Py_DECREF( tmp_args_element_name_8 );
Py_DECREF( tmp_args_element_name_9 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "token" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 71;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 70;
{
PyObject *call_args[] = { tmp_args_element_name_7, tmp_args_element_name_8, tmp_args_element_name_9, tmp_args_element_name_10 };
tmp_unused = CALL_FUNCTION_WITH_ARGS4( tmp_called_name_6, call_args );
}
Py_DECREF( tmp_called_name_6 );
Py_DECREF( tmp_args_element_name_8 );
Py_DECREF( tmp_args_element_name_9 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 70;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_return_value = PyTuple_New( 3 );
tmp_tuple_element_3 = var_headers;
if ( tmp_tuple_element_3 == NULL )
{
Py_DECREF( tmp_return_value );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "headers" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 72;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
Py_INCREF( tmp_tuple_element_3 );
PyTuple_SET_ITEM( tmp_return_value, 0, tmp_tuple_element_3 );
tmp_source_name_14 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_json );
if (unlikely( tmp_source_name_14 == NULL ))
{
tmp_source_name_14 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_json );
}
if ( tmp_source_name_14 == NULL )
{
Py_DECREF( tmp_return_value );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "json" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 72;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_called_name_7 = LOOKUP_ATTRIBUTE( tmp_source_name_14, const_str_plain_dumps );
if ( tmp_called_name_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_return_value );
exception_lineno = 72;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
tmp_args_element_name_11 = var_token;
if ( tmp_args_element_name_11 == NULL )
{
Py_DECREF( tmp_return_value );
Py_DECREF( tmp_called_name_7 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "token" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 72;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame.f_lineno = 72;
{
PyObject *call_args[] = { tmp_args_element_name_11 };
tmp_tuple_element_3 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_7, call_args );
}
Py_DECREF( tmp_called_name_7 );
if ( tmp_tuple_element_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_return_value );
exception_lineno = 72;
type_description_1 = "ooooooo";
goto frame_exception_exit_1;
}
PyTuple_SET_ITEM( tmp_return_value, 1, tmp_tuple_element_3 );
tmp_tuple_element_3 = const_int_pos_200;
Py_INCREF( tmp_tuple_element_3 );
PyTuple_SET_ITEM( tmp_return_value, 2, tmp_tuple_element_3 );
goto frame_return_exit_1;
#if 1
RESTORE_FRAME_EXCEPTION( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_return_exit_1:;
#if 1
RESTORE_FRAME_EXCEPTION( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
#endif
// Put the previous frame back on top.
popFrameStack();
goto try_return_handler_1;
frame_exception_exit_1:;
#if 1
RESTORE_FRAME_EXCEPTION( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_4fb8fb5c300d19c3880e6efcc7e0f90c, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_4fb8fb5c300d19c3880e6efcc7e0f90c->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_4fb8fb5c300d19c3880e6efcc7e0f90c, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_4fb8fb5c300d19c3880e6efcc7e0f90c,
type_description_1,
par_self,
par_request,
par_token_handler,
var_headers,
var_e,
var_token,
var_modifier
);
// Release cached frame.
if ( frame_4fb8fb5c300d19c3880e6efcc7e0f90c == cache_frame_4fb8fb5c300d19c3880e6efcc7e0f90c )
{
Py_DECREF( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
}
cache_frame_4fb8fb5c300d19c3880e6efcc7e0f90c = NULL;
assertFrameObject( frame_4fb8fb5c300d19c3880e6efcc7e0f90c );
// 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( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_self );
par_self = NULL;
Py_XDECREF( par_request );
par_request = NULL;
Py_XDECREF( par_token_handler );
par_token_handler = NULL;
Py_XDECREF( var_headers );
var_headers = NULL;
Py_XDECREF( var_e );
var_e = NULL;
Py_XDECREF( var_token );
var_token = NULL;
Py_XDECREF( var_modifier );
var_modifier = NULL;
goto function_return_exit;
// Exception handler code:
try_except_handler_1:;
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;
Py_XDECREF( par_self );
par_self = NULL;
Py_XDECREF( par_request );
par_request = NULL;
Py_XDECREF( par_token_handler );
par_token_handler = NULL;
Py_XDECREF( var_headers );
var_headers = NULL;
Py_XDECREF( var_e );
var_e = NULL;
Py_XDECREF( var_token );
var_token = NULL;
Py_XDECREF( var_modifier );
var_modifier = NULL;
// 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 function_exception_exit;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response );
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_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request( 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_self = python_pars[ 0 ];
PyObject *par_request = python_pars[ 1 ];
PyObject *var_validator = NULL;
struct Nuitka_CellObject *var_original_scopes = PyCell_EMPTY();
PyObject *tmp_for_loop_1__for_iterator = NULL;
PyObject *tmp_for_loop_1__iter_value = NULL;
PyObject *tmp_for_loop_2__for_iterator = NULL;
PyObject *tmp_for_loop_2__iter_value = NULL;
PyObject *tmp_genexpr_1__$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;
PyObject *tmp_and_left_value_1;
PyObject *tmp_and_right_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_args_element_name_16;
PyObject *tmp_args_element_name_17;
PyObject *tmp_args_element_name_18;
PyObject *tmp_args_element_name_19;
PyObject *tmp_args_element_name_20;
PyObject *tmp_args_element_name_21;
PyObject *tmp_args_element_name_22;
PyObject *tmp_args_element_name_23;
PyObject *tmp_args_element_name_24;
PyObject *tmp_args_element_name_25;
PyObject *tmp_args_element_name_26;
PyObject *tmp_args_element_name_27;
PyObject *tmp_args_element_name_28;
PyObject *tmp_args_element_name_29;
PyObject *tmp_args_element_name_30;
PyObject *tmp_args_element_name_31;
PyObject *tmp_args_element_name_32;
PyObject *tmp_args_element_name_33;
PyObject *tmp_assattr_name_1;
PyObject *tmp_assattr_name_2;
PyObject *tmp_assattr_target_1;
PyObject *tmp_assattr_target_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_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_called_name_15;
PyObject *tmp_called_name_16;
PyObject *tmp_called_name_17;
PyObject *tmp_called_name_18;
PyObject *tmp_called_name_19;
PyObject *tmp_called_name_20;
PyObject *tmp_called_name_21;
PyObject *tmp_called_name_22;
PyObject *tmp_called_name_23;
PyObject *tmp_called_name_24;
int tmp_cmp_NotEq_1;
PyObject *tmp_compare_left_1;
PyObject *tmp_compare_left_2;
PyObject *tmp_compare_right_1;
PyObject *tmp_compare_right_2;
int tmp_cond_truth_1;
int tmp_cond_truth_2;
int tmp_cond_truth_3;
int tmp_cond_truth_4;
int tmp_cond_truth_5;
int tmp_cond_truth_6;
PyObject *tmp_cond_value_1;
PyObject *tmp_cond_value_2;
PyObject *tmp_cond_value_3;
PyObject *tmp_cond_value_4;
PyObject *tmp_cond_value_5;
PyObject *tmp_cond_value_6;
PyObject *tmp_dict_key_1;
PyObject *tmp_dict_key_2;
PyObject *tmp_dict_key_3;
PyObject *tmp_dict_key_4;
PyObject *tmp_dict_key_5;
PyObject *tmp_dict_key_6;
PyObject *tmp_dict_key_7;
PyObject *tmp_dict_value_1;
PyObject *tmp_dict_value_2;
PyObject *tmp_dict_value_3;
PyObject *tmp_dict_value_4;
PyObject *tmp_dict_value_5;
PyObject *tmp_dict_value_6;
PyObject *tmp_dict_value_7;
bool tmp_is_1;
PyObject *tmp_iter_arg_1;
PyObject *tmp_iter_arg_2;
PyObject *tmp_iter_arg_3;
PyObject *tmp_kw_name_1;
PyObject *tmp_kw_name_2;
PyObject *tmp_kw_name_3;
PyObject *tmp_kw_name_4;
PyObject *tmp_kw_name_5;
PyObject *tmp_kw_name_6;
PyObject *tmp_next_source_1;
PyObject *tmp_next_source_2;
PyObject *tmp_operand_name_1;
PyObject *tmp_operand_name_2;
PyObject *tmp_outline_return_value_1;
PyObject *tmp_raise_type_1;
PyObject *tmp_raise_type_2;
PyObject *tmp_raise_type_3;
PyObject *tmp_raise_type_4;
PyObject *tmp_raise_type_5;
PyObject *tmp_raise_type_6;
int tmp_res;
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_source_name_12;
PyObject *tmp_source_name_13;
PyObject *tmp_source_name_14;
PyObject *tmp_source_name_15;
PyObject *tmp_source_name_16;
PyObject *tmp_source_name_17;
PyObject *tmp_source_name_18;
PyObject *tmp_source_name_19;
PyObject *tmp_source_name_20;
PyObject *tmp_source_name_21;
PyObject *tmp_source_name_22;
PyObject *tmp_source_name_23;
PyObject *tmp_source_name_24;
PyObject *tmp_source_name_25;
PyObject *tmp_source_name_26;
PyObject *tmp_source_name_27;
PyObject *tmp_source_name_28;
PyObject *tmp_source_name_29;
PyObject *tmp_source_name_30;
PyObject *tmp_source_name_31;
PyObject *tmp_source_name_32;
PyObject *tmp_source_name_33;
PyObject *tmp_source_name_34;
PyObject *tmp_source_name_35;
PyObject *tmp_source_name_36;
PyObject *tmp_source_name_37;
PyObject *tmp_source_name_38;
PyObject *tmp_source_name_39;
PyObject *tmp_source_name_40;
PyObject *tmp_source_name_41;
PyObject *tmp_source_name_42;
PyObject *tmp_source_name_43;
PyObject *tmp_source_name_44;
PyObject *tmp_source_name_45;
PyObject *tmp_source_name_46;
PyObject *tmp_source_name_47;
PyObject *tmp_source_name_48;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
static struct Nuitka_FrameObject *cache_frame_63747e9cb9a8f20473e6b2eb0348134b = NULL;
struct Nuitka_FrameObject *frame_63747e9cb9a8f20473e6b2eb0348134b;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_return_value = NULL;
tmp_outline_return_value_1 = NULL;
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_63747e9cb9a8f20473e6b2eb0348134b, codeobj_63747e9cb9a8f20473e6b2eb0348134b, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token, sizeof(void *)+sizeof(void *)+sizeof(void *)+sizeof(void *) );
frame_63747e9cb9a8f20473e6b2eb0348134b = cache_frame_63747e9cb9a8f20473e6b2eb0348134b;
// Push the new frame as the currently active one.
pushFrameStack( frame_63747e9cb9a8f20473e6b2eb0348134b );
// Mark the frame object as in use, ref count 1 will be up for reuse.
assert( Py_REFCNT( frame_63747e9cb9a8f20473e6b2eb0348134b ) == 2 ); // Frame stack
// Framed code:
tmp_source_name_1 = par_request;
CHECK_OBJECT( tmp_source_name_1 );
tmp_compare_left_1 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_grant_type );
if ( tmp_compare_left_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 76;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_compare_right_1 = const_str_plain_refresh_token;
tmp_cmp_NotEq_1 = RICH_COMPARE_BOOL_NE( tmp_compare_left_1, tmp_compare_right_1 );
if ( tmp_cmp_NotEq_1 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_compare_left_1 );
exception_lineno = 76;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_compare_left_1 );
if ( tmp_cmp_NotEq_1 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_2 == NULL ))
{
tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_2 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 77;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_1 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_UnsupportedGrantTypeError );
if ( tmp_called_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 77;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_1 = _PyDict_NewPresized( 1 );
tmp_dict_key_1 = const_str_plain_request;
tmp_dict_value_1 = par_request;
if ( tmp_dict_value_1 == NULL )
{
Py_DECREF( tmp_called_name_1 );
Py_DECREF( tmp_kw_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 77;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_1, tmp_dict_key_1, tmp_dict_value_1 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 77;
tmp_raise_type_1 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_1, tmp_kw_name_1 );
Py_DECREF( tmp_called_name_1 );
Py_DECREF( tmp_kw_name_1 );
if ( tmp_raise_type_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 77;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_1;
exception_lineno = 77;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_1:;
tmp_source_name_4 = par_self;
if ( tmp_source_name_4 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 79;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_4, const_str_plain_custom_validators );
if ( tmp_source_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 79;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_iter_arg_1 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_pre_token );
Py_DECREF( tmp_source_name_3 );
if ( tmp_iter_arg_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 79;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_assign_source_1 = MAKE_ITERATOR( tmp_iter_arg_1 );
Py_DECREF( tmp_iter_arg_1 );
if ( tmp_assign_source_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 79;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
assert( tmp_for_loop_1__for_iterator == NULL );
tmp_for_loop_1__for_iterator = tmp_assign_source_1;
// Tried code:
loop_start_1:;
tmp_next_source_1 = tmp_for_loop_1__for_iterator;
CHECK_OBJECT( tmp_next_source_1 );
tmp_assign_source_2 = ITERATOR_NEXT( tmp_next_source_1 );
if ( tmp_assign_source_2 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_1;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
exception_lineno = 79;
goto try_except_handler_2;
}
}
{
PyObject *old = tmp_for_loop_1__iter_value;
tmp_for_loop_1__iter_value = tmp_assign_source_2;
Py_XDECREF( old );
}
tmp_assign_source_3 = tmp_for_loop_1__iter_value;
CHECK_OBJECT( tmp_assign_source_3 );
{
PyObject *old = var_validator;
var_validator = tmp_assign_source_3;
Py_INCREF( var_validator );
Py_XDECREF( old );
}
tmp_called_name_2 = var_validator;
CHECK_OBJECT( tmp_called_name_2 );
tmp_args_element_name_1 = par_request;
if ( tmp_args_element_name_1 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 80;
type_description_1 = "oooc";
goto try_except_handler_2;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 80;
{
PyObject *call_args[] = { tmp_args_element_name_1 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_2, call_args );
}
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 80;
type_description_1 = "oooc";
goto try_except_handler_2;
}
Py_DECREF( tmp_unused );
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 79;
type_description_1 = "oooc";
goto try_except_handler_2;
}
goto loop_start_1;
loop_end_1:;
goto try_end_1;
// Exception handler code:
try_except_handler_2:;
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_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = 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_for_loop_1__iter_value );
tmp_for_loop_1__iter_value = NULL;
Py_XDECREF( tmp_for_loop_1__for_iterator );
tmp_for_loop_1__for_iterator = NULL;
tmp_source_name_5 = par_request;
if ( tmp_source_name_5 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 82;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_compare_left_2 = LOOKUP_ATTRIBUTE( tmp_source_name_5, const_str_plain_refresh_token );
if ( tmp_compare_left_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 82;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_compare_right_2 = Py_None;
tmp_is_1 = ( tmp_compare_left_2 == tmp_compare_right_2 );
Py_DECREF( tmp_compare_left_2 );
if ( tmp_is_1 )
{
goto branch_yes_2;
}
else
{
goto branch_no_2;
}
branch_yes_2:;
tmp_source_name_6 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_6 == NULL ))
{
tmp_source_name_6 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_6 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 83;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_6, const_str_plain_InvalidRequestError );
if ( tmp_called_name_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 83;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_2 = _PyDict_NewPresized( 2 );
tmp_dict_key_2 = const_str_plain_description;
tmp_dict_value_2 = const_str_digest_6568feb2cea58a2d23fcc0174d2a66c2;
tmp_res = PyDict_SetItem( tmp_kw_name_2, tmp_dict_key_2, tmp_dict_value_2 );
assert( !(tmp_res != 0) );
tmp_dict_key_3 = const_str_plain_request;
tmp_dict_value_3 = par_request;
if ( tmp_dict_value_3 == NULL )
{
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_kw_name_2 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 85;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_2, tmp_dict_key_3, tmp_dict_value_3 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 83;
tmp_raise_type_2 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_3, tmp_kw_name_2 );
Py_DECREF( tmp_called_name_3 );
Py_DECREF( tmp_kw_name_2 );
if ( tmp_raise_type_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 83;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_2;
exception_lineno = 83;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_2:;
tmp_source_name_8 = par_self;
if ( tmp_source_name_8 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 94;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_7 = LOOKUP_ATTRIBUTE( tmp_source_name_8, const_str_plain_request_validator );
if ( tmp_source_name_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 94;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_4 = LOOKUP_ATTRIBUTE( tmp_source_name_7, const_str_plain_client_authentication_required );
Py_DECREF( tmp_source_name_7 );
if ( tmp_called_name_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 94;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_2 = par_request;
if ( tmp_args_element_name_2 == 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", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 94;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 94;
{
PyObject *call_args[] = { tmp_args_element_name_2 };
tmp_cond_value_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_4, call_args );
}
Py_DECREF( tmp_called_name_4 );
if ( tmp_cond_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 94;
type_description_1 = "oooc";
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 = 94;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_1 );
if ( tmp_cond_truth_1 == 1 )
{
goto branch_yes_3;
}
else
{
goto branch_no_3;
}
branch_yes_3:;
tmp_source_name_9 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_9 == NULL ))
{
tmp_source_name_9 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_9 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 95;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_5 = LOOKUP_ATTRIBUTE( tmp_source_name_9, const_str_plain_debug );
if ( tmp_called_name_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 95;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_3 = const_str_digest_468773523eb8e0ab1a2621d8a4b4fbf2;
tmp_args_element_name_4 = par_request;
if ( tmp_args_element_name_4 == 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", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 95;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 95;
{
PyObject *call_args[] = { tmp_args_element_name_3, tmp_args_element_name_4 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( 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 = 95;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_11 = par_self;
if ( tmp_source_name_11 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_10 = LOOKUP_ATTRIBUTE( tmp_source_name_11, const_str_plain_request_validator );
if ( tmp_source_name_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_6 = LOOKUP_ATTRIBUTE( tmp_source_name_10, const_str_plain_authenticate_client );
Py_DECREF( tmp_source_name_10 );
if ( tmp_called_name_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_5 = par_request;
if ( tmp_args_element_name_5 == 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", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 96;
{
PyObject *call_args[] = { tmp_args_element_name_5 };
tmp_cond_value_2 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_6, call_args );
}
Py_DECREF( tmp_called_name_6 );
if ( tmp_cond_value_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
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 = 96;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_2 );
if ( tmp_cond_truth_2 == 1 )
{
goto branch_no_4;
}
else
{
goto branch_yes_4;
}
branch_yes_4:;
tmp_source_name_12 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_12 == NULL ))
{
tmp_source_name_12 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_12 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 97;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_7 = LOOKUP_ATTRIBUTE( tmp_source_name_12, const_str_plain_debug );
if ( tmp_called_name_7 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 97;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_6 = const_str_digest_7d87b8a7beb472784c8f817c5cf003af;
tmp_args_element_name_7 = par_request;
if ( tmp_args_element_name_7 == 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", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 97;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 97;
{
PyObject *call_args[] = { tmp_args_element_name_6, tmp_args_element_name_7 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( 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 = 97;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_13 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_13 == NULL ))
{
tmp_source_name_13 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_13 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 98;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_8 = LOOKUP_ATTRIBUTE( tmp_source_name_13, const_str_plain_InvalidClientError );
if ( tmp_called_name_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 98;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_3 = _PyDict_NewPresized( 1 );
tmp_dict_key_4 = const_str_plain_request;
tmp_dict_value_4 = par_request;
if ( tmp_dict_value_4 == NULL )
{
Py_DECREF( tmp_called_name_8 );
Py_DECREF( tmp_kw_name_3 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 98;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_3, tmp_dict_key_4, tmp_dict_value_4 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 98;
tmp_raise_type_3 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_8, tmp_kw_name_3 );
Py_DECREF( tmp_called_name_8 );
Py_DECREF( tmp_kw_name_3 );
if ( tmp_raise_type_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 98;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_3;
exception_lineno = 98;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_4:;
goto branch_end_3;
branch_no_3:;
tmp_source_name_15 = par_self;
if ( tmp_source_name_15 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_14 = LOOKUP_ATTRIBUTE( tmp_source_name_15, const_str_plain_request_validator );
if ( tmp_source_name_14 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_9 = LOOKUP_ATTRIBUTE( tmp_source_name_14, const_str_plain_authenticate_client_id );
Py_DECREF( tmp_source_name_14 );
if ( tmp_called_name_9 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_16 = par_request;
if ( tmp_source_name_16 == 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", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_8 = LOOKUP_ATTRIBUTE( tmp_source_name_16, const_str_plain_client_id );
if ( tmp_args_element_name_8 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_9 );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_9 = par_request;
if ( tmp_args_element_name_9 == NULL )
{
Py_DECREF( tmp_called_name_9 );
Py_DECREF( tmp_args_element_name_8 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 99;
{
PyObject *call_args[] = { tmp_args_element_name_8, tmp_args_element_name_9 };
tmp_cond_value_3 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_9, call_args );
}
Py_DECREF( tmp_called_name_9 );
Py_DECREF( tmp_args_element_name_8 );
if ( tmp_cond_value_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_truth_3 = CHECK_IF_TRUE( tmp_cond_value_3 );
if ( tmp_cond_truth_3 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_3 );
exception_lineno = 99;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_3 );
if ( tmp_cond_truth_3 == 1 )
{
goto branch_no_5;
}
else
{
goto branch_yes_5;
}
branch_yes_5:;
tmp_source_name_17 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_17 == NULL ))
{
tmp_source_name_17 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_17 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_10 = LOOKUP_ATTRIBUTE( tmp_source_name_17, const_str_plain_debug );
if ( tmp_called_name_10 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_10 = const_str_digest_12db482c55f456d3fa96605a189c21fd;
tmp_args_element_name_11 = par_request;
if ( tmp_args_element_name_11 == NULL )
{
Py_DECREF( tmp_called_name_10 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 100;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 100;
{
PyObject *call_args[] = { tmp_args_element_name_10, tmp_args_element_name_11 };
tmp_unused = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_10, call_args );
}
Py_DECREF( tmp_called_name_10 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 100;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_18 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_18 == NULL ))
{
tmp_source_name_18 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_18 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_11 = LOOKUP_ATTRIBUTE( tmp_source_name_18, const_str_plain_InvalidClientError );
if ( tmp_called_name_11 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_4 = _PyDict_NewPresized( 1 );
tmp_dict_key_5 = const_str_plain_request;
tmp_dict_value_5 = par_request;
if ( tmp_dict_value_5 == NULL )
{
Py_DECREF( tmp_called_name_11 );
Py_DECREF( tmp_kw_name_4 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 101;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_4, tmp_dict_key_5, tmp_dict_value_5 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 101;
tmp_raise_type_4 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_11, tmp_kw_name_4 );
Py_DECREF( tmp_called_name_11 );
Py_DECREF( tmp_kw_name_4 );
if ( tmp_raise_type_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 101;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_4;
exception_lineno = 101;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_5:;
branch_end_3:;
tmp_source_name_19 = par_self;
if ( tmp_source_name_19 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 104;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_12 = LOOKUP_ATTRIBUTE( tmp_source_name_19, const_str_plain_validate_grant_type );
if ( tmp_called_name_12 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 104;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_12 = par_request;
if ( tmp_args_element_name_12 == NULL )
{
Py_DECREF( tmp_called_name_12 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 104;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 104;
{
PyObject *call_args[] = { tmp_args_element_name_12 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_12, call_args );
}
Py_DECREF( tmp_called_name_12 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 104;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_20 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_20 == NULL ))
{
tmp_source_name_20 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_20 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 107;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_13 = LOOKUP_ATTRIBUTE( tmp_source_name_20, const_str_plain_debug );
if ( tmp_called_name_13 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 107;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_13 = const_str_digest_eb1c78d62a3d3030bb88e6017862dd99;
tmp_source_name_21 = par_request;
if ( tmp_source_name_21 == NULL )
{
Py_DECREF( tmp_called_name_13 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 108;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_14 = LOOKUP_ATTRIBUTE( tmp_source_name_21, const_str_plain_refresh_token );
if ( tmp_args_element_name_14 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_13 );
exception_lineno = 108;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_22 = par_request;
if ( tmp_source_name_22 == NULL )
{
Py_DECREF( tmp_called_name_13 );
Py_DECREF( tmp_args_element_name_14 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 108;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_15 = LOOKUP_ATTRIBUTE( tmp_source_name_22, const_str_plain_client );
if ( tmp_args_element_name_15 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_13 );
Py_DECREF( tmp_args_element_name_14 );
exception_lineno = 108;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 107;
{
PyObject *call_args[] = { tmp_args_element_name_13, tmp_args_element_name_14, tmp_args_element_name_15 };
tmp_unused = CALL_FUNCTION_WITH_ARGS3( tmp_called_name_13, call_args );
}
Py_DECREF( tmp_called_name_13 );
Py_DECREF( tmp_args_element_name_14 );
Py_DECREF( tmp_args_element_name_15 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 107;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_24 = par_self;
if ( tmp_source_name_24 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 109;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_23 = LOOKUP_ATTRIBUTE( tmp_source_name_24, const_str_plain_request_validator );
if ( tmp_source_name_23 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 109;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_14 = LOOKUP_ATTRIBUTE( tmp_source_name_23, const_str_plain_validate_refresh_token );
Py_DECREF( tmp_source_name_23 );
if ( tmp_called_name_14 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 109;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_25 = par_request;
if ( tmp_source_name_25 == 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", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 110;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_16 = LOOKUP_ATTRIBUTE( tmp_source_name_25, const_str_plain_refresh_token );
if ( tmp_args_element_name_16 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_14 );
exception_lineno = 110;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_26 = par_request;
if ( tmp_source_name_26 == NULL )
{
Py_DECREF( tmp_called_name_14 );
Py_DECREF( tmp_args_element_name_16 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 110;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_17 = LOOKUP_ATTRIBUTE( tmp_source_name_26, const_str_plain_client );
if ( tmp_args_element_name_17 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_14 );
Py_DECREF( tmp_args_element_name_16 );
exception_lineno = 110;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_18 = par_request;
if ( tmp_args_element_name_18 == NULL )
{
Py_DECREF( tmp_called_name_14 );
Py_DECREF( tmp_args_element_name_16 );
Py_DECREF( tmp_args_element_name_17 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 110;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 109;
{
PyObject *call_args[] = { tmp_args_element_name_16, tmp_args_element_name_17, tmp_args_element_name_18 };
tmp_cond_value_4 = CALL_FUNCTION_WITH_ARGS3( tmp_called_name_14, call_args );
}
Py_DECREF( tmp_called_name_14 );
Py_DECREF( tmp_args_element_name_16 );
Py_DECREF( tmp_args_element_name_17 );
if ( tmp_cond_value_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 109;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_truth_4 = CHECK_IF_TRUE( tmp_cond_value_4 );
if ( tmp_cond_truth_4 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_4 );
exception_lineno = 109;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_4 );
if ( tmp_cond_truth_4 == 1 )
{
goto branch_no_6;
}
else
{
goto branch_yes_6;
}
branch_yes_6:;
tmp_source_name_27 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_27 == NULL ))
{
tmp_source_name_27 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_27 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 111;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_15 = LOOKUP_ATTRIBUTE( tmp_source_name_27, const_str_plain_debug );
if ( tmp_called_name_15 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 111;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_19 = const_str_digest_cb8a1ca4c0d67d12f88e0ed3a0740e39;
tmp_source_name_28 = par_request;
if ( tmp_source_name_28 == NULL )
{
Py_DECREF( tmp_called_name_15 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 112;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_20 = LOOKUP_ATTRIBUTE( tmp_source_name_28, const_str_plain_refresh_token );
if ( tmp_args_element_name_20 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_15 );
exception_lineno = 112;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_29 = par_request;
if ( tmp_source_name_29 == NULL )
{
Py_DECREF( tmp_called_name_15 );
Py_DECREF( tmp_args_element_name_20 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 112;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_21 = LOOKUP_ATTRIBUTE( tmp_source_name_29, const_str_plain_client );
if ( tmp_args_element_name_21 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_15 );
Py_DECREF( tmp_args_element_name_20 );
exception_lineno = 112;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 111;
{
PyObject *call_args[] = { tmp_args_element_name_19, tmp_args_element_name_20, tmp_args_element_name_21 };
tmp_unused = CALL_FUNCTION_WITH_ARGS3( tmp_called_name_15, call_args );
}
Py_DECREF( tmp_called_name_15 );
Py_DECREF( tmp_args_element_name_20 );
Py_DECREF( tmp_args_element_name_21 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 111;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_30 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_30 == NULL ))
{
tmp_source_name_30 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_30 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 113;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_16 = LOOKUP_ATTRIBUTE( tmp_source_name_30, const_str_plain_InvalidGrantError );
if ( tmp_called_name_16 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 113;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_5 = _PyDict_NewPresized( 1 );
tmp_dict_key_6 = const_str_plain_request;
tmp_dict_value_6 = par_request;
if ( tmp_dict_value_6 == NULL )
{
Py_DECREF( tmp_called_name_16 );
Py_DECREF( tmp_kw_name_5 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 113;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_5, tmp_dict_key_6, tmp_dict_value_6 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 113;
tmp_raise_type_5 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_16, tmp_kw_name_5 );
Py_DECREF( tmp_called_name_16 );
Py_DECREF( tmp_kw_name_5 );
if ( tmp_raise_type_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 113;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_5;
exception_lineno = 113;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_6:;
tmp_source_name_31 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_utils );
if (unlikely( tmp_source_name_31 == NULL ))
{
tmp_source_name_31 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_utils );
}
if ( tmp_source_name_31 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "utils" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 115;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_17 = LOOKUP_ATTRIBUTE( tmp_source_name_31, const_str_plain_scope_to_list );
if ( tmp_called_name_17 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 115;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_33 = par_self;
if ( tmp_source_name_33 == NULL )
{
Py_DECREF( tmp_called_name_17 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 116;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_32 = LOOKUP_ATTRIBUTE( tmp_source_name_33, const_str_plain_request_validator );
if ( tmp_source_name_32 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_17 );
exception_lineno = 116;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_18 = LOOKUP_ATTRIBUTE( tmp_source_name_32, const_str_plain_get_original_scopes );
Py_DECREF( tmp_source_name_32 );
if ( tmp_called_name_18 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_17 );
exception_lineno = 116;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_34 = par_request;
if ( tmp_source_name_34 == NULL )
{
Py_DECREF( tmp_called_name_17 );
Py_DECREF( tmp_called_name_18 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 117;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_23 = LOOKUP_ATTRIBUTE( tmp_source_name_34, const_str_plain_refresh_token );
if ( tmp_args_element_name_23 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_17 );
Py_DECREF( tmp_called_name_18 );
exception_lineno = 117;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_24 = par_request;
if ( tmp_args_element_name_24 == NULL )
{
Py_DECREF( tmp_called_name_17 );
Py_DECREF( tmp_called_name_18 );
Py_DECREF( tmp_args_element_name_23 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 117;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 116;
{
PyObject *call_args[] = { tmp_args_element_name_23, tmp_args_element_name_24 };
tmp_args_element_name_22 = CALL_FUNCTION_WITH_ARGS2( tmp_called_name_18, call_args );
}
Py_DECREF( tmp_called_name_18 );
Py_DECREF( tmp_args_element_name_23 );
if ( tmp_args_element_name_22 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_17 );
exception_lineno = 116;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 115;
{
PyObject *call_args[] = { tmp_args_element_name_22 };
tmp_assign_source_4 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_17, call_args );
}
Py_DECREF( tmp_called_name_17 );
Py_DECREF( tmp_args_element_name_22 );
if ( tmp_assign_source_4 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 115;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
{
PyObject *old = PyCell_GET( var_original_scopes );
PyCell_SET( var_original_scopes, tmp_assign_source_4 );
Py_XDECREF( old );
}
tmp_source_name_35 = par_request;
if ( tmp_source_name_35 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 119;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_value_5 = LOOKUP_ATTRIBUTE( tmp_source_name_35, const_str_plain_scope );
if ( tmp_cond_value_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 119;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_truth_5 = CHECK_IF_TRUE( tmp_cond_value_5 );
if ( tmp_cond_truth_5 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_cond_value_5 );
exception_lineno = 119;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_cond_value_5 );
if ( tmp_cond_truth_5 == 1 )
{
goto branch_yes_7;
}
else
{
goto branch_no_7;
}
branch_yes_7:;
tmp_source_name_36 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_utils );
if (unlikely( tmp_source_name_36 == NULL ))
{
tmp_source_name_36 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_utils );
}
if ( tmp_source_name_36 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "utils" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_19 = LOOKUP_ATTRIBUTE( tmp_source_name_36, const_str_plain_scope_to_list );
if ( tmp_called_name_19 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_37 = par_request;
if ( tmp_source_name_37 == NULL )
{
Py_DECREF( tmp_called_name_19 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_25 = LOOKUP_ATTRIBUTE( tmp_source_name_37, const_str_plain_scope );
if ( tmp_args_element_name_25 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_19 );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 120;
{
PyObject *call_args[] = { tmp_args_element_name_25 };
tmp_assattr_name_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_19, call_args );
}
Py_DECREF( tmp_called_name_19 );
Py_DECREF( tmp_args_element_name_25 );
if ( tmp_assattr_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_assattr_target_1 = par_request;
if ( tmp_assattr_target_1 == NULL )
{
Py_DECREF( tmp_assattr_name_1 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_result = SET_ATTRIBUTE( tmp_assattr_target_1, const_str_plain_scopes, tmp_assattr_name_1 );
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_assattr_name_1 );
exception_lineno = 120;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_assattr_name_1 );
tmp_called_name_20 = LOOKUP_BUILTIN( const_str_plain_all );
assert( tmp_called_name_20 != NULL );
tmp_source_name_38 = par_request;
if ( tmp_source_name_38 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 121;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_iter_arg_2 = LOOKUP_ATTRIBUTE( tmp_source_name_38, const_str_plain_scopes );
if ( tmp_iter_arg_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_assign_source_5 = MAKE_ITERATOR( tmp_iter_arg_2 );
Py_DECREF( tmp_iter_arg_2 );
if ( tmp_assign_source_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
assert( tmp_genexpr_1__$0 == NULL );
tmp_genexpr_1__$0 = tmp_assign_source_5;
// Tried code:
tmp_outline_return_value_1 = Nuitka_Generator_New(
oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_context,
module_oauthlib$oauth2$rfc6749$grant_types$refresh_token,
const_str_angle_genexpr,
#if PYTHON_VERSION >= 350
const_str_digest_0a85429d17cf7c1498bc5d74cde5deef,
#endif
codeobj_d97b4b0e63e7446557f598731ac2685c,
2
);
((struct Nuitka_GeneratorObject *)tmp_outline_return_value_1)->m_closure[0] = PyCell_NEW0( tmp_genexpr_1__$0 );
((struct Nuitka_GeneratorObject *)tmp_outline_return_value_1)->m_closure[1] = var_original_scopes;
Py_INCREF( ((struct Nuitka_GeneratorObject *)tmp_outline_return_value_1)->m_closure[1] );
assert( Py_SIZE( tmp_outline_return_value_1 ) >= 2 );
goto try_return_handler_3;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request );
return NULL;
// Return handler code:
try_return_handler_3:;
CHECK_OBJECT( (PyObject *)tmp_genexpr_1__$0 );
Py_DECREF( tmp_genexpr_1__$0 );
tmp_genexpr_1__$0 = NULL;
goto outline_result_1;
// End of try:
CHECK_OBJECT( (PyObject *)tmp_genexpr_1__$0 );
Py_DECREF( tmp_genexpr_1__$0 );
tmp_genexpr_1__$0 = NULL;
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request );
return NULL;
outline_result_1:;
tmp_args_element_name_26 = tmp_outline_return_value_1;
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 121;
{
PyObject *call_args[] = { tmp_args_element_name_26 };
tmp_operand_name_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_20, call_args );
}
Py_DECREF( tmp_args_element_name_26 );
if ( tmp_operand_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "oooc";
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 = 121;
type_description_1 = "oooc";
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 = 122;
type_description_1 = "oooc";
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_source_name_40 = par_self;
if ( tmp_source_name_40 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_39 = LOOKUP_ATTRIBUTE( tmp_source_name_40, const_str_plain_request_validator );
if ( tmp_source_name_39 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_21 = LOOKUP_ATTRIBUTE( tmp_source_name_39, const_str_plain_is_within_original_scope );
Py_DECREF( tmp_source_name_39 );
if ( tmp_called_name_21 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_41 = par_request;
if ( tmp_source_name_41 == NULL )
{
Py_DECREF( tmp_called_name_21 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 123;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_27 = LOOKUP_ATTRIBUTE( tmp_source_name_41, const_str_plain_scopes );
if ( tmp_args_element_name_27 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_21 );
exception_lineno = 123;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_42 = par_request;
if ( tmp_source_name_42 == NULL )
{
Py_DECREF( tmp_called_name_21 );
Py_DECREF( tmp_args_element_name_27 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 123;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_28 = LOOKUP_ATTRIBUTE( tmp_source_name_42, const_str_plain_refresh_token );
if ( tmp_args_element_name_28 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_21 );
Py_DECREF( tmp_args_element_name_27 );
exception_lineno = 123;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_29 = par_request;
if ( tmp_args_element_name_29 == NULL )
{
Py_DECREF( tmp_called_name_21 );
Py_DECREF( tmp_args_element_name_27 );
Py_DECREF( tmp_args_element_name_28 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 123;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 122;
{
PyObject *call_args[] = { tmp_args_element_name_27, tmp_args_element_name_28, tmp_args_element_name_29 };
tmp_operand_name_2 = CALL_FUNCTION_WITH_ARGS3( tmp_called_name_21, call_args );
}
Py_DECREF( tmp_called_name_21 );
Py_DECREF( tmp_args_element_name_27 );
Py_DECREF( tmp_args_element_name_28 );
if ( tmp_operand_name_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_and_right_value_1 = UNARY_OPERATION( UNARY_NOT, tmp_operand_name_2 );
Py_DECREF( tmp_operand_name_2 );
if ( tmp_and_right_value_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_cond_value_6 = tmp_and_right_value_1;
goto and_end_1;
and_left_1:;
tmp_cond_value_6 = tmp_and_left_value_1;
and_end_1:;
tmp_cond_truth_6 = CHECK_IF_TRUE( tmp_cond_value_6 );
if ( tmp_cond_truth_6 == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 122;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
if ( tmp_cond_truth_6 == 1 )
{
goto branch_yes_8;
}
else
{
goto branch_no_8;
}
branch_yes_8:;
tmp_source_name_43 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log );
if (unlikely( tmp_source_name_43 == NULL ))
{
tmp_source_name_43 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_log );
}
if ( tmp_source_name_43 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "log" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 124;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_22 = LOOKUP_ATTRIBUTE( tmp_source_name_43, const_str_plain_debug );
if ( tmp_called_name_22 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 124;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_30 = const_str_digest_2683d3f8d9f4c4f400b58e6db8957b1b;
tmp_source_name_44 = par_request;
if ( tmp_source_name_44 == NULL )
{
Py_DECREF( tmp_called_name_22 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 125;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_31 = LOOKUP_ATTRIBUTE( tmp_source_name_44, const_str_plain_refresh_token );
if ( tmp_args_element_name_31 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_22 );
exception_lineno = 125;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_45 = par_request;
if ( tmp_source_name_45 == NULL )
{
Py_DECREF( tmp_called_name_22 );
Py_DECREF( tmp_args_element_name_31 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 125;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_args_element_name_32 = LOOKUP_ATTRIBUTE( tmp_source_name_45, const_str_plain_scopes );
if ( tmp_args_element_name_32 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_called_name_22 );
Py_DECREF( tmp_args_element_name_31 );
exception_lineno = 125;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 124;
{
PyObject *call_args[] = { tmp_args_element_name_30, tmp_args_element_name_31, tmp_args_element_name_32 };
tmp_unused = CALL_FUNCTION_WITH_ARGS3( tmp_called_name_22, call_args );
}
Py_DECREF( tmp_called_name_22 );
Py_DECREF( tmp_args_element_name_31 );
Py_DECREF( tmp_args_element_name_32 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 124;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
Py_DECREF( tmp_unused );
tmp_source_name_46 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors );
if (unlikely( tmp_source_name_46 == NULL ))
{
tmp_source_name_46 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_errors );
}
if ( tmp_source_name_46 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "errors" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 126;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_called_name_23 = LOOKUP_ATTRIBUTE( tmp_source_name_46, const_str_plain_InvalidScopeError );
if ( tmp_called_name_23 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 126;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_kw_name_6 = _PyDict_NewPresized( 1 );
tmp_dict_key_7 = const_str_plain_request;
tmp_dict_value_7 = par_request;
if ( tmp_dict_value_7 == NULL )
{
Py_DECREF( tmp_called_name_23 );
Py_DECREF( tmp_kw_name_6 );
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 126;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_res = PyDict_SetItem( tmp_kw_name_6, tmp_dict_key_7, tmp_dict_value_7 );
assert( !(tmp_res != 0) );
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 126;
tmp_raise_type_6 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_23, tmp_kw_name_6 );
Py_DECREF( tmp_called_name_23 );
Py_DECREF( tmp_kw_name_6 );
if ( tmp_raise_type_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 126;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
exception_type = tmp_raise_type_6;
exception_lineno = 126;
RAISE_EXCEPTION_WITH_TYPE( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
goto frame_exception_exit_1;
branch_no_8:;
goto branch_end_7;
branch_no_7:;
if ( var_original_scopes == NULL )
{
tmp_assattr_name_2 = NULL;
}
else
{
tmp_assattr_name_2 = PyCell_GET( var_original_scopes );
}
if ( tmp_assattr_name_2 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "original_scopes" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 128;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_assattr_target_2 = par_request;
if ( tmp_assattr_target_2 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 128;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_result = SET_ATTRIBUTE( tmp_assattr_target_2, const_str_plain_scopes, tmp_assattr_name_2 );
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 128;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
branch_end_7:;
tmp_source_name_48 = par_self;
if ( tmp_source_name_48 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "self" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 130;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_source_name_47 = LOOKUP_ATTRIBUTE( tmp_source_name_48, const_str_plain_custom_validators );
if ( tmp_source_name_47 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 130;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_iter_arg_3 = LOOKUP_ATTRIBUTE( tmp_source_name_47, const_str_plain_post_token );
Py_DECREF( tmp_source_name_47 );
if ( tmp_iter_arg_3 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 130;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
tmp_assign_source_6 = MAKE_ITERATOR( tmp_iter_arg_3 );
Py_DECREF( tmp_iter_arg_3 );
if ( tmp_assign_source_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 130;
type_description_1 = "oooc";
goto frame_exception_exit_1;
}
assert( tmp_for_loop_2__for_iterator == NULL );
tmp_for_loop_2__for_iterator = tmp_assign_source_6;
// Tried code:
loop_start_2:;
tmp_next_source_2 = tmp_for_loop_2__for_iterator;
CHECK_OBJECT( tmp_next_source_2 );
tmp_assign_source_7 = ITERATOR_NEXT( tmp_next_source_2 );
if ( tmp_assign_source_7 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_2;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
type_description_1 = "oooc";
exception_lineno = 130;
goto try_except_handler_4;
}
}
{
PyObject *old = tmp_for_loop_2__iter_value;
tmp_for_loop_2__iter_value = tmp_assign_source_7;
Py_XDECREF( old );
}
tmp_assign_source_8 = tmp_for_loop_2__iter_value;
CHECK_OBJECT( tmp_assign_source_8 );
{
PyObject *old = var_validator;
var_validator = tmp_assign_source_8;
Py_INCREF( var_validator );
Py_XDECREF( old );
}
tmp_called_name_24 = var_validator;
CHECK_OBJECT( tmp_called_name_24 );
tmp_args_element_name_33 = par_request;
if ( tmp_args_element_name_33 == NULL )
{
exception_type = PyExc_UnboundLocalError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "local variable '%s' referenced before assignment", "request" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 131;
type_description_1 = "oooc";
goto try_except_handler_4;
}
frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame.f_lineno = 131;
{
PyObject *call_args[] = { tmp_args_element_name_33 };
tmp_unused = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_24, call_args );
}
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 131;
type_description_1 = "oooc";
goto try_except_handler_4;
}
Py_DECREF( tmp_unused );
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 130;
type_description_1 = "oooc";
goto try_except_handler_4;
}
goto loop_start_2;
loop_end_2:;
goto try_end_2;
// Exception handler code:
try_except_handler_4:;
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( tmp_for_loop_2__iter_value );
tmp_for_loop_2__iter_value = NULL;
Py_XDECREF( tmp_for_loop_2__for_iterator );
tmp_for_loop_2__for_iterator = 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 frame_exception_exit_1;
// End of try:
try_end_2:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_63747e9cb9a8f20473e6b2eb0348134b );
#endif
// Put the previous frame back on top.
popFrameStack();
goto frame_no_exception_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_63747e9cb9a8f20473e6b2eb0348134b );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_63747e9cb9a8f20473e6b2eb0348134b, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_63747e9cb9a8f20473e6b2eb0348134b->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_63747e9cb9a8f20473e6b2eb0348134b, exception_lineno );
}
// Attachs locals to frame if any.
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)frame_63747e9cb9a8f20473e6b2eb0348134b,
type_description_1,
par_self,
par_request,
var_validator,
var_original_scopes
);
// Release cached frame.
if ( frame_63747e9cb9a8f20473e6b2eb0348134b == cache_frame_63747e9cb9a8f20473e6b2eb0348134b )
{
Py_DECREF( frame_63747e9cb9a8f20473e6b2eb0348134b );
}
cache_frame_63747e9cb9a8f20473e6b2eb0348134b = NULL;
assertFrameObject( frame_63747e9cb9a8f20473e6b2eb0348134b );
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
Py_XDECREF( tmp_for_loop_2__iter_value );
tmp_for_loop_2__iter_value = NULL;
Py_XDECREF( tmp_for_loop_2__for_iterator );
tmp_for_loop_2__for_iterator = NULL;
tmp_return_value = Py_None;
Py_INCREF( tmp_return_value );
goto try_return_handler_1;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request );
return NULL;
// Return handler code:
try_return_handler_1:;
Py_XDECREF( par_self );
par_self = NULL;
Py_XDECREF( par_request );
par_request = NULL;
Py_XDECREF( var_validator );
var_validator = NULL;
CHECK_OBJECT( (PyObject *)var_original_scopes );
Py_DECREF( var_original_scopes );
var_original_scopes = 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_self );
par_self = NULL;
Py_XDECREF( par_request );
par_request = NULL;
Py_XDECREF( var_validator );
var_validator = NULL;
CHECK_OBJECT( (PyObject *)var_original_scopes );
Py_DECREF( var_original_scopes );
var_original_scopes = 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( oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request );
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;
}
#if _NUITKA_EXPERIMENTAL_GENERATOR_GOTO
struct oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_locals {
PyObject *var_s
PyObject *tmp_iter_value_0
PyObject *exception_type
PyObject *exception_value
PyTracebackObject *exception_tb
int exception_lineno
PyObject *exception_keeper_type_1;
PyObject *exception_keeper_value_1;
PyTracebackObject *exception_keeper_tb_1;
int exception_keeper_lineno_1;
PyObject *exception_keeper_type_2;
PyObject *exception_keeper_value_2;
PyTracebackObject *exception_keeper_tb_2;
int exception_keeper_lineno_2;
PyObject *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_compexpr_left_1;
PyObject *tmp_compexpr_right_1;
PyObject *tmp_expression_name_1;
PyObject *tmp_next_source_1;
char const *type_description_1
};
#endif
#if _NUITKA_EXPERIMENTAL_GENERATOR_GOTO
static PyObject *oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_context( struct Nuitka_GeneratorObject *generator, PyObject *yield_return_value )
#else
static void oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request$$$genexpr_1_genexpr_context( struct Nuitka_GeneratorObject *generator )
#endif
{
CHECK_OBJECT( (PyObject *)generator );
assert( Nuitka_Generator_Check( (PyObject *)generator ) );
// Local variable initialization
PyObject *var_s = NULL;
PyObject *tmp_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 *tmp_assign_source_1;
PyObject *tmp_assign_source_2;
PyObject *tmp_compexpr_left_1;
PyObject *tmp_compexpr_right_1;
PyObject *tmp_expression_name_1;
PyObject *tmp_next_source_1;
NUITKA_MAY_BE_UNUSED PyObject *tmp_unused;
static struct Nuitka_FrameObject *cache_frame_generator = NULL;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
// Dispatch to yield based on return label index:
// Actual function code.
// Tried code:
MAKE_OR_REUSE_FRAME( cache_frame_generator, codeobj_d97b4b0e63e7446557f598731ac2685c, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token, sizeof(void *)+sizeof(void *)+sizeof(void *) );
generator->m_frame = cache_frame_generator;
// Mark the frame object as in use, ref count 1 will be up for reuse.
Py_INCREF( generator->m_frame );
assert( Py_REFCNT( generator->m_frame ) == 2 ); // Frame stack
#if PYTHON_VERSION >= 340
generator->m_frame->m_frame.f_gen = (PyObject *)generator;
#endif
Py_CLEAR( generator->m_frame->m_frame.f_back );
generator->m_frame->m_frame.f_back = PyThreadState_GET()->frame;
Py_INCREF( generator->m_frame->m_frame.f_back );
PyThreadState_GET()->frame = &generator->m_frame->m_frame;
Py_INCREF( generator->m_frame );
Nuitka_Frame_MarkAsExecuting( generator->m_frame );
#if PYTHON_VERSION >= 300
// Accept currently existing exception as the one to publish again when we
// yield or yield from.
PyThreadState *thread_state = PyThreadState_GET();
generator->m_frame->m_frame.f_exc_type = thread_state->exc_type;
if ( generator->m_frame->m_frame.f_exc_type == Py_None ) generator->m_frame->m_frame.f_exc_type = NULL;
Py_XINCREF( generator->m_frame->m_frame.f_exc_type );
generator->m_frame->m_frame.f_exc_value = thread_state->exc_value;
Py_XINCREF( generator->m_frame->m_frame.f_exc_value );
generator->m_frame->m_frame.f_exc_traceback = thread_state->exc_traceback;
Py_XINCREF( generator->m_frame->m_frame.f_exc_traceback );
#endif
// Framed code:
// Tried code:
loop_start_1:;
if ( generator->m_closure[0] == NULL )
{
tmp_next_source_1 = NULL;
}
else
{
tmp_next_source_1 = PyCell_GET( generator->m_closure[0] );
}
CHECK_OBJECT( tmp_next_source_1 );
tmp_assign_source_1 = ITERATOR_NEXT( tmp_next_source_1 );
if ( tmp_assign_source_1 == NULL )
{
if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() )
{
goto loop_end_1;
}
else
{
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
type_description_1 = "Noc";
exception_lineno = 121;
goto try_except_handler_2;
}
}
{
PyObject *old = tmp_iter_value_0;
tmp_iter_value_0 = tmp_assign_source_1;
Py_XDECREF( old );
}
tmp_assign_source_2 = tmp_iter_value_0;
CHECK_OBJECT( tmp_assign_source_2 );
{
PyObject *old = var_s;
var_s = tmp_assign_source_2;
Py_INCREF( var_s );
Py_XDECREF( old );
}
tmp_compexpr_left_1 = var_s;
CHECK_OBJECT( tmp_compexpr_left_1 );
if ( generator->m_closure[1] == NULL )
{
tmp_compexpr_right_1 = NULL;
}
else
{
tmp_compexpr_right_1 = PyCell_GET( generator->m_closure[1] );
}
if ( tmp_compexpr_right_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "free variable '%s' referenced before assignment in enclosing scope", "original_scopes" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 121;
type_description_1 = "Noc";
goto try_except_handler_2;
}
tmp_expression_name_1 = SEQUENCE_CONTAINS( tmp_compexpr_left_1, tmp_compexpr_right_1 );
if ( tmp_expression_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "Noc";
goto try_except_handler_2;
}
Py_INCREF( tmp_expression_name_1 );
tmp_unused = GENERATOR_YIELD( generator, tmp_expression_name_1 );
if ( tmp_unused == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "Noc";
goto try_except_handler_2;
}
if ( CONSIDER_THREADING() == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 121;
type_description_1 = "Noc";
goto try_except_handler_2;
}
goto loop_start_1;
loop_end_1:;
goto try_end_1;
// Exception handler code:
try_except_handler_2:;
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_iter_value_0 );
tmp_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_1;
// End of try:
try_end_1:;
Nuitka_Frame_MarkAsNotExecuting( generator->m_frame );
#if PYTHON_VERSION >= 300
Py_CLEAR( generator->m_frame->m_frame.f_exc_type );
Py_CLEAR( generator->m_frame->m_frame.f_exc_value );
Py_CLEAR( generator->m_frame->m_frame.f_exc_traceback );
#endif
// Allow re-use of the frame again.
Py_DECREF( generator->m_frame );
goto frame_no_exception_1;
frame_exception_exit_1:;
// If it's not an exit exception, consider and create a traceback for it.
if ( !EXCEPTION_MATCH_GENERATOR( exception_type ) )
{
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( generator->m_frame, exception_lineno );
}
else if ( exception_tb->tb_frame != &generator->m_frame->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, generator->m_frame, exception_lineno );
}
Nuitka_Frame_AttachLocals(
(struct Nuitka_FrameObject *)generator->m_frame,
type_description_1,
NULL,
var_s,
generator->m_closure[1]
);
// Release cached frame.
if ( generator->m_frame == cache_frame_generator )
{
Py_DECREF( generator->m_frame );
}
cache_frame_generator = NULL;
assertFrameObject( generator->m_frame );
}
#if PYTHON_VERSION >= 300
Py_CLEAR( generator->m_frame->m_frame.f_exc_type );
Py_CLEAR( generator->m_frame->m_frame.f_exc_value );
Py_CLEAR( generator->m_frame->m_frame.f_exc_traceback );
#endif
Py_DECREF( generator->m_frame );
// Return the error.
goto try_except_handler_1;
frame_no_exception_1:;
goto try_end_2;
// Exception handler code:
try_except_handler_1:;
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( var_s );
var_s = 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 function_exception_exit;
// End of try:
try_end_2:;
Py_XDECREF( tmp_iter_value_0 );
tmp_iter_value_0 = NULL;
Py_XDECREF( var_s );
var_s = NULL;
#if _NUITKA_EXPERIMENTAL_GENERATOR_GOTO
return NULL;
#else
generator->m_yielded = NULL;
return;
#endif
function_exception_exit:
assert( exception_type );
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
#if _NUITKA_EXPERIMENTAL_GENERATOR_GOTO
return NULL;
#else
generator->m_yielded = NULL;
return;
#endif
}
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__( PyObject *defaults )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__,
const_str_plain___init__,
#if PYTHON_VERSION >= 330
const_str_digest_5c08ddb60a0545fd1e17baf3a6ca1b93,
#endif
codeobj_b955a297be0011278f93db2870abd52a,
defaults,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_oauthlib$oauth2$rfc6749$grant_types$refresh_token,
Py_None,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response,
const_str_plain_create_token_response,
#if PYTHON_VERSION >= 330
const_str_digest_db37fe24851f7ebc30f9e552d120d953,
#endif
codeobj_4fb8fb5c300d19c3880e6efcc7e0f90c,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_oauthlib$oauth2$rfc6749$grant_types$refresh_token,
const_str_digest_5cace64d74a86e3d077a283b714130f4,
0
);
return (PyObject *)result;
}
static PyObject *MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request( )
{
struct Nuitka_FunctionObject *result = Nuitka_Function_New(
impl_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request,
const_str_plain_validate_token_request,
#if PYTHON_VERSION >= 330
const_str_digest_928cbf9bd4fb24f0cb2a442eef2e1a98,
#endif
codeobj_63747e9cb9a8f20473e6b2eb0348134b,
NULL,
#if PYTHON_VERSION >= 300
NULL,
const_dict_empty,
#endif
module_oauthlib$oauth2$rfc6749$grant_types$refresh_token,
Py_None,
0
);
return (PyObject *)result;
}
#if PYTHON_VERSION >= 300
static struct PyModuleDef mdef_oauthlib$oauth2$rfc6749$grant_types$refresh_token =
{
PyModuleDef_HEAD_INIT,
"oauthlib.oauth2.rfc6749.grant_types.refresh_token", /* 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( oauthlib$oauth2$rfc6749$grant_types$refresh_token )
{
#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_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
}
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("oauthlib.oauth2.rfc6749.grant_types.refresh_token: Calling createModuleConstants().");
#endif
createModuleConstants();
/* The code objects used by this module are created now. */
#ifdef _NUITKA_TRACE
puts("oauthlib.oauth2.rfc6749.grant_types.refresh_token: Calling createModuleCodeObjects().");
#endif
createModuleCodeObjects();
// puts( "in initoauthlib$oauth2$rfc6749$grant_types$refresh_token" );
// 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_oauthlib$oauth2$rfc6749$grant_types$refresh_token = Py_InitModule4(
"oauthlib.oauth2.rfc6749.grant_types.refresh_token", // 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_oauthlib$oauth2$rfc6749$grant_types$refresh_token = PyModule_Create( &mdef_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
#endif
moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token = MODULE_DICT( module_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
CHECK_OBJECT( module_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
// 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_e8b4fd301fda6069d21e5ec5f8ebfcf5, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
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_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (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_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___builtins__, value );
}
#if PYTHON_VERSION >= 330
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___loader__, metapath_based_loader );
#endif
// Temp variables if any
PyObject *outline_0_var___class__ = NULL;
PyObject *outline_0_var___qualname__ = NULL;
PyObject *outline_0_var___module__ = NULL;
PyObject *outline_0_var___doc__ = NULL;
PyObject *outline_0_var___init__ = NULL;
PyObject *outline_0_var_create_token_response = NULL;
PyObject *outline_0_var_validate_token_request = NULL;
PyObject *tmp_class_creation_1__bases = NULL;
PyObject *tmp_class_creation_1__class_decl_dict = NULL;
PyObject *tmp_class_creation_1__metaclass = NULL;
PyObject *tmp_class_creation_1__prepared = NULL;
PyObject *tmp_import_from_1__module = NULL;
PyObject *tmp_import_from_2__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 *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 *tmp_args_element_name_1;
PyObject *tmp_args_element_name_2;
PyObject *tmp_args_name_1;
PyObject *tmp_args_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_assign_source_29;
PyObject *tmp_bases_name_1;
PyObject *tmp_called_instance_1;
PyObject *tmp_called_name_1;
PyObject *tmp_called_name_2;
PyObject *tmp_called_name_3;
int tmp_cmp_In_1;
int tmp_cmp_In_2;
PyObject *tmp_compare_left_1;
PyObject *tmp_compare_left_2;
PyObject *tmp_compare_right_1;
PyObject *tmp_compare_right_2;
int tmp_cond_truth_1;
PyObject *tmp_cond_value_1;
PyObject *tmp_defaults_1;
PyObject *tmp_dict_name_1;
PyObject *tmp_dictdel_dict;
PyObject *tmp_dictdel_key;
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_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_hasattr_attr_1;
PyObject *tmp_hasattr_source_1;
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_key_name_1;
PyObject *tmp_kw_name_1;
PyObject *tmp_kw_name_2;
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_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_metaclass_name_1;
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_outline_return_value_1;
int tmp_res;
bool tmp_result;
PyObject *tmp_set_locals;
PyObject *tmp_source_name_1;
PyObject *tmp_subscribed_name_1;
PyObject *tmp_subscript_name_1;
PyObject *tmp_tuple_element_1;
PyObject *tmp_tuple_element_2;
PyObject *tmp_tuple_element_3;
PyObject *tmp_type_arg_1;
struct Nuitka_FrameObject *frame_fecfc1a1477f82e7708776ac673a0656;
NUITKA_MAY_BE_UNUSED char const *type_description_1 = NULL;
tmp_outline_return_value_1 = NULL;
// Locals dictionary setup.
PyObject *locals_dict_1 = PyDict_New();
// Module code.
tmp_assign_source_1 = const_str_digest_8731f29ba21067fcd86e2560f48c09b4;
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 );
tmp_assign_source_2 = module_filename_obj;
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 );
tmp_assign_source_3 = metapath_based_loader;
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___loader__, tmp_assign_source_3 );
// Frame without reuse.
frame_fecfc1a1477f82e7708776ac673a0656 = MAKE_MODULE_FRAME( codeobj_fecfc1a1477f82e7708776ac673a0656, module_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
// Push the new frame as the currently active one, and we should be exclusively
// owning it.
pushFrameStack( frame_fecfc1a1477f82e7708776ac673a0656 );
assert( Py_REFCNT( frame_fecfc1a1477f82e7708776ac673a0656 ) == 2 );
// Framed code:
frame_fecfc1a1477f82e7708776ac673a0656->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_e8b4fd301fda6069d21e5ec5f8ebfcf5;
tmp_args_element_name_2 = metapath_based_loader;
frame_fecfc1a1477f82e7708776ac673a0656->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_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___spec__, tmp_assign_source_4 );
tmp_assign_source_5 = Py_None;
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_5 );
tmp_assign_source_6 = const_str_digest_08fe0cb1e68b13e3e2a5584b97ab8c6f;
UPDATE_STRING_DICT0( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_6 );
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 6;
tmp_assign_source_7 = PyImport_ImportModule("__future__");
assert( tmp_assign_source_7 != NULL );
assert( tmp_import_from_1__module == NULL );
Py_INCREF( tmp_assign_source_7 );
tmp_import_from_1__module = tmp_assign_source_7;
// Tried code:
tmp_import_name_from_1 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_1 );
tmp_assign_source_8 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_absolute_import );
if ( tmp_assign_source_8 == 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_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_absolute_import, tmp_assign_source_8 );
tmp_import_name_from_2 = tmp_import_from_1__module;
CHECK_OBJECT( tmp_import_name_from_2 );
tmp_assign_source_9 = IMPORT_NAME( tmp_import_name_from_2, const_str_plain_unicode_literals );
if ( tmp_assign_source_9 == 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_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_unicode_literals, tmp_assign_source_9 );
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_1 = const_str_plain_json;
tmp_globals_name_1 = (PyObject *)moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
tmp_locals_name_1 = Py_None;
tmp_fromlist_name_1 = Py_None;
tmp_level_name_1 = const_int_0;
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 8;
tmp_assign_source_10 = 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_10 == 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_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_json, tmp_assign_source_10 );
tmp_name_name_2 = const_str_plain_logging;
tmp_globals_name_2 = (PyObject *)moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
tmp_locals_name_2 = Py_None;
tmp_fromlist_name_2 = Py_None;
tmp_level_name_2 = const_int_0;
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 9;
tmp_assign_source_11 = IMPORT_MODULE5( tmp_name_name_2, tmp_globals_name_2, tmp_locals_name_2, tmp_fromlist_name_2, tmp_level_name_2 );
if ( tmp_assign_source_11 == 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_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_logging, tmp_assign_source_11 );
tmp_name_name_3 = const_str_empty;
tmp_globals_name_3 = (PyObject *)moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
tmp_locals_name_3 = Py_None;
tmp_fromlist_name_3 = const_tuple_str_plain_errors_str_plain_utils_tuple;
tmp_level_name_3 = const_int_pos_2;
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 11;
tmp_assign_source_12 = 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_12 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 11;
goto frame_exception_exit_1;
}
assert( tmp_import_from_2__module == NULL );
tmp_import_from_2__module = tmp_assign_source_12;
// Tried code:
tmp_import_name_from_3 = tmp_import_from_2__module;
CHECK_OBJECT( tmp_import_name_from_3 );
tmp_assign_source_13 = IMPORT_NAME( tmp_import_name_from_3, const_str_plain_errors );
if ( tmp_assign_source_13 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 11;
goto try_except_handler_2;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_errors, tmp_assign_source_13 );
tmp_import_name_from_4 = tmp_import_from_2__module;
CHECK_OBJECT( tmp_import_name_from_4 );
tmp_assign_source_14 = IMPORT_NAME( tmp_import_name_from_4, const_str_plain_utils );
if ( tmp_assign_source_14 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 11;
goto try_except_handler_2;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_utils, tmp_assign_source_14 );
goto try_end_2;
// 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( tmp_import_from_2__module );
tmp_import_from_2__module = 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 frame_exception_exit_1;
// End of try:
try_end_2:;
Py_XDECREF( tmp_import_from_2__module );
tmp_import_from_2__module = NULL;
tmp_name_name_4 = const_str_plain_request_validator;
tmp_globals_name_4 = (PyObject *)moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
tmp_locals_name_4 = Py_None;
tmp_fromlist_name_4 = const_tuple_str_plain_RequestValidator_tuple;
tmp_level_name_4 = const_int_pos_2;
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 12;
tmp_import_name_from_5 = IMPORT_MODULE5( tmp_name_name_4, tmp_globals_name_4, tmp_locals_name_4, tmp_fromlist_name_4, tmp_level_name_4 );
if ( tmp_import_name_from_5 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 12;
goto frame_exception_exit_1;
}
tmp_assign_source_15 = IMPORT_NAME( tmp_import_name_from_5, const_str_plain_RequestValidator );
Py_DECREF( tmp_import_name_from_5 );
if ( tmp_assign_source_15 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 12;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_RequestValidator, tmp_assign_source_15 );
tmp_name_name_5 = const_str_plain_base;
tmp_globals_name_5 = (PyObject *)moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token;
tmp_locals_name_5 = Py_None;
tmp_fromlist_name_5 = const_tuple_str_plain_GrantTypeBase_tuple;
tmp_level_name_5 = const_int_pos_1;
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 13;
tmp_import_name_from_6 = 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_6 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 13;
goto frame_exception_exit_1;
}
tmp_assign_source_16 = IMPORT_NAME( tmp_import_name_from_6, const_str_plain_GrantTypeBase );
Py_DECREF( tmp_import_name_from_6 );
if ( tmp_assign_source_16 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 13;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_GrantTypeBase, tmp_assign_source_16 );
tmp_called_instance_1 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_logging );
if (unlikely( tmp_called_instance_1 == NULL ))
{
tmp_called_instance_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_logging );
}
if ( tmp_called_instance_1 == NULL )
{
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "logging" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 15;
goto frame_exception_exit_1;
}
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 15;
tmp_assign_source_17 = CALL_METHOD_WITH_ARGS1( tmp_called_instance_1, const_str_plain_getLogger, &PyTuple_GET_ITEM( const_tuple_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5_tuple, 0 ) );
if ( tmp_assign_source_17 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 15;
goto frame_exception_exit_1;
}
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_log, tmp_assign_source_17 );
// Tried code:
tmp_assign_source_18 = PyTuple_New( 1 );
tmp_tuple_element_1 = GET_STRING_DICT_VALUE( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_GrantTypeBase );
if (unlikely( tmp_tuple_element_1 == NULL ))
{
tmp_tuple_element_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_GrantTypeBase );
}
if ( tmp_tuple_element_1 == NULL )
{
Py_DECREF( tmp_assign_source_18 );
exception_type = PyExc_NameError;
Py_INCREF( exception_type );
exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "GrantTypeBase" );
exception_tb = NULL;
NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb );
CHAIN_EXCEPTION( exception_value );
exception_lineno = 18;
goto try_except_handler_3;
}
Py_INCREF( tmp_tuple_element_1 );
PyTuple_SET_ITEM( tmp_assign_source_18, 0, tmp_tuple_element_1 );
assert( tmp_class_creation_1__bases == NULL );
tmp_class_creation_1__bases = tmp_assign_source_18;
tmp_assign_source_19 = PyDict_New();
assert( tmp_class_creation_1__class_decl_dict == NULL );
tmp_class_creation_1__class_decl_dict = tmp_assign_source_19;
tmp_compare_left_1 = const_str_plain_metaclass;
tmp_compare_right_1 = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_compare_right_1 );
tmp_cmp_In_1 = PySequence_Contains( tmp_compare_right_1, tmp_compare_left_1 );
assert( !(tmp_cmp_In_1 == -1) );
if ( tmp_cmp_In_1 == 1 )
{
goto condexpr_true_1;
}
else
{
goto condexpr_false_1;
}
condexpr_true_1:;
tmp_dict_name_1 = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_dict_name_1 );
tmp_key_name_1 = const_str_plain_metaclass;
tmp_metaclass_name_1 = DICT_GET_ITEM( tmp_dict_name_1, tmp_key_name_1 );
if ( tmp_metaclass_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
goto condexpr_end_1;
condexpr_false_1:;
tmp_cond_value_1 = tmp_class_creation_1__bases;
CHECK_OBJECT( tmp_cond_value_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 );
exception_lineno = 18;
goto try_except_handler_3;
}
if ( tmp_cond_truth_1 == 1 )
{
goto condexpr_true_2;
}
else
{
goto condexpr_false_2;
}
condexpr_true_2:;
tmp_subscribed_name_1 = tmp_class_creation_1__bases;
CHECK_OBJECT( tmp_subscribed_name_1 );
tmp_subscript_name_1 = const_int_0;
tmp_type_arg_1 = LOOKUP_SUBSCRIPT( tmp_subscribed_name_1, tmp_subscript_name_1 );
if ( tmp_type_arg_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
tmp_metaclass_name_1 = BUILTIN_TYPE1( tmp_type_arg_1 );
Py_DECREF( tmp_type_arg_1 );
if ( tmp_metaclass_name_1 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
goto condexpr_end_2;
condexpr_false_2:;
tmp_metaclass_name_1 = (PyObject *)&PyType_Type;
Py_INCREF( tmp_metaclass_name_1 );
condexpr_end_2:;
condexpr_end_1:;
tmp_bases_name_1 = tmp_class_creation_1__bases;
CHECK_OBJECT( tmp_bases_name_1 );
tmp_assign_source_20 = SELECT_METACLASS( tmp_metaclass_name_1, tmp_bases_name_1 );
if ( tmp_assign_source_20 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_metaclass_name_1 );
exception_lineno = 18;
goto try_except_handler_3;
}
Py_DECREF( tmp_metaclass_name_1 );
assert( tmp_class_creation_1__metaclass == NULL );
tmp_class_creation_1__metaclass = tmp_assign_source_20;
tmp_compare_left_2 = const_str_plain_metaclass;
tmp_compare_right_2 = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_compare_right_2 );
tmp_cmp_In_2 = PySequence_Contains( tmp_compare_right_2, tmp_compare_left_2 );
assert( !(tmp_cmp_In_2 == -1) );
if ( tmp_cmp_In_2 == 1 )
{
goto branch_yes_1;
}
else
{
goto branch_no_1;
}
branch_yes_1:;
tmp_dictdel_dict = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_dictdel_dict );
tmp_dictdel_key = const_str_plain_metaclass;
tmp_result = DICT_REMOVE_ITEM( tmp_dictdel_dict, tmp_dictdel_key );
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
branch_no_1:;
tmp_hasattr_source_1 = tmp_class_creation_1__metaclass;
CHECK_OBJECT( tmp_hasattr_source_1 );
tmp_hasattr_attr_1 = const_str_plain___prepare__;
tmp_res = PyObject_HasAttr( tmp_hasattr_source_1, tmp_hasattr_attr_1 );
if ( tmp_res == -1 )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
if ( tmp_res == 1 )
{
goto condexpr_true_3;
}
else
{
goto condexpr_false_3;
}
condexpr_true_3:;
tmp_source_name_1 = tmp_class_creation_1__metaclass;
CHECK_OBJECT( tmp_source_name_1 );
tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain___prepare__ );
if ( tmp_called_name_2 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
tmp_args_name_1 = PyTuple_New( 2 );
tmp_tuple_element_2 = const_str_plain_RefreshTokenGrant;
Py_INCREF( tmp_tuple_element_2 );
PyTuple_SET_ITEM( tmp_args_name_1, 0, tmp_tuple_element_2 );
tmp_tuple_element_2 = tmp_class_creation_1__bases;
CHECK_OBJECT( tmp_tuple_element_2 );
Py_INCREF( tmp_tuple_element_2 );
PyTuple_SET_ITEM( tmp_args_name_1, 1, tmp_tuple_element_2 );
tmp_kw_name_1 = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_kw_name_1 );
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 18;
tmp_assign_source_21 = CALL_FUNCTION( tmp_called_name_2, tmp_args_name_1, tmp_kw_name_1 );
Py_DECREF( tmp_called_name_2 );
Py_DECREF( tmp_args_name_1 );
if ( tmp_assign_source_21 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_3;
}
goto condexpr_end_3;
condexpr_false_3:;
tmp_assign_source_21 = PyDict_New();
condexpr_end_3:;
assert( tmp_class_creation_1__prepared == NULL );
tmp_class_creation_1__prepared = tmp_assign_source_21;
tmp_set_locals = tmp_class_creation_1__prepared;
CHECK_OBJECT( tmp_set_locals );
Py_DECREF(locals_dict_1);
locals_dict_1 = tmp_set_locals;
Py_INCREF( tmp_set_locals );
tmp_assign_source_23 = const_str_digest_e8b4fd301fda6069d21e5ec5f8ebfcf5;
assert( outline_0_var___module__ == NULL );
Py_INCREF( tmp_assign_source_23 );
outline_0_var___module__ = tmp_assign_source_23;
tmp_assign_source_24 = const_str_digest_012be4d46b429a4aec730cf0f5831f69;
assert( outline_0_var___doc__ == NULL );
Py_INCREF( tmp_assign_source_24 );
outline_0_var___doc__ = tmp_assign_source_24;
tmp_assign_source_25 = const_str_plain_RefreshTokenGrant;
assert( outline_0_var___qualname__ == NULL );
Py_INCREF( tmp_assign_source_25 );
outline_0_var___qualname__ = tmp_assign_source_25;
tmp_defaults_1 = const_tuple_none_true_tuple;
Py_INCREF( tmp_defaults_1 );
tmp_assign_source_26 = MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_1___init__( tmp_defaults_1 );
assert( outline_0_var___init__ == NULL );
outline_0_var___init__ = tmp_assign_source_26;
tmp_assign_source_27 = MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_2_create_token_response( );
assert( outline_0_var_create_token_response == NULL );
outline_0_var_create_token_response = tmp_assign_source_27;
tmp_assign_source_28 = MAKE_FUNCTION_oauthlib$oauth2$rfc6749$grant_types$refresh_token$$$function_3_validate_token_request( );
assert( outline_0_var_validate_token_request == NULL );
outline_0_var_validate_token_request = tmp_assign_source_28;
// Tried code:
tmp_called_name_3 = tmp_class_creation_1__metaclass;
CHECK_OBJECT( tmp_called_name_3 );
tmp_args_name_2 = PyTuple_New( 3 );
tmp_tuple_element_3 = const_str_plain_RefreshTokenGrant;
Py_INCREF( tmp_tuple_element_3 );
PyTuple_SET_ITEM( tmp_args_name_2, 0, tmp_tuple_element_3 );
tmp_tuple_element_3 = tmp_class_creation_1__bases;
CHECK_OBJECT( tmp_tuple_element_3 );
Py_INCREF( tmp_tuple_element_3 );
PyTuple_SET_ITEM( tmp_args_name_2, 1, tmp_tuple_element_3 );
tmp_tuple_element_3 = locals_dict_1;
Py_INCREF( tmp_tuple_element_3 );
if ( outline_0_var___qualname__ != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain___qualname__,
outline_0_var___qualname__
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain___qualname__
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain___qualname__
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
if ( outline_0_var___module__ != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain___module__,
outline_0_var___module__
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain___module__
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain___module__
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
if ( outline_0_var___doc__ != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain___doc__,
outline_0_var___doc__
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain___doc__
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain___doc__
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
if ( outline_0_var___init__ != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain___init__,
outline_0_var___init__
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain___init__
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain___init__
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
if ( outline_0_var_create_token_response != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain_create_token_response,
outline_0_var_create_token_response
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain_create_token_response
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain_create_token_response
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
if ( outline_0_var_validate_token_request != NULL )
{
int res = PyObject_SetItem(
tmp_tuple_element_3,
const_str_plain_validate_token_request,
outline_0_var_validate_token_request
);
tmp_result = res == 0;
}
else
{
PyObject *test_value = PyObject_GetItem(
tmp_tuple_element_3,
const_str_plain_validate_token_request
);
if ( test_value )
{
Py_DECREF( test_value );
int res = PyObject_DelItem(
tmp_tuple_element_3,
const_str_plain_validate_token_request
);
tmp_result = res == 0;
}
else
{
CLEAR_ERROR_OCCURRED();
tmp_result = true;
}
}
if ( tmp_result == false )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
Py_DECREF( tmp_args_name_2 );
Py_DECREF( tmp_tuple_element_3 );
exception_lineno = 18;
goto try_except_handler_4;
}
PyTuple_SET_ITEM( tmp_args_name_2, 2, tmp_tuple_element_3 );
tmp_kw_name_2 = tmp_class_creation_1__class_decl_dict;
CHECK_OBJECT( tmp_kw_name_2 );
frame_fecfc1a1477f82e7708776ac673a0656->m_frame.f_lineno = 18;
tmp_assign_source_29 = CALL_FUNCTION( tmp_called_name_3, tmp_args_name_2, tmp_kw_name_2 );
Py_DECREF( tmp_args_name_2 );
if ( tmp_assign_source_29 == NULL )
{
assert( ERROR_OCCURRED() );
FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb );
exception_lineno = 18;
goto try_except_handler_4;
}
assert( outline_0_var___class__ == NULL );
outline_0_var___class__ = tmp_assign_source_29;
tmp_outline_return_value_1 = outline_0_var___class__;
CHECK_OBJECT( tmp_outline_return_value_1 );
Py_INCREF( tmp_outline_return_value_1 );
goto try_return_handler_4;
// tried codes exits in all cases
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token );
return MOD_RETURN_VALUE( NULL );
// Return handler code:
try_return_handler_4:;
CHECK_OBJECT( (PyObject *)outline_0_var___class__ );
Py_DECREF( outline_0_var___class__ );
outline_0_var___class__ = NULL;
Py_XDECREF( outline_0_var___qualname__ );
outline_0_var___qualname__ = NULL;
Py_XDECREF( outline_0_var___module__ );
outline_0_var___module__ = NULL;
Py_XDECREF( outline_0_var___doc__ );
outline_0_var___doc__ = NULL;
Py_XDECREF( outline_0_var___init__ );
outline_0_var___init__ = NULL;
Py_XDECREF( outline_0_var_create_token_response );
outline_0_var_create_token_response = NULL;
Py_XDECREF( outline_0_var_validate_token_request );
outline_0_var_validate_token_request = NULL;
goto outline_result_1;
// Exception handler code:
try_except_handler_4:;
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( outline_0_var___qualname__ );
outline_0_var___qualname__ = NULL;
Py_XDECREF( outline_0_var___module__ );
outline_0_var___module__ = NULL;
Py_XDECREF( outline_0_var___doc__ );
outline_0_var___doc__ = NULL;
Py_XDECREF( outline_0_var___init__ );
outline_0_var___init__ = NULL;
Py_XDECREF( outline_0_var_create_token_response );
outline_0_var_create_token_response = NULL;
Py_XDECREF( outline_0_var_validate_token_request );
outline_0_var_validate_token_request = 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 outline_exception_1;
// End of try:
// Return statement must have exited already.
NUITKA_CANNOT_GET_HERE( oauthlib$oauth2$rfc6749$grant_types$refresh_token );
return MOD_RETURN_VALUE( NULL );
outline_exception_1:;
exception_lineno = 18;
goto try_except_handler_3;
outline_result_1:;
tmp_assign_source_22 = tmp_outline_return_value_1;
UPDATE_STRING_DICT1( moduledict_oauthlib$oauth2$rfc6749$grant_types$refresh_token, (Nuitka_StringObject *)const_str_plain_RefreshTokenGrant, tmp_assign_source_22 );
goto try_end_3;
// Exception handler code:
try_except_handler_3:;
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;
Py_XDECREF( tmp_class_creation_1__bases );
tmp_class_creation_1__bases = NULL;
Py_XDECREF( tmp_class_creation_1__class_decl_dict );
tmp_class_creation_1__class_decl_dict = NULL;
Py_XDECREF( tmp_class_creation_1__metaclass );
tmp_class_creation_1__metaclass = NULL;
Py_XDECREF( tmp_class_creation_1__prepared );
tmp_class_creation_1__prepared = NULL;
// Re-raise.
exception_type = exception_keeper_type_4;
exception_value = exception_keeper_value_4;
exception_tb = exception_keeper_tb_4;
exception_lineno = exception_keeper_lineno_4;
goto frame_exception_exit_1;
// End of try:
try_end_3:;
// Restore frame exception if necessary.
#if 0
RESTORE_FRAME_EXCEPTION( frame_fecfc1a1477f82e7708776ac673a0656 );
#endif
popFrameStack();
assertFrameObject( frame_fecfc1a1477f82e7708776ac673a0656 );
goto frame_no_exception_1;
frame_exception_exit_1:;
#if 0
RESTORE_FRAME_EXCEPTION( frame_fecfc1a1477f82e7708776ac673a0656 );
#endif
if ( exception_tb == NULL )
{
exception_tb = MAKE_TRACEBACK( frame_fecfc1a1477f82e7708776ac673a0656, exception_lineno );
}
else if ( exception_tb->tb_frame != &frame_fecfc1a1477f82e7708776ac673a0656->m_frame )
{
exception_tb = ADD_TRACEBACK( exception_tb, frame_fecfc1a1477f82e7708776ac673a0656, exception_lineno );
}
// Put the previous frame back on top.
popFrameStack();
// Return the error.
goto module_exception_exit;
frame_no_exception_1:;
Py_XDECREF( tmp_class_creation_1__bases );
tmp_class_creation_1__bases = NULL;
Py_XDECREF( tmp_class_creation_1__class_decl_dict );
tmp_class_creation_1__class_decl_dict = NULL;
Py_XDECREF( tmp_class_creation_1__metaclass );
tmp_class_creation_1__metaclass = NULL;
Py_XDECREF( tmp_class_creation_1__prepared );
tmp_class_creation_1__prepared = NULL;
return MOD_RETURN_VALUE( module_oauthlib$oauth2$rfc6749$grant_types$refresh_token );
module_exception_exit:
RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb );
return MOD_RETURN_VALUE( NULL );
}
| 33.912031
| 278
| 0.708938
|
Pckool
|
42fd626ce7e61f29accaa7671597789e8a94f46f
| 7,529
|
cpp
|
C++
|
SharedUtility/MyOGL/MyOGLDynamicFontRects.cpp
|
sygh-JP/FbxModelViewer
|
690387451accd99f63e4385decc4cbbfea1c1603
|
[
"MIT"
] | 12
|
2017-07-27T10:37:20.000Z
|
2021-12-12T02:07:44.000Z
|
SharedUtility/MyOGL/MyOGLDynamicFontRects.cpp
|
sygh-JP/FbxModelViewer
|
690387451accd99f63e4385decc4cbbfea1c1603
|
[
"MIT"
] | 1
|
2018-02-22T20:32:38.000Z
|
2018-02-22T20:32:38.000Z
|
SharedUtility/MyOGL/MyOGLDynamicFontRects.cpp
|
sygh-JP/FbxModelViewer
|
690387451accd99f63e4385decc4cbbfea1c1603
|
[
"MIT"
] | 4
|
2018-03-06T15:12:54.000Z
|
2020-10-01T22:53:47.000Z
|
#include "stdafx.h"
#include "MyOGLDynamicFontRects.hpp"
namespace MyOGL
{
bool MyDynamicManyRectsBase::Create(uint32_t rectCount, uint32_t strideInBytes, const void* pInitialData)
{
_ASSERTE(m_vertexBuffer.get() == 0);
//_ASSERTE(pInitialData != nullptr); // OpenGL では D3D と違って頂点バッファ初期化用データに NULL も一応指定可能。ただしおそらく不定データになるはず。
_ASSERTE(rectCount > 0);
_ASSERTE(strideInBytes > 0);
const uint32_t vertexCount = rectCount * 4;
const uint32_t byteWidth = vertexCount * strideInBytes;
const void* pSrcData = pInitialData;
m_vertexBuffer = Factory::CreateOneBufferPtr();
_ASSERTE(m_vertexBuffer.get() != 0);
if (m_vertexBuffer.get() == 0)
{
return false;
}
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer.get());
// GL_STREAM_DRAW と GL_DYNAMIC_DRAW の違いが不明。
// 前者はフレームあたり1回程度の使い捨て用途、後者はフレームあたり2回以上書き換える用途に最適化されている?
// http://extns.cswiki.jp/index.php?OpenGL%2F%E3%83%90%E3%83%83%E3%83%95%E3%82%A1
// HACK: 1フレームで頂点バッファを何度も書き換える場合、都度 glFlush() や glFinish() を呼ばないといけない環境(ドライバー)も存在する。
// ある Android 実機では glFinish() なしで glBufferSubData() を1フレーム内で続けて呼び出すと、
// 意図した描画結果にならない(頂点バッファの内容が正しく更新されない)現象に遭遇した。
// なお、iPhone や Android などのモバイル環境では、
// 比較的余裕のある NVIDIA GeForce や AMD Radeon などの PC 向け GPU アーキテクチャ&ドライバーとは違って、
// パフォーマンス最優先のためにタイルベースの遅延レンダラー(Tile-Based Deferred Rendering, TBDR)が採用されているらしく、
// glTexSubImage2D() を1フレーム内で何度も呼び出すと性能が低下するらしい。
// http://blog.livedoor.jp/abars/archives/51879199.html
// フォント描画・スプライト描画に関しては、
// ID3DXSprite, ID3DX10Sprite や、XNA の SpriteBatch などのように、描画タスクをキューイングするバッチ処理を実装して、
// 頂点バッファの書き換え回数を減らすようにしたほうがよさげ。
// ID3DXSprite::Draw() は D3D9 テクスチャを、ID3DX10Sprite::DrawXXX() は D3D10 テクスチャの SRV をパラメータにとる。
// ID3DXFont::DrawText(), ID3DX10Font::DrawText() はスプライトのインターフェイスを受け取って効率化することも可能になっている。
// DirectX Tool Kit(DirectXTK, DXTK)には SpriteBatch クラスがオープンソース実装されているので、それを参考にする手もある。
// ただ、Direct3D 定数バッファ相当の OpenGL Uniform Block は通例頻繁にバッファ内容を書き換える用途で使用されるはずのため、
// ID3D11DeviceContext::UpdateSubresource() 相当機能が glBufferSubData() だとすれば、
// ES 3.0 対応モバイルでも glFinish() を呼ぶことなく glBufferSubData() だけできちんと更新してくれないと困るのだが……
// OpenGL 1.5 では D3D10/11 の Map(), Unmap() に似た glMapBuffer(), glUnmapBuffer() が導入されているが、
// モバイルでは glBufferSubData() 同様もしくはそれ以上に性能低下すると思われる。
// ちなみに glInvalidateBufferData(), glInvalidateBufferSubData() は何のために存在する?
glBufferData(GL_ARRAY_BUFFER, byteWidth, pSrcData, GL_DYNAMIC_DRAW);
//glBufferData(GL_ARRAY_BUFFER, byteWidth, pSrcData, GL_STREAM_DRAW);
glBufferStorage(GL_ARRAY_BUFFER, byteWidth, pSrcData, GL_DYNAMIC_STORAGE_BIT);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// NVIDIA ドライバーを更新すると、
// glBufferData(), glBufferStorage() 呼び出し箇所などで、
// Source="OpenGL API", Type="Other", ID=131185, Severity=Low, Message="Buffer detailed info: Buffer object 1 (bound to GL_ARRAY_BUFFER_ARB, usage hint is GL_STATIC_DRAW) will use VIDEO memory as the source for buffer object operations."
// などの診断メッセージが出力されるようになる。
std::vector<TIndex> indexArray(rectCount * 6);
for (size_t i = 0; i < rectCount; ++i)
{
// CCW
indexArray[i * 6 + 0] = TIndex(0 + (i * 4));
indexArray[i * 6 + 1] = TIndex(2 + (i * 4));
indexArray[i * 6 + 2] = TIndex(1 + (i * 4));
indexArray[i * 6 + 3] = TIndex(1 + (i * 4));
indexArray[i * 6 + 4] = TIndex(2 + (i * 4));
indexArray[i * 6 + 5] = TIndex(3 + (i * 4));
}
m_indexArray.swap(indexArray);
m_rectCount = rectCount;
m_vertexBufferSizeInBytes = byteWidth;
return true;
}
bool MyDynamicManyRectsBase::ReplaceVertexData(const void* pSrcData)
{
_ASSERTE(m_vertexBuffer.get() != 0);
_ASSERTE(pSrcData != nullptr);
const uint32_t byteWidth = m_vertexBufferSizeInBytes;
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer.get());
// 確保済みのバッファの内容を書き換える場合、glBufferData() ではなく glBufferSubData() を使う。
glBufferSubData(GL_ARRAY_BUFFER, 0, byteWidth, pSrcData);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return true;
}
bool MyDynamicFontRects::UpdateVertexBufferByString(LPCWSTR pString,
MyMath::Vector2F posInPixels,
const MyMath::Vector4F& upperColor, const MyMath::Vector4F& lowerColor,
long fontHeight, bool usesFixedFeed,
uint32_t fontTexWidth, uint32_t fontTexHeight,
const MyMath::TCharCodeUVMap& codeUVMap)
{
_ASSERTE(pString != nullptr);
m_stringLength = 0;
float offsetX = 0;
TVertex* pVertexArray = &m_vertexArray[0]; // ローカル変数にキャッシュして高速化。
for (int i = 0; pString[i] != 0 && i < MaxCharacterCount; ++i, ++m_stringLength)
{
// HACK: このアルゴリズム(というか単一の wchar_t キー)だと、サロゲート ペアにはどうしても対応不可能。
const size_t charCode = static_cast<size_t>(pString[i]);
if (charCode < codeUVMap.size())
{
const auto codeUV = codeUVMap[charCode];
const float uvLeft = static_cast<float>(codeUV.X) / fontTexWidth;
const float uvTop = static_cast<float>(codeUV.Y) / fontTexHeight;
const float uvRight = static_cast<float>(codeUV.GetRight()) / fontTexWidth;
const float uvBottom = static_cast<float>(codeUV.GetBottom()) / fontTexHeight;
const float uvWidth = codeUV.Width;
const float uvHeight = codeUV.Height;
// LT, RT, LB, RB.(0, 1, 2 は左手系の定義順)
const size_t index0 = i * 4 + 0;
// 文字の水平方向送り(カーニングは考慮しないが、プロポーショナルの場合は文字幅)。
// スペースの文字送りも考慮する。
// HUD 系は常にモノスペースのほうがいいこともある。
// 非 ASCII はテクスチャ作成時にフォント メトリックから取得した文字幅にする。
// ヨーロッパ言語など、非 ASCII でもモノスペース時は半角幅のほうがいい文字もあるが、それは考慮しない。
// したがって、メソッドのフラグで等幅指定されたら、ASCII のみ半角幅とし、
// 非 ASCII はフォント メトリックから取得した文字幅を使うようにする。
const float feed = (usesFixedFeed && iswascii(pString[i])) ? (fontHeight / 2) : uvWidth;
pVertexArray[index0].Position.x = posInPixels.x + offsetX;
pVertexArray[index0].Position.y = posInPixels.y;
pVertexArray[index0].Position.z = 0;
//pVertexArray[index0].Position.w = 1;
pVertexArray[index0].Color = upperColor;
pVertexArray[index0].TexCoord.x = uvLeft;
pVertexArray[index0].TexCoord.y = uvTop;
const size_t index1 = i * 4 + 1;
pVertexArray[index1].Position.x = posInPixels.x + offsetX + uvWidth;
pVertexArray[index1].Position.y = posInPixels.y;
pVertexArray[index1].Position.z = 0;
//pVertexArray[index1].Position.w = 1;
pVertexArray[index1].Color = upperColor;
pVertexArray[index1].TexCoord.x = uvRight;
pVertexArray[index1].TexCoord.y = uvTop;
const size_t index2 = i * 4 + 2;
pVertexArray[index2].Position.x = posInPixels.x + offsetX;
pVertexArray[index2].Position.y = posInPixels.y + uvHeight;
pVertexArray[index2].Position.z = 0;
//pVertexArray[index2].Position.w = 1;
pVertexArray[index2].Color = lowerColor;
pVertexArray[index2].TexCoord.x = uvLeft;
pVertexArray[index2].TexCoord.y = uvBottom;
const size_t index3 = i * 4 + 3;
pVertexArray[index3].Position.x = posInPixels.x + offsetX + uvWidth;
pVertexArray[index3].Position.y = posInPixels.y + uvHeight;
pVertexArray[index3].Position.z = 0;
//pVertexArray[index3].Position.w = 1;
pVertexArray[index3].Color = lowerColor;
pVertexArray[index3].TexCoord.x = uvRight;
pVertexArray[index3].TexCoord.y = uvBottom;
// ボールド体の場合はもう少しオフセットしたほうがいいかも。
// フォントによっては、強制的に半角幅分送るだけ、というのは問題あり。
// 特にプロポーショナル フォントは英数字であっても文字幅が異なる。
// モノスペースであっても、半角幅分とはかぎらない。
offsetX += feed + 1;
}
}
if (m_stringLength > 0)
{
return this->ReplaceVertexData(&m_vertexArray[0]);
}
else
{
return true;
}
}
} // end of namespace
| 41.368132
| 240
| 0.703148
|
sygh-JP
|
6e0233838b7f37894d460f2bfe5a8566d05f8eba
| 1,189
|
hh
|
C++
|
include/Attributes/StandardAttribute.hh
|
aaronbamberger/gerber_rs274x_parser
|
d2bbd6c66d322ab47715771642255f8302521300
|
[
"BSD-2-Clause"
] | 6
|
2016-09-28T18:26:42.000Z
|
2021-04-10T13:19:05.000Z
|
include/Attributes/StandardAttribute.hh
|
aaronbamberger/gerber_rs274x_parser
|
d2bbd6c66d322ab47715771642255f8302521300
|
[
"BSD-2-Clause"
] | 1
|
2021-02-09T00:24:04.000Z
|
2021-02-27T22:08:05.000Z
|
include/Attributes/StandardAttribute.hh
|
aaronbamberger/gerber_rs274x_parser
|
d2bbd6c66d322ab47715771642255f8302521300
|
[
"BSD-2-Clause"
] | 5
|
2017-09-14T09:48:17.000Z
|
2021-07-19T07:58:34.000Z
|
/*
* Copyright 2021 Aaron Bamberger
* Licensed under BSD 2-clause license
* See LICENSE file at root of source tree,
* or https://opensource.org/licenses/BSD-2-Clause
*/
#ifndef _STANDARD_ATTRIBUTE_H
#define _STANDARD_ATTRIBUTE_H
#include "Attributes/Attribute.hh"
#include "Util/ValueWithLocation.hh"
#include <string>
class StandardAttribute : public Attribute {
public:
enum class StandardAttributeType {
STANDARD_ATTRIBUTE_INVALID,
STANDARD_ATTRIBUTE_PART,
STANDARD_ATTRIBUTE_FILE_FUNCTION,
STANDARD_ATTRIBUTE_FILE_POLARITY,
STANDARD_ATTRIBUTE_SAME_COORDINATES,
STANDARD_ATTRIBUTE_CREATION_DATE,
STANDARD_ATTRIBUTE_GENERATION_SOFTWARE,
STANDARD_ATTRIBUTE_PROJECT_ID,
STANDARD_ATTRIBUTE_MD5,
STANDARD_ATTRIBUTE_APER_FUNCTION,
STANDARD_ATTRIBUTE_DRILL_TOLERANCE,
STANDARD_ATTRIBUTE_FLASH_TEXT,
STANDARD_ATTRIBUTE_NET,
STANDARD_ATTRIBUTE_PIN_NUMBER,
STANDARD_ATTRIBUTE_PIN_FUNCTION,
STANDARD_ATTRIBUTE_COMPONENT
};
StandardAttribute(ValueWithLocation<std::string> name, StandardAttributeType type);
virtual ~StandardAttribute();
StandardAttributeType get_type();
private:
StandardAttributeType m_type;
};
#endif // _STANDARD_ATTRIBUTE_H
| 25.297872
| 84
| 0.827586
|
aaronbamberger
|
6e07ecf0b5b6d597eb132a6ed3f2aede8627d1c6
| 9,709
|
cpp
|
C++
|
src/mainwindow.cpp
|
AshBringer47/Graph
|
0f18f0989edc49e0ca11b16bc6d179e6cb0f4f95
|
[
"MIT"
] | 2
|
2015-03-07T12:31:29.000Z
|
2017-08-31T03:15:21.000Z
|
src/mainwindow.cpp
|
AshBringer47/Graph
|
0f18f0989edc49e0ca11b16bc6d179e6cb0f4f95
|
[
"MIT"
] | null | null | null |
src/mainwindow.cpp
|
AshBringer47/Graph
|
0f18f0989edc49e0ca11b16bc6d179e6cb0f4f95
|
[
"MIT"
] | 6
|
2016-10-17T02:04:29.000Z
|
2019-10-13T21:12:39.000Z
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "algorithm/getallvertexlistinordervorker.h"
#include "view/settings.h"
#include <QFileDialog>
#include <QUrl>
#include <QMessageBox>
#include "util/rand.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
_scene = new GraphScene(this);
_controlsWidget = new Controls(this);
_matrixViewWindow = new MatrixView(this);
_settingWindow = new Settings(this);
ui->graphView->setScene(_scene);
ui->mainToolBar->addWidget(_controlsWidget);
connect(_controlsWidget, &Controls::newNode,
_scene, &GraphScene::newNode);
connect(_controlsWidget, &Controls::clearScene,
_scene, &GraphScene::clearScene);
connect(ui->action_openSettings, &QAction::triggered,
_settingWindow, &QWidget::show);
connect(GraphicVertex::selectSignalEmitterInstance(), &graphItemSelectSignalEmitter::vertexSelected_,
_controlsWidget, &Controls::vertexSelected);
connect(GraphicVertex::selectSignalEmitterInstance(), &graphItemSelectSignalEmitter::vertexMoved,
_controlsWidget, &Controls::selectedVertexMoved);
connect(ui->action_forTest, &QAction::triggered,
_scene->graph(), &Graph::forTest);
connect(ui->graphView, &GraphView::removeSelectedVertex,
_scene, &GraphScene::removeSelectedVertex);
connect(ui->graphView, &GraphView::addIsolatedVertex,
_scene, &GraphScene::addIsolatedVertex);
}
MainWindow::~MainWindow()
{
delete ui;
}
QString *MainWindow::getTextGraphFromFile()
{
QString str = QFileDialog::getOpenFileName(this, tr("Open graph"), tr(""), tr("txt graph data (*.txt)"));
if(str.isEmpty()) {
return nullptr;
}
QFile file(str);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return nullptr;
}
QTextStream fileStream(&file);
QString *tmp = new QString(fileStream.readAll());
file.close();
return tmp;
}
void MainWindow::on_action_addVericesFromFile_triggered()
{
QScopedPointer<QString> textGraph(getTextGraphFromFile());
if(textGraph.isNull()) {
return;
}
if(textGraph->at(0) == 'w' || textGraph->at(0) == 'n') {
_scene->addNodesFromString(*textGraph, textGraph->at(0) == 'w');
} else {
QMessageBox::warning(this, tr("Попередження"), tr("Помилка читання типу графа"));
}
}
void MainWindow::on_action_showHangingVertex_triggered()
{
auto vertices = _scene->graph()->hangingVertex();
_matrixViewWindow->showVertexList(vertices, tr("Висячі вершини"));
delete vertices;
}
void MainWindow::on_action_showIsolatedVertex_triggered()
{
auto vertices = _scene->graph()->isolatedVertex();
_matrixViewWindow->showVertexList(vertices, tr("Ізольовані вершини"));
delete vertices;
}
void MainWindow::on_action_showIncidenceMatrix_triggered()
{
auto matrix = _scene->graph()->incidenceMatrix();
_matrixViewWindow->showMatrix(matrix, tr("Матриця інцидентності"));
delete matrix;
}
void MainWindow::on_action_showAdjacencyMatrix_triggered()
{
auto matrix = _scene->graph()->adjacencyMatrix();
_matrixViewWindow->showMatrix(matrix, tr("Матриця суміжності"));
delete matrix;
}
void MainWindow::on_action_showDistanceMatrix_triggered()
{
auto matrix = _scene->graph()->distanceMatrix();
_matrixViewWindow->showMatrix(matrix, tr("Матриця відстаней"));
delete matrix;
}
void MainWindow::on_action_showReachabilityMatrix_triggered()
{
auto matrix = _scene->graph()->reachabilityMatrix();
_matrixViewWindow->showMatrix(matrix, tr("Матриця досяжності"));
delete matrix;
}
void MainWindow::on_action_checkCycles_triggered()
{
graphCycles *cycles = _scene->graph()->checkCycles();
_matrixViewWindow->showManyVertexList(cycles->cyclesVertexId, tr("Деякі цикли з графу"));
delete cycles;
}
void MainWindow::on_action_breadthSearch_triggered()
{
int vertexId = _scene->selectVertex();
if(vertexId == -1) {
return;
}
getVertexSearchOrderWorker w;
_scene->graph()->breadthSearch(vertexId, &w);
_scene->graph()->highlightVertex(w.allItem().toList(), 600);
}
void MainWindow::on_action_depthSearch_triggered()
{
int vertexId = _scene->selectVertex();
if(vertexId == -1) {
return;
}
getVertexSearchOrderWorker w;
_scene->graph()->depthSearch(vertexId, &w);
_scene->graph()->highlightVertex(w.allItem().toList(), 600);
}
void MainWindow::on_action_checkConnectivity_triggered()
{
auto connectType = _scene->graph()->connectivity();
_matrixViewWindow->showGraphConnectivity(connectType, tr("Зв’язність графу"));
}
void MainWindow::on_action_showWeightedDistanceMatrix_triggered()
{
auto matrix = _scene->graph()->weightedDistanceMatrix();
_matrixViewWindow->showMatrix(matrix, tr("Матриця відстаней (зваж.)"));
delete matrix;
}
void MainWindow::on_action_DijkstraMinPaths_triggered()
{
int vertexId = _scene->selectVertex();
if(vertexId == -1) {
return;
}
auto v = _scene->graph()->minPathsDijkstra(vertexId);
_matrixViewWindow->showPathToAll(v, tr("Шлях"));
}
void MainWindow::on_action_BellmanFord_triggered()
{
int vertexId = _scene->selectVertex();
if(vertexId == -1) {
return;
}
auto v = _scene->graph()->minPathsBellmanFord(vertexId);
_matrixViewWindow->showPathToAll(v, tr("Шлях"));
}
void MainWindow::on_action_isPlanarity_triggered()
{
if(_scene->graph()->isPlanarity()) {
_matrixViewWindow->showSimpleString("Граф планарний", "Планарність графу");
} else {
_matrixViewWindow->showSimpleString("Граф не планарний", "Планарність графу");
}
}
void MainWindow::on_action_coloring_triggered()
{
QMap<int, QColor> colorTable;
colorTable.insert(0, Qt::red);
colorTable.insert(1, Qt::blue);
colorTable.insert(2, Qt::black);
colorTable.insert(3, Qt::cyan);
colorTable.insert(4, Qt::magenta);
colorTable.insert(5, Qt::darkRed);
colorTable.insert(6, Qt::darkGreen);
colorTable.insert(7, Qt::darkBlue);
colorTable.insert(7, Qt::darkCyan);
colorTable.insert(8, Qt::darkMagenta);
QMap<int, int> resultColors = _scene->graph()->coloring();
for(int key : resultColors.keys()) {
Vertex *v = _scene->graph()->getVertex(key);
if(v == nullptr) {
continue;
}
QPen newPen = v->graphicsVertex()->pen();
if(!colorTable.contains(resultColors[key])) {
colorTable.insert(resultColors[key], QColor(Rand::intNumber(0, 255), Rand::intNumber(0, 255), Rand::intNumber(0, 255)));
}
newPen.setColor(colorTable[resultColors[key]]);
v->graphicsVertex()->setPen(newPen);
}
// TODO: restore color
}
void MainWindow::on_action_clearScene_triggered()
{
_scene->clearScene();
}
void MainWindow::on_action_FordFulkerson_triggered()
{
int startVertexId = _scene->selectVertex();
if(startVertexId == -1) {
return;
}
int endVertexId = _scene->selectVertex();
if(endVertexId == -1) {
return;
}
flow maxFlow = _scene->graph()->maxFlowFordFulkerson(startVertexId, endVertexId);
if(maxFlow.value != INF) {
_matrixViewWindow->showSimpleString("Максималний потік між вершиною "
+ QString::number(maxFlow.beginVertexId)
+ " та вершиною "
+ QString::number(maxFlow.endVertexId)
+ " дорівнює "
+ QString::number(maxFlow.value),
"Максимальний потік");
} else {
_matrixViewWindow->showSimpleString("Максималний потік між вершиною "
+ QString::number(maxFlow.beginVertexId)
+ " та вершиною "
+ QString::number(maxFlow.endVertexId)
+ " дорівнює нескінченності",
"Максимальний потік");
}
}
void MainWindow::on_action_topologicalSorting_triggered()
{
QList<int> topologicalSorting = _scene->graph()->topologicalSorting();
QString sorting;
if(!topologicalSorting.isEmpty()) {
sorting.reserve(topologicalSorting.size() * 4);
for(int v : topologicalSorting) {
sorting.append(QString::number(v));
sorting.append(" - ");
}
sorting.resize(sorting.size() - 3);
} else {
sorting = tr("Топологічне сортування, для даного графу, неможливе");
}
_matrixViewWindow->showSimpleString(sorting, tr("Топологічне сортування"));
}
void MainWindow::on_action_showVertexDegree_triggered()
{
auto degree = _scene->graph()->vertexDegree();
_matrixViewWindow->showVertexDegree(degree, tr("Степені6 вершин графу"));
}
void MainWindow::on_action_saveGraph_triggered()
{
QString str = QFileDialog::getSaveFileName(this, tr("Open graph"), tr(""), tr("txt graph data (*.txt)"));
if(str.isEmpty()) {
return;
}
QFile file(str);
if(file.open(QIODevice::WriteOnly | QIODevice::Text) ) {
QTextStream outStream(&file);
outStream << _scene->graph()->toTextGraph();
}
file.close();
}
void MainWindow::on_action_inverseGraph_triggered()
{
_scene->graph()->inverseGraph();
}
| 30.152174
| 132
| 0.639304
|
AshBringer47
|
6e08be03ac82cd7eb5635d5a38622565495d536b
| 424
|
cpp
|
C++
|
test/ac-library/segtree.min.test.cpp
|
sash2104/library
|
ecb52543e4f8a66300ffd8794ea9c13bc74bdb19
|
[
"Unlicense"
] | null | null | null |
test/ac-library/segtree.min.test.cpp
|
sash2104/library
|
ecb52543e4f8a66300ffd8794ea9c13bc74bdb19
|
[
"Unlicense"
] | 10
|
2020-01-27T15:57:45.000Z
|
2021-12-20T03:26:26.000Z
|
test/ac-library/segtree.min.test.cpp
|
sash2104/library
|
ecb52543e4f8a66300ffd8794ea9c13bc74bdb19
|
[
"Unlicense"
] | null | null | null |
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_A"
#include <iostream>
#include "../../atcoder/segtree/min.hpp"
using namespace std;
// @title セグメント木、min (ac-library)
int main() {
int n, q; cin >> n >> q;
segtree::min::type<int> seg(n);
for (int i = 0; i < q; ++i) {
int c, x, y; cin >> c >> x >> y;
if (c == 0) seg.set(x, y);
else cout << seg.prod(x, y+1) << endl;
}
}
| 24.941176
| 82
| 0.570755
|
sash2104
|
6e09fa2515f524b3a4b661b90b8391205cc9dd67
| 983
|
cpp
|
C++
|
source/entity/Drain.cpp
|
Tomash667/carpg
|
7e89d83f51cb55a89baf509915a9a9f8c642825f
|
[
"MIT"
] | 19
|
2015-05-30T12:14:07.000Z
|
2021-05-26T19:17:21.000Z
|
source/entity/Drain.cpp
|
Tomash667/carpg
|
7e89d83f51cb55a89baf509915a9a9f8c642825f
|
[
"MIT"
] | 402
|
2016-02-26T08:39:21.000Z
|
2021-07-06T16:47:16.000Z
|
source/entity/Drain.cpp
|
Tomash667/carpg
|
7e89d83f51cb55a89baf509915a9a9f8c642825f
|
[
"MIT"
] | 21
|
2015-07-28T14:11:39.000Z
|
2020-12-11T07:54:09.000Z
|
#include "Pch.h"
#include "Drain.h"
#include "Unit.h"
#include <ParticleSystem.h>
//=================================================================================================
bool Drain::Update(float dt)
{
t += dt;
if(pe->manual_delete == 2)
{
delete pe;
return true;
}
if(Unit* unit = target)
{
Vec3 center = unit->GetCenter();
for(ParticleEmitter::Particle& p : pe->particles)
p.pos = Vec3::Lerp(p.pos, center, t / 1.5f);
return false;
}
else
{
pe->time = 0.3f;
pe->manual_delete = 0;
return true;
}
}
//=================================================================================================
void Drain::Save(GameWriter& f)
{
f << target;
f << pe->id;
f << t;
}
//=================================================================================================
void Drain::Load(GameReader& f)
{
if(LOAD_VERSION < V_0_13)
f.Skip<int>(); // old from
f >> target;
pe = ParticleEmitter::GetById(f.Read<int>());
f >> t;
}
| 18.903846
| 99
| 0.417091
|
Tomash667
|
6e0a177518fa95590055e0ff0956db84506214e0
| 26,704
|
cpp
|
C++
|
Src/Assets/Mitsuba/MitsubaLoader.cpp
|
dennis-lynch/GPU-Raytracer
|
93eb8cfb148ca54d4e5655c63bf32f32d0d3bd9e
|
[
"MIT"
] | null | null | null |
Src/Assets/Mitsuba/MitsubaLoader.cpp
|
dennis-lynch/GPU-Raytracer
|
93eb8cfb148ca54d4e5655c63bf32f32d0d3bd9e
|
[
"MIT"
] | null | null | null |
Src/Assets/Mitsuba/MitsubaLoader.cpp
|
dennis-lynch/GPU-Raytracer
|
93eb8cfb148ca54d4e5655c63bf32f32d0d3bd9e
|
[
"MIT"
] | null | null | null |
#include "MitsubaLoader.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "Core/Array.h"
#include "Core/HashMap.h"
#include "Core/Format.h"
#include "Core/Parser.h"
#include "Core/StringView.h"
#include "Assets/BVHLoader.h"
#include "Assets/OBJLoader.h"
#include "Assets/PLYLoader.h"
#include "Renderer/Scene.h"
#include "Renderer/MeshData.h"
#include "Util/Util.h"
#include "Util/Geometry.h"
#include "XMLParser.h"
#include "MitshairLoader.h"
#include "SerializedLoader.h"
struct ShapeGroup {
MeshDataHandle mesh_data_handle;
MaterialHandle material_handle;
};
using ShapeGroupMap = HashMap<String, ShapeGroup>;
using MaterialMap = HashMap<String, MaterialHandle>;
using TextureMap = HashMap<String, TextureHandle>;
static TextureHandle parse_texture(const XMLNode * node, TextureMap & texture_map, StringView path, Scene & scene, Vector3 * rgb) {
StringView type = node->get_attribute_value("type");
if (type == "scale") {
if (const XMLNode * scale = node->get_child_by_name("scale")) {
if (scale->tag == "float") {
*rgb *= scale->get_attribute_value<float>("value");
} else if (scale->tag == "rgb") {
*rgb *= scale->get_attribute_value<Vector3>("value");
} else {
WARNING(scale->location, "Invalid scale tag <{}>!\n", scale->tag);
}
}
node = node->get_child_by_tag("texture");
type = node->get_attribute_value("type");
}
if (type == "bitmap") {
StringView filename_rel = node->get_child_value<StringView>("filename");
String filename_abs = Util::combine_stringviews(path, filename_rel, scene.allocator);
String texture_name = String(Util::remove_directory(filename_abs.view()), scene.allocator);
TextureHandle texture_handle = scene.asset_manager.add_texture(std::move(filename_abs), std::move(texture_name));
if (const XMLAttribute * id = node->get_attribute("id")) {
texture_map.insert(id->value, texture_handle);
}
return texture_handle;
} else {
WARNING(node->location, "Only bitmap textures are supported!\n");
}
return TextureHandle { INVALID };
}
static void parse_rgb_or_texture(const XMLNode * node, const char * name, TextureMap & texture_map, StringView path, Scene & scene, Vector3 * rgb, TextureHandle * texture_handle) {
const XMLNode * colour = node->get_child_by_name(name);
if (colour) {
if (colour->tag == "rgb") {
*rgb = colour->get_attribute_optional("value", Vector3(1.0f));
} else if (colour->tag == "srgb") {
*rgb = colour->get_attribute_optional("value", Vector3(1.0f));
rgb->x = Math::gamma_to_linear(rgb->x);
rgb->y = Math::gamma_to_linear(rgb->y);
rgb->z = Math::gamma_to_linear(rgb->z);
} else if (colour->tag == "texture") {
*texture_handle = parse_texture(colour, texture_map, path, scene, rgb);
const XMLNode * scale = colour->get_child_by_name("scale");
if (scale) {
*rgb = scale->get_attribute_optional("value", Vector3(1.0f));
}
} else if (colour->tag == "ref") {
StringView texture_name = colour->get_attribute_value<StringView>("id");
TextureHandle * ref_handle = texture_map.try_get(texture_name);
if (ref_handle) {
*texture_handle = *ref_handle;
} else {
WARNING(colour->location, "Invalid texture ref '{}'!\n", texture_name);
}
}
} else {
*rgb = Vector3(1.0f);
}
}
static Matrix4 parse_transform_matrix(const XMLNode * node) {
Matrix4 world = { };
const XMLNode * transform = node->get_child_by_tag("transform");
if (!transform) {
return world;
}
for (size_t i = 0; i < transform->children.size(); i++) {
const XMLNode & transformation = transform->children[i];
if (transformation.tag == "matrix") {
world = transformation.get_attribute_value<Matrix4>("value") * world;
} else if (transformation.tag == "lookat") {
Vector3 origin = transformation.get_attribute_optional("origin", Vector3(0.0f, 0.0f, 0.0f));
Vector3 target = transformation.get_attribute_optional("target", Vector3(0.0f, 0.0f, -1.0f));
Vector3 up = transformation.get_attribute_optional("up", Vector3(0.0f, 1.0f, 0.0f));
world = Matrix4::create_translation(origin) * Matrix4::create_rotation(Quaternion::look_rotation(target - origin, up)) * world;
} else if (transformation.tag == "scale") {
const XMLAttribute * scale = transformation.get_attribute("value");
if (scale) {
world = Matrix4::create_scale(scale->get_value<float>()) * world;
} else {
float x = transformation.get_attribute_optional("x", 1.0f);
float y = transformation.get_attribute_optional("y", 1.0f);
float z = transformation.get_attribute_optional("z", 1.0f);
world = Matrix4::create_scale(x, y, z) * world;
}
} else if (transformation.tag == "rotate") {
float x = transformation.get_attribute_optional("x", 0.0f);
float y = transformation.get_attribute_optional("y", 0.0f);
float z = transformation.get_attribute_optional("z", 0.0f);
if (x == 0.0f && y == 0.0f && z == 0.0f) {
WARNING(transformation.location, "WARNING: Rotation without axis specified!\n");
} else {
float angle = transformation.get_attribute_optional("angle", 0.0f);
world = Matrix4::create_rotation(Quaternion::axis_angle(Vector3(x, y, z), Math::deg_to_rad(angle))) * world;
}
} else if (transformation.tag == "translate") {
world = Matrix4::create_translation(Vector3(
transformation.get_attribute_optional("x", 0.0f),
transformation.get_attribute_optional("y", 0.0f),
transformation.get_attribute_optional("z", 0.0f)
)) * world;
} else {
WARNING(transformation.location, "Node <{}> is not a valid transformation!\n", transformation.tag);
}
}
return world;
}
static void parse_transform(const XMLNode * node, Vector3 * position, Quaternion * rotation, float * scale, const Vector3 & forward = Vector3(0.0f, 0.0f, 1.0f)) {
Matrix4 world = parse_transform_matrix(node);
Matrix4::decompose(world, position, rotation, scale, forward);
}
static MaterialHandle parse_material(const XMLNode * node, Scene & scene, const MaterialMap & material_map, TextureMap & texture_map, StringView path) {
Material material = { };
const XMLNode * bsdf;
if (node->tag != "bsdf") {
// Check if there is an emitter defined
const XMLNode * emitter = node->get_child_by_tag("emitter");
if (emitter) {
material.type = Material::Type::LIGHT;
material.name = "emitter";
material.emission = emitter->get_child_value<Vector3>("radiance");
return scene.asset_manager.add_material(std::move(material));
}
// Check if an existing Material is referenced
const XMLNode * ref = node->get_child_by_tag("ref");
if (ref) {
StringView material_name = ref->get_attribute_value<StringView>("id");
if (MaterialHandle * material_id = material_map.try_get(material_name)) {
return *material_id;
} else {
WARNING(ref->location, "Invalid material Ref '{}'!\n", material_name);
return MaterialHandle::get_default();
}
}
// Otherwise, parse BSDF
bsdf = node->get_child_by_tag("bsdf");
if (bsdf == nullptr) {
WARNING(node->location, "Unable to parse BSDF!\n");
return MaterialHandle::get_default();
}
} else {
bsdf = node;
}
const XMLAttribute * name = bsdf->get_attribute("id");
const XMLNode * inner_bsdf = bsdf;
StringView inner_bsdf_type = inner_bsdf->get_attribute_value<StringView>("type");
// Keep peeling back nested BSDFs, we only care about the innermost one
while (
inner_bsdf_type == "twosided" ||
inner_bsdf_type == "mask" ||
inner_bsdf_type == "bumpmap" ||
inner_bsdf_type == "coating"
) {
const XMLNode * inner_bsdf_child = inner_bsdf->get_child_by_tag("bsdf");
if (inner_bsdf_child) {
inner_bsdf = inner_bsdf_child;
} else {
const XMLNode * ref = inner_bsdf->get_child_by_tag("ref");
if (ref) {
StringView id = ref->get_attribute_value<StringView>("id");
if (MaterialHandle * material_handle = material_map.try_get(id)) {
return *material_handle;
} else {
WARNING(ref->location, "Invalid material Ref '{}'!\n", id);
return MaterialHandle::get_default();
}
} else {
return MaterialHandle::get_default();
}
}
inner_bsdf_type = inner_bsdf->get_attribute_value<StringView>("type");
if (name == nullptr) {
name = inner_bsdf->get_attribute("id");
}
}
if (name) {
material.name = String(name->value, scene.allocator);
} else {
material.name = "Material";
}
if (inner_bsdf_type == "diffuse") {
material.type = Material::Type::DIFFUSE;
parse_rgb_or_texture(inner_bsdf, "reflectance", texture_map, path, scene, &material.diffuse, &material.texture_handle);
} else if (inner_bsdf_type == "conductor" || inner_bsdf_type == "roughconductor") {
material.type = Material::Type::CONDUCTOR;
if (inner_bsdf_type == "conductor") {
material.linear_roughness = 0.0f;
} else {
material.linear_roughness = sqrtf(inner_bsdf->get_child_value_optional("alpha", 0.25f));
}
const XMLNode * material_str = inner_bsdf->get_child_by_name("material");
if (material_str && material_str->get_attribute_value<StringView>("value") == "none") {
material.eta = Vector3(0.0f);
material.k = Vector3(1.0f);
} else {
material.eta = inner_bsdf->get_child_value_optional("eta", Vector3(1.33f));
material.k = inner_bsdf->get_child_value_optional("k", Vector3(1.0f));
}
} else if (inner_bsdf_type == "plastic" || inner_bsdf_type == "roughplastic" || inner_bsdf_type == "roughdiffuse") {
material.type = Material::Type::PLASTIC;
parse_rgb_or_texture(inner_bsdf, "diffuseReflectance", texture_map, path, scene, &material.diffuse, &material.texture_handle);
if (inner_bsdf_type == "plastic") {
material.linear_roughness = 0.0f;
} else {
material.linear_roughness = sqrtf(inner_bsdf->get_child_value_optional("alpha", 0.25f));
}
} else if (inner_bsdf_type == "phong") {
material.type = Material::Type::PLASTIC;
parse_rgb_or_texture(inner_bsdf, "diffuseReflectance", texture_map, path, scene, &material.diffuse, &material.texture_handle);
float exponent = inner_bsdf->get_child_value_optional("exponent", 1.0f);
material.linear_roughness = powf(0.5f * exponent + 1.0f, 0.25f);
} else if (inner_bsdf_type == "thindielectric" || inner_bsdf_type == "dielectric" || inner_bsdf_type == "roughdielectric") {
float int_ior = 0.0f;
float ext_ior = 0.0f;
auto lookup_known_ior = [](StringView name, float * ior) {
// Based on: https://www.mitsuba-renderer.org/releases/0.5.0/documentation.pdf (page 58)
struct IOR {
const char * name;
float ior;
};
static IOR known_iors[] = {
{ "vacuum", 1.0f },
{ "helium", 1.00004f },
{ "hydrogen", 1.00013f },
{ "air", 1.00028f },
{ "carbon dioxide", 1.00045f },
{ "water", 1.3330f },
{ "acetone", 1.36f },
{ "ethanol", 1.361f },
{ "carbon tetrachloride", 1.461f },
{ "glycerol", 1.4729f },
{ "benzene", 1.501f },
{ "silicone oil", 1.52045f },
{ "bromine", 1.661f },
{ "water ice", 1.31f },
{ "fused quartz", 1.458f },
{ "pyrex", 1.470f },
{ "acrylic glass", 1.49f },
{ "polypropylene", 1.49f },
{ "bk7", 1.5046f },
{ "sodium chloride", 1.544f },
{ "amber", 1.55f },
{ "pet", 1.575f },
{ "diamond", 2.419f }
};
for (int i = 0; i < Util::array_count(known_iors); i++) {
if (name == known_iors[i].name) {
*ior = known_iors[i].ior;
return true;
}
}
return false;
};
const XMLNode * child_int_ior = inner_bsdf->get_child_by_name("intIOR");
if (child_int_ior && child_int_ior->tag == "string") {
StringView int_ior_name = child_int_ior->get_attribute_value("value");
if (!lookup_known_ior(int_ior_name, &int_ior)) {
ERROR(child_int_ior->location, "Index of refraction not known for '{}'\n", int_ior_name);
}
} else {
int_ior = inner_bsdf->get_child_value_optional("intIOR", 1.33f);
}
const XMLNode * child_ext_ior = inner_bsdf->get_child_by_name("extIOR");
if (child_ext_ior && child_ext_ior->tag == "string") {
StringView ext_ior_name = child_ext_ior->get_attribute_value("value");
if (!lookup_known_ior(ext_ior_name, &ext_ior)) {
ERROR(child_ext_ior->location, "Index of refraction not known for '{}'\n", ext_ior_name);
}
} else {
ext_ior = inner_bsdf->get_child_value_optional("extIOR", 1.0f);
}
material.type = Material::Type::DIELECTRIC;
material.index_of_refraction = ext_ior == 0.0f ? int_ior : int_ior / ext_ior;
if (inner_bsdf_type == "roughdielectric") {
material.linear_roughness = sqrtf(inner_bsdf->get_child_value_optional("alpha", 0.25f));
} else {
material.linear_roughness = 0.0f;
}
} else if (inner_bsdf_type == "difftrans") {
material.type = Material::Type::DIFFUSE;
parse_rgb_or_texture(inner_bsdf, "transmittance", texture_map, path, scene, &material.diffuse, &material.texture_handle);
} else {
WARNING(inner_bsdf->location, "WARNING: BSDF type '{}' not supported!\n", inner_bsdf_type);
return MaterialHandle::get_default();
}
return scene.asset_manager.add_material(std::move(material));
}
static MediumHandle parse_medium(const XMLNode * node, Scene & scene) {
const XMLNode * xml_medium = node->get_child_by_tag("medium");
if (!xml_medium) {
return MediumHandle { INVALID };
}
StringView medium_type = xml_medium->get_attribute_value("type");
if (medium_type == "homogeneous") {
Medium medium = { };
if (const XMLAttribute * name = xml_medium->get_attribute("name")) {
medium.name = String(name->value, scene.allocator);
}
const XMLNode * xml_sigma_a = xml_medium->get_child_by_name("sigmaA");
const XMLNode * xml_sigma_s = xml_medium->get_child_by_name("sigmaS");
const XMLNode * xml_sigma_t = xml_medium->get_child_by_name("sigmaT");
const XMLNode * xml_albedo = xml_medium->get_child_by_name("albedo"); // Single scatter albedo
Vector3 sigma_a = { };
Vector3 sigma_s = { };
if (!((xml_sigma_a && xml_sigma_s) ^ (xml_sigma_t && xml_albedo))) {
WARNING(xml_medium->location, "WARNING: Incorrect configuration of Medium properties\nPlease provide EITHER sigmaA and sigmaS OR sigmaT and albedo\n");
} else if (xml_sigma_a && xml_sigma_s) {
sigma_a = xml_sigma_a->get_attribute_value<Vector3>("value");
sigma_s = xml_sigma_s->get_attribute_value<Vector3>("value");
} else {
Vector3 sigma_t = xml_sigma_t->get_attribute_value<Vector3>("value");
Vector3 albedo = xml_albedo ->get_attribute_value<Vector3>("value");
sigma_s = albedo * sigma_t;
sigma_a = sigma_t - sigma_s;
}
float scale = xml_medium->get_child_value_optional("scale", 1.0f);
medium.set_A_and_d(scale * sigma_a, scale * sigma_s);
if (const XMLNode * phase = xml_medium->get_child_by_tag("phase")) {
StringView phase_type = phase->get_attribute_value("type");
if (phase_type == "isotropic") {
medium.g = 0.0f;
} else if (phase_type == "hg") {
medium.g = phase->get_child_value_optional("g", 0.0f);
} else {
WARNING(xml_medium->location, "WARNING: Phase function type '{}' not supported!\n", phase_type);
}
}
return scene.asset_manager.add_medium(medium);
} else {
WARNING(xml_medium->location, "WARNING: Medium type '{}' not supported!\n", medium_type);
}
return MediumHandle { INVALID };
}
static MeshDataHandle parse_shape(const XMLNode * node, Allocator * allocator, Scene & scene, StringView path, String * name) {
StringView type = node->get_attribute_value<StringView>("type");
if (type == "obj" || type == "ply") {
String filename = Util::combine_stringviews(path, node->get_child_value<StringView>("filename"), scene.allocator);
MeshDataHandle mesh_data_handle;
if (type == "obj") {
mesh_data_handle = scene.asset_manager.add_mesh_data(filename, OBJLoader::load);
} else {
mesh_data_handle = scene.asset_manager.add_mesh_data(filename, PLYLoader::load);
}
*name = String(Util::remove_directory(filename.view()), scene.allocator);
return mesh_data_handle;
} else if (type == "rectangle" || type == "cube" || type == "disk" || type == "cylinder" || type == "sphere") {
Matrix4 transform = parse_transform_matrix(node);
Array<Triangle> triangles;
if (type == "rectangle") {
triangles = Geometry::rectangle(transform);
} else if (type == "cube") {
triangles = Geometry::cube(transform);
} else if (type == "disk") {
triangles = Geometry::disk(transform);
} else if (type == "cylinder") {
Vector3 p0 = node->get_child_value_optional("p0", Vector3(0.0f, 0.0f, 0.0f));
Vector3 p1 = node->get_child_value_optional("p1", Vector3(0.0f, 0.0f, 1.0f));
float radius = node->get_child_value_optional("radius", 1.0f);
triangles = Geometry::cylinder(transform, p0, p1, radius);
} else if (type == "sphere") {
float radius = node->get_child_value_optional("radius", 1.0f);
Vector3 center = Vector3(0.0f);
const XMLNode * xml_center = node->get_child_by_name("center");
if (xml_center) {
center = Vector3(
xml_center->get_attribute_optional("x", 0.0f),
xml_center->get_attribute_optional("y", 0.0f),
xml_center->get_attribute_optional("z", 0.0f)
);
}
transform = transform * Matrix4::create_translation(center) * Matrix4::create_scale(radius);
triangles = Geometry::sphere(transform);
} else {
ASSERT_UNREACHABLE();
}
*name = String(type, scene.allocator);
return scene.asset_manager.add_mesh_data(std::move(triangles));
} else if (type == "serialized") {
StringView filename_rel = node->get_child_value<StringView>("filename");
String filename_abs = Util::combine_stringviews(path, filename_rel);
int shape_index = node->get_child_value_optional("shapeIndex", 0);
*name = Format(scene.allocator).format("{}_{}"_sv, filename_rel, shape_index);
String bvh_filename = Format().format("{}.shape_{}.bvh"_sv, filename_abs, shape_index);
auto fallback_loader = [filename_abs = std::move(filename_abs), location = node->location, shape_index](const String & filename, Allocator * allocator) {
return SerializedLoader::load(filename_abs, allocator, location, shape_index);
};
return scene.asset_manager.add_mesh_data(bvh_filename, bvh_filename, fallback_loader);
} else if (type == "hair") {
StringView filename_rel = node->get_child_value<StringView>("filename");
String filename_abs = Util::combine_stringviews(path, filename_rel, scene.allocator);
*name = String(filename_rel, scene.allocator);
float radius = node->get_child_value_optional("radius", 0.0025f);
auto fallback_loader = [location = node->location, radius](const String & filename, Allocator * allocator) {
return MitshairLoader::load(filename, allocator, location, radius);
};
return scene.asset_manager.add_mesh_data(filename_abs, fallback_loader);
} else {
WARNING(node->location, "WARNING: Shape type '{}' not supported!\n", type);
return MeshDataHandle { INVALID };
}
}
static void walk_xml_tree(const XMLNode * node, Allocator * allocator, Scene & scene, ShapeGroupMap & shape_group_map, MaterialMap & material_map, TextureMap & texture_map, StringView path) {
if (node->tag == "bsdf") {
MaterialHandle material_handle = parse_material(node, scene, material_map, texture_map, path);
const Material & material = scene.asset_manager.get_material(material_handle);
material_map.insert(material.name, material_handle);
} else if (node->tag == "texture") {
Vector3 scale = 1.0f;
parse_texture(node, texture_map, path, scene, &scale);
} else if (node->tag == "shape") {
StringView type = node->get_attribute_value<StringView>("type");
if (type == "shapegroup") {
if (node->children.size() > 0) {
const XMLNode * shape = node->get_child_by_tag("shape");
if (!shape) {
ERROR(node->location, "Shapegroup needs a <shape> child!\n");
}
String name = { };
MeshDataHandle mesh_data_handle = parse_shape(shape, allocator, scene, path, &name);
MaterialHandle material_handle = parse_material(shape, scene, material_map, texture_map, path);
StringView id = node->get_attribute_value<StringView>("id");
shape_group_map[id] = { mesh_data_handle, material_handle };
}
} else if (type == "instance") {
const XMLNode * ref = node->get_child_by_tag("ref");
if (!ref) {
WARNING(node->location, "Instance without ref!\n");
return;
}
StringView id = ref->get_attribute_value<StringView>("id");
const ShapeGroup * shape_group = shape_group_map.try_get(id);
if (shape_group && shape_group->mesh_data_handle.handle != INVALID) {
Mesh & mesh = scene.add_mesh(id, shape_group->mesh_data_handle, shape_group->material_handle);
parse_transform(node, &mesh.position, &mesh.rotation, &mesh.scale);
}
} else {
String name = { };
MeshDataHandle mesh_data_handle = parse_shape(node, allocator, scene, path, &name);
MaterialHandle material_handle = parse_material(node, scene, material_map, texture_map, path);
MediumHandle medium_handle = parse_medium(node, scene);
if (material_handle.handle != INVALID) {
Material & material = scene.asset_manager.get_material(material_handle);
if (material.medium_handle.handle != INVALID && material.medium_handle.handle != medium_handle.handle) {
// This Material is already used with a different Medium
// Make a copy of the Material and add it as a new Material to the Scene
Material material_copy = material;
material_copy.medium_handle = medium_handle;
material_handle = scene.asset_manager.add_material(std::move(material_copy));
} else {
material.medium_handle = medium_handle;
}
}
if (mesh_data_handle.handle != INVALID) {
Mesh & mesh = scene.add_mesh(std::move(name), mesh_data_handle, material_handle);
// Do not apply transform to primitive shapes, since they have the transform baked into their vertices
bool type_is_primitive = type == "rectangle" || type == "cube" || type == "disk" || type == "cylinder" || type == "sphere";
if (!type_is_primitive) {
parse_transform(node, &mesh.position, &mesh.rotation, &mesh.scale);
}
}
}
} else if (node->tag == "sensor") {
StringView camera_type = node->get_attribute_value<StringView>("type");
if (camera_type == "perspective" || camera_type == "perspective_rdist" || camera_type == "thinlens") {
if (const XMLNode * fov = node->get_child_by_name("fov")) {
scene.camera.set_fov(Math::deg_to_rad(fov->get_attribute_value<float>("value")));
}
if (camera_type == "perspective") {
scene.camera.aperture_radius = 0.0f;
} else {
scene.camera.aperture_radius = node->get_child_value_optional("apertureRadius", 0.05f);
scene.camera.focal_distance = node->get_child_value_optional("focusDistance", 10.0f);
}
parse_transform(node, &scene.camera.position, &scene.camera.rotation, nullptr, Vector3(0.0f, 0.0f, -1.0f));
} else {
WARNING(node->location, "WARNING: Camera type '{}' not supported!\n", camera_type);
}
if (const XMLNode * film = node->get_child_by_tag("film")) {
cpu_config.initial_width = film->get_child_value_optional("width", cpu_config.initial_width);
cpu_config.initial_height = film->get_child_value_optional("height", cpu_config.initial_height);
scene.camera.resize(cpu_config.initial_width, cpu_config.initial_height);
}
} else if (node->tag == "integrator") {
gpu_config.num_bounces = node->get_child_value_optional("maxDepth", gpu_config.num_bounces);
} else if (node->tag == "emitter") {
StringView emitter_type = node->get_attribute_value<StringView>("type");
if (emitter_type == "area") {
WARNING(node->location, "Area emitter defined without geometry!\n");
} else if (emitter_type == "envmap") {
StringView filename_rel = node->get_child_value<StringView>("filename");
StringView extension = Util::get_file_extension(filename_rel);
if (extension.is_empty()) {
WARNING(node->location, "Environment Map '{}' has no file extension!\n", filename_rel);
} else if (extension != "hdr") {
WARNING(node->location, "Environment Map '{}' has unsupported file extension. Only HDR Environment Maps are supported!\n", filename_rel);
} else {
cpu_config.sky_filename = Util::combine_stringviews(path, filename_rel, scene.allocator);
}
} else if (emitter_type == "point") {
// Make small area light
constexpr float RADIUS = 0.0001f;
Matrix4 transform = parse_transform_matrix(node) * Matrix4::create_scale(RADIUS);
Array<Triangle> triangles = Geometry::sphere(transform, 0);
MeshDataHandle mesh_data_handle = scene.asset_manager.add_mesh_data(std::move(triangles));
Material material = { };
material.type = Material::Type::LIGHT;
material.emission = node->get_child_value_optional<Vector3>("intensity", Vector3(1.0f));
MaterialHandle material_handle = scene.asset_manager.add_material(std::move(material));
scene.add_mesh("PointLight", mesh_data_handle, material_handle);
} else {
WARNING(node->location, "Emitter type '{}' is not supported!\n", emitter_type);
}
} else if (node->tag == "include") {
StringView filename_rel = node->get_attribute_value<StringView>("filename");
String filename_abs = Util::combine_stringviews(path, filename_rel, allocator);
MitsubaLoader::load(filename_abs, allocator, scene);
} else for (int i = 0; i < node->children.size(); i++) {
walk_xml_tree(&node->children[i], allocator, scene, shape_group_map, material_map, texture_map, path);
}
}
void MitsubaLoader::load(const String & filename, Allocator * allocator, Scene & scene) {
XMLParser xml_parser(filename, allocator);
XMLNode root = xml_parser.parse_root();
const XMLNode * scene_node = root.get_child_by_tag("scene");
if (!scene_node) {
ERROR(root.location, "File does not contain a <scene> tag!\n");
}
{
StringView version = scene_node->get_attribute_value<StringView>("version");
Parser version_parser(version);
int major = version_parser.parse_int(); version_parser.expect('.');
int minor = version_parser.parse_int(); version_parser.expect('.');
int patch = version_parser.parse_int();
int version_number = major * 100 + minor * 10 + patch;
if (version_number >= 200) {
ERROR(scene_node->location, "Mitsuba 2 files are not supported!\n");
}
}
ShapeGroupMap shape_group_map(allocator);
MaterialMap material_map (allocator);
TextureMap texture_map (allocator);
walk_xml_tree(scene_node, allocator, scene, shape_group_map, material_map, texture_map, Util::get_directory(filename.view()));
}
| 38.645441
| 191
| 0.688586
|
dennis-lynch
|
6e15f02e9829b9cf7c214485ba63634a9445fd68
| 45,024
|
hpp
|
C++
|
Libs/jsoncons/include/jsoncons_ext/jsonpath/jsonpath_filter.hpp
|
Samuel-Harden/SimWorldsBoids
|
ae560181aa77bde75adc4ab2687952d919b4e988
|
[
"MIT"
] | null | null | null |
Libs/jsoncons/include/jsoncons_ext/jsonpath/jsonpath_filter.hpp
|
Samuel-Harden/SimWorldsBoids
|
ae560181aa77bde75adc4ab2687952d919b4e988
|
[
"MIT"
] | null | null | null |
Libs/jsoncons/include/jsoncons_ext/jsonpath/jsonpath_filter.hpp
|
Samuel-Harden/SimWorldsBoids
|
ae560181aa77bde75adc4ab2687952d919b4e988
|
[
"MIT"
] | null | null | null |
// Copyright 2013 Daniel Parker
// Distributed under the Boost license, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See https://github.com/danielaparker/jsoncons for latest version
#ifndef JSONCONS_JSONPATH_FILTER_HPP
#define JSONCONS_JSONPATH_FILTER_HPP
#include <string>
#include <sstream>
#include <vector>
#include <istream>
#include <cstdlib>
#include <memory>
#include <regex>
#include "jsoncons/json.hpp"
#include "jsonpath_error_category.hpp"
namespace jsoncons { namespace jsonpath {
template <class Json>
class jsonpath_evaluator;
enum class filter_states
{
start,
cr,
lf,
expect_right_round_bracket,
expect_oper_or_right_round_bracket,
expect_path_or_value,
expect_regex,
regex,
single_quoted_text,
double_quoted_text,
unquoted_text,
path,
value,
oper
};
enum class token_types
{
left_paren,
right_paren,
term,
eq,
ne,
regex,
ampamp,
pipepipe,
lt,
gt,
lte,
gte,
plus,
minus,
exclaim,
done
};
template <class Json>
class term
{
public:
typedef typename Json::string_type string_type;
typedef typename Json::char_type char_type;
virtual ~term() {}
virtual void initialize(const Json&)
{
}
virtual bool accept_single_node() const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json evaluate_single_node() const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool exclaim() const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool eq(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool eq(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool ne(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool ne(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool regex(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool regex2(const string_type&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool ampamp(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool ampamp(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool pipepipe(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool pipepipe(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool lt(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool lt(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool gt(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual bool gt(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json minus(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json minus(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json unary_minus() const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json plus(const term&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
virtual Json plus(const Json&) const
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unsupported_operator,1,1);
}
};
template <class Json>
class token
{
token_types type_;
std::shared_ptr<term<Json>> term_ptr_;
public:
token(token_types type)
: type_(type)
{
}
token(token_types type, std::shared_ptr<term<Json>> term_ptr)
: type_(type), term_ptr_(term_ptr)
{
}
token(const token& t)
: type_(t.type_), term_ptr_(t.term_ptr_)
{
}
token_types type() const
{
return type_;
}
std::shared_ptr<term<Json>> term_ptr()
{
return term_ptr_;
}
void initialize(const Json& context_node)
{
if (term_ptr_.get() != nullptr)
{
term_ptr_->initialize(context_node);
}
}
};
template <class Json>
class token_stream
{
std::vector<token<Json>>& tokens_;
size_t index_;
public:
token_stream(std::vector<token<Json>>& tokens)
: tokens_(tokens), index_(0)
{
}
token<Json> get()
{
static token<Json> done = token<Json>(token_types::done);
return index_ < tokens_.size() ? tokens_[index_++] : done;
}
void putback()
{
--index_;
}
};
template <class Json>
bool ampamp(const Json& lhs, const Json& rhs)
{
return lhs.as_bool() && rhs.as_bool();
}
template <class Json>
bool pipepipe(const Json& lhs, const Json& rhs)
{
return lhs.as_bool() || rhs.as_bool();
}
template <class Json>
bool lt(const Json& lhs, const Json& rhs)
{
bool result = false;
if (lhs. template is<unsigned long long>() && rhs. template is<unsigned long long>())
{
result = lhs. template as<unsigned long long>() < rhs. template as<unsigned long long>();
}
else if (lhs. template is<long long>() && rhs. template is<long long>())
{
result = lhs. template as<long long>() < rhs. template as<long long>();
}
else if ((lhs.is_number() && rhs.is_double()) || (lhs.is_double() && rhs.is_number()))
{
result = lhs.as_double() < rhs.as_double();
}
else if (lhs.is_string() && rhs.is_string())
{
result = lhs.as_string() < rhs.as_string();
}
return result;
}
template <class Json>
bool gt(const Json& lhs, const Json& rhs)
{
return lt(rhs,lhs);
}
template <class Json>
Json plus(const Json& lhs, const Json& rhs)
{
Json result = Json(jsoncons::null_type());
if (lhs.is_integer() && rhs.is_integer())
{
result = Json(((lhs.as_integer() + rhs.as_integer())));
}
else if ((lhs.is_number() && rhs.is_double()) || (lhs.is_double() && rhs.is_number()))
{
result = Json((lhs.as_double() + rhs.as_double()));
}
else if (lhs.is_uinteger() && rhs.is_uinteger())
{
result = Json((lhs.as_uinteger() + rhs.as_uinteger()));
}
return result;
}
template <class Json>
Json unary_minus(const Json& lhs)
{
Json result = Json::null();
if (lhs.is_integer())
{
result = -lhs.as_integer();
}
else if (lhs.is_double())
{
result = -lhs.as_double();
}
return result;
}
template <class Json>
Json minus(const Json& lhs, const Json& rhs)
{
Json result = Json::null();
if (lhs.is_integer() && rhs.is_integer())
{
result = ((lhs.as_integer() - rhs.as_integer()));
}
else if ((lhs.is_number() && rhs.is_double()) || (lhs.is_double() && rhs.is_number()))
{
result = (lhs.as_double() - rhs.as_double());
}
else if (lhs.is_uinteger() && rhs.is_uinteger() && lt(rhs,lhs))
{
result = (lhs.as_uinteger() - rhs.as_uinteger());
}
return result;
}
template <class Json>
class value_term : public term<Json>
{
Json value_;
public:
template <class T>
value_term(const T& value)
: value_(value)
{
}
bool accept_single_node() const override
{
return value_.as_bool();
}
Json evaluate_single_node() const override
{
return value_;
}
bool exclaim() const override
{
return !value_.as_bool();
}
bool eq(const term<Json>& rhs) const override
{
return rhs.eq(value_);
}
bool eq(const Json& rhs) const override
{
return value_ == rhs;
}
bool ne(const term<Json>& rhs) const override
{
return rhs.ne(value_);
}
bool ne(const Json& rhs) const override
{
return value_ != rhs;
}
bool regex(const term<Json>& rhs) const override
{
return rhs.regex2(value_.as_string());
}
bool ampamp(const term<Json>& rhs) const override
{
return rhs.ampamp(value_);
}
bool ampamp(const Json& rhs) const override
{
return jsoncons::jsonpath::ampamp(value_,rhs);
}
bool pipepipe(const term<Json>& rhs) const override
{
return rhs.pipepipe(value_);
}
bool pipepipe(const Json& rhs) const override
{
return jsoncons::jsonpath::pipepipe(value_,rhs);
}
bool lt(const term<Json>& rhs) const override
{
return rhs.gt(value_);
}
bool lt(const Json& rhs) const override
{
return jsoncons::jsonpath::lt(value_,rhs);
}
bool gt(const term<Json>& rhs) const override
{
return rhs.lt(value_);
}
bool gt(const Json& rhs) const override
{
return jsoncons::jsonpath::gt(value_,rhs);
}
Json minus(const term<Json>& rhs) const override
{
return jsoncons::jsonpath::plus(rhs.unary_minus(),value_);
}
Json minus(const Json& rhs) const override
{
return jsoncons::jsonpath::minus(value_,rhs);
}
Json unary_minus() const override
{
return jsoncons::jsonpath::unary_minus(value_);
}
Json plus(const term<Json>& rhs) const override
{
return rhs.plus(value_);
}
Json plus(const Json& rhs) const override
{
return jsoncons::jsonpath::plus(value_,rhs);
}
};
template <class Json>
class regex_term : public term<Json>
{
typedef typename Json::char_type char_type;
typedef typename Json::string_type string_type;
string_type pattern_;
std::regex::flag_type flags_;
public:
regex_term(const string_type& pattern, std::regex::flag_type flags)
: pattern_(pattern), flags_(flags)
{
}
bool regex2(const string_type& subject) const override
{
std::basic_regex<char_type> pattern(pattern_,
flags_);
return std::regex_match(subject, pattern);
}
};
template <class Json>
class path_term : public term<Json>
{
typedef typename Json::string_type string_type;
string_type path_;
Json nodes_;
public:
path_term(const string_type& path)
: path_(path)
{
}
void initialize(const Json& context_node) override
{
jsonpath_evaluator<Json> evaluator;
evaluator.evaluate(context_node,path_);
nodes_ = evaluator.get_values();
}
bool accept_single_node() const override
{
return nodes_.size() != 0;
}
Json evaluate_single_node() const override
{
return nodes_.size() == 1 ? nodes_[0] : nodes_;
}
bool exclaim() const override
{
return nodes_.size() == 0;
}
bool eq(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.eq(nodes_[i]);
}
}
return result;
}
bool eq(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = nodes_[i] == rhs;
}
}
return result;
}
bool ne(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.ne(nodes_[i]);
}
}
return result;
}
bool ne(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = nodes_[i] != rhs;
}
}
return result;
}
bool regex(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.regex2(nodes_[i].as_string());
}
}
return result;
}
bool ampamp(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.ampamp(nodes_[i]);
}
}
return result;
}
bool ampamp(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = jsoncons::jsonpath::ampamp(nodes_[i],rhs);
}
}
return result;
}
bool pipepipe(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.pipepipe(nodes_[i]);
}
}
return result;
}
bool pipepipe(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = jsoncons::jsonpath::pipepipe(nodes_[i],rhs);
}
}
return result;
}
bool lt(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = jsoncons::jsonpath::lt(nodes_[i],rhs);
}
}
return result;
}
bool lt(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.gt(nodes_[i]);
}
}
return result;
}
bool gt(const Json& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = jsoncons::jsonpath::gt(nodes_[i],rhs);
}
}
return result;
}
bool gt(const term<Json>& rhs) const override
{
bool result = false;
if (nodes_.size() > 0)
{
result = true;
for (size_t i = 0; result && i < nodes_.size(); ++i)
{
result = rhs.lt(nodes_[i]);
}
}
return result;
}
Json minus(const Json& rhs) const override
{
return nodes_.size() == 1 ? jsoncons::jsonpath::minus(nodes_[0],rhs) : Json(jsoncons::null_type());
}
Json minus(const term<Json>& rhs) const override
{
return nodes_.size() == 1 ? jsoncons::jsonpath::plus(rhs.unary_minus(),nodes_[0]) : Json(jsoncons::null_type());
}
Json unary_minus() const override
{
return nodes_.size() == 1 ? jsoncons::jsonpath::unary_minus(nodes_[0]) : Json::null();
}
Json plus(const Json& rhs) const override
{
static auto a_null = Json(jsoncons::null_type());
return nodes_.size() == 1 ? jsoncons::jsonpath::plus(nodes_[0],rhs) : a_null;
}
Json plus(const term<Json>& rhs) const override
{
static auto a_null = Json(jsoncons::null_type());
return nodes_.size() == 1 ? rhs.plus(nodes_[0]) : a_null;
}
};
template <class Json>
class jsonpath_filter_parser
{
typedef typename Json::string_type string_type;
typedef typename Json::char_type char_type;
size_t& line_;
size_t& column_;
filter_states state_;
string_type buffer_;
std::vector<token<Json>> tokens_;
int depth_;
const char_type* begin_input_;
const char_type* end_input_;
const char_type*& p_;
filter_states pre_line_break_state_;
public:
jsonpath_filter_parser(const char_type** expr, size_t* line,size_t* column)
: line_(*line), column_(*column), depth_(0), p_(*expr)
{
}
bool exists(const Json& context_node)
{
for (auto it=tokens_.begin(); it != tokens_.end(); ++it)
{
it->initialize(context_node);
}
bool result = false;
token_stream<Json> ts(tokens_);
auto e = expression(ts);
result = e->accept_single_node();
return result;
}
Json eval(const Json& context_node)
{
try
{
for (auto it=tokens_.begin(); it != tokens_.end(); ++it)
{
it->initialize(context_node);
}
token_stream<Json> ts(tokens_);
auto e = expression(ts);
Json result = e->evaluate_single_node();
return result;
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
}
std::shared_ptr<term<Json>> primary(token_stream<Json>& ts)
{
auto t = ts.get();
switch (t.type())
{
case token_types::left_paren:
{
auto expr = expression(ts);
t = ts.get();
if (t.type() != token_types::right_paren)
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_expected_right_brace,line_,column_);
}
return expr;
}
case token_types::term:
return t.term_ptr();
case token_types::exclaim:
{
Json val = Json(primary(ts)->exclaim());
auto expr = std::make_shared<value_term<Json>>(val);
return expr;
}
case token_types::minus:
{
Json val = primary(ts)->unary_minus();
auto expr = std::make_shared<value_term<Json>>(val);
return expr;
}
default:
throw parse_exception(jsonpath_parser_errc::invalid_filter_expected_primary,line_,column_);
}
}
std::shared_ptr<term<Json>> expression(token_stream<Json>& ts)
{
auto left = make_term(ts);
auto t = ts.get();
while (true)
{
switch (t.type())
{
case token_types::plus:
{
Json val = left->plus(*(make_term(ts)));
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::minus:
{
Json val = left->minus(*(make_term(ts)));
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
default:
ts.putback();
return left;
}
}
return left;
}
std::shared_ptr<term<Json>> make_term(token_stream<Json>& ts)
{
auto left = primary(ts);
auto t = ts.get();
while (true)
{
switch (t.type())
{
case token_types::eq:
{
bool e = left->eq(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::ne:
{
bool e = left->ne(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::regex:
{
bool e = left->regex(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::ampamp:
{
bool e = left->ampamp(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::pipepipe:
{
bool e = left->pipepipe(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::lt:
{
bool e = left->lt(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::gt:
{
bool e = left->gt(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::lte:
{
bool e = left->lt(*(primary(ts))) || left->eq(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
case token_types::gte:
{
bool e = left->gt(*(primary(ts))) || left->eq(*(primary(ts)));
Json val(e);
left = std::make_shared<value_term<Json>>(val);
t = ts.get();
}
break;
default:
ts.putback();
return left;
}
}
}
void parse(const char_type* expr, size_t length)
{
parse(expr,expr+length);
}
void parse(const char_type* expr, const char_type* end_expr)
{
p_ = expr;
end_input_ = end_expr;
depth_ = 0;
tokens_.clear();
state_ = filter_states::start;
bool done = false;
while (!done && p_ < end_input_)
{
switch (state_)
{
case filter_states::cr:
++line_;
column_ = 1;
switch (*p_)
{
case '\n':
state_ = pre_line_break_state_;
++p_;
++column_;
break;
default:
state_ = pre_line_break_state_;
break;
}
break;
case filter_states::lf:
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case filter_states::start:
switch (*p_)
{
case '\r':
case '\n':
pre_line_break_state_ = state_;
state_ = filter_states::lf;
break;
case '(':
state_ = filter_states::expect_path_or_value;
++depth_;
tokens_.push_back(token<Json>(token_types::left_paren));
break;
case ')':
tokens_.push_back(token<Json>(token_types::right_paren));
if (--depth_ == 0)
{
done = true;
}
break;
}
++p_;
++column_;
break;
case filter_states::oper:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '!':
if (p_+1 < end_input_ && *(p_+1) == '=')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::ne));
}
else
{
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::exclaim));
}
break;
case '&':
if (p_+1 < end_input_ && *(p_+1) == '&')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::ampamp));
}
break;
case '|':
if (p_+1 < end_input_ && *(p_+1) == '|')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::pipepipe));
}
break;
case '=':
if (p_+1 < end_input_ && *(p_+1) == '=')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::eq));
}
else if (p_+1 < end_input_ && *(p_+1) == '~')
{
++p_;
++column_;
state_ = filter_states::expect_regex;
tokens_.push_back(token<Json>(token_types::regex));
}
break;
case '>':
if (p_+1 < end_input_ && *(p_+1) == '=')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::gte));
}
else
{
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::gt));
}
break;
case '<':
if (p_+1 < end_input_ && *(p_+1) == '=')
{
++p_;
++column_;
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::lte));
}
else
{
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::lt));
}
break;
case '+':
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::plus));
break;
case '-':
state_ = filter_states::expect_path_or_value;
tokens_.push_back(token<Json>(token_types::minus));
break;
case ' ':case '\t':
break;
default:
throw parse_exception(jsonpath_parser_errc::invalid_filter,line_,column_);
break;
}
++p_;
++column_;
break;
case filter_states::unquoted_text:
{
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '<':
case '>':
case '!':
case '=':
case '&':
case '|':
case '+':
case '-':
{
if (buffer_.length() > 0)
{
try
{
auto val = Json::parse(buffer_);
tokens_.push_back(token<Json>(token_types::term,std::make_shared<value_term<Json>>(val)));
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
buffer_.clear();
}
state_ = filter_states::oper;
}
break;
case ')':
if (buffer_.length() > 0)
{
try
{
auto val = Json::parse(buffer_);
tokens_.push_back(token<Json>(token_types::term,std::make_shared<value_term<Json>>(val)));
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
buffer_.clear();
}
tokens_.push_back(token<Json>(token_types::right_paren));
if (--depth_ == 0)
{
state_ = filter_states::start;
done = true;
}
else
{
state_ = filter_states::expect_path_or_value;
}
++p_;
++column_;
break;
case ' ':case '\t':
if (buffer_.length() > 0)
{
try
{
auto val = Json::parse(buffer_);
tokens_.push_back(token<Json>(token_types::term,std::make_shared<value_term<Json>>(val)));
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
buffer_.clear();
}
++p_;
++column_;
break;
default:
buffer_.push_back(*p_);
++p_;
++column_;
break;
}
}
break;
case filter_states::single_quoted_text:
{
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '\\':
buffer_.push_back(*p_);
if (p_+1 < end_input_)
{
++p_;
++column_;
buffer_.push_back(*p_);
}
break;
case '\'':
buffer_.push_back('\"');
//if (buffer_.length() > 0)
{
try
{
auto val = Json::parse(buffer_);
tokens_.push_back(token<Json>(token_types::term,std::make_shared<value_term<Json>>(val)));
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
buffer_.clear();
}
state_ = filter_states::expect_path_or_value;
break;
default:
buffer_.push_back(*p_);
break;
}
}
++p_;
++column_;
break;
case filter_states::double_quoted_text:
{
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '\\':
buffer_.push_back(*p_);
if (p_+1 < end_input_)
{
++p_;
++column_;
buffer_.push_back(*p_);
}
break;
case '\"':
buffer_.push_back(*p_);
//if (buffer_.length() > 0)
{
try
{
auto val = Json::parse(buffer_);
tokens_.push_back(token<Json>(token_types::term,std::make_shared<value_term<Json>>(val)));
}
catch (const parse_exception& e)
{
throw parse_exception(e.code(),line_,column_);
}
buffer_.clear();
}
state_ = filter_states::expect_path_or_value;
break;
default:
buffer_.push_back(*p_);
break;
}
}
++p_;
++column_;
break;
case filter_states::expect_path_or_value:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '<':
case '>':
case '!':
case '=':
case '&':
case '|':
case '+':
case '-':
state_ = filter_states::oper;
// don't increment
break;
case '@':
buffer_.push_back(*p_);
state_ = filter_states::path;
++p_;
++column_;
break;
case ' ':case '\t':
++p_;
++column_;
break;
case '\'':
buffer_.push_back('\"');
state_ = filter_states::single_quoted_text;
++p_;
++column_;
break;
case '\"':
buffer_.push_back(*p_);
state_ = filter_states::double_quoted_text;
++p_;
++column_;
break;
case '(':
++depth_;
tokens_.push_back(token<Json>(token_types::left_paren));
++p_;
++column_;
break;
case ')':
tokens_.push_back(token<Json>(token_types::right_paren));
if (--depth_ == 0)
{
done = true;
state_ = filter_states::start;
}
++p_;
++column_;
break;
default:
// don't increment
state_ = filter_states::unquoted_text;
break;
};
break;
case filter_states::expect_oper_or_right_round_bracket:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case ' ':case '\t':
break;
case ')':
tokens_.push_back(token<Json>(token_types::right_paren));
if (--depth_ == 0)
{
done = true;
state_ = filter_states::start;
}
break;
case '<':
case '>':
case '!':
case '=':
case '&':
case '|':
case '+':
case '-':
{
state_ = filter_states::oper;
// don't increment p
}
break;
default:
throw parse_exception(jsonpath_parser_errc::invalid_filter,line_,column_);
break;
};
break;
case filter_states::expect_right_round_bracket:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case ' ':case '\t':
break;
case ')':
tokens_.push_back(token<Json>(token_types::right_paren));
if (--depth_ == 0)
{
done = true;
state_ = filter_states::start;
}
else
{
state_ = filter_states::expect_oper_or_right_round_bracket;
}
break;
default:
throw parse_exception(jsonpath_parser_errc::invalid_filter,line_,column_);
break;
};
++p_;
++column_;
break;
case filter_states::path:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '<':
case '>':
case '!':
case '=':
case '&':
case '|':
case '+':
case '-':
{
if (buffer_.length() > 0)
{
tokens_.push_back(token<Json>(token_types::term,std::make_shared<path_term<Json>>(buffer_)));
buffer_.clear();
}
state_ = filter_states::oper;
// don't increment
}
break;
case ')':
if (buffer_.length() > 0)
{
tokens_.push_back(token<Json>(token_types::term,std::make_shared<path_term<Json>>(buffer_)));
tokens_.push_back(token<Json>(token_types::right_paren));
buffer_.clear();
}
if (--depth_ == 0)
{
state_ = filter_states::start;
done = true;
}
else
{
state_ = filter_states::expect_path_or_value;
}
++p_;
++column_;
break;
default:
buffer_.push_back(*p_);
++p_;
++column_;
break;
};
break;
case filter_states::expect_regex:
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '/':
state_ = filter_states::regex;
break;
case ' ':case '\t':
break;
default:
throw parse_exception(jsonpath_parser_errc::invalid_filter_expected_slash,line_,column_);
break;
};
++p_;
++column_;
break;
case filter_states::regex:
{
switch (*p_)
{
case '\r':
case '\n':
++line_;
column_ = 1;
state_ = pre_line_break_state_;
break;
case '/':
//if (buffer_.length() > 0)
{
std::regex::flag_type flags = std::regex_constants::ECMAScript;
if (p_+1 < end_input_ && *(p_+1) == 'i')
{
++p_;
++column_;
flags |= std::regex_constants::icase;
}
tokens_.push_back(token<Json>(token_types::term,std::make_shared<regex_term<Json>>(buffer_,flags)));
buffer_.clear();
}
state_ = filter_states::expect_path_or_value;
break;
default:
buffer_.push_back(*p_);
break;
}
}
++p_;
++column_;
break;
default:
++p_;
++column_;
break;
}
}
if (depth_ != 0)
{
throw parse_exception(jsonpath_parser_errc::invalid_filter_unbalanced_paren,line_,column_);
}
}
};
}}
#endif
| 30.076152
| 128
| 0.427172
|
Samuel-Harden
|
6e15f4a68a455b18d41e30fc01dab5c134fd3a9d
| 216
|
cpp
|
C++
|
src/rynx/tech/reflection.cpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | 11
|
2019-08-19T08:44:14.000Z
|
2020-09-22T20:04:46.000Z
|
src/rynx/tech/reflection.cpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | null | null | null |
src/rynx/tech/reflection.cpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | null | null | null |
#include <rynx/tech/reflection.hpp>
namespace rynx::reflection::internal {
registration_object* global_linked_list_initializer_head = nullptr;
registration_object* global_linked_list_initializer_tail = nullptr;
}
| 30.857143
| 68
| 0.837963
|
Apodus
|
6e1636d1ea96946231d627d9212c2f85697003b9
| 584
|
cpp
|
C++
|
Day-15/Day-15-CodeForces/227-B-EffectiveApproach.cpp
|
LawranceMichaelite/100-Days-of-Code
|
de80015c2ab7c94956d4fe39f6e143627cdd7bc9
|
[
"Apache-2.0"
] | null | null | null |
Day-15/Day-15-CodeForces/227-B-EffectiveApproach.cpp
|
LawranceMichaelite/100-Days-of-Code
|
de80015c2ab7c94956d4fe39f6e143627cdd7bc9
|
[
"Apache-2.0"
] | null | null | null |
Day-15/Day-15-CodeForces/227-B-EffectiveApproach.cpp
|
LawranceMichaelite/100-Days-of-Code
|
de80015c2ab7c94956d4fe39f6e143627cdd7bc9
|
[
"Apache-2.0"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int main()
{
unordered_map<int , int>one;
unordered_multimap<int,int>two;
int num ;
cin >> num;
int temp ;
for(int i= 0 ; i < num ; i++)
{
cin >> temp ;
one.insert(make_pair(temp ,i));
two.insert(make_pair(temp, i));
}
int q;
cin >> q;
long long comp1 = 0;
long long comp2 = 0;
while(q--)
{
cin >> temp ;
comp1 += ((one.find(temp)->second) +1 );
comp2 += (num - (two.find(temp)->second) );
}
cout << comp1 << " " << comp2 << endl;
return 0;
}
| 18.25
| 50
| 0.506849
|
LawranceMichaelite
|
6e1922c98d47293a8a4193f5994b49955608852c
| 10,256
|
cpp
|
C++
|
test/rix/core/helpers/src/Textures.cpp
|
asuessenbach/pipeline
|
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
|
[
"BSD-3-Clause"
] | 217
|
2015-01-06T09:26:53.000Z
|
2022-03-23T14:03:18.000Z
|
test/rix/core/helpers/src/Textures.cpp
|
asuessenbach/pipeline
|
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
|
[
"BSD-3-Clause"
] | 10
|
2015-01-25T12:42:05.000Z
|
2017-11-28T16:10:16.000Z
|
test/rix/core/helpers/src/Textures.cpp
|
asuessenbach/pipeline
|
2e49968cc3b9948a57f7ee6c4cc3258925c92ab2
|
[
"BSD-3-Clause"
] | 44
|
2015-01-13T01:19:41.000Z
|
2022-02-21T21:35:08.000Z
|
// Copyright NVIDIA Corporation 2012
// 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 NVIDIA CORPORATION 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 ``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 <dp/math/math.h>
#include <dp/math/Matmnt.h>
#include <test/rix/core/helpers/SimplexNoise1234.h>
#include <test/rix/core/helpers/Textures.h>
namespace dp
{
namespace rix
{
using namespace std;
using namespace math;
namespace util
{
TextureObjectDataSharedPtr TextureObjectData::create()
{
return( std::shared_ptr<TextureObjectData>( new TextureObjectData() ) );
}
TextureObjectData::TextureObjectData()
{
}
TextureObjectData::~TextureObjectData()
{
}
TextureObjectDataSharedPtr createTextureColored( const Vec2ui& size, const Vec4f& color )
{
TextureObjectDataSharedPtr texture = TextureObjectData::create();
texture->m_size = size;
unsigned int length = size[0] * size[1];
texture->m_data.resize(length);
for(unsigned int i = 0; i < length; i++)
{
texture->m_data[i] = color;
}
return texture;
}
TextureObjectDataSharedPtr createTextureCheckered(const Vec2ui& size, const Vec2ui& tileCount, const Vec4f& oddColor, const Vec4f& evenColor)
{
TextureObjectDataSharedPtr texture = TextureObjectData::create();
texture->m_size = size;
texture->m_data.resize(size[0] * size[1]);
for(unsigned int iy = 0; iy < size[1]; iy++)
{
unsigned iycheck = tileCount[1] * iy / size[1];
for(unsigned int ix = 0; ix < size[0]; ix++)
{
unsigned ixcheck = tileCount[0] * ix / size[0];
texture->m_data[ iy * size[1] + ix ] = (iycheck^ixcheck)&1 ? oddColor : evenColor;
}
}
return texture;
}
TextureObjectDataSharedPtr createTextureGradient(const Vec2ui& size, const Vec4f& bottomColor, const Vec4f& topLeftColor, const Vec4f& topRightColor)
{
TextureObjectDataSharedPtr texture = TextureObjectData::create();
texture->m_size = size;
texture->m_data.resize(size[0] * size[1]);
for(unsigned int iy = 0; iy < size[1]; iy++)
{
float weight0 = (float)iy / (size[1] - 1);
float sumWeight12 = 1.0f - weight0;
for(unsigned int ix = 0; ix < size[0]; ix++)
{
float weight1 = sumWeight12 * ix / (size[0] - 1);
float weight2 = sumWeight12 - weight1;
Vec4f color = weight0 * bottomColor + weight1 * topLeftColor + weight2 * topRightColor;
texture->m_data[ iy * size[1] + ix ] = color;
}
}
return texture;
}
TextureObjectDataSharedPtr convertHeightMapToNormalMap( const TextureObjectDataSharedPtr& heightMap
, float factor ) //Maximum apparent bump depth
{
TextureObjectDataSharedPtr normalMap = TextureObjectData::create();
unsigned int texWidth = heightMap->m_size[0];
unsigned int texHeight = heightMap->m_size[1];
normalMap->m_size = heightMap->m_size;
normalMap->m_data.resize(texWidth * texHeight);
//Texel lengths in texture space
Vec2f incr( 2.0f / texWidth, 2.0f / texHeight );
//Loop through all texels and get our tangents and binormals by taking the central differences
for(unsigned int iy = 0; iy < texHeight; iy++)
{
for(unsigned int ix = 0; ix < texWidth; ix++)
{
unsigned int curTexel = iy * texWidth + ix;
unsigned int nextTexelX = ix < texWidth - 1 ? curTexel + 1 : iy * texWidth;
unsigned int prevTexelX = ix > 0 ? curTexel - 1 : iy * texWidth + texWidth - 1;
unsigned int nextTexelY = iy < texHeight - 1 ? curTexel + texWidth : ix;
unsigned int prevTexelY = iy > 0 ? curTexel - texWidth : curTexel + (texHeight - 1) * texWidth;
Vec3f tangent( incr[0]
, 0.0f
, (heightMap->m_data[nextTexelX][0] - heightMap->m_data[prevTexelX][0]) * factor );
Vec3f binormal( 0.0f
, incr[1]
, (heightMap->m_data[nextTexelY][0] - heightMap->m_data[prevTexelY][0]) * factor );
Vec3f normal = tangent ^ binormal;
normalize(normal);
//clamp the normal to [0, 1]
normalMap->m_data[curTexel] = Vec4f(0.5f, 0.5f, 0.5f, 0.0f) + 0.5f * Vec4f(normal, 0.0f);
}
}
return normalMap;
}
TextureObjectDataSharedPtr createNoiseTexture( const math::Vec2ui& size, float frequencyX, float frequencyY )
{
TextureObjectDataSharedPtr texture = TextureObjectData::create();
unsigned int texWidth = size[0];
unsigned int texHeight = size[1];
texture->m_size = size;
texture->m_data.resize(size[0] * size[1]);
for(unsigned int iy = 0; iy < texHeight; iy++)
{
for(unsigned int ix = 0; ix < texWidth; ix++)
{
unsigned int curTexel = iy * texWidth + ix;
float intensity = 0.5f * ( dp::rix::util::SimplexNoise1234::noise( frequencyX * iy / texHeight - 1.0f, frequencyY * ix / texWidth - 1.0f ) + 1.0f );
texture->m_data[curTexel][0] = intensity;
texture->m_data[curTexel][1] = intensity;
texture->m_data[curTexel][2] = intensity;
texture->m_data[curTexel][3] = 1.0f;
}
}
return texture;
}
TextureObjectDataSharedPtr createPyramidNormalMap( const math::Vec2ui& size
, const math::Vec2ui& pyramidTiles
, float pyramidHeight ) //Depth of a pyramid in texel space
{
TextureObjectDataSharedPtr texture = TextureObjectData::create();
unsigned int texWidth = size[0];
unsigned int texHeight = size[1];
texture->m_size = size;
texture->m_data.resize(size[0] * size[1]);
//Texel lengths in texture space
Vec2f incr( 1.0f / texWidth, 1.0f / texHeight );
//Dimensions of one pyramid
unsigned int pyramidIX = texWidth / pyramidTiles[0];
unsigned int pyramidIY = texHeight / pyramidTiles[1];
//Calculate all four occurring normals of the pyramid ahead of time
Vec4f wNormalLeft = Vec4f( -pyramidHeight, 0.0f, 0.5f * incr[0] * pyramidIX, 0.0f);
Vec4f wNormalRight = Vec4f( pyramidHeight, 0.0f, 0.5f * incr[0] * pyramidIX, 0.0f);
Vec4f wNormalTop = Vec4f( 0.0f, pyramidHeight, 0.5f * incr[1] * pyramidIY, 0.0f);
Vec4f wNormalBottom = Vec4f( 0.0f, -pyramidHeight, 0.5f * incr[1] * pyramidIY, 0.0f);
//Normalize our normals
wNormalLeft.normalize();
wNormalRight.normalize();
wNormalTop.normalize();
wNormalBottom.normalize();
//Clamp our normals to [0, 1]
wNormalLeft = 0.5f*wNormalLeft + Vec4f(0.5f, 0.5f, 0.5f, 0.0f);
wNormalRight = 0.5f*wNormalRight + Vec4f(0.5f, 0.5f, 0.5f, 0.0f);
wNormalTop = 0.5f*wNormalTop + Vec4f(0.5f, 0.5f, 0.5f, 0.0f);
wNormalBottom = 0.5f*wNormalBottom + Vec4f(0.5f, 0.5f, 0.5f, 0.0f);
for(unsigned int iy = 0; iy < texHeight; iy++)
{
//Get our vertical texel position relative to the center of the current pyramid tile
int iyrel = iy % pyramidIY - pyramidIY / 2;
for(unsigned int ix = 0; ix < texWidth; ix++)
{
//Get our horizontal texel position relative to the center of the current pyramid tile
int ixrel = ix % pyramidIX - pyramidIX / 2;
unsigned int curTexel = iy * texWidth + ix;
//Assign the appropriate normal according to what face of the pyramid we're on
if( iyrel > abs(ixrel) )
{
texture->m_data[curTexel] = wNormalTop;
}
else if( iyrel > ixrel )
{
texture->m_data[curTexel] = wNormalLeft;
}
else if( iyrel > -ixrel )
{
texture->m_data[curTexel] = wNormalRight;
}
else
{
texture->m_data[curTexel] = wNormalBottom;
}
}
}
return texture;
}
} // namespace generator
} // namespace util
} // namespace dp
| 40.698413
| 161
| 0.579076
|
asuessenbach
|
6e1bfe314c1a6b3c6c098d2846ab7c1476252146
| 236
|
hpp
|
C++
|
wfc/logger.hpp
|
mambaru/wfc
|
170bf87302487c0cedc40b47c84447a765894774
|
[
"MIT"
] | 1
|
2018-10-18T10:15:53.000Z
|
2018-10-18T10:15:53.000Z
|
wfc/logger.hpp
|
mambaru/wfc
|
170bf87302487c0cedc40b47c84447a765894774
|
[
"MIT"
] | 7
|
2019-12-04T23:36:03.000Z
|
2021-04-21T12:37:07.000Z
|
wfc/logger.hpp
|
mambaru/wfc
|
170bf87302487c0cedc40b47c84447a765894774
|
[
"MIT"
] | null | null | null |
//
// Author: Vladimir Migashko <migashko@gmail.com>, (C) 2013-2015
//
// Copyright: See COPYING file that comes with this distribution
//
#pragma once
#include <wfc/logger/logger.hpp>
namespace wfc
{
using ::wlog::only_for_log;
}
| 15.733333
| 64
| 0.707627
|
mambaru
|
6e1e22d26093e587114dd69b7c5c796891fac952
| 3,352
|
cpp
|
C++
|
hangman.cpp
|
AfaanBilal/hangman
|
f1b50e48039a26f25d2046dd8f209b3117e58c35
|
[
"MIT"
] | 1
|
2020-01-04T19:38:26.000Z
|
2020-01-04T19:38:26.000Z
|
hangman.cpp
|
AfaanBilal/hangman
|
f1b50e48039a26f25d2046dd8f209b3117e58c35
|
[
"MIT"
] | null | null | null |
hangman.cpp
|
AfaanBilal/hangman
|
f1b50e48039a26f25d2046dd8f209b3117e58c35
|
[
"MIT"
] | null | null | null |
/*
Hangman
(c) Afaan Bilal
Play hangman!
*/
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <fstream>
using namespace std;
const int numWords = 50;
string wordlist[numWords];
string input;
size_t f;
int sel = 0;
int maxTries = 10;
int tries = 0;
void cls();
void display();
bool checkIfWon();
int main()
{
ifstream file("hangman.txt");
if(file.is_open())
{
for(int i = 0; i < numWords; ++i)
{
file >> wordlist[i];
}
}
srand(time(NULL));
sel = rand() % numWords;
char c = ' ';
display();
cout << endl << "\tEnter an alphabet: ";
c = _getch();
while (c != '.')
{
c = toupper(c);
f = input.find(c);
if (f == string::npos)
{
input.push_back(c);
if (wordlist[sel].find(c) == string::npos)
{
tries++;
if (tries >= maxTries)
{
display();
cout << endl << "\t\tSorry! You have lost!" << endl << endl;
cout << "\t\tThe word was " << wordlist[sel] << endl << endl;
break;
}
}
display();
if (checkIfWon())
{
cout << endl << "\t\tCongratulations! You have won!" << endl << endl;
break;
}
}
else
{
cout << endl << "\tAlphabet already entered." << endl;
}
cout << endl << "\tEnter an alphabet: ";
c = _getch();
}
}
void cls()
{
system("@cls || clear");
}
void drawHangman()
{
cout << endl;
switch (tries)
{
case 10:
cout << "\t\t YOU KILLED ME!" << endl;
cout << "\t\t\t _________ " << endl;
case 9: cout << "\t\t\t | |" << endl;
case 8: cout << "\t\t\t --- |" << endl;
case 7: cout << "\t\t\t | | |" << endl;
case 6: cout << "\t\t\t --- |" << endl;
case 5: cout << "\t\t\t ----|---- |" << endl;
case 4: cout << "\t\t\t | |" << endl;
case 3: cout << "\t\t\t | |" << endl;
case 2: cout << "\t\t\t --- |" << endl;
case 1: cout << "\t\t\t / \\ |" << endl;
cout << "\t\t\t |" << endl;
cout << "\t\t\t____________|" << endl;
}
cout << endl << endl;
}
void display()
{
cls();
cout << endl << "\t\t\t" << "HANGMAN" << endl << endl;
cout << "\thttps://github.com/AfaanBilal/hangman" << endl << endl;
drawHangman();
cout << "\tPress '.' to exit." << endl;
cout << "\tTries left: " << (maxTries - tries) << endl << endl;
cout << "\t\t ";
for (int i = 0; i < wordlist[sel].length(); i++)
{
f = input.find(wordlist[sel][i]);
if (f == string::npos)
cout << "_" << " ";
else
cout << wordlist[sel][i] << " ";
}
cout << endl;
}
bool checkIfWon()
{
for (int i = 0; i < wordlist[sel].length(); i++)
{
if (input.find(wordlist[sel][i]) == string::npos)
return false;
}
return true;
}
| 22.346667
| 85
| 0.406026
|
AfaanBilal
|
6e24d37d9c5ac8ee13ad5e9a1b113c7fd9b0eedb
| 8,285
|
hxx
|
C++
|
libbuild2/script/parser.hxx
|
build2/build2
|
af662849b756ef2ff0f3d5148a6771acab78fd80
|
[
"MIT"
] | 422
|
2018-05-30T12:00:00.000Z
|
2022-03-29T07:29:56.000Z
|
libbuild2/script/parser.hxx
|
build2/build2
|
af662849b756ef2ff0f3d5148a6771acab78fd80
|
[
"MIT"
] | 183
|
2018-07-02T20:38:30.000Z
|
2022-03-31T09:54:35.000Z
|
libbuild2/script/parser.hxx
|
build2/build2
|
af662849b756ef2ff0f3d5148a6771acab78fd80
|
[
"MIT"
] | 14
|
2019-01-09T12:34:02.000Z
|
2021-03-16T09:10:53.000Z
|
// file : libbuild2/script/parser.hxx -*- C++ -*-
// license : MIT; see accompanying LICENSE file
#ifndef LIBBUILD2_SCRIPT_PARSER_HXX
#define LIBBUILD2_SCRIPT_PARSER_HXX
#include <libbuild2/types.hxx>
#include <libbuild2/forward.hxx>
#include <libbuild2/utility.hxx>
#include <libbuild2/parser.hxx>
#include <libbuild2/diagnostics.hxx>
#include <libbuild2/script/token.hxx>
#include <libbuild2/script/lexer.hxx> // redirect_aliases
#include <libbuild2/script/script.hxx>
namespace build2
{
namespace script
{
class lexer;
struct lexer_mode;
class parser: protected build2::parser
{
public:
parser (context& c, bool relex): build2::parser (c), relex_ (relex) {}
// Helpers.
//
// Parse attribute string and perform attribute-guided assignment.
// Issue diagnostics and throw failed in case of an error.
//
void
apply_value_attributes (const variable*, // Optional.
value& lhs,
value&& rhs,
const string& attributes,
token_type assign_kind,
const path_name&); // For diagnostics.
using build2::parser::apply_value_attributes;
// Commonly used parsing functions. Issue diagnostics and throw failed
// in case of an error.
//
// Usually (but not always) parse functions receive the token/type
// from which it should start consuming and in return the token/type
// should contain the first token that has not been consumed.
//
// Functions that are called parse_*() rather than pre_parse_*() can be
// used for both stages.
//
protected:
value
parse_variable_line (token&, token_type&);
// Ordered sequence of here-document redirects that we can expect to
// see after the command line.
//
struct here_redirect
{
size_t expr; // Index in command_expr.
size_t pipe; // Index in command_pipe.
int fd; // Redirect fd (0 - in, 1 - out, 2 - err).
};
struct here_doc
{
// Redirects that share here_doc. Most of the time we will have no
// more than 2 (2 - for the roundtrip cases). Doesn't refer overridden
// redirects and thus can be empty.
//
small_vector<here_redirect, 2> redirects;
string end;
bool literal; // Literal (single-quote).
string modifiers;
// Regex introducer ('\0' if not a regex, so can be used as bool).
//
char regex;
// Regex global flags. Meaningful if regex != '\0'.
//
string regex_flags;
};
using here_docs = vector<here_doc>;
pair<command_expr, here_docs>
parse_command_expr (token&, token_type&, const redirect_aliases&);
command_exit
parse_command_exit (token&, token_type&);
void
parse_here_documents (token&, token_type&,
pair<command_expr, here_docs>&);
struct parsed_doc
{
union
{
string str; // Here-document literal.
regex_lines regex; // Here-document regex.
};
bool re; // True if regex.
uint64_t end_line; // Here-document end marker location.
uint64_t end_column;
parsed_doc (string, uint64_t line, uint64_t column);
parsed_doc (regex_lines&&, uint64_t line, uint64_t column);
parsed_doc (parsed_doc&&); // Note: move constuctible-only type.
~parsed_doc ();
};
parsed_doc
parse_here_document (token&, token_type&,
const string&,
const string& mode,
char re_intro); // '\0' if not a regex.
// Start pre-parsing a script line returning its type, detected based on
// the first two tokens. Use the specified lexer mode to peek the second
// token.
//
line_type
pre_parse_line_start (token&, token_type&, lexer_mode);
// Parse the env pseudo-builtin arguments up to the program name. Return
// the program execution timeout, CWD, the list of the variables that
// should be unset ("name") and/or set ("name=value") in the command
// environment, and the token/type that starts the program name. Note
// that the variable unsets come first, if present.
//
struct parsed_env
{
optional<duration> timeout;
optional<dir_path> cwd;
environment_vars variables;
};
parsed_env
parse_env_builtin (token&, token_type&);
// Execute.
//
protected:
// Return false if the execution of the script should be terminated with
// the success status (e.g., as a result of encountering the exit
// builtin). For unsuccessful termination the failed exception is thrown.
//
using exec_set_function = void (const variable&,
token&, token_type&,
const location&);
using exec_cmd_function = void (token&, token_type&,
size_t li,
bool single,
const location&);
using exec_if_function = bool (token&, token_type&,
size_t li,
const location&);
// If a parser implementation doesn't pre-enter variables into a pool
// during the pre-parsing phase, then they are entered during the
// execution phase and so the variable pool must be provided. Note that
// in this case the variable pool insertions are not MT-safe.
//
bool
exec_lines (lines::const_iterator b, lines::const_iterator e,
const function<exec_set_function>&,
const function<exec_cmd_function>&,
const function<exec_if_function>&,
size_t& li,
variable_pool* = nullptr);
// Customization hooks.
//
protected:
// Parse the command's leading name chunk. The argument first is true if
// this is the first command in the line. The argument env is true if
// the command is executed via the env pseudo-builtin.
//
// During the execution phase try to parse and translate the leading
// names into the process path and return nullopt if choose not to do
// so, leaving it to the parser to handle. Also return in the last
// two arguments uninterpreted names, if any.
//
// The default implementation always returns nullopt. The derived parser
// can provide an override that can, for example, handle process path
// values, executable targets, etc.
//
// Note that normally it makes sense to leave simple unpaired names for
// the parser to handle, unless there is a good reason not to (e.g.,
// it's a special builtin or some such). Such names may contain
// something that requires re-lexing, for example `foo|bar`, which won't
// be easy to translate but which are handled by the parser.
//
// During the pre-parsing phase the returned process path and names
// (that must still be parsed) are discarded. The main purpose of the
// call is to allow implementations to perform static script analysis,
// recognize and execute certain directives, or some such.
//
virtual optional<process_path>
parse_program (token&, token_type&,
bool first, bool env,
names&, parse_names_result&);
// Set lexer pointers for both the current and the base classes.
//
protected:
void
set_lexer (lexer*);
// Number of quoted tokens since last reset. Note that this includes the
// peeked token, if any.
//
protected:
size_t
quoted () const;
void
reset_quoted (token& current);
size_t replay_quoted_;
protected:
bool relex_;
lexer* lexer_ = nullptr;
};
}
}
#endif // LIBBUILD2_SCRIPT_PARSER_HXX
| 34.665272
| 79
| 0.595413
|
build2
|
6e25735d9d1090bac9cc52f7c1ee1d1619a595ac
| 834
|
hpp
|
C++
|
src/FeatureExtraction.hpp
|
Trojahn/BackShotCoSS
|
cf0b996720612ab4bb1b579701f50e8cdd14f2c3
|
[
"MIT"
] | 1
|
2021-04-01T23:00:10.000Z
|
2021-04-01T23:00:10.000Z
|
src/FeatureExtraction.hpp
|
Trojahn/BackShotCoSS
|
cf0b996720612ab4bb1b579701f50e8cdd14f2c3
|
[
"MIT"
] | null | null | null |
src/FeatureExtraction.hpp
|
Trojahn/BackShotCoSS
|
cf0b996720612ab4bb1b579701f50e8cdd14f2c3
|
[
"MIT"
] | 2
|
2016-08-27T17:29:27.000Z
|
2018-11-05T02:10:45.000Z
|
#ifndef FEATUREEXTRACTION_H
#define FEATUREEXTRACTION_H
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <iomanip>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <cmath>
#include <thread>
#include <mutex>
#include "Utils.hpp"
#include "Shot.hpp"
#include "Parameters.hpp"
using namespace std;
class FeatureExtraction {
private:
void processOpticalFlow(vector<Mat> frames, pair<int,double> &opticalFlow);
vector<pair<int,int>> keyframes;
vector<pair<int,int>> shots;
string videoPath;
public:
FeatureExtraction(vector< pair<int,int> > keyframes, vector<pair<int,int>> shots, string videoPath);
vector<Shot> extractFeatures(bool enableOpticalFlow);
};
#endif
| 21.947368
| 102
| 0.747002
|
Trojahn
|
6e294a0debd6730c77212cc53db0ebf86335b103
| 2,178
|
hpp
|
C++
|
src/include/randest/ks_test.hpp
|
renegat96/randest
|
29449ff61398526cc1b88a1f003ed8fddef14693
|
[
"MIT"
] | null | null | null |
src/include/randest/ks_test.hpp
|
renegat96/randest
|
29449ff61398526cc1b88a1f003ed8fddef14693
|
[
"MIT"
] | null | null | null |
src/include/randest/ks_test.hpp
|
renegat96/randest
|
29449ff61398526cc1b88a1f003ed8fddef14693
|
[
"MIT"
] | null | null | null |
/*
* Kolmogorov-Smirnov goodness-of-fit test.
* H_0 the data follow a specified distribution
* H_a the data do not follow the specified distribution
* D = max (F(Y_i) -
* */
#pragma once
#include <functional>
#include <randest/test.hpp>
#include <randest/data_provider.hpp>
#include <randest/data_sort.hpp>
namespace randest {
template<typename OutputT = long double>
struct NormalDistribution {
long double operator()(const OutputT &x) {
return static_cast<long double>(x);
}
};
template<typename OutputT = long double,
typename Compare = std::less<OutputT>,
typename CDF = std::function<long double(OutputT)>>
class ks_test : public test {
private:
bool ran;
randest::data_provider<OutputT> *data;
long double ks_statistic;
/*
ks_test();
*/
ks_test();
CDF cdf;
public:
/*
ks_test(data_provider<OutputT> *data, CDF cdf = NormalDistribution<OutputT>());
void run();
long double getPerformance();
*/
ks_test(data_provider<OutputT> *data, CDF cdf = NormalDistribution<OutputT>()) {
this->data = data;
this->ks_statistic = 0;
this->cdf = cdf;
}
void run() {
::randest::data_sort<OutputT> sorted = data_sort<OutputT, Compare>(data);
ks_statistic = 0;
size_t size = sorted.size();
for (size_t i = 0; i < size; ++i) {
long double fx = static_cast<long double>(sorted.count_smaller(sorted[i])) / sorted.size();
long double observation = cdf(sorted[i]);
long double candidate = fabsl(observation - fx);
//ks_statistic = std::max(ks_statistic, candidate);
if (ks_statistic < candidate) {
ks_statistic = candidate;
}
}
ran = true;
}
long double getPerformance() {
if (!this->ran) throw "trying to get the result from a test that has not been ran";
return ks_statistic;
}
};
}
| 27.923077
| 107
| 0.556933
|
renegat96
|
6e2c5d22fbd5e41daabc748c5eb43e2e1c6679a6
| 2,310
|
cpp
|
C++
|
backends/graphs/graphs.cpp
|
srivani/p4c
|
6891448af6834c0798350f4b2a7c54ad3532148e
|
[
"Apache-2.0"
] | 487
|
2016-12-22T03:33:27.000Z
|
2022-03-29T06:36:45.000Z
|
backends/graphs/graphs.cpp
|
srivani/p4c
|
6891448af6834c0798350f4b2a7c54ad3532148e
|
[
"Apache-2.0"
] | 2,114
|
2016-12-18T11:36:27.000Z
|
2022-03-31T22:33:23.000Z
|
backends/graphs/graphs.cpp
|
srivani/p4c
|
6891448af6834c0798350f4b2a7c54ad3532148e
|
[
"Apache-2.0"
] | 456
|
2016-12-20T14:01:11.000Z
|
2022-03-30T19:26:05.000Z
|
/*
Copyright 2013-present Barefoot Networks, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "lib/log.h"
#include "lib/error.h"
#include "lib/exceptions.h"
#include "lib/gc.h"
#include "lib/crash.h"
#include "lib/nullstream.h"
#include "graphs.h"
namespace graphs {
Graphs::vertex_t Graphs::add_vertex(const cstring &name, VertexType type) {
auto v = boost::add_vertex(*g);
boost::put(&Vertex::name, *g, v, name);
boost::put(&Vertex::type, *g, v, type);
return g->local_to_global(v);
}
void Graphs::add_edge(const vertex_t &from, const vertex_t &to, const cstring &name) {
auto ep = boost::add_edge(from, to, g->root());
boost::put(boost::edge_name, g->root(), ep.first, name);
}
boost::optional<Graphs::vertex_t> Graphs::merge_other_statements_into_vertex() {
if (statementsStack.empty()) return boost::none;
std::stringstream sstream;
if (statementsStack.size() == 1) {
statementsStack[0]->dbprint(sstream);
} else if (statementsStack.size() == 2) {
statementsStack[0]->dbprint(sstream);
sstream << "\n";
statementsStack[1]->dbprint(sstream);
} else {
statementsStack[0]->dbprint(sstream);
sstream << "\n...\n";
statementsStack.back()->dbprint(sstream);
}
auto v = add_vertex(cstring(sstream), VertexType::STATEMENTS);
for (auto parent : parents)
add_edge(parent.first, v, parent.second->label());
parents = {{v, new EdgeUnconditional()}};
statementsStack.clear();
return v;
}
Graphs::vertex_t Graphs::add_and_connect_vertex(const cstring &name, VertexType type) {
merge_other_statements_into_vertex();
auto v = add_vertex(name, type);
for (auto parent : parents)
add_edge(parent.first, v, parent.second->label());
return v;
}
} // namespace graphs
| 32.535211
| 87
| 0.687446
|
srivani
|
6e305f319f9aba9b5e4c1ccdb60f56d5fe3f74bc
| 1,392
|
cpp
|
C++
|
Leetcode Daily Challenge/May-2021/27. Maximum Product of Word Lengths.cpp
|
Akshad7829/DataStructures-Algorithms
|
439822c6a374672d1734e2389d3fce581a35007d
|
[
"MIT"
] | 5
|
2021-08-10T18:47:49.000Z
|
2021-08-21T15:42:58.000Z
|
Leetcode Daily Challenge/May-2021/27. Maximum Product of Word Lengths.cpp
|
Akshad7829/DataStructures-Algorithms
|
439822c6a374672d1734e2389d3fce581a35007d
|
[
"MIT"
] | 2
|
2022-02-25T13:36:46.000Z
|
2022-02-25T14:06:44.000Z
|
Leetcode Daily Challenge/May-2021/27. Maximum Product of Word Lengths.cpp
|
Akshad7829/DataStructures-Algorithms
|
439822c6a374672d1734e2389d3fce581a35007d
|
[
"MIT"
] | 1
|
2021-08-11T06:36:42.000Z
|
2021-08-11T06:36:42.000Z
|
/*
Maximum Product of Word Lengths
====================================
Given a string array words, return the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. If no such two words exist, return 0.
Example 1:
Input: words = ["abcw","baz","foo","bar","xtfn","abcdef"]
Output: 16
Explanation: The two words can be "abcw", "xtfn".
Example 2:
Input: words = ["a","ab","abc","d","cd","bcd","abcd"]
Output: 4
Explanation: The two words can be "ab", "cd".
Example 3:
Input: words = ["a","aa","aaa","aaaa"]
Output: 0
Explanation: No such pair of words.
Constraints:
2 <= words.length <= 1000
1 <= words[i].length <= 1000
words[i] consists only of lowercase English letters.
*/
class Solution
{
public:
int maxProduct(vector<string> &words)
{
vector<int> masks;
for (auto &i : words)
{
int mask = 0;
for (auto &e : i)
// agr phele se bit set hai toh mt krdo vapas, galat hojayega
if (!(mask & (1 << (e - 'a'))))
mask += (1 << (e - 'a'));
masks.push_back(mask);
cout << mask << " ";
}
int ans = 0;
for (int i = 0; i < words.size(); ++i)
{
for (int j = i + 1; j < words.size(); ++j)
{
if ((masks[i] & masks[j]) == 0)
{
ans = max(ans, (int)(words[i].size() * words[j].size()));
}
}
}
return ans;
}
};
| 23.2
| 176
| 0.538793
|
Akshad7829
|
6e36a0342a3c3168b494244b86008946b851782f
| 4,329
|
cpp
|
C++
|
src/GC/Circuit.cpp
|
GPikra/python-smpc-wrapper-importer
|
43a8945e63f7c8996da699dae0a9f9240084214f
|
[
"BSD-2-Clause"
] | 3
|
2019-08-10T10:03:15.000Z
|
2020-05-20T03:53:40.000Z
|
src/GC/Circuit.cpp
|
GPikra/python-smpc-wrapper-importer
|
43a8945e63f7c8996da699dae0a9f9240084214f
|
[
"BSD-2-Clause"
] | 6
|
2019-06-10T13:20:34.000Z
|
2019-07-10T17:28:52.000Z
|
src/GC/Circuit.cpp
|
athenarc/SCALE-MAMBA
|
18fa886d820bec7e441448357b8f09e2be0e7c9e
|
[
"BSD-2-Clause"
] | null | null | null |
/*
Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom.
Copyright (c) 2018, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium.
All rights reserved
*/
#include "Circuit.h"
istream &operator>>(istream &s, Circuit &C)
{
unsigned int nG, te;
s >> nG >> C.nWires;
C.num_AND= 0;
C.GateT.resize(nG);
C.GateI.resize(nG, vector<unsigned int>(2));
C.GateO.resize(nG);
s >> te;
C.numI.resize(te);
for (unsigned int i= 0; i < C.numI.size(); i++)
{
s >> C.numI[i];
}
s >> te;
C.numO.resize(te);
for (unsigned int i= 0; i < C.numO.size(); i++)
{
s >> C.numO[i];
}
unsigned int in, out;
string ss;
for (unsigned int i= 0; i < nG; i++)
{
s >> in >> out;
if (in > 2 || out > 1)
{
throw circuit_error();
}
for (unsigned int j= 0; j < in; j++)
{
s >> C.GateI[i][j];
}
s >> C.GateO[i];
s >> ss;
if (ss.compare("AND") == 0)
{
C.GateT[i]= AND;
C.num_AND++;
}
else if (ss.compare("XOR") == 0)
{
C.GateT[i]= XOR;
}
else if (ss.compare("INV") == 0)
{
C.GateT[i]= INV;
}
else
{
throw circuit_error();
}
if (C.GateT[i] == INV && in == 2)
{
throw circuit_error();
}
if (C.GateT[i] != INV && in == 1)
{
throw circuit_error();
}
}
// Define map between AND gates and the actual gates
C.map.resize(C.num_AND);
C.imap.resize(nG);
// Set stupid default value for imap, to be caught in access function
for (unsigned int i= 0; i < nG; i++)
{
C.imap[i]= 2 * nG;
}
unsigned int cnt= 0;
for (unsigned int i= 0; i < nG; i++)
{
if (C.GateT[i] == AND)
{
C.map[cnt]= i;
C.imap[i]= cnt;
cnt++;
}
}
return s;
}
ostream &operator<<(ostream &s, const Circuit &C)
{
s << C.GateT.size() << " " << C.nWires << endl;
s << C.numI.size() << " ";
for (unsigned int i= 0; i < C.numI.size(); i++)
{
s << C.numI[i] << " ";
}
s << endl;
s << C.numO.size() << " ";
for (unsigned int i= 0; i < C.numO.size(); i++)
{
s << C.numO[i] << " ";
}
s << endl
<< endl;
for (unsigned int i= 0; i < C.GateT.size(); i++)
{
if (C.GateT[i] == INV)
{
s << "1 1 " << C.GateI[i][0] << " " << C.GateO[i] << " INV\n";
}
else
{
s << "2 1 " << C.GateI[i][0] << " " << C.GateI[i][1] << " ";
s << C.GateO[i] << " ";
if (C.GateT[i] == AND)
{
s << "AND\n";
}
else
{
s << "XOR\n";
}
}
}
s << endl;
return s;
}
void Circuit::evaluate(const vector<vector<int>> &inputs,
vector<vector<int>> &outputs) const
{
vector<int> W(nWires);
for (unsigned int i= 0; i < nWires; i++)
{
W[i]= -1;
}
// Load inputs
unsigned int cnt= 0;
for (unsigned int i= 0; i < numI.size(); i++)
{
for (unsigned int j= 0; j < numI[i]; j++)
{
W[cnt]= inputs[i][j];
cnt++;
}
}
// Evaluate the circuit
for (unsigned int i= 0; i < GateT.size(); i++)
{ // First check if ordering is broken
if (W[GateI[i][0]] < 0)
{
throw circuit_error();
}
if (GateT[i] != INV && W[GateI[i][1]] < 0)
{
throw circuit_error();
}
// Now evaluate the gate
if (GateT[i] == AND)
{
W[GateO[i]]= W[GateI[i][0]] & W[GateI[i][1]];
}
else if (GateT[i] == XOR)
{
W[GateO[i]]= W[GateI[i][0]] ^ W[GateI[i][1]];
}
else
{
W[GateO[i]]= 1 - W[GateI[i][0]];
}
}
// Now produce the output
outputs.resize(numO.size());
cnt= nWires;
for (unsigned int i= 0; i < numO.size(); i++)
{
cnt-= numO[i];
}
for (unsigned int i= 0; i < numO.size(); i++)
{
outputs[i].resize(numO[i]);
for (unsigned int j= 0; j < numO[i]; j++)
{
outputs[i][j]= W[cnt];
cnt++;
}
}
}
| 21.325123
| 110
| 0.429891
|
GPikra
|
6e38645a4bf8350cb46779807f81f4526a749086
| 15,415
|
cpp
|
C++
|
src/core/tunnel/TunnelPool.cpp
|
moneromooo-monero/kovri
|
7532037cd590617c27474112080e4bbc52faf586
|
[
"BSD-3-Clause"
] | 2
|
2017-10-13T09:22:20.000Z
|
2018-02-13T16:32:02.000Z
|
src/core/tunnel/TunnelPool.cpp
|
Menutra/kovri
|
7532037cd590617c27474112080e4bbc52faf586
|
[
"BSD-3-Clause"
] | null | null | null |
src/core/tunnel/TunnelPool.cpp
|
Menutra/kovri
|
7532037cd590617c27474112080e4bbc52faf586
|
[
"BSD-3-Clause"
] | 2
|
2017-10-15T08:21:55.000Z
|
2018-11-29T08:40:06.000Z
|
/**
* Copyright (c) 2013-2016, The Kovri I2P Router Project
*
* 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.
*
* 3. Neither the name of the copyright holder 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 HOLDER 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.
*
* Parts of the project are originally copyright (c) 2013-2015 The PurpleI2P Project
*/
#include "TunnelPool.h"
#include <algorithm>
#include <vector>
#include "Garlic.h"
#include "NetworkDatabase.h"
#include "Tunnel.h"
#include "crypto/Rand.h"
#include "transport/Transports.h"
#include "util/I2PEndian.h"
#include "util/Timestamp.h"
#include "util/Log.h"
namespace i2p {
namespace tunnel {
TunnelPool::TunnelPool(
i2p::garlic::GarlicDestination* localDestination,
int numInboundHops,
int numOutboundHops,
int numInboundTunnels,
int numOutboundTunnels)
: m_LocalDestination(localDestination),
m_NumInboundHops(numInboundHops),
m_NumOutboundHops(numOutboundHops),
m_NumInboundTunnels(numInboundTunnels),
m_NumOutboundTunnels(numOutboundTunnels),
m_IsActive(true) {}
TunnelPool::~TunnelPool() {
DetachTunnels();
}
void TunnelPool::SetExplicitPeers(
std::shared_ptr<std::vector<i2p::data::IdentHash> > explicitPeers) {
m_ExplicitPeers = explicitPeers;
if (m_ExplicitPeers) {
int size = m_ExplicitPeers->size();
if (m_NumInboundHops > size) {
m_NumInboundHops = size;
LogPrint(eLogInfo,
"TunnelPool: inbound tunnel length has been adjusted to ",
size, " for explicit peers");
}
if (m_NumOutboundHops > size) {
m_NumOutboundHops = size;
LogPrint(eLogInfo,
"TunnelPool: outbound tunnel length has been adjusted to ",
size, " for explicit peers");
}
m_NumInboundTunnels = 1;
m_NumOutboundTunnels = 1;
}
}
void TunnelPool::DetachTunnels() {
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
for (auto it : m_InboundTunnels)
it->SetTunnelPool(nullptr);
m_InboundTunnels.clear();
}
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
for (auto it : m_OutboundTunnels)
it->SetTunnelPool(nullptr);
m_OutboundTunnels.clear();
}
m_Tests.clear();
}
void TunnelPool::TunnelCreated(
std::shared_ptr<InboundTunnel> createdTunnel) {
if (!m_IsActive)
return;
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
m_InboundTunnels.insert(createdTunnel);
}
if (m_LocalDestination)
m_LocalDestination->SetLeaseSetUpdated();
}
void TunnelPool::TunnelExpired(
std::shared_ptr<InboundTunnel> expiredTunnel) {
if (expiredTunnel) {
expiredTunnel->SetTunnelPool(nullptr);
for (auto it : m_Tests)
if (it.second.second == expiredTunnel)
it.second.second = nullptr;
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
m_InboundTunnels.erase(expiredTunnel);
}
}
void TunnelPool::TunnelCreated(
std::shared_ptr<OutboundTunnel> createdTunnel) {
if (!m_IsActive)
return;
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
m_OutboundTunnels.insert(createdTunnel);
}
// CreatePairedInboundTunnel (createdTunnel);
// TODO(unassigned): ^ ???
}
void TunnelPool::TunnelExpired(
std::shared_ptr<OutboundTunnel> expiredTunnel) {
if (expiredTunnel) {
expiredTunnel->SetTunnelPool(nullptr);
for (auto it : m_Tests)
if (it.second.first == expiredTunnel)
it.second.first = nullptr;
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
m_OutboundTunnels.erase(expiredTunnel);
}
}
std::vector<std::shared_ptr<InboundTunnel> > TunnelPool::GetInboundTunnels(
int num) const {
std::vector<std::shared_ptr<InboundTunnel> > v;
int i = 0;
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
for (auto it : m_InboundTunnels) {
if (i >= num) break;
if (it->IsEstablished()) {
v.push_back(it);
i++;
}
}
return v;
}
std::shared_ptr<OutboundTunnel> TunnelPool::GetNextOutboundTunnel(
std::shared_ptr<OutboundTunnel> excluded) const {
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
return GetNextTunnel(m_OutboundTunnels, excluded);
}
std::shared_ptr<InboundTunnel> TunnelPool::GetNextInboundTunnel(
std::shared_ptr<InboundTunnel> excluded) const {
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
return GetNextTunnel(m_InboundTunnels, excluded);
}
template<class TTunnels>
typename TTunnels::value_type TunnelPool::GetNextTunnel(
TTunnels& tunnels,
typename TTunnels::value_type excluded) const {
if (tunnels.empty ())
return nullptr;
uint32_t ind = i2p::crypto::RandInRange<uint32_t>(0, tunnels.size() / 2);
uint32_t i = 0;
typename TTunnels::value_type tunnel = nullptr;
for (auto it : tunnels) {
if (it->IsEstablished() && it != excluded) {
tunnel = it;
i++;
}
if (i > ind && tunnel)
break;
}
if (!tunnel && excluded && excluded->IsEstablished())
tunnel = excluded;
return tunnel;
}
std::shared_ptr<OutboundTunnel> TunnelPool::GetNewOutboundTunnel(
std::shared_ptr<OutboundTunnel> old) const {
if (old && old->IsEstablished())
return old;
std::shared_ptr<OutboundTunnel> tunnel;
if (old) {
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
for (auto it : m_OutboundTunnels)
if (it->IsEstablished() &&
old->GetEndpointRouter()->GetIdentHash() ==
it->GetEndpointRouter()->GetIdentHash()) {
tunnel = it;
break;
}
}
if (!tunnel)
tunnel = GetNextOutboundTunnel();
return tunnel;
}
void TunnelPool::CreateTunnels() {
int num = 0;
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
for (auto it : m_InboundTunnels)
if (it->IsEstablished())
num++;
}
for (int i = num; i < m_NumInboundTunnels; i++)
CreateInboundTunnel();
num = 0;
{
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
for (auto it : m_OutboundTunnels)
if (it->IsEstablished())
num++;
}
for (int i = num; i < m_NumOutboundTunnels; i++)
CreateOutboundTunnel();
}
void TunnelPool::TestTunnels() {
for (auto it : m_Tests) {
LogPrint(eLogWarn,
"TunnelPool: tunnel test ", static_cast<int>(it.first), " failed");
// if test failed again with another tunnel we consider it failed
if (it.second.first) {
if (it.second.first->GetState() == e_TunnelStateTestFailed) {
it.second.first->SetState(e_TunnelStateFailed);
std::unique_lock<std::mutex> l(m_OutboundTunnelsMutex);
m_OutboundTunnels.erase(it.second.first);
} else {
it.second.first->SetState(e_TunnelStateTestFailed);
}
}
if (it.second.second) {
if (it.second.second->GetState() == e_TunnelStateTestFailed) {
it.second.second->SetState(e_TunnelStateFailed);
{
std::unique_lock<std::mutex> l(m_InboundTunnelsMutex);
m_InboundTunnels.erase(it.second.second);
}
if (m_LocalDestination)
m_LocalDestination->SetLeaseSetUpdated();
} else {
it.second.second->SetState(e_TunnelStateTestFailed);
}
}
}
m_Tests.clear();
// new tests
auto it1 = m_OutboundTunnels.begin();
auto it2 = m_InboundTunnels.begin();
while (it1 != m_OutboundTunnels.end() && it2 != m_InboundTunnels.end()) {
bool failed = false;
if ((*it1)->IsFailed()) {
failed = true;
it1++;
}
if ((*it2)->IsFailed()) {
failed = true;
it2++;
}
if (!failed) {
uint32_t msgID = i2p::crypto::Rand<uint32_t>();
m_Tests[msgID] = std::make_pair(*it1, *it2);
(*it1)->SendTunnelDataMsg(
(*it2)->GetNextIdentHash(),
(*it2)->GetNextTunnelID(),
CreateDeliveryStatusMsg(msgID));
it1++;
it2++;
}
}
}
void TunnelPool::ProcessGarlicMessage(
std::shared_ptr<I2NPMessage> msg) {
if (m_LocalDestination)
m_LocalDestination->ProcessGarlicMessage(msg);
else
LogPrint(eLogWarn,
"TunnelPool: local destination doesn't exist, dropped");
}
void TunnelPool::ProcessDeliveryStatus(
std::shared_ptr<I2NPMessage> msg) {
const uint8_t* buf = msg->GetPayload();
uint32_t msgID = bufbe32toh(buf);
buf += 4;
uint64_t timestamp = bufbe64toh(buf);
auto it = m_Tests.find(msgID);
if (it != m_Tests.end()) {
// restore from test failed state if any
if (it->second.first->GetState() == e_TunnelStateTestFailed)
it->second.first->SetState(e_TunnelStateEstablished);
if (it->second.second->GetState() == e_TunnelStateTestFailed)
it->second.second->SetState(e_TunnelStateEstablished);
LogPrint(eLogInfo,
"TunnelPool: tunnel test ", it->first,
" successful: ", i2p::util::GetMillisecondsSinceEpoch() - timestamp,
" milliseconds");
m_Tests.erase(it);
} else {
if (m_LocalDestination)
m_LocalDestination->ProcessDeliveryStatusMessage(msg);
else
LogPrint(eLogWarn, "TunnelPool: local destination doesn't exist, dropped");
}
}
std::shared_ptr<const i2p::data::RouterInfo> TunnelPool::SelectNextHop(
std::shared_ptr<const i2p::data::RouterInfo> prevHop) const {
// TODO(unassigned): implement it better
bool isExploratory = (m_LocalDestination == &i2p::context);
auto hop = isExploratory ?
i2p::data::netdb.GetRandomRouter(prevHop) :
i2p::data::netdb.GetHighBandwidthRandomRouter(prevHop);
if (!hop || hop->GetProfile ()->IsBad())
hop = i2p::data::netdb.GetRandomRouter();
return hop;
}
bool TunnelPool::SelectPeers(
std::vector<std::shared_ptr<const i2p::data::RouterInfo> >& hops,
bool isInbound) {
if (m_ExplicitPeers)
return SelectExplicitPeers(hops, isInbound);
auto prevHop = i2p::context.GetSharedRouterInfo();
int numHops = isInbound ?
m_NumInboundHops :
m_NumOutboundHops;
if (i2p::transport::transports.GetNumPeers() > 25) {
auto r = i2p::transport::transports.GetRandomPeer();
if (r && !r->GetProfile()->IsBad()) {
prevHop = r;
hops.push_back(r);
numHops--;
}
}
for (int i = 0; i < numHops; i++) {
auto hop = SelectNextHop(prevHop);
if (!hop) {
LogPrint(eLogError, "TunnelPool: can't select next hop");
return false;
}
prevHop = hop;
hops.push_back(hop);
}
return true;
}
bool TunnelPool::SelectExplicitPeers(
std::vector<std::shared_ptr<const i2p::data::RouterInfo> >& hops,
bool isInbound) {
int size = m_ExplicitPeers->size();
std::vector<int> peerIndicies;
for (int i = 0; i < size; i++)
peerIndicies.push_back(i);
std::random_shuffle(peerIndicies.begin(), peerIndicies.end());
int numHops = isInbound ? m_NumInboundHops : m_NumOutboundHops;
for (int i = 0; i < numHops; i++) {
auto& ident = (*m_ExplicitPeers)[peerIndicies[i]];
auto r = i2p::data::netdb.FindRouter(ident);
if (r) {
hops.push_back(r);
} else {
LogPrint(eLogInfo,
"TunnelPool: can't find router for ", ident.ToBase64());
i2p::data::netdb.RequestDestination(ident);
return false;
}
}
return true;
}
void TunnelPool::CreateInboundTunnel() {
auto outboundTunnel = GetNextOutboundTunnel();
if (!outboundTunnel)
outboundTunnel = tunnels.GetNextOutboundTunnel();
LogPrint(eLogInfo, "TunnelPool: creating destination inbound tunnel");
std::vector<std::shared_ptr<const i2p::data::RouterInfo> > hops;
if (SelectPeers(hops, true)) {
std::reverse(hops.begin(), hops.end());
auto tunnel = tunnels.CreateTunnel<InboundTunnel> (
std::make_shared<TunnelConfig> (hops),
outboundTunnel);
tunnel->SetTunnelPool(shared_from_this());
} else {
LogPrint(eLogError,
"TunnelPool: can't create inbound tunnel, no peers available");
}
}
void TunnelPool::RecreateInboundTunnel(
std::shared_ptr<InboundTunnel> tunnel) {
auto outboundTunnel = GetNextOutboundTunnel();
if (!outboundTunnel)
outboundTunnel = tunnels.GetNextOutboundTunnel();
LogPrint(eLogInfo, "TunnelPool: re-creating destination inbound tunnel");
auto newTunnel =
tunnels.CreateTunnel<InboundTunnel> (
tunnel->GetTunnelConfig()->Clone(),
outboundTunnel);
newTunnel->SetTunnelPool(shared_from_this());
}
void TunnelPool::CreateOutboundTunnel() {
auto inboundTunnel = GetNextInboundTunnel();
if (!inboundTunnel)
inboundTunnel = tunnels.GetNextInboundTunnel();
if (inboundTunnel) {
LogPrint(eLogInfo, "TunnelPool: creating destination outbound tunnel");
std::vector<std::shared_ptr<const i2p::data::RouterInfo> > hops;
if (SelectPeers(hops, false)) {
auto tunnel = tunnels.CreateTunnel<OutboundTunnel> (
std::make_shared<TunnelConfig> (
hops,
inboundTunnel->GetTunnelConfig()));
tunnel->SetTunnelPool(shared_from_this());
} else {
LogPrint(eLogError,
"TunnelPool: can't create outbound tunnel, no peers available");
}
} else {
LogPrint(eLogError,
"TunnelPool: can't create outbound tunnel, no inbound tunnels found");
}
}
void TunnelPool::RecreateOutboundTunnel(
std::shared_ptr<OutboundTunnel> tunnel) {
auto inboundTunnel = GetNextInboundTunnel();
if (!inboundTunnel)
inboundTunnel = tunnels.GetNextInboundTunnel();
if (inboundTunnel) {
LogPrint(eLogInfo, "TunnelPool: re-creating destination outbound tunnel");
auto newTunnel = tunnels.CreateTunnel<OutboundTunnel> (
tunnel->GetTunnelConfig()->Clone(
inboundTunnel->GetTunnelConfig()));
newTunnel->SetTunnelPool(shared_from_this());
} else {
LogPrint(eLogError,
"TunnelPool: can't re-create outbound tunnel, no inbound tunnels found");
}
}
void TunnelPool::CreatePairedInboundTunnel(
std::shared_ptr<OutboundTunnel> outboundTunnel) {
LogPrint(eLogInfo, "TunnelPool: creating paired inbound tunnel");
auto tunnel = tunnels.CreateTunnel<InboundTunnel> (
outboundTunnel->GetTunnelConfig()->Invert(),
outboundTunnel);
tunnel->SetTunnelPool(shared_from_this());
}
} // namespace tunnel
} // namespace i2p
| 32.114583
| 90
| 0.684139
|
moneromooo-monero
|
6e3881616a89359c3390c471bce95a7a6ea66c36
| 5,950
|
cpp
|
C++
|
test/cedar_tests.cpp
|
dominiKoeppl/tudocomp
|
b5512f85f6b3408fb88e19c08899ec4c2716c642
|
[
"ECL-2.0",
"Apache-2.0"
] | 17
|
2017-03-04T13:04:49.000Z
|
2021-12-03T06:58:20.000Z
|
test/cedar_tests.cpp
|
dominiKoeppl/tudocomp
|
b5512f85f6b3408fb88e19c08899ec4c2716c642
|
[
"ECL-2.0",
"Apache-2.0"
] | 27
|
2016-01-22T18:31:37.000Z
|
2021-11-27T10:50:40.000Z
|
test/cedar_tests.cpp
|
dominiKoeppl/tudocomp
|
b5512f85f6b3408fb88e19c08899ec4c2716c642
|
[
"ECL-2.0",
"Apache-2.0"
] | 16
|
2017-03-14T12:46:51.000Z
|
2021-06-25T18:19:50.000Z
|
#include "test/util.hpp"
#include <gtest/gtest.h>
#include <tudocomp/CreateAlgorithm.hpp>
#include <tudocomp/Literal.hpp>
#include <tudocomp/compressors/LZ78Compressor.hpp>
#include <tudocomp/compressors/LZWCompressor.hpp>
#include <tudocomp/compressors/lz78/BinaryTrie.hpp>
#include <tudocomp/compressors/lz78/TernaryTrie.hpp>
#include <tudocomp/compressors/lz78/CedarTrie.hpp>
#include <tudocomp/coders/ASCIICoder.hpp>
#include <tudocomp/coders/BitCoder.hpp>
using namespace tdc;
struct InputOutput {
View in;
View out;
};
std::ostream& operator<<(std::ostream& os, const InputOutput& v) {
return os << v.in << " : " << v.out;
}
class NotCedarLz78Compress: public ::testing::TestWithParam<InputOutput> {};
TEST_P(NotCedarLz78Compress, test) {
auto c = create_algo<LZ78Compressor<ASCIICoder, lz78::BinaryTrie>>();
test::TestInput i(GetParam().in, false);
test::TestOutput o(false);
c.compress(i, o);
ASSERT_EQ(o.result(), GetParam().out);
}
INSTANTIATE_TEST_CASE_P(
InputOutput, NotCedarLz78Compress, ::testing::Values(
InputOutput { "aababcabcdabcde"_v, "0:a1:b2:c3:d4:e\0"_v },
InputOutput { "aababcabcdabcdeabc"_v, "0:a1:b2:c3:d4:e2:c\0"_v },
InputOutput { "\0\0b\0bc\0bcd\0bcde"_v, "0:\0""1:b2:c3:d4:e\0"_v },
InputOutput { "\xfe\xfe""b\xfe""bc\xfe""bcd\xfe""bcde"_v, "0:\xfe""1:b2:c3:d4:e\0"_v },
InputOutput { "\xff\xff""b\xff""bc\xff""bcd\xff""bcde"_v, "0:\xff""1:b2:c3:d4:e\0"_v }
)
);
class CedarLz78Compress: public ::testing::TestWithParam<InputOutput> {};
TEST_P(CedarLz78Compress, test) {
auto c = create_algo<LZ78Compressor<ASCIICoder, lz78::CedarTrie>>();
test::TestInput i(GetParam().in, false);
test::TestOutput o(false);
c.compress(i, o);
ASSERT_EQ(o.result(), GetParam().out);
}
INSTANTIATE_TEST_CASE_P(
InputOutput, CedarLz78Compress, ::testing::Values(
InputOutput { "aababcabcdabcde"_v, "0:a1:b2:c3:d4:e\0"_v },
InputOutput { "aababcabcdabcdeabc"_v, "0:a1:b2:c3:d4:e2:c\0"_v },
InputOutput { "\0\0b\0bc\0bcd\0bcde"_v, "0:\0""1:b2:c3:d4:e\0"_v },
InputOutput { "\xfe\xfe""b\xfe""bc\xfe""bcd\xfe""bcde"_v, "0:\xfe""1:b2:c3:d4:e\0"_v },
InputOutput { "\xff\xff""b\xff""bc\xff""bcd\xff""bcde"_v, "0:\xff""1:b2:c3:d4:e\0"_v }
)
);
class NotCedarLzwCompress: public ::testing::TestWithParam<InputOutput> {};
TEST_P(NotCedarLzwCompress, test) {
auto c = create_algo<LZWCompressor<ASCIICoder, lz78::BinaryTrie>>();
test::TestInput i(GetParam().in, false);
test::TestOutput o(false);
c.compress(i, o);
ASSERT_EQ(o.result(), GetParam().out);
}
INSTANTIATE_TEST_CASE_P(InputOutput,
NotCedarLzwCompress,
::testing::Values(
InputOutput { "aaaaaa"_v, "97:256:257:\0"_v },
InputOutput { "aaaaaaa"_v, "97:256:257:97:\0"_v },
InputOutput { "a\0b"_v, "97:0:98:\0"_v },
InputOutput { "a\xfe""b"_v, "97:254:98:\0"_v },
InputOutput { "a\xff""b"_v, "97:255:98:\0"_v },
InputOutput { "\0\0\0"_v, "0:256:\0"_v },
InputOutput { "\xfe\xfe\xfe"_v, "254:256:\0"_v },
InputOutput { "\xff\xff\xff"_v, "255:256:\0"_v }
));
class CedarLzwCompress: public ::testing::TestWithParam<InputOutput> {};
TEST_P(CedarLzwCompress, test) {
auto c = create_algo<LZWCompressor<ASCIICoder, lz78::CedarTrie>>();
test::TestInput i(GetParam().in, false);
test::TestOutput o(false);
c.compress(i, o);
ASSERT_EQ(o.result(), GetParam().out);
}
INSTANTIATE_TEST_CASE_P(InputOutput,
CedarLzwCompress,
::testing::Values(
InputOutput { "aaaaaa"_v, "97:256:257:\0"_v },
InputOutput { "aaaaaaa"_v, "97:256:257:97:\0"_v },
InputOutput { "a\0b"_v, "97:0:98:\0"_v },
InputOutput { "a\xfe""b"_v, "97:254:98:\0"_v },
InputOutput { "a\xff""b"_v, "97:255:98:\0"_v },
InputOutput { "\0\0\0"_v, "0:256:\0"_v },
InputOutput { "\xfe\xfe\xfe"_v, "254:256:\0"_v },
InputOutput { "\xff\xff\xff"_v, "255:256:\0"_v }
));
/*
TEST(zcedar, base) {
cedar::da<uint32_t> trie;
for (uint16_t j = 0; j < 256; j++) {
const char c = uint8_t(j);
auto letter = &c;
size_t from = 0;
size_t pos = 0;
auto i = j;
//DLOG(INFO) << "i: " << i << ", from: " << from << ", pos: " << pos;
trie.update(letter, from, pos, 1, i);
DLOG(INFO) << "i: " << i << ", from: " << from << ", pos: " << pos;
}
for (uint16_t i = 0; i < 256; i++) {
const char c = uint8_t(i);
auto letter = &c;
size_t from = 0;
size_t pos = 0;
auto r = trie.traverse(letter, from, pos, 1);
DLOG(INFO) << "r: " << r << ", from: " << from << ", pos: " << pos
<< ", NO_PATH: " << int(r == lz78::CEDAR_NO_PATH)
<< ", NO_VALUE: " << int(r == lz78::CEDAR_NO_VALUE);
}
for (uint16_t i = 0; i < 256; i++) {
const char c = uint8_t(i);
auto letter = &c;
size_t from = 0;
size_t pos = 0;
auto r = trie.traverse(letter, from, pos, 1);
//if (r != lz78::CEDAR_NO_PATH && r != lz78::CEDAR_NO_VALUE)
{
const char c2 = 'a';
auto letter2 = &c2;
pos = 0;
trie.update(letter2, from, pos, 1);
}
DLOG(INFO) << " r: " << r << ", from: " << from << ", pos: " << pos
<< ", NO_PATH: " << int(r == lz78::CEDAR_NO_PATH)
<< ", NO_VALUE: " << int(r == lz78::CEDAR_NO_VALUE);
}
}
*/
| 36.956522
| 95
| 0.540168
|
dominiKoeppl
|
6e3c240f69dbf0efe4f5387bed47dcfb9dff54ab
| 6,606
|
cc
|
C++
|
src/native/tchmain/TchMainExportWin.cc
|
dudes-come/tchapp
|
24844869813edafff277e8c0ca6126d195423134
|
[
"MIT"
] | 8
|
2016-11-08T08:56:58.000Z
|
2017-03-30T02:34:00.000Z
|
src/native/tchmain/TchMainExportWin.cc
|
dudes-come/tchapp
|
24844869813edafff277e8c0ca6126d195423134
|
[
"MIT"
] | 32
|
2016-11-08T10:22:08.000Z
|
2016-12-19T07:51:55.000Z
|
src/native/tchmain/TchMainExportWin.cc
|
dudes-come/tchapp
|
24844869813edafff277e8c0ca6126d195423134
|
[
"MIT"
] | 5
|
2016-11-08T08:57:02.000Z
|
2022-01-29T09:22:46.000Z
|
#include "TchMainExport.h"
#include <Windows.h>
#include <iostream>
#include <string>
#include <locale>
#include <cstring>
#include <experimental/filesystem>
#include "../tch_include/TchVersion.h"
#include <io.h>
namespace gnu_fs = std::experimental::filesystem;
mbstate_t in_cvt_state;
mbstate_t out_cvt_state;
std::wstring s2ws(const std::string& s)
{
std::locale sys_loc("");
const char* src_str = s.c_str();
const size_t BUFFER_SIZE = s.size() + 1;
wchar_t* intern_buffer = new wchar_t[BUFFER_SIZE];
std::wmemset(intern_buffer, 0, BUFFER_SIZE);
const char* extern_from = src_str;
const char* extern_from_end = extern_from + s.size();
const char* extern_from_next = 0;
wchar_t* intern_to = intern_buffer;
wchar_t* intern_to_end = intern_to + BUFFER_SIZE;
wchar_t* intern_to_next = 0;
typedef std::codecvt<wchar_t, char, mbstate_t> CodecvtFacet;
const std::codecvt<wchar_t,char,mbstate_t>& ct=std::use_facet<CodecvtFacet>(sys_loc);
auto cvt_rst=ct.in(
in_cvt_state,
extern_from, extern_from_end, extern_from_next,
intern_to, intern_to_end, intern_to_next);
if (cvt_rst != CodecvtFacet::ok) {
switch (cvt_rst) {
case CodecvtFacet::partial:
std::cerr << "partial";
break;
case CodecvtFacet::error:
std::cerr << "error";
break;
case CodecvtFacet::noconv:
std::cerr << "noconv";
break;
default:
std::cerr << "unknown";
}
std::cerr << ", please check in_cvt_state."
<< std::endl;
}
std::wstring result = intern_buffer;
delete[]intern_buffer;
return result;
}
std::string ws2s(const std::wstring& ws)
{
std::locale sys_loc("");
const wchar_t* src_wstr = ws.c_str();
const size_t MAX_UNICODE_BYTES = 4;
const size_t BUFFER_SIZE =
ws.size() * MAX_UNICODE_BYTES + 1;
char* extern_buffer = new char[BUFFER_SIZE];
std::memset(extern_buffer, 0, BUFFER_SIZE);
const wchar_t* intern_from = src_wstr;
const wchar_t* intern_from_end = intern_from + ws.size();
const wchar_t* intern_from_next = 0;
char* extern_to = extern_buffer;
char* extern_to_end = extern_to + BUFFER_SIZE;
char* extern_to_next = 0;
typedef std::codecvt<wchar_t, char, mbstate_t> CodecvtFacet;
const std::codecvt<wchar_t, char, mbstate_t>& ct = std::use_facet<CodecvtFacet>(sys_loc);
auto cvt_rst =ct.out(
out_cvt_state,
intern_from, intern_from_end, intern_from_next,
extern_to, extern_to_end, extern_to_next);
if (cvt_rst != CodecvtFacet::ok) {
switch (cvt_rst) {
case CodecvtFacet::partial:
std::cerr << "partial";
break;
case CodecvtFacet::error:
std::cerr << "error";
break;
case CodecvtFacet::noconv:
std::cerr << "noconv";
break;
default:
std::cerr << "unknown";
}
std::cerr << ", please check out_cvt_state."
<< std::endl;
}
std::string result = extern_buffer;
delete[]extern_buffer;
return result;
}
void AddFilesFromDirectoryToTpaList(std::wstring directory, std::wstring& tpa_list_out) {
for (auto& dirent : gnu_fs::directory_iterator(directory)) {
std::wstring path = s2ws(dirent.path().string());
if (!path.compare(path.length() - 4, 4, L".dll")) {
tpa_list_out.append(path + L";");
}
}
tpa_list_out.erase(tpa_list_out.size() - 1, 1);
}
int TchMain(int argc,char* argv[]){
wchar_t exe_path[MAX_PATH];
GetModuleFileName(GetModuleHandle(0), exe_path, MAX_PATH);
std::wstring cmd_line_str(exe_path);
int scan_i = cmd_line_str.rfind('\\');
std::wstring app_name = cmd_line_str.substr(scan_i + 1, cmd_line_str.size() - scan_i);
std::wstring app_path(exe_path);
std::wstring app_dir = app_path.substr(0, app_path.length() - app_name.length() - 1);
std::wstring cli_entry_path = app_path.substr(0, app_path.size() - 4).append(L".dll");
std::wstring clr_dir;
std::wstring clr_path;
std::string clr_path_c(ws2s(app_dir));
clr_path_c.append("\\clr\\coreclr.dll");
bool is_use_local_clr = access(clr_path_c.c_str(), 0)==0;//检查是否存在本地clr
if (!is_use_local_clr) {
auto clr_path_var = ::getenv("ProgramFiles");
clr_dir = s2ws(clr_path_var).append(L"\\dotnet").append(L"\\shared\\Microsoft.NETCore.App\\").append(DOTNETCORE_VERSION);
}
else {
clr_dir=app_dir;
clr_dir.append(L"\\clr");
}
clr_path = clr_dir;
clr_path.append(L"\\coreclr.dll");
std::wstring tpa_list;
AddFilesFromDirectoryToTpaList(clr_dir, tpa_list);
std::wstring nativeDllSearchDirs(app_dir);
nativeDllSearchDirs.append(L";").append(clr_dir);
const char* serverGcVar = "CORECLR_SERVER_GC";
const char* useServerGc = std::getenv(serverGcVar);
if (useServerGc == nullptr)
{
useServerGc = "0";
}
useServerGc = std::strcmp(useServerGc, "1") == 0 ? "true" : "false";
const char *propertyKeys[] = {
"TRUSTED_PLATFORM_ASSEMBLIES",
"APP_PATHS",
"APP_NI_PATHS",
"NATIVE_DLL_SEARCH_DIRECTORIES",
"System.GC.Server",
};
std::string tpa_list_c = ws2s(tpa_list);
std::string app_dir_c = ws2s(app_dir);
std::string nativeDllSearchDirs_c = ws2s(nativeDllSearchDirs);
const char *propertyValues[] = {
// TRUSTED_PLATFORM_ASSEMBLIES
tpa_list_c.c_str(),
// APP_PATHS
app_dir_c.c_str(),
// APP_NI_PATHS
app_dir_c.c_str(),
// NATIVE_DLL_SEARCH_DIRECTORIES
nativeDllSearchDirs_c.c_str(),
// System.GC.Server
useServerGc,
};
auto coreclr_hmodule = ::LoadLibrary(clr_path.c_str());
auto coreclr_initialize = (coreclr_initialize_ptr)::GetProcAddress(coreclr_hmodule, "coreclr_initialize");
auto coreclr_shutdown = (coreclr_shutdown_ptr)::GetProcAddress(coreclr_hmodule, "coreclr_shutdown");
//auto coreclr_create_delegate = (coreclr_create_delegate_ptr)::GetProcAddress(coreclr_hmodule, "coreclr_create_delegate");
auto coreclr_execute_assembly = (coreclr_execute_assembly_ptr)::GetProcAddress(coreclr_hmodule, "coreclr_execute_assembly");
void* hostHandle;
unsigned int domainId;
int status = 0;
status = coreclr_initialize(ws2s(app_path).c_str(), "TchApp", sizeof(propertyKeys) / sizeof(propertyKeys[0]), propertyKeys, propertyValues, &hostHandle, &domainId);
LPWSTR str_status;
printf("coreclr_initialize status:%x\r\n", status);
unsigned int exit_code = 0;
std::string cli_entry_path_c = ws2s(cli_entry_path);
const char** argv_c = const_cast<const char**>(argv);
status = coreclr_execute_assembly(hostHandle, domainId, argc, argv_c, cli_entry_path_c.c_str(), &exit_code);
printf("coreclr_execute_assembly status:%x\r\n", status);
//Run run = 0;
//status = coreclr_create_delegate(hostHandle, domainId, "TchApp.CLIEntrance", "TchApp.CLIEntrance.Program", "EnterCLI", reinterpret_cast<void**>(&run));
//printf("coreclr_create_delegate status:%x\r\n", status);
coreclr_shutdown(hostHandle, domainId);
return exit_code;
}
| 30.725581
| 165
| 0.725401
|
dudes-come
|
6e44146463e32b7e0207db0fc807c245742eedf4
| 865
|
cpp
|
C++
|
Source/Shared/UI/WidgetGameButton.cpp
|
PsichiX/Unreal-Systems-Architecture
|
fb2ccb243c8e79b0890736d611db7ba536937a93
|
[
"Apache-2.0"
] | 5
|
2022-02-09T21:19:03.000Z
|
2022-03-03T01:53:03.000Z
|
Source/Shared/UI/WidgetGameButton.cpp
|
PsichiX/Unreal-Systems-Architecture
|
fb2ccb243c8e79b0890736d611db7ba536937a93
|
[
"Apache-2.0"
] | null | null | null |
Source/Shared/UI/WidgetGameButton.cpp
|
PsichiX/Unreal-Systems-Architecture
|
fb2ccb243c8e79b0890736d611db7ba536937a93
|
[
"Apache-2.0"
] | null | null | null |
#include "Shared/UI/WidgetGameButton.h"
#include "Components/Button.h"
#include "Components/TextBlock.h"
#include "Kismet/GameplayStatics.h"
void UWidgetGameButton::NativeConstruct()
{
Super::NativeConstruct();
if (IsValid(this->Button))
{
this->Button->OnClicked.AddUniqueDynamic(this, &ThisClass::OnClicked);
}
}
void UWidgetGameButton::NativeDestruct()
{
Super::NativeDestruct();
if (IsValid(this->Button))
{
this->Button->OnClicked.RemoveAll(this);
}
}
void UWidgetGameButton::NativeOnListItemObjectSet(UObject* ListItemObject)
{
this->GameInfo = Cast<UWidgetGameInfo>(ListItemObject);
if (IsValid(this->GameInfo) && IsValid(this->Text))
{
this->Text->SetText(this->GameInfo->GameName);
}
}
void UWidgetGameButton::OnClicked()
{
if (IsValid(this->GameInfo))
{
UGameplayStatics::OpenLevel(GetWorld(), this->GameInfo->MapName);
}
}
| 19.659091
| 74
| 0.734104
|
PsichiX
|
6e45f2a66417dc67c04cfc99f03269b9a4486a3f
| 599
|
cpp
|
C++
|
src/Context.cpp
|
desktopgame/ofxLua
|
098cc40277dd00d42aaf191bbf0cc43d3b2349fd
|
[
"BSL-1.0",
"MIT"
] | 1
|
2020-01-28T05:10:19.000Z
|
2020-01-28T05:10:19.000Z
|
src/Context.cpp
|
desktopgame/ofxLua
|
098cc40277dd00d42aaf191bbf0cc43d3b2349fd
|
[
"BSL-1.0",
"MIT"
] | null | null | null |
src/Context.cpp
|
desktopgame/ofxLua
|
098cc40277dd00d42aaf191bbf0cc43d3b2349fd
|
[
"BSL-1.0",
"MIT"
] | null | null | null |
#include "Context.h"
#include <stdexcept>
namespace ofxLua {
std::stack<Context::Instance> Context::stack;
Context::Instance Context::push() {
Instance inst = std::shared_ptr<Context>(new Context());
stack.push(inst);
return inst;
}
Context::Instance Context::top() {
if (stack.empty()) {
throw std::logic_error("stack is empty");
}
return stack.top();
}
void Context::pop() {
if (stack.empty()) {
throw std::logic_error("stack is empty");
}
stack.pop();
}
bool Context::contains(const std::string & name) const {
return map.count(name);
}
// private
Context::Context() : map() {
}
}
| 19.966667
| 57
| 0.672788
|
desktopgame
|
6e5192c204f0327c507d2eb370e626d5e9d3cda0
| 67
|
hpp
|
C++
|
tests/src/utils/generate_unique_mock_id.hpp
|
aahmed-2/telemetry
|
7e098e93ef0974739459d296f99ddfab54722c23
|
[
"Apache-2.0"
] | 4
|
2019-11-14T10:41:34.000Z
|
2021-12-09T23:54:52.000Z
|
tests/src/utils/generate_unique_mock_id.hpp
|
aahmed-2/telemetry
|
7e098e93ef0974739459d296f99ddfab54722c23
|
[
"Apache-2.0"
] | 2
|
2021-10-04T20:12:53.000Z
|
2021-12-14T18:13:03.000Z
|
tests/src/utils/generate_unique_mock_id.hpp
|
aahmed-2/telemetry
|
7e098e93ef0974739459d296f99ddfab54722c23
|
[
"Apache-2.0"
] | 2
|
2021-08-05T11:17:03.000Z
|
2021-12-13T15:22:48.000Z
|
#pragma once
#include <cstdint>
uint64_t generateUniqueMockId();
| 11.166667
| 32
| 0.776119
|
aahmed-2
|
6e5296191454b28306a2722dc1d12cfda2fef7b7
| 1,302
|
cpp
|
C++
|
Enviados/Brinde_Face_2015.cpp
|
VictorCurti/URI
|
abc344597682a3099e8b1899c78584f9b762a494
|
[
"MIT"
] | null | null | null |
Enviados/Brinde_Face_2015.cpp
|
VictorCurti/URI
|
abc344597682a3099e8b1899c78584f9b762a494
|
[
"MIT"
] | null | null | null |
Enviados/Brinde_Face_2015.cpp
|
VictorCurti/URI
|
abc344597682a3099e8b1899c78584f9b762a494
|
[
"MIT"
] | null | null | null |
/* Brinde Face 2015
Data: 25/03/2019 Autor: Victor Curti
ex:
4
0 1 2 3 4
(F A C E - E C F A - A C F E - A C E F - F E C A)
F A C E E C F A A C F E A C E F F E C A
F A C E E C F A A C F E
A C E F - F E C A
Stack A:
F
E
C
A
*/
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main(){
string Dado ("FACE");
int num,Ganhadores=0;
cin >> num;
cin.get();
while(num--){
string Leirura;
getline(cin,Leirura);
for (char c: Leirura)
if(c != ' ' && c!= '\n')
Dado += c;
stack <char> StackA;
bool Test = true;
for(int i=0 ; i<=4 ; i++){
StackA.push(Dado[Dado.size()-i]);
}
//Apaga ultimas 4 letras ja lidas
for(int i=4 ; i<=7 && Test; i++){
if(StackA.top()!= Dado[(Dado.size()-1)-i])
Test = false;
StackA.pop();
}
//Caso Ganhador Tirar as 4 anterios tambem
if(Test){
Dado.erase(Dado.size()-8,8);
Ganhadores++;
}
if(Dado.empty())
Dado += "FACE";
}
cout << Ganhadores;
return 0;
}
| 21
| 54
| 0.417819
|
VictorCurti
|
6e5b52dd869faa243903a19d3e2f3ae1221c8412
| 619
|
cpp
|
C++
|
AllCombinationsOfString/combinations.cpp
|
Electrux/CCPP-Code
|
3c5e5b866cf050c11bced9651b112eb31dd2465d
|
[
"BSD-3-Clause"
] | 6
|
2019-08-29T23:31:17.000Z
|
2021-11-14T20:35:47.000Z
|
AllCombinationsOfString/combinations.cpp
|
Electrux/CCPP-Code
|
3c5e5b866cf050c11bced9651b112eb31dd2465d
|
[
"BSD-3-Clause"
] | null | null | null |
AllCombinationsOfString/combinations.cpp
|
Electrux/CCPP-Code
|
3c5e5b866cf050c11bced9651b112eb31dd2465d
|
[
"BSD-3-Clause"
] | 1
|
2019-09-01T12:22:58.000Z
|
2019-09-01T12:22:58.000Z
|
#include <iostream>
#include <string>
void find_permutations( std::string first, std::string others )
{
if( others.size() <= 0 ) {
std::cout << first << "\n";
return;
}
int len = others.size();
for( int i = 0; i < len; ++i ) {
std::string sub = others;
std::string first_tmp = first;
first_tmp += sub[ i ];
sub.erase( sub.begin() + i );
find_permutations( first_tmp, sub );
}
}
int main()
{
std::string s = "chirag";
int len = s.size();
for( int i = 0; i < len; ++i ) {
std::string sub = s;
sub.erase( sub.begin() + i );
find_permutations( std::string( 1, s[ i ] ), sub );
}
return 0;
}
| 19.967742
| 63
| 0.573506
|
Electrux
|
6e5bca89d247516231fb68cf075693d455fd0450
| 422
|
hpp
|
C++
|
src/tree/base/import.hpp
|
Azer0s/littl
|
3d2bfd979bdeee74cded9f31b62640b45b86a155
|
[
"MIT"
] | 4
|
2018-12-30T13:15:55.000Z
|
2019-05-12T17:39:38.000Z
|
src/tree/base/import.hpp
|
Azer0s/littl
|
3d2bfd979bdeee74cded9f31b62640b45b86a155
|
[
"MIT"
] | null | null | null |
src/tree/base/import.hpp
|
Azer0s/littl
|
3d2bfd979bdeee74cded9f31b62640b45b86a155
|
[
"MIT"
] | 1
|
2018-12-29T19:12:07.000Z
|
2018-12-29T19:12:07.000Z
|
#pragma once
#include "../syntaxtree.hpp"
namespace littl {
class Import : public SyntaxTree{
public:
Import(SyntaxTree* name){
this->name = name;
}
virtual ~Import(){
delete name;
};
virtual std::string toCode() const{
return "";
}
private:
SyntaxTree* name;
};
}
| 21.1
| 47
| 0.440758
|
Azer0s
|
6e5e03b24741ecdc6c83cae97aedd0b7b61eff5e
| 1,328
|
cpp
|
C++
|
Code/C++/selection_sort.cpp
|
parthmshah1302/Algo-Tree
|
451e3d3fde2b841f77bed0dfaa9b83e5d9a7d3dc
|
[
"MIT"
] | 356
|
2021-01-24T11:34:15.000Z
|
2022-03-16T08:39:02.000Z
|
Code/C++/selection_sort.cpp
|
parthmshah1302/Algo-Tree
|
451e3d3fde2b841f77bed0dfaa9b83e5d9a7d3dc
|
[
"MIT"
] | 1,778
|
2021-01-24T10:52:44.000Z
|
2022-01-30T12:34:05.000Z
|
Code/C++/selection_sort.cpp
|
parthmshah1302/Algo-Tree
|
451e3d3fde2b841f77bed0dfaa9b83e5d9a7d3dc
|
[
"MIT"
] | 782
|
2021-01-24T10:54:10.000Z
|
2022-03-23T10:16:04.000Z
|
/*
Selection sort is an algorithm that selects the smallest element from an unsorted list in each iteration
and places that element at the beginning of the unsorted list.
* Strategy:
find the smallest number in the array and exchange it with the value in first position of array.
Now, find the second smallest element in the remainder of array and exchange it with a value in the second position,
carry on till you have reached the end of array. Now all the elements have been sorted in ascending order.
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,i,j,k;
cin>>n;
int a[n];
for(i=0;i<n;i++){
cin>>a[i];
}
// move boundary of unsorted subarray one by one
for(i=0;i<n-1;i++){
// Find the minimum element in unsorted array
for(j=k=i;j<n;j++){
if(a[j]<a[k])
k=j;
}
// Swap the minimum element with the ith element of array
swap(a[i],a[k]);
}
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}
/*
Test case 1:
Input : 7
3 5 4 1 2 7 6
Output :
1 2 3 4 5 6 7
Test case 2:
Input : 5
50 20 40 10 30
Output:
10 20 30 40 50
Time Complexity: O(n^2)
Space Complexity: O(1)
*/
| 16.395062
| 124
| 0.576054
|
parthmshah1302
|
6e61a110389e77a76be83f94d795d9465eb0c47f
| 2,646
|
hpp
|
C++
|
include/stl2/detail/algorithm/swap_ranges.hpp
|
marehr/cmcstl2
|
7a7cae1e23beacb18fd786240baef4ae121d813f
|
[
"MIT"
] | null | null | null |
include/stl2/detail/algorithm/swap_ranges.hpp
|
marehr/cmcstl2
|
7a7cae1e23beacb18fd786240baef4ae121d813f
|
[
"MIT"
] | null | null | null |
include/stl2/detail/algorithm/swap_ranges.hpp
|
marehr/cmcstl2
|
7a7cae1e23beacb18fd786240baef4ae121d813f
|
[
"MIT"
] | null | null | null |
// cmcstl2 - A concept-enabled C++ standard library
//
// Copyright Casey Carter 2015
//
// Use, modification and distribution is subject to the
// Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// Project home: https://github.com/caseycarter/cmcstl2
//
#ifndef STL2_DETAIL_ALGORITHM_SWAP_RANGES_HPP
#define STL2_DETAIL_ALGORITHM_SWAP_RANGES_HPP
#include <stl2/iterator.hpp>
#include <stl2/utility.hpp>
#include <stl2/detail/algorithm/tagspec.hpp>
///////////////////////////////////////////////////////////////////////////
// swap_ranges [alg.swap]
//
STL2_OPEN_NAMESPACE {
namespace __swap_ranges {
template<ForwardIterator I1, Sentinel<I1> S1, ForwardIterator I2>
requires
IndirectlySwappable<I1, I2>
constexpr tagged_pair<tag::in1(I1), tag::in2(I2)>
impl(I1 first1, S1 last1, I2 first2)
{
for (; first1 != last1; ++first1, void(++first2)) {
__stl2::iter_swap(first1, first2);
}
return {std::move(first1), std::move(first2)};
}
}
template<ForwardIterator I1, Sentinel<I1> S1, class I2>
[[deprecated]] tagged_pair<tag::in1(I1), tag::in2(std::decay_t<I2>)>
swap_ranges(I1 first1, S1 last1, I2&& first2_)
requires ForwardIterator<std::decay_t<I2>> && !Range<I2> &&
IndirectlySwappable<I1, std::decay_t<I2>>
{
return __swap_ranges::impl(
std::move(first1), std::move(last1), std::forward<I2>(first2_));
}
template<ForwardRange Rng, class I>
[[deprecated]] tagged_pair<tag::in1(safe_iterator_t<Rng>), tag::in2(std::decay_t<I>)>
swap_ranges(Rng&& rng1, I&& first2_)
requires ForwardIterator<std::decay_t<I>> && !Range<I> &&
IndirectlySwappable<iterator_t<Rng>, std::decay_t<I>>
{
auto first2 = std::forward<I>(first2_);
return __swap_ranges::impl(__stl2::begin(rng1), __stl2::end(rng1), std::move(first2));
}
template<ForwardIterator I1, Sentinel<I1> S1,
ForwardIterator I2, Sentinel<I2> S2>
requires
IndirectlySwappable<I1, I2>
tagged_pair<tag::in1(I1), tag::in2(I2)>
swap_ranges(I1 first1, S1 last1, I2 first2, S2 last2)
{
for (; first1 != last1 && first2 != last2; ++first1, void(++first2)) {
__stl2::iter_swap(first1, first2);
}
return {std::move(first1), std::move(first2)};
}
template<ForwardRange Rng1, ForwardRange Rng2>
requires
IndirectlySwappable<iterator_t<Rng1>, iterator_t<Rng2>>
tagged_pair<tag::in1(safe_iterator_t<Rng1>),
tag::in2(safe_iterator_t<Rng2>)>
swap_ranges(Rng1&& rng1, Rng2&& rng2)
{
return __stl2::swap_ranges(
__stl2::begin(rng1), __stl2::end(rng1),
__stl2::begin(rng2), __stl2::end(rng2));
}
} STL2_CLOSE_NAMESPACE
#endif
| 31.5
| 88
| 0.688209
|
marehr
|
6e637694e3e4aff5c1efb30f44f91330b7b5d80e
| 1,287
|
hpp
|
C++
|
bunsan/process/include/bunsan/interprocess/sync/file_guard.hpp
|
bacsorg/bacs
|
2b52feb9efc805655cdf7829cf77ee028d567969
|
[
"Apache-2.0"
] | null | null | null |
bunsan/process/include/bunsan/interprocess/sync/file_guard.hpp
|
bacsorg/bacs
|
2b52feb9efc805655cdf7829cf77ee028d567969
|
[
"Apache-2.0"
] | 10
|
2018-02-06T14:46:36.000Z
|
2018-03-20T13:37:20.000Z
|
bunsan/process/include/bunsan/interprocess/sync/file_guard.hpp
|
bacsorg/bacs
|
2b52feb9efc805655cdf7829cf77ee028d567969
|
[
"Apache-2.0"
] | 1
|
2021-11-26T10:59:09.000Z
|
2021-11-26T10:59:09.000Z
|
#pragma once
#include <bunsan/error.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/optional.hpp>
namespace bunsan::interprocess {
struct file_guard_error : virtual bunsan::error {
using lock_path =
boost::error_info<struct tag_lock_path, boost::filesystem::path>;
};
struct file_guard_create_error : virtual file_guard_error {};
struct file_guard_locked_error : virtual file_guard_create_error {};
struct file_guard_remove_error : virtual file_guard_error {};
class file_guard {
public:
/// Unlocked guard.
file_guard() = default;
/*!
* \brief Create file at specified path.
*
* \throw file_guard_locked_error if file exists (type of file does not
*matter)
*/
explicit file_guard(const boost::filesystem::path &path);
// move semantics
file_guard(file_guard &&) noexcept;
file_guard &operator=(file_guard &&) noexcept;
// no copying
file_guard(const file_guard &) = delete;
file_guard &operator=(const file_guard &) = delete;
explicit operator bool() const noexcept;
void swap(file_guard &guard) noexcept;
void remove();
~file_guard();
private:
boost::optional<boost::filesystem::path> m_path;
};
inline void swap(file_guard &a, file_guard &b) noexcept { a.swap(b); }
} // namespace bunsan::interprocess
| 23.4
| 73
| 0.724165
|
bacsorg
|
6e6a804df0c9963523df7aef487638803473235b
| 7,687
|
cpp
|
C++
|
Source/EditorScriptingTools/Private/EditorScriptingToolsCommon/AssetTypeActions/EditorScriptingAssetTypeActions_Base.cpp
|
jswigart/UE4-EditorScriptingToolsPlugin
|
5fa4012bf10c1fc918d2c6ddeab0d1c6bbac85ca
|
[
"MIT"
] | 77
|
2020-12-04T21:10:16.000Z
|
2021-09-20T03:47:47.000Z
|
Source/EditorScriptingTools/Private/EditorScriptingToolsCommon/AssetTypeActions/EditorScriptingAssetTypeActions_Base.cpp
|
ProjectBorealis/UE4-EditorScriptingToolsPlugin
|
251b9b4f64bb465e74514fac2cec82a824ea2200
|
[
"MIT"
] | 11
|
2021-03-03T19:00:05.000Z
|
2021-06-19T18:11:42.000Z
|
Source/EditorScriptingTools/Private/EditorScriptingToolsCommon/AssetTypeActions/EditorScriptingAssetTypeActions_Base.cpp
|
ProjectBorealis/UE4-EditorScriptingToolsPlugin
|
251b9b4f64bb465e74514fac2cec82a824ea2200
|
[
"MIT"
] | 12
|
2020-12-09T04:47:41.000Z
|
2021-09-11T12:19:34.000Z
|
//==========================================================================//
// Copyright Elhoussine Mehnik (ue4resources@gmail.com). All Rights Reserved.
//================== http://unrealengineresources.com/ =====================//
#include "EditorScriptingAssetTypeActions_Base.h"
#include "Framework/MultiBox/MultiBoxBuilder.h"
#include "Misc/PackageName.h"
#include "Misc/MessageDialog.h"
#include "Kismet2/KismetEditorUtilities.h"
#include "BlueprintEditorModule.h"
#include "IContentBrowserSingleton.h"
#include "ContentBrowserModule.h"
#include "Widgets/Layout/SBorder.h"
#include "Widgets/Images/SThrobber.h"
#include "EditorScriptingToolsModule.h"
#include "EditorScriptingToolsSubsystem.h"
#include "BluEdMode.h"
#include "EditorModeToolInstance.h"
#include "EditorTypesWrapperTypes.h"
#include "EditorScriptingToolsStyle.h"
#include "EditorFontGlyphs.h"
#include "IEditorScriptingUtilityAssetInterface.h"
#include "EditorScriptingUtilityBlueprint.h"
#include "Widgets/Images/SImage.h"
#define LOCTEXT_NAMESPACE "AssetTypeActions"
uint32 FEditorScriptingAssetTypeActions_Base::GetCategories()
{
if (IEditorScriptingToolsModule* EditorScriptingToolsModulePtr = IEditorScriptingToolsModule::GetPtr())
{
return EditorScriptingToolsModulePtr->GetEditorScriptingAssetCategory();
}
return EAssetTypeCategories::Blueprint;
}
bool FEditorScriptingAssetTypeActions_Base::CanLocalize() const
{
return false;
}
bool FEditorScriptingAssetTypeActions_Base::HasActions(const TArray<UObject*>& InObjects) const
{
return InObjects.Num() > 0;
}
TSharedPtr<class SWidget> FEditorScriptingAssetTypeActions_Base::GetThumbnailOverlay(const FAssetData& AssetData) const
{
TWeakObjectPtr<UObject> ObjectWeakPtr = AssetData.GetAsset();
return SNew(SImage)
.Visibility(this, &FEditorScriptingAssetTypeActions_Base::GetThumbnailOverlayVisibility, ObjectWeakPtr)
.ColorAndOpacity(FLinearColor(1.0f, 1.0f, 1.0f, .1f));
}
void FEditorScriptingAssetTypeActions_Base::GetActions(const TArray<UObject*>& InObjects, FMenuBuilder& MenuBuilder)
{
if (InObjects.Num() == 1)
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
TWeakObjectPtr<UObject> ObjectWeakPtr = InObjects[0];
IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get());
check(ScriptingUtilityAsset != nullptr);
MenuBuilder.AddMenuEntry(
ScriptingToolsModule->GetRegisterScriptingUtilityText(ScriptingUtilityAsset),
ScriptingToolsModule->GetRegisterScriptingUtilityToolTipText(ScriptingUtilityAsset),
FSlateIcon(FEditorScriptingToolsStyle::Get()->GetStyleSetName(), TEXT("EditorScriptingUtility.Register")),
FUIAction(
FExecuteAction::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::RegisterUtility, ObjectWeakPtr),
FCanExecuteAction::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::CanRegisterUtility, ObjectWeakPtr),
FIsActionChecked(),
FIsActionButtonVisible::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::CanRegisterUtility, ObjectWeakPtr)
)
);
MenuBuilder.AddMenuEntry(
ScriptingToolsModule->GetUnregisterScriptingUtilityText(ScriptingUtilityAsset),
ScriptingToolsModule->GetUnregisterScriptingUtilityToolTipText(ScriptingUtilityAsset),
FSlateIcon(FEditorScriptingToolsStyle::Get()->GetStyleSetName(), TEXT("EditorScriptingUtility.Unregister")),
FUIAction(
FExecuteAction::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::UnregisterUtility, ObjectWeakPtr),
FCanExecuteAction::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::CanUnregisterUtility, ObjectWeakPtr),
FIsActionChecked(),
FIsActionButtonVisible::CreateSP(this, &FEditorScriptingAssetTypeActions_Base::CanUnregisterUtility, ObjectWeakPtr)
)
);
GetAdditionalActions(ObjectWeakPtr, MenuBuilder);
}
else
{
MenuBuilder.AddWidget
(
SNew(SHorizontalBox)
+SHorizontalBox::Slot()
.AutoWidth()
[
SNew(STextBlock)
.ColorAndOpacity(FLinearColor(0.65f, 0.4f, 0.15f, 1.0f))
.TextStyle(FEditorStyle::Get(), "ContentBrowser.TopBar.Font")
.Font(FEditorStyle::Get().GetFontStyle("FontAwesome.11"))
.Text(FEditorFontGlyphs::Exclamation_Triangle)
]
+SHorizontalBox::Slot()
.Padding(8.f, 0.f)
.AutoWidth()
[
SNew(STextBlock)
.ColorAndOpacity(FLinearColor(0.65f, 0.4f, 0.15f, 1.0f))
.Text(LOCTEXT("WarningMsg", "Select a single asset to see utility actions"))
],
FText::GetEmpty()
);
}
}
void FEditorScriptingAssetTypeActions_Base::OpenAssetEditor(const TArray<UObject*>& InObjects, TSharedPtr<class IToolkitHost> EditWithinLevelEditor)
{
EToolkitMode::Type Mode = EditWithinLevelEditor.IsValid() ? EToolkitMode::WorldCentric : EToolkitMode::Standalone;
for (auto ObjIt = InObjects.CreateConstIterator(); ObjIt; ++ObjIt)
{
if (UEditorScriptingUtilityBlueprint* ScriptingUtilityBlueprint = Cast<UEditorScriptingUtilityBlueprint>(*ObjIt))
{
FBlueprintEditorModule& BlueprintEditorModule = FModuleManager::LoadModuleChecked<FBlueprintEditorModule>("Kismet");
TSharedRef<IBlueprintEditor> NewBlueprintEditor = BlueprintEditorModule.CreateBlueprintEditor(Mode, EditWithinLevelEditor, ScriptingUtilityBlueprint, false);
}
}
}
void FEditorScriptingAssetTypeActions_Base::RegisterUtility(TWeakObjectPtr<UObject> ObjectWeakPtr)
{
if (IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get()))
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
ScriptingToolsModule->RegisterEditorScriptingUtility(ScriptingUtilityAsset);
}
}
bool FEditorScriptingAssetTypeActions_Base::CanRegisterUtility(TWeakObjectPtr<UObject> ObjectWeakPtr) const
{
if (IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get()))
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
return ScriptingToolsModule->CanRegisterEditorScriptingUtility(ScriptingUtilityAsset);
}
return false;
}
void FEditorScriptingAssetTypeActions_Base::UnregisterUtility(TWeakObjectPtr<UObject> ObjectWeakPtr)
{
if (IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get()))
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
ScriptingToolsModule->UnregisterEditorScriptingUtility(ScriptingUtilityAsset);
}
}
bool FEditorScriptingAssetTypeActions_Base::CanUnregisterUtility(TWeakObjectPtr<UObject> ObjectWeakPtr) const
{
if (IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get()))
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
return ScriptingToolsModule->IsEditorScriptingUtilityRegistered(ScriptingUtilityAsset);
}
return false;
}
EVisibility FEditorScriptingAssetTypeActions_Base::GetThumbnailOverlayVisibility(TWeakObjectPtr<UObject> ObjectWeakPtr) const
{
if (UEditorScriptingToolsSubsystem::GetSubsystem()->bEnableThumbnailOverlayOnRegisteredUtilities)
{
if (IEditorScriptingUtilityAssetInterface* ScriptingUtilityAsset = Cast<IEditorScriptingUtilityAssetInterface>(ObjectWeakPtr.Get()))
{
IEditorScriptingToolsModule* ScriptingToolsModule = IEditorScriptingToolsModule::GetPtr();
if (ScriptingToolsModule->IsEditorScriptingUtilityRegistered(ScriptingUtilityAsset))
{
return EVisibility::Visible;
}
}
}
return EVisibility::Collapsed;
}
#undef LOCTEXT_NAMESPACE
| 38.435
| 160
| 0.802133
|
jswigart
|
6e6c5ded5de564bb58c9911c3dbdb1d927458c82
| 12,194
|
cpp
|
C++
|
process_data.cpp
|
skpang/Teensy32_can_fd_to_usb_converter
|
8717188d059dbfe67185815e7dc223b60355c511
|
[
"MIT"
] | 1
|
2020-01-13T23:50:15.000Z
|
2020-01-13T23:50:15.000Z
|
process_data.cpp
|
skpang/Teensy32_can_fd_to_usb_converter
|
8717188d059dbfe67185815e7dc223b60355c511
|
[
"MIT"
] | 1
|
2018-10-20T21:58:40.000Z
|
2018-10-20T21:58:40.000Z
|
process_data.cpp
|
skpang/Teensy32_can_fd_to_usb_converter
|
8717188d059dbfe67185815e7dc223b60355c511
|
[
"MIT"
] | null | null | null |
#include "process_data.h"
#include "drv_canfdspi_defines.h"
#include "drv_canfdspi_api.h"
unsigned char timestamping = 0;
CAN_BITTIME_SETUP bt;
extern CAN_TX_MSGOBJ txObj;
extern CAN_RX_MSGOBJ rxObj;
extern uint8_t txd[MAX_DATA_BYTES];
extern uint8_t rxd[MAX_DATA_BYTES];
extern uint8_t prompt;
extern volatile uint8_t state;
#define DRV_CANFDSPI_INDEX_0 0
unsigned char parseHex(char * line, unsigned char len, unsigned long * value)
{
*value = 0;
while (len--) {
if (*line == 0) return 0;
*value <<= 4;
if ((*line >= '0') && (*line <= '9')) {
*value += *line - '0';
} else if ((*line >= 'A') && (*line <= 'F')) {
*value += *line - 'A' + 10;
} else if ((*line >= 'a') && (*line <= 'f')) {
*value += *line - 'a' + 10;
} else return 0;
line++;
}
return 1;
}
void sendByteHex(unsigned char value)
{
unsigned char ch = value >> 4;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
Serial.print(ch,BYTE);
ch = value & 0xF;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
Serial.print(ch,BYTE);
}
unsigned char transmitStd(char *line)
{
uint32_t temp;
unsigned char idlen;
unsigned char i;
unsigned char length;
switch(line[0])
{
case 'D':
case 'd':
txObj.bF.ctrl.BRS = 1;
txObj.bF.ctrl.FDF = 1;
break;
case 'B':
case 'b':
txObj.bF.ctrl.BRS = 0;
txObj.bF.ctrl.FDF = 1;
break;
default:
txObj.bF.ctrl.BRS = 0;
txObj.bF.ctrl.FDF = 0;
break;
}
if (line[0] < 'Z') {
txObj.bF.ctrl.IDE = 1;
idlen = 8;
} else {
txObj.bF.ctrl.IDE = 0;
idlen = 3;
}
if (!parseHex(&line[1], idlen, &temp)) return 0;
if (line[0] < 'Z') {
txObj.bF.id.SID = (uint32_t)(0xffff0000 & temp) >> 18;
txObj.bF.id.EID = 0x0000ffff & temp;
} else {
txObj.bF.id.SID = temp;
}
if (!parseHex(&line[1 + idlen], 1, &temp)) return 0;
txObj.bF.ctrl.DLC = temp;
length = temp;
if(txObj.bF.ctrl.FDF == 0)
{
// Classic CAN
if (length > 8) length = 8;
for (i = 0; i < length; i++) {
if (!parseHex(&line[idlen + 2 + i*2], 2, &temp)) return 0;
txd[i] = temp;
}
}else
{
// CAN FD
length = DRV_CANFDSPI_DlcToDataBytes((CAN_DLC) txObj.bF.ctrl.DLC);
if (length > 64) length = 64;
for (i = 0; i < length; i++) {
if (!parseHex(&line[idlen + 2 + i*2], 2, &temp)) return 0;
txd[i] = temp;
}
}
APP_TransmitMessageQueue();
return 1;
}
void parseLine(char * line)
{
unsigned char result = BELL;
switch (line[0]) {
case 'S': // Setup with standard CAN bitrates
if (state == STATE_CONFIG)
{
switch (line[1]) {
// case '0': ; result = CR; break;
// case '1': ; result = CR; break;
// case '2': ; result = CR; break;
// case '3': ; result = CR; break;
case '4': APP_CANFDSPI_Init(CAN_125K_500K); result = CR; break;
case '5': APP_CANFDSPI_Init(CAN_250K_500K); result = CR; break;
case '6': APP_CANFDSPI_Init(CAN_500K_1M); result = CR; break;
// case '7': ; result = CR; break;
case '8': APP_CANFDSPI_Init(CAN_1000K_4M); result = CR; break;
case '9': APP_CANFDSPI_Init(CAN_500K_1M); result = CR; break;
case 'A': APP_CANFDSPI_Init(CAN_500K_2M); result = CR; break;
case 'B': APP_CANFDSPI_Init(CAN_500K_3M); result = CR; break;
case 'C': APP_CANFDSPI_Init(CAN_500K_4M); result = CR; break;
case 'D': APP_CANFDSPI_Init(CAN_500K_5M); result = CR; break;
case 'E': APP_CANFDSPI_Init(CAN_500K_8M); result = CR; break;
case 'F': APP_CANFDSPI_Init(CAN_500K_10M); result = CR; break;
case 'G': APP_CANFDSPI_Init(CAN_250K_500K); result = CR; break;
case 'H': APP_CANFDSPI_Init(CAN_250K_1M); result = CR; break;
case 'I': APP_CANFDSPI_Init(CAN_250K_2M); result = CR; break;
case 'J': APP_CANFDSPI_Init(CAN_250K_3M); result = CR; break;
case 'K': APP_CANFDSPI_Init(CAN_250K_4M); result = CR; break;
case 'L': APP_CANFDSPI_Init(CAN_1000K_4M); result = CR; break;
case 'M': APP_CANFDSPI_Init(CAN_1000K_8M); result = CR; break;
case 'N': APP_CANFDSPI_Init(CAN_125K_500K); result = CR; break;
}
}
break;
case 's':
if (state == STATE_CONFIG)
{
unsigned long cnf1, cnf2, cnf3;
if (parseHex(&line[1], 2, &cnf1) && parseHex(&line[3], 2, &cnf2) && parseHex(&line[5], 2, &cnf3)) {
result = CR;
}
}
break;
case 'G':
{
unsigned long address;
if (parseHex(&line[1], 2, &address)) {
//
// sendByteHex(value);
result = CR;
}
}
break;
case 'W':
{
unsigned long address, data;
if (parseHex(&line[1], 2, &address) && parseHex(&line[3], 2, &data)) {
result = CR;
}
}
break;
case 'V': // Get hardware version
{
Serial.print('V');
sendByteHex(VERSION_HARDWARE_MAJOR);
sendByteHex(VERSION_HARDWARE_MINOR);
result = CR;
}
break;
case 'v': // Get firmware version
{
Serial.print('v');;
sendByteHex(VERSION_FIRMWARE_MAJOR);
sendByteHex(VERSION_FIRMWARE_MINOR);
result = CR;
}
break;
case 'N': // Get serial number
{
result = CR;
}
break;
case 'O': // Open CAN channel
if (state == STATE_CONFIG)
{
DRV_CANFDSPI_OperationModeSelect(DRV_CANFDSPI_INDEX_0, CAN_NORMAL_MODE);
state = STATE_OPEN;
result = CR;
}
break;
case 'l': // Loop-back mode
if (state == STATE_CONFIG)
{
state = STATE_OPEN;
result = CR;
}
break;
case 'L': // Open CAN channel in listen-only mode
if (state == STATE_CONFIG)
{
state = STATE_LISTEN;
result = CR;
}
break;
case 'C': // Close CAN channel
if (state != STATE_CONFIG)
{
DRV_CANFDSPI_OperationModeSelect(0, CAN_CONFIGURATION_MODE);
state = STATE_CONFIG;
result = CR;
}
break;
case 'r': // Transmit standard RTR (11 bit) frame
case 'R': // Transmit extended RTR (29 bit) frame
case 't': // Transmit standard (11 bit) frame
case 'T': // Transmit extended (29 bit) frame
case 'd': // Transmit FD standard (11 bit) frame with BRS
case 'D': // Transmit FD extended (29 bit) frame with BRS
case 'B': // Transmit FD standard (11 bit) frame no BRS
case 'b': // Transmit FD extended (29 bit) frame no BRS
if (state == STATE_OPEN)
{
if (transmitStd(line)) {
Serial.print('z');
result = CR;
}
}
break;
case 'F': // Read status flags
{
unsigned char status = 0;
sendByteHex(status);
result = CR;
}
break;
case 'Z': // Set time stamping
{
unsigned long stamping;
if (parseHex(&line[1], 1, &stamping)) {
timestamping = (stamping != 0);
result = CR;
}
}
break;
case 'm': // Set accpetance filter mask
if (state == STATE_CONFIG)
{
unsigned long am0, am1, am2, am3;
result = CR;
}
break;
case 'M': // Set accpetance filter code
if (state == STATE_CONFIG)
{
unsigned long ac0, ac1, ac2, ac3;
result = CR;
}
break;
}
Serial.print(result,BYTE);
}
unsigned char canmsg2ascii_getNextChar(uint32_t id, unsigned char dlc, unsigned char * step) {
char ch = BELL;
char newstep = *step;
if (*step == RX_STEP_TYPE) {
// type 1st char
if ((rxObj.bF.ctrl.IDE == 1) && (rxObj.bF.ctrl.FDF == 1) && (rxObj.bF.ctrl.BRS == 1))
{
newstep = RX_STEP_ID_EXT;
ch = 'D';
} else if ((rxObj.bF.ctrl.IDE == 0) && (rxObj.bF.ctrl.FDF == 1)&& (rxObj.bF.ctrl.BRS == 1))
{
newstep = RX_STEP_ID_STD;
ch = 'd';
} else if ((rxObj.bF.ctrl.IDE == 1) && (rxObj.bF.ctrl.FDF == 0))
{
newstep = RX_STEP_ID_EXT;
ch = 'T';
}else if ((rxObj.bF.ctrl.IDE == 0) && (rxObj.bF.ctrl.FDF == 0))
{
newstep = RX_STEP_ID_STD;
ch = 't';
}else if ((rxObj.bF.ctrl.IDE == 1) && (rxObj.bF.ctrl.FDF == 1)&& (rxObj.bF.ctrl.BRS == 0))
{
newstep = RX_STEP_ID_EXT;
ch = 'B';
}else if ((rxObj.bF.ctrl.IDE == 0) && (rxObj.bF.ctrl.FDF == 1)&& (rxObj.bF.ctrl.BRS == 0))
{
newstep = RX_STEP_ID_STD;
ch = 'b';
}
} else if (*step < RX_STEP_DLC) {
unsigned char i = *step - 1;
unsigned char * id_bp = (unsigned char*)&id; // rxObj.bF.id.SID;
ch = id_bp[3 - (i / 2)];
if ((i % 2) == 0) ch = ch >> 4;
ch = ch & 0xF;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
newstep++;
} else if (*step < RX_STEP_DATA) {
ch = rxObj.bF.ctrl.DLC;
ch = ch & 0xF;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
if (dlc ==0) newstep = RX_STEP_TIMESTAMP;
else newstep++;
} else if (*step < RX_STEP_TIMESTAMP) {
unsigned char i = *step - RX_STEP_DATA;
ch = rxd[i/2];
if ((i % 2) == 0) ch = ch >> 4;
ch = ch & 0xF;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
newstep++;
if (newstep - RX_STEP_DATA ==dlc*2) newstep = RX_STEP_TIMESTAMP;
} else if (timestamping && (*step < RX_STEP_CR)) {
unsigned char i = *step - RX_STEP_TIMESTAMP;
if ((i % 2) == 0) ch = ch >> 4;
ch = ch & 0xF;
if (ch > 9) ch = ch - 10 + 'A';
else ch = ch + '0';
newstep++;
} else {
ch = CR;
newstep = RX_STEP_FINISHED;
}
*step = newstep;
return ch;
}
void out_usb(void)
{
uint8_t dlc,i,rxstep;
uint8_t out_buff[200];
uint8_t outdata = 0;
uint32_t id = 0;
i =0;
rxstep = 0;
dlc = DRV_CANFDSPI_DlcToDataBytes((CAN_DLC)rxObj.bF.ctrl.DLC);
if(rxObj.bF.ctrl.IDE == 1)
{
id = (((uint32_t)rxObj.bF.id.SID) <<18) |rxObj.bF.id.EID;
}else
{
id = rxObj.bF.id.SID;
}
while( rxstep != RX_STEP_FINISHED)
{
outdata = canmsg2ascii_getNextChar(id, dlc, &rxstep);
out_buff[i++] =outdata;
}
out_buff[i] = 0; //Add null
Serial.print((char *)out_buff);
}
| 27.525959
| 115
| 0.454568
|
skpang
|
6e6d46d3f098ac9491d606ac53421d7ae2c024ce
| 13,964
|
cpp
|
C++
|
Nesis/Common/CanUnitInfo/MagSphereCalibration.cpp
|
jpoirier/x-gauges
|
8261b19a9678ad27db44eb8c354f5e66bd061693
|
[
"BSD-3-Clause"
] | 3
|
2015-11-08T07:17:46.000Z
|
2019-04-05T17:08:05.000Z
|
Nesis/Common/CanUnitInfo/MagSphereCalibration.cpp
|
jpoirier/x-gauges
|
8261b19a9678ad27db44eb8c354f5e66bd061693
|
[
"BSD-3-Clause"
] | null | null | null |
Nesis/Common/CanUnitInfo/MagSphereCalibration.cpp
|
jpoirier/x-gauges
|
8261b19a9678ad27db44eb8c354f5e66bd061693
|
[
"BSD-3-Clause"
] | null | null | null |
/***************************************************************************
* *
* Copyright (C) 2008 by Kanardia d.o.o. [see www.kanardia.eu] *
* Writen by: *
* Ales Krajnc [ales.krajnc@kanardia.eu] *
* *
* Status: Open Source *
* *
* Licence: GPL - GNU General Public License *
* See 'COPYING.html' for more details about the license. *
* *
***************************************************************************/
#include <QDebug>
#include <QDate>
#include <fstream>
#include "BestFit/AbstractBestFitLinear.h"
#include "GeoMag/GeoMagModel.h"
#include "JulianDay.h"
#include "MagSphereCalibration.h"
#define MIN_MAGU_RAW_DISTANCE 30
namespace can {
// ------------------------------------------------------------------------
MagSphereCalibration::MagSphereCalibration()
{
m_vS.SetAllTo(1.0f);
}
// ------------------------------------------------------------------------
int MagSphereCalibration::CreateRecord()
{
int id = m_conRecord.count();
m_conRecord.push_back(Record());
qDebug() << "Magu record" << id << "was created.";
return id;
}
// ------------------------------------------------------------------------
void MagSphereCalibration::UndoRecord()
{
if(!m_conRecord.isEmpty())
m_conRecord.pop_back();
}
// ------------------------------------------------------------------------
bool MagSphereCalibration::AddItem(int iRec, const V3f& v)
{
Q_ASSERT(iRec >= 0 && iRec < m_conRecord.count());
// Check all items in the record.
// This prevents forming groups on one spot.
bool bReject = false;
for(int i=0; i<m_conRecord[iRec].count(); i++) {
V3f x(v);
x.Subtract(m_conRecord[iRec][i]);
// Check if the new item is far enough from all other items in the record.
if(x.GetNorm() < MIN_MAGU_RAW_DISTANCE) {
bReject = true;
break;
}
}
if(bReject)
return false;
// Ok, we can accept new item.
m_conRecord[iRec].push_back(v);
// qDebug() << "vM =" << v[0] << v[1] << v[2];
return true;
}
// ------------------------------------------------------------------------
bool MagSphereCalibration::AddItem(const V3f& v)
{
return AddItem(m_conRecord.count()-1, v);
}
// ------------------------------------------------------------------------
using namespace bestfit;
class MagLinFit3D : public AbstractBestFitLinear
{
public:
MagLinFit3D() : AbstractBestFitLinear(6,3) {};
double CalcFunction(const Vec& vC, const common::VectorD& vD) const
{
smx::Vector<double, 6> vX;
CalcX(vD, vX);
return vC.Multiply(vX);
}
protected:
//! Calculate the "Xi" vector for best fit function for given vD data point.
virtual void CalcX(const common::VectorD& vM, smx::VectorBase<double>& vX) const
{
ASSERT(vX.GetSize() == m_vC.GetSize());
vX[0] = vM[1]*vM[1]; // my2 * A
vX[1] = vM[2]*vM[2]; // mz2 * B
vX[2] = vM[0]; // mx * C
vX[3] = vM[1]; // my * D
vX[4] = vM[2]; // my * E
vX[5] = 1.0; // 1 * F
}
//! The yi value out of the data.
double CalcY(const common::VectorD& vM) const
{ return -vM[0]*vM[0]; }
};
// ------------------------------------------------------------------------
class MagLinFit2D : public AbstractBestFitLinear
{
public:
MagLinFit2D() : AbstractBestFitLinear(4,2) {};
double CalcFunction(const Vec& vC, const common::VectorD& vD) const
{
smx::Vector<double, 4> vX;
CalcX(vD, vX);
return vC.Multiply(vX);
}
protected:
//! Calculate the "Xi" vector for best fit function for given vD data point.
virtual void CalcX(const common::VectorD& vM, smx::VectorBase<double>& vX) const
{
ASSERT(vX.GetSize() == m_vC.GetSize());
vX[0] = vM[1]*vM[1]; // my2 * A
vX[1] = vM[0]; // mx * B
vX[2] = vM[1]; // my * C
vX[3] = 1.0; // 1 * D
}
//! The yi value out of the data.
double CalcY(const common::VectorD& vM) const
{ return -vM[0]*vM[0]; }
};
// ------------------------------------------------------------------------
/*
using namespace numeric;
class MagNonFit3D : public BestFit
{
public:
//! Fit Compass constructor
MagNonFit3D(double dR) : BestFit(6) { m_dR=dR;}
//! The fit function. (vX are coefficients, and vData is x,y argument.)
double CalcFitFunction(const Vec& vX, const common::VectorD& vD) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& mz = vD[2];
const double& bx = vX[0];
const double& by = vX[1];
const double& bz = vX[2];
const double& sx = vX[3];
const double& sy = vX[4];
const double& sz = vX[5];
return -m_dR*m_dR + pow((mx-bx)/sx, 2) + pow((my-by)/sy, 2) + pow((mz-bz)/sz, 2);
}
//! The derivatives over coefficients.
void CalcFitDerivative(const Vec& vX, const common::VectorD& vD, Vec& vd) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& mz = vD[2];
const double& bx = vX[0];
const double& by = vX[1];
const double& bz = vX[2];
const double& sx = vX[3];
const double& sy = vX[4];
const double& sz = vX[5];
vd.Resize(m_uiUnknowns);
vd[0] = 2*(bx-mx)/(sx*sx);
vd[1] = 2*(by-my)/(sy*sy);
vd[2] = 2*(bz-mz)/(sz*sz);
vd[3] = (-2*pow(bx-mx,2))/pow(sx,3);
vd[4] = (-2*pow(by-my,2))/pow(sy,3);
vd[5] = (-2*pow(bz-mz,2))/pow(sz,3);
}
protected:
//! Radius
double m_dR;
};
// ------------------------------------------------------------------------
class MagNonFit2D : public BestFit
{
public:
//! Fit Compass constructor
MagNonFit2D(double dR) : BestFit(4) { m_dR=dR;}
//! The fit function. (vX are coefficients, and vData is x,y argument.)
double CalcFitFunction(const Vec& vX, const common::VectorD& vD) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& bx = vX[0];
const double& by = vX[1];
const double& sx = vX[2];
const double& sy = vX[3];
return -m_dR*m_dR + pow((mx-bx)/sx, 2) + pow((my-by)/sy, 2);
}
//! The derivatives over coefficients.
void CalcFitDerivative(const Vec& vX, const common::VectorD& vD, Vec& vd) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& bx = vX[0];
const double& by = vX[1];
const double& sx = vX[2];
const double& sy = vX[3];
vd.Resize(m_uiUnknowns);
vd[0] = 2*(bx-mx)/(sx*sx);
vd[1] = 2*(by-my)/(sy*sy);
vd[2] = (-2*pow(bx-mx,2))/pow(sx,3);
vd[3] = (-2*pow(by-my,2))/pow(sy,3);
}
protected:
//! Radius
double m_dR;
};
// ------------------------------------------------------------------------
class MagNonFitSqrt : public BestFit
{
public:
//! Fit Compass constructor
MagNonFitSqrt(double dR) : BestFit(6) { m_dR=dR;}
//! The fit function. (vX are coefficients, and vData is x,y argument.)
double CalcFitFunction(const Vec& vX, const common::VectorD& vD) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& mz = vD[2];
const double& bx = vX[0];
const double& by = vX[1];
const double& bz = vX[2];
const double& sx = vX[3];
const double& sy = vX[4];
const double& sz = vX[5];
return -m_dR + sqrt(pow((mx-bx)/sx, 2) + pow((my-by)/sy, 2) + pow((mz-bz)/sz, 2));
}
//! The derivatives over coefficients.
void CalcFitDerivative(const Vec& vX, const common::VectorD& vD, Vec& vd) const
{
const double& mx = vD[0];
const double& my = vD[1];
const double& mz = vD[2];
const double& bx = vX[0];
const double& by = vX[1];
const double& bz = vX[2];
const double& sx = vX[3];
const double& sy = vX[4];
const double& sz = vX[5];
vd.Resize(m_uiUnknowns);
double A = sqrt(pow((mx-bx)/sx, 2) + pow((my-by)/sy, 2) + pow((mz-bz)/sz, 2));
vd[0] = 2*(bx-mx)/(sx*sx*A);
vd[1] = 2*(by-my)/(sy*sy*A);
vd[2] = 2*(bz-mz)/(sz*sz*A);
vd[3] = (-2*pow(bx-mx,2))/(A*pow(sx,3));
vd[4] = (-2*pow(by-my,2))/(A*pow(sy,3));
vd[5] = (-2*pow(bz-mz,2))/(A*pow(sz,3));
}
protected:
//! Radius
double m_dR;
};
*/
// ------------------------------------------------------------------------
bool MagSphereCalibration::Solve(float fLon, float fLat, float fAlt_km)
{
using namespace common;
// We need the geomag model for today and given geographic position.
GeoMagModel gmm;
JulianDay jd(QDate::currentDate().toJulianDay());
gmm.SetDate(jd.GetDateAsDecimalYear());
gmm.Evaluate(fLat, fLon, fAlt_km);
// We need total radius and xy-plane radius.
float fRxy = sqrt(pow(gmm.GetX(),2) + pow(gmm.GetY(),2));
float fR, fI, fD;
gmm.CalcIDH(fI, fD, fR);
// Show some results
qDebug() << "Total Earth magnetic field strenth" << fR;
qDebug() << "XY plane Earth magnetic field strenth" << fRxy;
qDebug() << "Inclination =" << Deg(fI) << ", declination =" << Deg(fD);
VectorD vX(3);
MagLinFit3D mlf3D;
MagLinFit2D mlf2D;
// MagNonFit2D mnf2D(fRxy);
// Merge the data and output the mathematica version
std::ofstream out("MagSphereData.txt");
for(int r=0; r<m_conRecord.count(); r++) {
out << "\nPts" << r+1 << " = {\n";
for(int i=0; i<m_conRecord[r].count(); i++) {
mlf3D.AddData(m_conRecord[r][i]);
// The first data record MUST be the xy plane. We take x and y only.
if(r==0) {
mlf2D.AddData(
m_conRecord[r][i][0], // x
m_conRecord[r][i][1] // y
);
/* mnf2D.AddData(
m_conRecord[r][i][0], // x
m_conRecord[r][i][1] // y
);*/
}
out << "{"
<< m_conRecord[r][i][0] << ","
<< m_conRecord[r][i][1] << ","
<< m_conRecord[r][i][2];
if(i==m_conRecord[r].count()-1)
out << "}";
else
out << "},";
}
out << "};\n";
}
out.close();
// The linear LSM
bool bSuccess3D = mlf3D.Solve();
// Convert resulting LMS parameters into meaningful 3D results.
const smx::VectorBase<double>& vC = mlf3D.GetParameters();
double fBx3, fBy3, fBz3, fSx3, fSy3, fSz3;
fBx3 = -vC[2]/2;
fBy3 = -vC[3]/(2*vC[0]);
fBz3 = -vC[4]/(2*vC[1]);
fSx3 = (fBx3*fBx3 + vC[0]*fBy3*fBy3 + vC[1]*fBz3*fBz3 - vC[5])/(fR*fR);
fSy3 = fSx3/vC[0];
fSz3 = fSx3/vC[1];
fSx3 = sqrt(fSx3);
fSy3 = sqrt(fSy3);
fSz3 = sqrt(fSz3);
// Now, get the 2D linear LSM solution.
bool bSuccess2D = mlf2D.Solve();
// Convert resulting parameters into 2D results.
const smx::VectorBase<double>& vE = mlf2D.GetParameters();
double fBx2, fBy2, fSx2, fSy2;
fBx2 = -vE[1]/2;
fBy2 = -vE[2]/(2*vE[0]);
fSx2 = (fBx2*fBx2 + vE[0]*fBy2*fBy2 - vE[3])/(fRxy*fRxy);
fSy2 = fSx2/vE[0];
fSx2 = sqrt(fSx2);
fSy2 = sqrt(fSy2);
// Store results in a bit unusual way.
// x and y values are taken from 2D solution, while the z values are
// taken from 3D solution.
m_vB[0] = fBx2;
m_vB[1] = fBy2;
m_vB[2] = fBz3;
m_vS[0] = fSx2;
m_vS[1] = fSy2;
m_vS[2] = fSz3;
qDebug() << "Linear 3D solution:"
<< fBx3 << fBy3 << fBz3 << fSx3 << fSy3 << fSz3;
qDebug() << "Linear 2D solution:"
<< fBx2 << fBy2 << fSx2 << fSy2;
// Nonliear 2D solution
/* BestFit::Vec vY2(4);
vY2[0] = fBx3;
vY2[1] = fBy3;
vY2[2] = fSx3;
vY2[3] = fSy3;
FitSolverLevenbergMarquard fslm2;
FitSolverLevenbergMarquard::StoppingCriterion sc;
sc = fslm2.Solve(mnf2D, vY2);
qDebug() << "Nonlinear 2D solution:"
<< vY2[0] << vY2[1] << vY2[2] << vY2[3];
m_vB[0] = vY2[0];
m_vB[1] = vY2[1];
m_vS[0] = vY2[2];
m_vS[1] = vY2[3];
// Nonlinear solutions
MagNonFit3D mnf(fR);
// Kontrola
const AbstractBestFit::Data& mD = mlf3D.GetData();
for(unsigned int i=0; i<mD.size(); i++) {
float fmx = mD[i][0];
float fmy = mD[i][1];
float fmz = mD[i][2];
fmx = (fmx - fBx3)/fSx3;
fmy = (fmy - fBy3)/fSy3;
fmz = (fmz - fBz3)/fSz3;
float fRC = sqrt(fmx*fmx + fmy*fmy + fmz*fmz);
mnf.AddData(mD[i]);
}
qDebug() << "Second stage" << mnf.GetData().size() << "items";
BestFit::Vec vY(6);
vY[0] = fBx3;
vY[1] = fBy3;
vY[2] = fBz3;
vY[3] = fSx3;
vY[4] = fSy3;
vY[5] = fSz3;
FitSolverLevenbergMarquard fslm;
//FitSolverLevenbergMarquard::StoppingCriterion sc;
sc = fslm.Solve(mnf, vY);
qDebug() << "Nonlinear 3D solution:"
<< vY[0] << vY[1] << vY[2] << vY[3] << vY[4] << vY[5];*/
/* m_vB[0] = vY[0];
m_vB[1] = vY[1];
m_vB[2] = vY[2];
m_vS[0] = vY[3];
m_vS[1] = vY[4];
m_vS[2] = vY[5];*/
// Kontrola
/* const BestFit::Data& mD2 = mnf.GetData();
for(unsigned int i=0; i<mD2.size(); i++) {
float fmx = mD2[i][0];
float fmy = mD2[i][1];
float fmz = mD2[i][2];
fmx = (fmx - fBx3)/fSx3;
fmy = (fmy - fBy3)/fSy3;
fmz = (fmz - fBz3)/fSz3;
float fRC = sqrt(fmx*fmx + fmy*fmy + fmz*fmz);
// qDebug() << i << ":" << fmx << fmy << fmz << fRC << fabs(fR-fRC);
}*/
/* qDebug() << "Final solution:"
<< m_vB[0] << m_vB[1] << m_vB[2]
<< m_vS[0] << m_vS[1] << m_vS[2];*/
return bSuccess3D && bSuccess2D;
}
// ------------------------------------------------------------------------
void MagSphereCalibration::VerifyItem(
const V3f& v, //!< Raw magnetic field sensor reading.
float fRoll, //!< Roll angle
float fPitch //!< Pitch angle
)
{
// Get "true" magnetic vector.
V3f m = v;
m.Subtract(m_vB);
for(int i=0; i<3; i++)
m[i]/=m_vS[i];
// Calculate heading - use pitch and roll correction.
// Convert magnetic sensor values into xy plane first.
float fSinR, fCosR; // Roll
float fSinP, fCosP; // Pitch
// XXX:
// sincosf(fRoll, &fSinR, &fCosR);
// sincosf(fPitch, &fSinP, &fCosP);
// We will uses sensor values ...
float fXh = m[0]*fCosP + m[1]*fSinR*fSinP + m[2]*fCosR*fSinP;
float fYh = m[1]*fCosR - m[2]*fSinR;
qDebug("Xh = %f, Yh = %f", fXh, fYh);
// Now, calculate heading ...
float fYaw = -common::ATan2Safe(m[1],m[0]);
if(fYaw < 0)
fYaw += M_PI*2;
qDebug("Yaw = %f", common::Deg(fYaw));
}
// ------------------------------------------------------------------------
} // namespace
| 27.488189
| 84
| 0.533228
|
jpoirier
|
6e6e458bc3694dd2c6548bebe2889912422c33d2
| 143
|
cpp
|
C++
|
examples/polar_plots/ezpolar/ezpolar_1.cpp
|
solosuper/matplotplusplus
|
87ff5728b14ad904bc6acaa2bf010c1a03c6cb4a
|
[
"MIT"
] | 2,709
|
2020-08-29T01:25:40.000Z
|
2022-03-31T18:35:25.000Z
|
examples/polar_plots/ezpolar/ezpolar_1.cpp
|
p-ranav/matplotplusplus
|
b45015e2be88e3340b400f82637b603d733d45ce
|
[
"MIT"
] | 124
|
2020-08-29T04:48:17.000Z
|
2022-03-25T15:45:59.000Z
|
examples/polar_plots/ezpolar/ezpolar_1.cpp
|
p-ranav/matplotplusplus
|
b45015e2be88e3340b400f82637b603d733d45ce
|
[
"MIT"
] | 203
|
2020-08-29T04:16:22.000Z
|
2022-03-30T02:08:36.000Z
|
#include <cmath>
#include <matplot/matplot.h>
int main() {
using namespace matplot;
ezpolar("1+cos(t)");
show();
return 0;
}
| 13
| 28
| 0.594406
|
solosuper
|
6e7672a2b632a5a3c092e701bccec80007eaa4b7
| 16,329
|
cpp
|
C++
|
vision/blackItem/image_converter.cpp
|
Eithwa/kymavoid
|
2cd099021f111aa342c3f655c0eee06f9e2e3f2a
|
[
"Apache-2.0"
] | null | null | null |
vision/blackItem/image_converter.cpp
|
Eithwa/kymavoid
|
2cd099021f111aa342c3f655c0eee06f9e2e3f2a
|
[
"Apache-2.0"
] | null | null | null |
vision/blackItem/image_converter.cpp
|
Eithwa/kymavoid
|
2cd099021f111aa342c3f655c0eee06f9e2e3f2a
|
[
"Apache-2.0"
] | 1
|
2020-08-10T03:19:27.000Z
|
2020-08-10T03:19:27.000Z
|
#include "image_converter.hpp"
#include "math.h"
#include "omp.h"
using namespace std;
using namespace cv;
const double ALPHA = 0.5;
ImageConverter::ImageConverter():
it_(nh),
FrameRate(0.0),
obj_filter_size(500)
{
get_Camera();
get_center();
get_distance();
get_whitedata();
image_sub_ = it_.subscribe("/camera/image_raw", 1, &ImageConverter::imageCb, this);
black_pub = nh.advertise<std_msgs::Int32MultiArray>("/vision/BlackRealDis", 1);
red_pub = nh.advertise<std_msgs::Int32MultiArray>("/vision/redRealDis", 1);
mpicture = nh.advertise<vision::visionlook>("/vision/picture_m", 1);
double ang_PI;
for (int ang = 0; ang < 360; ang++)
{
ang_PI = ang * M_PI / 180;
Angle_sin.push_back(sin(ang_PI));
Angle_cos.push_back(cos(ang_PI));
}
}
ImageConverter::~ImageConverter()
{
}
int Frame_area(int num, int range)
{
if (num < 0)
num = 0;
else if (num >= range)
num = range - 1;
return num;
}
void ImageConverter::imageCb(const sensor_msgs::ImageConstPtr &msg)
{
cv_bridge::CvImagePtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvCopy(msg, enc::BGR8);
cv::flip(cv_ptr->image, Main_frame, 1);
Black_Mask = Main_frame.clone();
Red_Mask = Main_frame.clone();
static double StartTime = ros::Time::now().toSec();
double EndTime = ros::Time::now().toSec();
if(EndTime-StartTime>2){
get_Camera();
get_center();
get_distance();
get_whitedata();
StartTime = EndTime;
}
#pragma omp parallel sections
{
#pragma omp section
{
//================Black obstacle detection========
black_binarization();
black_filter();
black_item();
}
#pragma omp section
{
//================Red line detection==============
red_binarization();
red_line();
}
}
cv::imshow("black_item", Black_Mask);
cv::imshow("red_line", Red_Mask);
cv::waitKey(1);
//=======================FPS======================
FrameRate = Rate();
//================================================
}
catch (cv_bridge::Exception &e)
{
ROS_ERROR("cv_bridge exception: %s", e.what());
return;
}
}
double ImageConverter::Rate()
{
double ALPHA = 0.5;
double dt;
static int frame_counter = 0;
static double frame_rate = 0.0;
static double StartTime = ros::Time::now().toNSec();
double EndTime;
frame_counter++;
if (frame_counter == 10)
{
EndTime = ros::Time::now().toNSec();
dt = (EndTime - StartTime) / frame_counter;
StartTime = EndTime;
if (dt != 0)
{
frame_rate = (1000000000.0 / dt) * ALPHA + frame_rate * (1.0 - ALPHA);
//cout << "FPS: " << frame_rate << endl;
}
frame_counter = 0;
}
return frame_rate;
}
void ImageConverter::black_binarization()
{
int gray_count = 0;
gray_ave = 0;
for (int i = 0; i < Main_frame.rows; i++)
{
for (int j = 0; j < Main_frame.cols; j++)
{
unsigned char gray = (Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 0]
+ Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 1]
+ Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 2]) / 3;
if (gray < black_gray)
{
gray_ave += gray;
gray_count++;
}
}
}
gray_count = (gray_count == 0) ? 0.00001 : gray_count;
gray_ave = gray_ave / gray_count;
for (int i = 0; i < Main_frame.rows; i++)
{
for (int j = 0; j < Main_frame.cols; j++)
{
unsigned char gray = (Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 0]
+ Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 1]
+ Main_frame.data[(i * Main_frame.cols * 3) + (j * 3) + 2]) / 3;
if (gray < black_gray - (setgray - gray_ave))
{
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 0] = 0;
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 1] = 0;
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 2] = 0;
}
else
{
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 0] = 255;
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 1] = 255;
Black_Mask.data[(i * Black_Mask.cols * 3) + (j * 3) + 2] = 255;
}
}
}
}
class Coord
{
public:
Coord(int x_, int y_) : x(x_), y(y_) {}
Coord operator+(const Coord &addon) const { return Coord(x + addon.x, y + addon.y); }
int get_x() const { return x; }
int get_y() const { return y; }
private:
int x, y;
};
Coord directions[8] = {
Coord(0, 1),
Coord(0, -1),
Coord(-1, 0),
Coord(1, 0),
Coord(-1, 1),
Coord(1, 1),
Coord(-1, -1),
Coord(1, -1)};
bool is_black(Mat &img, const Coord &c)
{
if(img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 0] == 0
&&img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 1] == 0
&&img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 2] == 0)
{
return true;
}else{
return false;
}
}
void is_checked(Mat &img, const Coord &c){
img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 0] = 255;
img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 1] = 255;
img.data[(c.get_y() * img.cols + c.get_x()) * 3 + 2] = 255;
}
Mat convertTo3Channels(const Mat &binImg)
{
Mat three_channel = Mat::zeros(binImg.rows, binImg.cols, CV_8UC3);
vector<Mat> channels;
for (int i = 0; i < 3; i++)
{
channels.push_back(binImg);
}
merge(channels, three_channel);
return three_channel;
}
void ImageConverter::black_filter()
{
int inner = center_inner, outer = center_outer, centerx = center_x, centery = center_y;
int detection_range = (inner+outer)/2;
int width = Black_Mask.cols-1, length = Black_Mask.rows-1;
int obj_size = obj_filter_size;
vector<vector<Coord> > obj; //物件列表
Mat check_map = Mat(Size(Black_Mask.cols, Black_Mask.rows), CV_8UC3, Scalar(0, 0, 0));//確認搜尋過的pix
//inner中心塗白 outer切斷與外面相連黑色物體
circle(Black_Mask, Point(centerx, centery), inner, Scalar(255, 255, 255), -1);
circle(Black_Mask, Point(centerx, centery), outer, Scalar(255, 0, 0), 2);
//搜尋範圍顯示
circle(Black_Mask, Point(centerx, centery), detection_range, Scalar(255, 0, 0), 1);
//rectangle(Black_Mask, Point(centerx - detection_range, centery - detection_range), Point(centerx + detection_range, centery + detection_range), Scalar(255, 0, 0), 1);
//選取的範圍做搜尋
//0為黑
for (int i = centerx - detection_range; i < centerx + detection_range; i++)
{
for (int j = centery - detection_range; j < centery + detection_range; j++)
{
//std::cout << i << " " << j << std::endl;
if(hypot(centerx-i,centery-j)>detection_range) continue;
if (is_black(check_map,Coord(i, j)))
{
is_checked(check_map,Coord(i, j));
if (is_black(Black_Mask, Coord(i, j)))
{
queue<Coord> bfs_list;
bfs_list.push(Coord(i, j));
vector<Coord> dot;
dot.push_back(Coord(i, j));
//放入佇列
while (!bfs_list.empty())
{
Coord ori = bfs_list.front();
bfs_list.pop();
//搜尋八方向
for (int k = 0; k < 8; k++)
{
Coord dst = ori + directions[k];
//處理邊界
if ((dst.get_x() < 0) || (dst.get_x() >= width) || (dst.get_y() < 0) || (dst.get_y() >= length)) continue;
if(hypot(centerx-dst.get_x(),centery-dst.get_y())>outer) continue;
if (!is_black(check_map,Coord(dst.get_x(), dst.get_y()))) continue;
if (is_black(Black_Mask, dst))
{
bfs_list.push(dst);
dot.push_back(dst);
}
is_checked(check_map,Coord(dst.get_x(), dst.get_y()));
}
}
obj.push_back(dot);
}
}
}
}
//上色
for (int i = 0; i < obj.size(); i++)
{
//需要塗色的物體大小
if (obj[i].size() > obj_size) continue;
for (int j = 0; j < obj[i].size(); j++)
{
Coord point = obj[i][j];
line(Black_Mask, Point(point.get_x(), point.get_y()), Point(point.get_x(), point.get_y()), Scalar(255, 0, 255), 1);
}
}
//cv::imshow("black filter", Black_Mask);
//cv::waitKey(1);
}
void ImageConverter::black_item()
{
int object_dis;
blackItem_pixel.clear();
BlackRealDis.data.clear();
Mat binarization_map = Black_Mask.clone();
for (int angle = 0; angle < 360; angle = angle + black_angle)
{
int angle_be = angle + center_front;
if (angle_be >= 360)
angle_be -= 360;
double x_ = Angle_cos[angle_be];
double y_ = Angle_sin[angle_be];
for (int r = center_inner - 1; r <= center_outer; r++)
{
int dis_x = x_ * r;
int dis_y = y_ * r;
int image_x = Frame_area(center_x + dis_x, binarization_map.cols);
int image_y = Frame_area(center_y - dis_y, binarization_map.rows);
if (binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 0] == 0
&& binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 1] == 0
&& binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 2] == 0)
{
blackItem_pixel.push_back(hypot(dis_x, dis_y));
break;
}
else
{
Black_Mask.data[(image_y * Black_Mask.cols + image_x) * 3 + 0] = 0;
Black_Mask.data[(image_y * Black_Mask.cols + image_x) * 3 + 1] = 0;
Black_Mask.data[(image_y * Black_Mask.cols + image_x) * 3 + 2] = 255;
}
if (r == center_outer)
{
blackItem_pixel.push_back(hypot(dis_x, dis_y));
}
}
}
//ROS_INFO("%d , blackangle=%d",blackItem_pixel.size(),black_angle);
for (int j = 0; j < blackItem_pixel.size(); j++)
{
object_dis = Omni_distance(blackItem_pixel[j]);
BlackRealDis.data.push_back(object_dis);
}
black_pub.publish(BlackRealDis);
//cv::imshow("black_item", Black_Mask);
//cv::waitKey(1);
}
void ImageConverter::red_binarization()
{
Mat inputMat = Red_Mask.clone();
Mat hsv(inputMat.rows, inputMat.cols, CV_8UC3, Scalar(0, 0, 0));
Mat mask(inputMat.rows, inputMat.cols, CV_8UC1, Scalar(0, 0, 0));
Mat mask2(inputMat.rows, inputMat.cols, CV_8UC1, Scalar(0, 0, 0));
Mat dst(inputMat.rows, inputMat.cols, CV_8UC3, Scalar(0, 0, 0));
Mat white(inputMat.rows, inputMat.cols, CV_8UC3, Scalar(255, 255, 255));
int hmin, hmax, smin, smax, vmin, vmax;
cvtColor(inputMat, hsv, CV_BGR2HSV);
hmax = double(red[0]*0.5);
hmin = double(red[1]*0.5);
smax = red[2];
smin = red[3];
vmax = red[4];
vmin = red[5];
if (red[0] >= red[1])
{
inRange(hsv, Scalar(hmin, smin, vmin), Scalar(hmax, smax, vmax), mask);
}
else
{
inRange(hsv, Scalar(hmin, smin, vmin), Scalar(255, smax, vmax), mask);
inRange(hsv, Scalar(0, smin, vmin), Scalar(hmax, smax, vmax), mask2);
mask = mask + mask2;
}
convertTo3Channels(mask);
//開操作 (去除一些噪點)
Mat element = getStructuringElement(MORPH_RECT, Size(2, 2));
morphologyEx(mask, mask, MORPH_OPEN, element);
white.copyTo(dst, (cv::Mat::ones(mask.size(), mask.type()) * 255 - mask));
Red_Mask = dst;
///////////////////Show view/////////////////
//cv::imshow("dst", dst);
//cv::imshow("Red_Mask", Red_Mask);
//cv::waitKey(1);
/////////////////////////////////////////////
}
void ImageConverter::red_line()
{
int object_dis;
redItem_pixel.clear();
redRealDis.data.clear();
Mat binarization_map = Red_Mask.clone();
for (int angle = 0; angle < 360; angle = angle + black_angle)
{
int angle_be = angle + center_front;
if (angle_be >= 360)
angle_be -= 360;
double x_ = Angle_cos[angle_be];
double y_ = Angle_sin[angle_be];
for (int r = center_inner; r <= center_outer; r++)
{
int dis_x = x_ * r;
int dis_y = y_ * r;
int image_x = Frame_area(center_x + dis_x, binarization_map.cols);
int image_y = Frame_area(center_y - dis_y, binarization_map.rows);
if (binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 0] == 0
&& binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 1] == 0
&& binarization_map.data[(image_y * binarization_map.cols + image_x) * 3 + 2] == 0)
{
redItem_pixel.push_back(hypot(dis_x, dis_y));
break;
}
else
{
Red_Mask.data[(image_y * Red_Mask.cols + image_x) * 3 + 0] = 0;
Red_Mask.data[(image_y * Red_Mask.cols + image_x) * 3 + 1] = 0;
Red_Mask.data[(image_y * Red_Mask.cols + image_x) * 3 + 2] = 255;
}
if (r == center_outer)
{
redItem_pixel.push_back(hypot(dis_x, dis_y));
}
}
}
for (int j = 0; j < redItem_pixel.size(); j++)
{
object_dis = Omni_distance(redItem_pixel[j]);
redRealDis.data.push_back(object_dis);
}
red_pub.publish(redRealDis);
to_strategy.mpicture++;
to_strategy.gray_ave = gray_ave;
mpicture.publish(to_strategy);
///////////////////Show view/////////////////
//cv::imshow("red_line", Red_Mask);
//cv::waitKey(1);
/////////////////////////////////////////////
}
double ImageConverter::Omni_distance(double dis_pixel)
{
double Z = -1 * Camera_H;
double c = 83.125;
double b = c * 0.8722;
double f = Camera_f;
double dis;
//double pixel_dis = sqrt(pow(object_x,2)+pow(object_y,2));
double pixel_dis = dis_pixel;
double r = atan2(f, pixel_dis * 0.0099);
dis = Z * (pow(b, 2) - pow(c, 2)) * cos(r) / ((pow(b, 2) + pow(c, 2)) * sin(r) - 2 * b * c);
if (dis / 10 < 0 || dis / 10 > 999)
{
dis = 9990;
}
return dis / 10;
}
void ImageConverter::get_center()
{
nh.setParam("/FIRA/gray_ave", gray_ave);
nh.getParam("/AvoidChallenge/GraySet", setgray);
nh.getParam("/FIRA/Center/X", center_x);
nh.getParam("/FIRA/Center/Y", center_y);
nh.getParam("/FIRA/Center/Inner", center_inner);
nh.getParam("/FIRA/Center/Outer", center_outer);
nh.getParam("/FIRA/Center/Front", center_front);
}
void ImageConverter::get_distance()
{
nh.getParam("/FIRA/Distance/Gap", dis_gap);
nh.getParam("/FIRA/Distance/Space", dis_space);
nh.getParam("/FIRA/Distance/Pixel", dis_pixel);
}
void ImageConverter::get_Camera()
{
nh.getParam("/FIRA/Camera/High", Camera_H);
nh.getParam("/FIRA/Camera/Focal", Camera_f);
}
void ImageConverter::get_whitedata()
{
red.clear();
if (nh.hasParam("/FIRA/blackItem/obj_filter_size"))
{
nh.getParam("/FIRA/blackItem/obj_filter_size", obj_filter_size);
}
nh.getParam("/FIRA/blackItem/gray", black_gray);
nh.getParam("/FIRA/blackItem/angle", black_angle);
nh.getParam("/FIRA/HSV/Redrange", red);
//std::cout<<red[0]<<" "<<red[1]<<" "<<red[2]<<" "<<red[3]<<" "<<red[4]<<" "<<red[5]<<std::endl;
}
| 32.334653
| 172
| 0.519873
|
Eithwa
|
6e797c232267aa24a883602c87355ef60000f3c7
| 5,818
|
cc
|
C++
|
src/d3d11/d3d11_main.cc
|
R2Northstar/NorthstarStubs
|
e60bba45092f7fdb70b60c0e2e920584f78f1b85
|
[
"Zlib"
] | 3
|
2022-02-17T03:11:52.000Z
|
2022-02-20T21:20:16.000Z
|
src/d3d11/d3d11_main.cc
|
pg9182/NorthstarStubs
|
e60bba45092f7fdb70b60c0e2e920584f78f1b85
|
[
"Zlib"
] | null | null | null |
src/d3d11/d3d11_main.cc
|
pg9182/NorthstarStubs
|
e60bba45092f7fdb70b60c0e2e920584f78f1b85
|
[
"Zlib"
] | 2
|
2022-02-17T14:04:09.000Z
|
2022-02-20T17:52:55.000Z
|
#include "d3d11_device.h"
#include "dxgi_factory.h"
#include "d3d11_include.h"
extern "C" {
using namespace dxvk;
DLLEXPORT HRESULT __stdcall D3D11CoreCreateDevice(
IDXGIFactory* pFactory,
IDXGIAdapter* pAdapter,
UINT Flags,
const D3D_FEATURE_LEVEL* pFeatureLevels,
UINT FeatureLevels,
ID3D11Device** ppDevice) {
InitReturnPtr(ppDevice);
D3D_FEATURE_LEVEL defaultFeatureLevels[] = {
D3D_FEATURE_LEVEL_11_0,
};
if (pFeatureLevels == nullptr || FeatureLevels == 0) {
pFeatureLevels = defaultFeatureLevels,
FeatureLevels = sizeof(defaultFeatureLevels) / sizeof(*defaultFeatureLevels);
}
UINT flId;
for (flId = 0 ; flId < FeatureLevels; flId++) {
if (pFeatureLevels[flId] == D3D_FEATURE_LEVEL_11_1 || pFeatureLevels[flId] == D3D_FEATURE_LEVEL_11_0)
break;
}
if (flId == FeatureLevels) {
DXVK_LOG_FUNC("err", "Requested feature level not supported");
return E_INVALIDARG;
}
// Try to create the device with the given parameters.
const D3D_FEATURE_LEVEL fl = pFeatureLevels[flId];
Com<D3D11DXGIDevice> device = new D3D11DXGIDevice(pAdapter, fl, Flags);
return device->QueryInterface(__uuidof(ID3D11Device), reinterpret_cast<void**>(ppDevice));
}
static HRESULT D3D11InternalCreateDeviceAndSwapChain(
IDXGIAdapter* pAdapter,
D3D_DRIVER_TYPE DriverType,
HMODULE Software,
UINT Flags,
const D3D_FEATURE_LEVEL* pFeatureLevels,
UINT FeatureLevels,
UINT SDKVersion,
const DXGI_SWAP_CHAIN_DESC* pSwapChainDesc,
IDXGISwapChain** ppSwapChain,
ID3D11Device** ppDevice,
D3D_FEATURE_LEVEL* pFeatureLevel,
ID3D11DeviceContext** ppImmediateContext) {
InitReturnPtr(ppDevice);
InitReturnPtr(ppSwapChain);
InitReturnPtr(ppImmediateContext);
if (pFeatureLevel)
*pFeatureLevel = D3D_FEATURE_LEVEL(0);
HRESULT hr;
Com<IDXGIFactory> dxgiFactory = nullptr;
Com<IDXGIAdapter> dxgiAdapter = pAdapter;
Com<ID3D11Device> device = nullptr;
if (ppSwapChain && !pSwapChainDesc)
return E_INVALIDARG;
if (!pAdapter) {
hr = (new DxgiFactory(0))->QueryInterface(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgiFactory));
if (FAILED(hr)) {
DXVK_LOG_FUNC("err", "Failed to create a DXGI factory");
return hr;
}
hr = dxgiFactory->EnumAdapters(0, &dxgiAdapter);
if (FAILED(hr)) {
DXVK_LOG_FUNC("err", "No default adapter available");
return hr;
}
} else {
if (FAILED(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgiFactory)))) {
DXVK_LOG_FUNC("err", "Failed to query DXGI factory from DXGI adapter");
return E_INVALIDARG;
}
if (DriverType != D3D_DRIVER_TYPE_UNKNOWN || Software)
return E_INVALIDARG;
}
hr = D3D11CoreCreateDevice(
dxgiFactory.ptr(), dxgiAdapter.ptr(),
Flags, pFeatureLevels, FeatureLevels,
&device);
if (FAILED(hr))
return hr;
// Create the swap chain, if requested
if (ppSwapChain) {
DXGI_SWAP_CHAIN_DESC desc = *pSwapChainDesc;
hr = dxgiFactory->CreateSwapChain(device.ptr(), &desc, ppSwapChain);
if (FAILED(hr)) {
DXVK_LOG_FUNC("err", "Failed to create swap chain");
return hr;
}
}
// Write back whatever info the application requested
if (pFeatureLevel)
*pFeatureLevel = device->GetFeatureLevel();
if (ppDevice)
*ppDevice = device.ref();
if (ppImmediateContext)
device->GetImmediateContext(ppImmediateContext);
// If we were unable to write back the device and the
// swap chain, the application has no way of working
// with the device so we should report S_FALSE here.
if (!ppDevice && !ppImmediateContext && !ppSwapChain)
return S_FALSE;
return S_OK;
}
DLLEXPORT HRESULT __stdcall D3D11CreateDevice(
IDXGIAdapter* pAdapter,
D3D_DRIVER_TYPE DriverType,
HMODULE Software,
UINT Flags,
const D3D_FEATURE_LEVEL* pFeatureLevels,
UINT FeatureLevels,
UINT SDKVersion,
ID3D11Device** ppDevice,
D3D_FEATURE_LEVEL* pFeatureLevel,
ID3D11DeviceContext** ppImmediateContext) {
DXVK_LOG("D3D11CreateDevice", "initializing d3d11 stub for northstar (github.com/R2Northstar/NorthstarStubs)");
return D3D11InternalCreateDeviceAndSwapChain(
pAdapter, DriverType, Software, Flags,
pFeatureLevels, FeatureLevels, SDKVersion,
nullptr, nullptr,
ppDevice, pFeatureLevel, ppImmediateContext);
}
DLLEXPORT HRESULT __stdcall D3D11CreateDeviceAndSwapChain(
IDXGIAdapter* pAdapter,
D3D_DRIVER_TYPE DriverType,
HMODULE Software,
UINT Flags,
const D3D_FEATURE_LEVEL* pFeatureLevels,
UINT FeatureLevels,
UINT SDKVersion,
const DXGI_SWAP_CHAIN_DESC* pSwapChainDesc,
IDXGISwapChain** ppSwapChain,
ID3D11Device** ppDevice,
D3D_FEATURE_LEVEL* pFeatureLevel,
ID3D11DeviceContext** ppImmediateContext) {
return D3D11InternalCreateDeviceAndSwapChain(
pAdapter, DriverType, Software, Flags,
pFeatureLevels, FeatureLevels, SDKVersion,
pSwapChainDesc, ppSwapChain,
ppDevice, pFeatureLevel, ppImmediateContext);
}
}
| 32.502793
| 115
| 0.630113
|
R2Northstar
|
6e7acaaeb160f14ee94a4b522c3d80999863bbcf
| 2,197
|
cpp
|
C++
|
test/unittests/test_parser.cpp
|
SmaranTum/syrec
|
7fd0eece4c3376e52c1f5f17add71a49e5826dac
|
[
"MIT"
] | 1
|
2022-03-19T21:51:58.000Z
|
2022-03-19T21:51:58.000Z
|
test/unittests/test_parser.cpp
|
SmaranTum/syrec
|
7fd0eece4c3376e52c1f5f17add71a49e5826dac
|
[
"MIT"
] | 9
|
2022-02-28T17:03:50.000Z
|
2022-03-25T16:02:39.000Z
|
test/unittests/test_parser.cpp
|
cda-tum/syrec
|
43dcdd997edd02c80304f53f66118f9dd0fc5f68
|
[
"MIT"
] | 2
|
2022-02-02T10:35:09.000Z
|
2022-02-02T15:52:24.000Z
|
#include "core/syrec/program.hpp"
#include "gtest/gtest.h"
using namespace syrec;
class SyrecParserTest: public testing::TestWithParam<std::string> {
protected:
std::string test_circuits_dir = "./circuits/";
std::string file_name;
void SetUp() override {
file_name = test_circuits_dir + GetParam() + ".src";
}
};
INSTANTIATE_TEST_SUITE_P(SyrecParserTest, SyrecParserTest,
testing::Values(
"alu_2",
"binary_numeric",
"bitwise_and_2",
"bitwise_or_2",
"bn_2",
"call_8",
"divide_2",
"for_4",
"for_32",
"gray_binary_conversion_16",
"input_repeated_2",
"input_repeated_4",
"logical_and_1",
"logical_or_1",
"modulo_2",
"multiply_2",
"negate_8",
"numeric_2",
"operators_repeated_4",
"parity_4",
"parity_check_16",
"shift_4",
"simple_add_2",
"single_longstatement_4",
"skip",
"swap_2"),
[](const testing::TestParamInfo<SyrecParserTest::ParamType>& info) {
auto s = info.param;
std::replace( s.begin(), s.end(), '-', '_');
return s; });
TEST_P(SyrecParserTest, GenericParserTest) {
program prog;
read_program_settings settings;
std::string error_string;
error_string = prog.read(file_name, settings);
EXPECT_TRUE(error_string.empty());
}
| 38.54386
| 93
| 0.383705
|
SmaranTum
|
6e7e54b9a9a38df535c5340485638e5c4fe83116
| 1,820
|
hpp
|
C++
|
include/header.hpp
|
Skvortsovvv/lab-05-stack-Skvortsovvv
|
e658a314c8a729dc024daba28dbd585c21987526
|
[
"MIT"
] | null | null | null |
include/header.hpp
|
Skvortsovvv/lab-05-stack-Skvortsovvv
|
e658a314c8a729dc024daba28dbd585c21987526
|
[
"MIT"
] | null | null | null |
include/header.hpp
|
Skvortsovvv/lab-05-stack-Skvortsovvv
|
e658a314c8a729dc024daba28dbd585c21987526
|
[
"MIT"
] | null | null | null |
// Copyright 2020 Your Name <your_email>
#ifndef INCLUDE_HEADER_HPP_
#define INCLUDE_HEADER_HPP_
#include <memory>
#include <atomic>
#include <type_traits>
#include <utility>
#include <iostream>
#include <stdexcept>
template<typename T>
class Stack
{
private:
Stack(Stack&) = delete;
Stack& operator=(Stack&) = delete;
static_assert(std::is_move_assignable<T>::value,
"Error: this type is not moveable");
static_assert(!std::is_copy_assignable<T>::value,
"Error: type cant be copyable");
static_assert(!std::is_copy_constructible<T>::value,
"Error: type cant be copy construtible");
struct node
{
node* next;
//std::shared_ptr<T> data;
T data;
explicit node(T& d, node* n = nullptr):
next(n), data(std::move(d)) {}
};
node* Head = nullptr;
public:
Stack(){}
~Stack() {
while (Head) {
node* temp = Head;
Head = Head->next;
delete temp;
}
}
template <typename ... Args>
void push_emplace(Args&&... value) {
T temp(std::forward<Args>(value)...);
node* new_node = new node(temp, Head);
Head = new_node;
}
void push(T&& value) {
T temp(std::move(value));
node* new_node = new node(
temp, Head);
Head = new_node;
}
const T& head() const {
return Head->data;
/*return *(Head->data);*/
}
T pop() {
T Data = std::move(Head->data);
node* to_be_delted = Head;
Head = Head->next;
delete to_be_delted;
return Data;
/*T Data = std::move(*(Head->data));
node* to_be_deleted = Head;
Head = Head->next;
delete to_be_deleted;
return Data;*/
}
};
#endif // INCLUDE_HEADER_HPP_
| 23.947368
| 56
| 0.558242
|
Skvortsovvv
|
6e7e621088102c1f3a2229315eb53a33bd6452c0
| 4,501
|
hpp
|
C++
|
include/mserialize/make_template_tag.hpp
|
linhanwang/binlog
|
b4da55f2ae9b61c31c34bf307c0937ec515293df
|
[
"Apache-2.0"
] | 248
|
2019-12-05T20:59:51.000Z
|
2021-01-19T15:56:12.000Z
|
include/mserialize/make_template_tag.hpp
|
Galaxy2416/binlog
|
14bf705b51602d43403733670d6110f8742b0409
|
[
"Apache-2.0"
] | 57
|
2019-12-18T07:00:46.000Z
|
2021-01-04T14:04:16.000Z
|
include/mserialize/make_template_tag.hpp
|
Galaxy2416/binlog
|
14bf705b51602d43403733670d6110f8742b0409
|
[
"Apache-2.0"
] | 22
|
2021-03-27T20:43:40.000Z
|
2022-03-31T10:01:38.000Z
|
#ifndef MSERIALIZE_MAKE_TEMPLATE_TAG_HPP
#define MSERIALIZE_MAKE_TEMPLATE_TAG_HPP
#include <mserialize/cx_string.hpp>
#include <mserialize/detail/foreach.hpp>
#include <mserialize/detail/preprocessor.hpp>
#include <mserialize/make_struct_tag.hpp>
/**
* MSERIALIZE_MAKE_TEMPLATE_TAG(TemplateArgs, TypenameWithTemplateArgs, members...)
*
* Define a CustomTag specialization for the given
* struct or class template, allowing serialized objects
* of it to be visited using mserialize::visit.
*
* The first argument of the macro must be the arguments
* of the template, with the necessary typename prefix,
* where needed, as they appear after the template keyword
* in the definition, wrapped by parentheses.
* (The parentheses are required to avoid the preprocessor
* splitting the arguments at the commas)
*
* The second argument is the template name with
* the template arguments, as it should appear in a specialization,
* wrapped by parentheses.
*
* Following the second argument come the members,
* which are either accessible fields or getters.
*
* Example:
*
* template <typename A, typename B>
* struct Pair {
* A a;
* B b;
* };
* MSERIALIZE_MAKE_TEMPLATE_TAG((typename A, typename B), (Pair<A,B>), a, b)
*
* The macro has to be called in global scope
* (outside of any namespace).
*
* The member list can be empty.
* The member list does not have to enumerate every member
* of the given type, but it must be sync with
* the specialization of CustomSerializer,
* if visitation of objects serialized that way
* is desired.
*
* The maximum number of members and template arguments
* is limited by mserialize/detail/foreach.hpp, currently 100.
*
* Limitation: it is not possible to generate
* a tag for a recursive types with this macro.
* CustomTag for recursive types need to be manually
* specialized.
*
* If some of the members are private, the following friend
* declaration can be added to the type declaration:
*
* template <typename, typename>
* friend struct mserialize::CustomTag;
*/
//
// The macros below deserve a bit of an explanation.
//
// Given the following example call:
//
// MSERIALIZE_MAKE_TEMPLATE_TAG((typename A, typename B, typename C), (Tuple<A,B,C>), a, b, c)
//
// Then the below macros expand to:
//
// TemplateArgs = (typename A, typename B, typename C)
// __VA_ARGS__ = (Tuple<A,B,C>), a, b, c
// ^-- this is here to avoid empty pack if there are no members,
// as until C++20 the pack cannot be empty
//
// MSERIALIZE_FIRST(__VA_ARGS__) = (Tuple<A,B,C>)
// MSERIALIZE_UNTUPLE((Tuple<A,B,C>)) = Tuple<A,B,C>
// MSERIALIZE_STRINGIZE_LIST(Tuple<A,B,C>) ~= "Tuple<A,B,C>"
//
#define MSERIALIZE_MAKE_TEMPLATE_TAG(TemplateArgs, ...) \
namespace mserialize { \
template <MSERIALIZE_UNTUPLE(TemplateArgs)> \
struct CustomTag<MSERIALIZE_UNTUPLE(MSERIALIZE_FIRST(__VA_ARGS__)), void> \
{ \
using T = MSERIALIZE_UNTUPLE(MSERIALIZE_FIRST(__VA_ARGS__)); \
static constexpr auto tag_string() \
{ \
return cx_strcat( \
make_cx_string( \
"{" MSERIALIZE_STRINGIZE_LIST(MSERIALIZE_UNTUPLE(MSERIALIZE_FIRST(__VA_ARGS__))) \
), \
MSERIALIZE_FOREACH( \
MSERIALIZE_STRUCT_MEMBER_TAG, _, __VA_ARGS__ \
) \
make_cx_string("}") \
); \
} \
}; \
} /* namespace mserialize */ \
/**/
/** MSERIALIZE_STRINGIZE_LIST(a,b,c) -> "a" "," "b" "," "c" */
#define MSERIALIZE_STRINGIZE_LIST(...) \
MSERIALIZE_STRINGIZE(MSERIALIZE_FIRST(__VA_ARGS__)) \
MSERIALIZE_FOREACH(MSERIALIZE_STRINGIZE_LIST_I, _, __VA_ARGS__) \
/**/
#define MSERIALIZE_STRINGIZE_LIST_I(_, a) "," #a
#endif // MSERIALIZE_MAKE_TEMPLATE_TAG_HPP
| 40.1875
| 94
| 0.582537
|
linhanwang
|
6e8026c4eacc4dc6bff492879ed3821c9a2ad587
| 4,897
|
cpp
|
C++
|
Framework/DrawPass/ShadowMapPass.cpp
|
kiorisyshen/newbieGameEngine
|
d1e68fbd75884fdf0f171212396d8bc5fec8ad9e
|
[
"MIT"
] | 3
|
2019-06-07T15:29:45.000Z
|
2019-11-11T01:26:12.000Z
|
Framework/DrawPass/ShadowMapPass.cpp
|
kiorisyshen/newbieGameEngine
|
d1e68fbd75884fdf0f171212396d8bc5fec8ad9e
|
[
"MIT"
] | null | null | null |
Framework/DrawPass/ShadowMapPass.cpp
|
kiorisyshen/newbieGameEngine
|
d1e68fbd75884fdf0f171212396d8bc5fec8ad9e
|
[
"MIT"
] | null | null | null |
#include "ShadowMapPass.hpp"
#include "GraphicsManager.hpp"
using namespace std;
using namespace newbieGE;
void ShadowMapPass::Draw(Frame &frame) {
if (frame.frameContext.shadowMapLight.size() > 0 ||
frame.frameContext.cubeShadowMapLight.size() > 0 ||
frame.frameContext.globalShadowMapLight.size() > 0) {
g_pGraphicsManager->DestroyShadowMaps();
frame.frameContext.shadowMapLight.clear();
frame.frameContext.cubeShadowMapLight.clear();
frame.frameContext.globalShadowMapLight.clear();
frame.frameContext.shadowMap = -1;
frame.frameContext.cubeShadowMap = -1;
frame.frameContext.globalShadowMap = -1;
}
// count shadow map
vector<Light *> lights_cast_shadow;
for (int32_t i = 0; i < frame.frameContext.numLights; i++) {
auto &light = frame.lightInfo.lights[i];
light.lightShadowMapIndex = -1;
if (light.lightCastShadow) {
switch (light.lightType) {
case LightType::Omni:
light.lightShadowMapIndex = frame.frameContext.cubeShadowMapLight.size();
frame.frameContext.cubeShadowMapLight.push_back(&light);
break;
case LightType::Spot:
light.lightShadowMapIndex = frame.frameContext.shadowMapLight.size();
frame.frameContext.shadowMapLight.push_back(&light);
break;
case LightType::Area:
light.lightShadowMapIndex = frame.frameContext.shadowMapLight.size();
frame.frameContext.shadowMapLight.push_back(&light);
break;
case LightType::Infinity:
light.lightShadowMapIndex = frame.frameContext.globalShadowMapLight.size();
frame.frameContext.globalShadowMapLight.push_back(&light);
break;
default:
assert(0);
}
}
}
if (frame.frameContext.shadowMapLight.size() > 0) {
int32_t shadowmapID = g_pGraphicsManager->GenerateShadowMapArray(m_kNormalShadowMap.type,
m_kNormalShadowMap.width, m_kNormalShadowMap.height,
frame.frameContext.shadowMapLight.size());
frame.frameContext.shadowMap = shadowmapID;
}
if (frame.frameContext.cubeShadowMapLight.size() > 0) {
int32_t shadowmapID = g_pGraphicsManager->GenerateShadowMapArray(m_kCubeShadowMap.type,
m_kCubeShadowMap.width, m_kCubeShadowMap.height,
frame.frameContext.cubeShadowMapLight.size());
frame.frameContext.cubeShadowMap = shadowmapID;
}
if (frame.frameContext.globalShadowMapLight.size() > 0) {
int32_t shadowmapID = g_pGraphicsManager->GenerateShadowMapArray(m_kGlobalShadowMap.type,
m_kGlobalShadowMap.width, m_kGlobalShadowMap.height,
frame.frameContext.globalShadowMapLight.size());
frame.frameContext.globalShadowMap = shadowmapID;
}
for (auto it : frame.frameContext.shadowMapLight) {
g_pGraphicsManager->BeginShadowPass(frame.frameContext.shadowMap, it->lightShadowMapIndex);
g_pGraphicsManager->UseShaderProgram(DefaultShaderIndex::ShadowMap2DShader);
g_pGraphicsManager->DrawBatchDepthFromLight(*it, ShadowMapType::NormalShadowMapType, frame.batchContext);
g_pGraphicsManager->EndShadowPass(frame.frameContext.shadowMap, it->lightShadowMapIndex);
}
for (auto it : frame.frameContext.cubeShadowMapLight) {
g_pGraphicsManager->BeginShadowPass(frame.frameContext.cubeShadowMap, it->lightShadowMapIndex);
#ifdef USE_METALCUBEDEPTH
g_pGraphicsManager->UseShaderProgram(DefaultShaderIndex::ShadowMapCubeShader);
#endif
g_pGraphicsManager->DrawBatchDepthFromLight(*it, ShadowMapType::CubeShadowMapType, frame.batchContext);
g_pGraphicsManager->EndShadowPass(frame.frameContext.cubeShadowMap, it->lightShadowMapIndex);
}
for (auto it : frame.frameContext.globalShadowMapLight) {
g_pGraphicsManager->BeginShadowPass(frame.frameContext.globalShadowMap, it->lightShadowMapIndex);
g_pGraphicsManager->UseShaderProgram(DefaultShaderIndex::ShadowMap2DShader);
g_pGraphicsManager->DrawBatchDepthFromLight(*it, ShadowMapType::GlobalShadowMapType, frame.batchContext);
g_pGraphicsManager->EndShadowPass(frame.frameContext.globalShadowMap, it->lightShadowMapIndex);
}
}
| 51.547368
| 125
| 0.627731
|
kiorisyshen
|
6e819d93aa468191533a76b7b5862970a87b8cb9
| 2,524
|
cpp
|
C++
|
Shrek2ModdingSDK/Shrek2ModdingSDK/Shrek2Timer.cpp
|
kevinjpetersen/Shrek2ModdingSDK
|
1d517fccc4d83b24342e62f80951318fd4f7c707
|
[
"MIT"
] | 1
|
2022-03-24T21:43:49.000Z
|
2022-03-24T21:43:49.000Z
|
Shrek2ModdingSDK/Shrek2ModdingSDK/Shrek2Timer.cpp
|
kevinjpetersen/Shrek2ModdingSDK
|
1d517fccc4d83b24342e62f80951318fd4f7c707
|
[
"MIT"
] | null | null | null |
Shrek2ModdingSDK/Shrek2ModdingSDK/Shrek2Timer.cpp
|
kevinjpetersen/Shrek2ModdingSDK
|
1d517fccc4d83b24342e62f80951318fd4f7c707
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2021 Kevin J. Petersen https://github.com/kevinjpetersen/
*/
#include "Shrek2ModdingSDK.h"
void Shrek2Timer::Start()
{
try {
if (IsRunning) return;
IsRunning = true;
timer.start();
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::Start", ex.what());
}
}
void Shrek2Timer::Stop()
{
try {
if (!IsRunning) return;
IsRunning = false;
timer.stop();
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::Stop", ex.what());
}
}
void Shrek2Timer::Reset()
{
try {
IsRunning = false;
timer.reset();
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::Reset", ex.what());
}
}
bool Shrek2Timer::IsTimerRunning()
{
return IsRunning;
}
std::string Shrek2Timer::GetTimeString()
{
try {
int mils = CurrentMilliseconds();
int secs = CurrentSeconds();
int mins = CurrentMinutes();
std::string milliseconds = (mils <= 9 ? "00" : (mils <= 99 ? "0" : "")) + std::to_string(mils);
std::string seconds = (secs <= 9 ? "0" : "") + std::to_string(secs);
std::string minutes = (mins <= 9 ? "0" : "") + std::to_string(mins);
return minutes + ":" + seconds + "." + milliseconds;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::GetTimeString", ex.what());
return "";
}
}
int Shrek2Timer::TotalMilliseconds()
{
try {
return timer.count<std::chrono::milliseconds>();
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::TotalMilliseconds", ex.what());
return 0;
}
}
int Shrek2Timer::TotalSeconds()
{
try {
return TotalMilliseconds() / 1000.0;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::TotalSeconds", ex.what());
return 0;
}
}
int Shrek2Timer::TotalMinutes()
{
try {
return TotalSeconds() / 60;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::TotalMinutes", ex.what());
return 0;
}
}
int Shrek2Timer::CurrentMilliseconds()
{
try {
return (int)TotalMilliseconds() % 1000;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::CurrentMilliseconds", ex.what());
return 0;
}
}
int Shrek2Timer::CurrentSeconds()
{
try {
return (int)TotalSeconds() % 60;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::CurrentSeconds", ex.what());
return 0;
}
}
int Shrek2Timer::CurrentMinutes()
{
try {
return (int)TotalMinutes() % 60;
}
catch (std::exception& ex)
{
Shrek2Logging::LogError("Shrek2Timer::CurrentMinutes", ex.what());
return 0;
}
}
| 18.028571
| 97
| 0.650951
|
kevinjpetersen
|
6e822a4c8963a206f5724481f638fbf508424e85
| 1,107
|
hh
|
C++
|
exp.hh
|
aicodix/dsp
|
c83add357c695482590825ddd2713dc29fd903d2
|
[
"0BSD"
] | 16
|
2019-01-25T02:02:21.000Z
|
2022-02-11T04:05:54.000Z
|
exp.hh
|
aicodix/dsp
|
c83add357c695482590825ddd2713dc29fd903d2
|
[
"0BSD"
] | 2
|
2020-12-10T05:46:36.000Z
|
2020-12-15T00:16:25.000Z
|
exp.hh
|
aicodix/dsp
|
c83add357c695482590825ddd2713dc29fd903d2
|
[
"0BSD"
] | 4
|
2019-01-25T02:02:15.000Z
|
2021-10-06T13:50:59.000Z
|
/*
Exponentiation approximations
Constants below lifted from the Cephes Mathematical Library:
https://www.netlib.org/cephes/cmath.tgz
Copyright 2018 Ahmet Inan <inan@aicodix.de>
*/
#pragma once
namespace DSP {
template <typename TYPE>
TYPE ldexp(TYPE x, int n)
{
int a = n < 0 ? -n : n;
int a8 = a / 8;
int ar = a - a8 * 8;
TYPE t = 1 << a8;
t *= t;
t *= t;
t *= t;
t *= 1 << ar;
return n < 0 ? x / t : x * t;
}
template <typename TYPE>
TYPE exp10(TYPE x)
{
static constexpr TYPE
LOG210 = 3.32192809488736234787e0,
LG102A = 3.01025390625000000000E-1,
LG102B = 4.60503898119521373889E-6,
P0 = 4.09962519798587023075E-2,
P1 = 1.17452732554344059015E1,
P2 = 4.06717289936872725516E2,
P3 = 2.39423741207388267439E3,
Q0 = 8.50936160849306532625E1,
Q1 = 1.27209271178345121210E3,
Q2 = 2.07960819286001865907E3;
TYPE i = nearbyint(x * LOG210);
x -= i * LG102A;
x -= i * LG102B;
TYPE xx = x * x;
TYPE py = x * (xx * (xx * (xx * P0 + P1) + P2) + P3);
TYPE qy = xx * (xx * (xx + Q0) + Q1) + Q2;
TYPE pq = TYPE(1) + TYPE(2) * py / (qy - py);
return ldexp(pq, (int)i);
}
}
| 20.5
| 60
| 0.630533
|
aicodix
|
6e87cd251d1062079c2f6635787a5405e720e4d7
| 143
|
cpp
|
C++
|
compiler/useful_visitors.cpp
|
Bhare8972/Cyth
|
334194be4b00456ed3fbf279f18bb22458d4ca81
|
[
"Apache-2.0"
] | null | null | null |
compiler/useful_visitors.cpp
|
Bhare8972/Cyth
|
334194be4b00456ed3fbf279f18bb22458d4ca81
|
[
"Apache-2.0"
] | 1
|
2016-01-09T19:00:14.000Z
|
2016-01-09T19:00:14.000Z
|
compiler/useful_visitors.cpp
|
Bhare8972/Cyth
|
334194be4b00456ed3fbf279f18bb22458d4ca81
|
[
"Apache-2.0"
] | null | null | null |
#include "AST_visitor.hpp"
#include "useful_visitors.hpp"
#include <string>
#include <sstream>
using namespace csu;
using namespace std;
| 11
| 30
| 0.748252
|
Bhare8972
|
6e8a30e159ef58180085f2e1d99af91a543eca85
| 571
|
hpp
|
C++
|
data_structure/graph/include/edge/readers/EdgeListEdgeReader.hpp
|
vlad-iancu/alg-lib
|
706b30253018a8a6f16d353396c8a9ddf2d0b51e
|
[
"MIT"
] | null | null | null |
data_structure/graph/include/edge/readers/EdgeListEdgeReader.hpp
|
vlad-iancu/alg-lib
|
706b30253018a8a6f16d353396c8a9ddf2d0b51e
|
[
"MIT"
] | 11
|
2021-09-04T19:12:23.000Z
|
2021-09-25T21:13:06.000Z
|
data_structure/graph/include/edge/readers/EdgeListEdgeReader.hpp
|
vlad-iancu/libalg
|
706b30253018a8a6f16d353396c8a9ddf2d0b51e
|
[
"MIT"
] | null | null | null |
#ifndef ALG_LIB_DATA_STRUCTURE_EDGE_EDGE_LIST_READER_H_
#define ALG_LIB_DATA_STRUCTURE_EDGE_EDGE_LIST_READER_H_
#include <graph/EdgeList.hpp>
#include <graph/types.hpp>
#include <edge/readers/EdgeReader.hpp>
namespace graph
{
class EdgeListEdgeReader : public EdgeReader
{
private:
const EdgeList &graph;
bool _can_read;
SizeE index;
public:
EdgeListEdgeReader(const EdgeList &graph);
bool increment();
EdgePtr current_edge() const;
bool can_read() const;
};
} // namespace graph
#endif
| 19.033333
| 55
| 0.69352
|
vlad-iancu
|
6e8a540e10842778612cec396c18b7549b904169
| 9,551
|
cpp
|
C++
|
Flw_Piano.cpp
|
jpcima/Flw_Piano
|
115ca63d8068c9bedbe40bc5ea8aeec5f1363855
|
[
"BSL-1.0"
] | 1
|
2019-08-15T13:57:23.000Z
|
2019-08-15T13:57:23.000Z
|
Flw_Piano.cpp
|
jpcima/Flw_Piano
|
115ca63d8068c9bedbe40bc5ea8aeec5f1363855
|
[
"BSL-1.0"
] | null | null | null |
Flw_Piano.cpp
|
jpcima/Flw_Piano
|
115ca63d8068c9bedbe40bc5ea8aeec5f1363855
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Jean Pierre Cimalando 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "Flw_Piano.h"
#include <FL/Fl_Button.H>
#include <FL/Fl.H>
#include <vector>
#include <math.h>
enum Key_Color { Key_White, Key_Black };
enum { white_keywidth = 24, black_keywidth = 14 };
struct Flw_Piano::Impl {
explicit Impl(Flw_Piano *q);
Flw_Piano *const Q;
Fl_Boxtype box_[2];
Fl_Color bg_[2];
class Key_Button : public Fl_Button {
public:
Key_Button(int x, int y, int w, int h, unsigned key)
: Fl_Button(x, y, w, h), key_(key) {}
unsigned piano_key() const
{ return key_; }
int handle(int event) override;
private:
unsigned key_;
};
std::vector<Key_Button *> keys_;
unsigned pushed_key_;
static int handle_key(Key_Button *btn, int event);
void create_keys(unsigned nkeys);
void delete_keys();
Key_Button *key_at(int x, int y);
static const int *keypos_;
static void make_positions(int *pos);
static Key_Color key_color(unsigned key);
static unsigned next_white_key(unsigned key);
static int key_position(unsigned key);
static int key_width(unsigned key);
static Piano_Event event_type_;
static unsigned event_key_;
void do_piano_callback(Piano_Event type, unsigned key);
};
Flw_Piano::Flw_Piano(int x, int y, int w, int h)
: Fl_Group(x, y, w, h),
P(new Impl(this))
{
if (!Impl::keypos_) {
static int table[12];
Impl::make_positions(table);
Impl::keypos_ = table;
}
key_count(48);
}
Flw_Piano::~Flw_Piano()
{
}
const Fl_Color *Flw_Piano::key_color() const
{
return P->bg_;
}
void Flw_Piano::key_color(Fl_Color wh, Fl_Color bl)
{
P->bg_[0] = wh;
P->bg_[1] = bl;
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = P->key_color(key);
Fl_Color bg = (keyc == Key_White) ? wh : bl;
keys[key]->color(bg, bg);
}
}
const Fl_Boxtype *Flw_Piano::key_box() const
{
return P->box_;
}
void Flw_Piano::key_box(Fl_Boxtype wh, Fl_Boxtype bl)
{
P->box_[0] = wh;
P->box_[1] = bl;
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = Impl::key_color(key);
keys[key]->box((keyc == Key_White) ? wh : bl);
}
}
unsigned Flw_Piano::key_count() const
{
return P->keys_.size();
}
void Flw_Piano::key_count(unsigned nkeys)
{
P->create_keys(nkeys);
}
int Flw_Piano::key_value(unsigned key) const
{
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
if (key >= nkeys)
return 0;
return keys[key]->value();
}
void Flw_Piano::key_value(unsigned key, int value)
{
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
if (key >= nkeys)
return;
keys[key]->value(value);
}
bool Flw_Piano::press_key(unsigned key)
{
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
if (key >= nkeys)
return false;
Impl::Key_Button *btn = keys[key];
if (btn->value())
return false;
btn->value(1);
P->do_piano_callback(PIANO_PRESS, key);
return true;
}
bool Flw_Piano::release_key(unsigned key)
{
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
if (key >= nkeys)
return false;
Impl::Key_Button *btn = keys[key];
if (!btn->value())
return false;
btn->value(0);
P->do_piano_callback(PIANO_RELEASE, key);
return true;
}
void Flw_Piano::draw()
{
Impl::Key_Button **keys = P->keys_.data();
unsigned nkeys = P->keys_.size();
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = P->key_color(key);
if (keyc == Key_White)
draw_child(*keys[key]);
}
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = P->key_color(key);
if (keyc == Key_Black)
draw_child(*keys[key]);
}
}
Flw_Piano::Impl::Impl(Flw_Piano *q)
: Q(q),
pushed_key_((unsigned)-1)
{
box_[0] = FL_UP_BOX;
box_[1] = FL_UP_BOX;
bg_[0] = fl_rgb_color(0xee, 0xee, 0xec);
bg_[1] = fl_rgb_color(0x88, 0x8a, 0x85);
}
int Flw_Piano::Impl::Key_Button::handle(int event)
{
if (static_cast<Flw_Piano::Impl *>(user_data())->handle_key(this, event))
return 1;
return Fl_Button::handle(event);
}
int Flw_Piano::Impl::handle_key(Key_Button *btn, int event)
{
Impl *self = static_cast<Impl *>(btn->user_data());
Flw_Piano *Q = self->Q;
Key_Button **keys = self->keys_.data();
switch (event) {
case FL_PUSH:
case FL_DRAG: {
int x = Fl::event_x();
int y = Fl::event_y();
Key_Button *btn = self->key_at(x, y);
if (btn) {
unsigned key = btn->piano_key();
unsigned oldkey = self->pushed_key_;
if (key != oldkey) {
Q->release_key(oldkey);
Q->press_key(key);
self->pushed_key_ = key;
}
}
return 1;
}
case FL_RELEASE: {
unsigned key = self->pushed_key_;
Q->release_key(key);
self->pushed_key_ = (unsigned)-1;
return 1;
}
}
return 0;
}
void Flw_Piano::Impl::create_keys(unsigned nkeys)
{
delete_keys();
if (nkeys == 0)
return;
const Fl_Boxtype *box = box_;
Fl_Color bg_white = bg_[0];
Fl_Color bg_black = bg_[1];
int x = Q->x();
int y = Q->y();
int w = Q->w();
int h = Q->h();
int fullw = key_position(nkeys - 1) + key_width(nkeys - 1);
double wr = (double)w / (double)fullw;
keys_.resize(nkeys);
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = key_color(key);
if (keyc == Key_White) {
int keyx = x + lround(wr * key_position(key));
unsigned nextkey = next_white_key(key);
int nextx = x + lround(wr * (keypos_[nextkey % 12] + (int)(nextkey / 12) * 7 * keypos_[2]));
int keyw = nextx - keyx;
int keyh = h;
Key_Button *btn = new Key_Button(keyx, y, keyw, keyh, key);
btn->user_data(this);
btn->visible_focus(0);
btn->color(bg_white, bg_white);
btn->box(box[0]);
keys_[key] = btn;
}
}
for (unsigned key = 0; key < nkeys; ++key) {
Key_Color keyc = key_color(key);
if (keyc == Key_Black) {
int keyx = x + lround(wr * key_position(key));
int keyw = lround(wr * black_keywidth);
int keyh = h / 2;
Key_Button *btn = new Key_Button(keyx, y, keyw, keyh, key);
btn->user_data(this);
btn->visible_focus(0);
btn->color(bg_black, bg_black);
btn->box(box[1]);
keys_[key] = btn;
}
}
}
void Flw_Piano::Impl::delete_keys()
{
while (!keys_.empty()) {
delete keys_.back();
keys_.pop_back();
}
}
Flw_Piano::Impl::Key_Button *Flw_Piano::Impl::key_at(int x, int y)
{
Key_Button **keys = keys_.data();
unsigned nkeys = keys_.size();
for (unsigned i = 0; i < nkeys; ++i) {
if (key_color(i) == Key_Black) {
Key_Button *btn = keys[i];
bool inside = x >= btn->x() && x < btn->x() + btn->w() &&
y >= btn->y() && y < btn->y() + btn->h();
if (inside)
return btn;
}
}
for (unsigned i = 0; i < nkeys; ++i) {
if (key_color(i) == Key_White) {
Key_Button *btn = keys[i];
bool inside = x >= btn->x() && x < btn->x() + btn->w() &&
y >= btn->y() && y < btn->y() + btn->h();
if (inside)
return btn;
}
}
return NULL;
}
Key_Color Flw_Piano::Impl::key_color(unsigned key)
{
unsigned n = key % 12;
n = (n < 5) ? n : (n - 1);
return (n & 1) ? Key_Black : Key_White;
}
unsigned Flw_Piano::Impl::next_white_key(unsigned key)
{
unsigned nextkey = key + 1;
while (key_color(nextkey) != Key_White)
++nextkey;
return nextkey;
}
int Flw_Piano::Impl::key_position(unsigned key)
{
return keypos_[key % 12] + (int)(key / 12) * 7 * keypos_[2];
}
int Flw_Piano::Impl::key_width(unsigned key)
{
if (key_color(key) == Key_White)
return key_position(next_white_key(key)) - key_position(key);
else
return black_keywidth;
}
const int *Flw_Piano::Impl::keypos_ = NULL;
void Flw_Piano::Impl::make_positions(int *pos)
{
unsigned nth = 0;
for (int i = 0; i < 7; ++i) {
int index = i * 2;
index -= (index > 4) ? 1 : 0;
pos[index] = i * white_keywidth;
}
for (int i = 0; i < 2; ++i)
pos[1 + 2 * i] = 15 + 2 * i * black_keywidth;
for (int i = 0; i < 3; ++i)
pos[6 + 2 * i] = pos[5] + 13 + 2 * i * black_keywidth;
}
Piano_Event Flw_Piano::Impl::event_type_;
unsigned Flw_Piano::Impl::event_key_;
void Flw_Piano::Impl::do_piano_callback(Piano_Event type, unsigned key)
{
event_type_ = type;
event_key_ = key;
Q->do_callback();
}
Piano_Event Piano::event()
{
return Flw_Piano::Impl::event_type_;
}
unsigned Piano::key()
{
return Flw_Piano::Impl::event_key_;
}
| 24.872396
| 104
| 0.564548
|
jpcima
|
6e8fd61636a4415133c16e1c79dc719373bfd776
| 1,299
|
cpp
|
C++
|
UVaOnlineJudge/Contest_Volumes(10000...)/Volume101(10100-10199)/10189/code.cpp
|
luiscbr92/algorithmic-challenges
|
bc35729e54e4284e9ade1aa61b51a1c2d72aa62c
|
[
"MIT"
] | 3
|
2015-10-21T18:56:43.000Z
|
2017-06-06T10:44:22.000Z
|
UVaOnlineJudge/Contest_Volumes(10000...)/Volume101(10100-10199)/10189/code.cpp
|
luiscbr92/algorithmic-challenges
|
bc35729e54e4284e9ade1aa61b51a1c2d72aa62c
|
[
"MIT"
] | null | null | null |
UVaOnlineJudge/Contest_Volumes(10000...)/Volume101(10100-10199)/10189/code.cpp
|
luiscbr92/algorithmic-challenges
|
bc35729e54e4284e9ade1aa61b51a1c2d72aa62c
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main(){
ios_base::sync_with_stdio (false);
int game = 1;
char field[100][100];
int rows, columns, i, j, count, ii, jj;
string line;
cin >> rows >> columns;
cin.ignore();
while(rows > 0 && columns > 0){
for(i = 0; i < rows; i++){
getline(cin, line);
for(j = 0; j < columns; j++) field[i][j] = line[j];
}
if(game > 1) cout << endl;
cout << "Field #" << game << ":" << endl;
for(i = 0; i < rows; i++){
for(j = 0; j < columns; j++){
if(field[i][j] == '*') cout << '*';
else{
count = 0;
for(ii = i-1; ii <= i+1; ii++){
if(ii < 0 || ii >= rows) continue;
for(jj = j-1; jj <= j+1; jj++){
if(jj < 0 || jj >= columns) continue;
if(ii == i && jj == j) continue;
if(field[ii][jj] == '*') count +=1;
}
}
cout << count;
}
}
cout << endl;
}
cin >> rows >> columns;
cin.ignore();
game +=1;
}
return 0;
}
| 25.470588
| 65
| 0.345651
|
luiscbr92
|
6e96f5995213da096cfa6fade9cccfd43d3c8f5f
| 3,558
|
cpp
|
C++
|
src/data/resources.cpp
|
danielnavarrogomez/Anaquin
|
563dbeb25aff15a55e4309432a967812cbfa0c98
|
[
"BSD-3-Clause"
] | null | null | null |
src/data/resources.cpp
|
danielnavarrogomez/Anaquin
|
563dbeb25aff15a55e4309432a967812cbfa0c98
|
[
"BSD-3-Clause"
] | null | null | null |
src/data/resources.cpp
|
danielnavarrogomez/Anaquin
|
563dbeb25aff15a55e4309432a967812cbfa0c98
|
[
"BSD-3-Clause"
] | null | null | null |
#include <string>
#include <algorithm>
#include "resources/VarCopy.txt"
#include "resources/anaquin.txt"
#include "resources/VarFlip.txt"
#include "resources/VarTrim.txt"
#include "resources/VarAlign.txt"
#include "resources/VarKmer.txt"
#include "resources/VarGermline.txt"
#include "resources/VarSomatic.txt"
#include "resources/VarConjoint.txt"
#include "resources/VarStructure.txt"
#include "resources/VarCalibrate.txt"
#include "resources/RnaAlign.txt"
#include "resources/RnaReport.txt"
#include "resources/RnaAssembly.txt"
#include "resources/RnaSubsample.txt"
#include "resources/RnaExpression.txt"
#include "resources/RnaFoldChange.txt"
#include "resources/MetaAssembly.txt"
#include "resources/MetaCoverage.txt"
#include "resources/MetaSubsample.txt"
#include "resources/plotCNV.R"
#include "resources/plotFold.R"
#include "resources/plotTROC.R"
#include "resources/plotVGROC.R"
#include "resources/plotVCROC.R"
#include "resources/plotTLODR.R"
#include "resources/plotAllele.R"
#include "resources/plotLinear.R"
#include "resources/plotKAllele.R"
#include "resources/plotConjoint.R"
#include "resources/plotLogistic.R"
#include "resources/report.py"
typedef std::string Scripts;
#define ToString(x) std::string(reinterpret_cast<char*>(x))
Scripts Manual()
{
return ToString(data_manuals_anaquin_txt);
}
Scripts PlotFold() { return ToString(src_r_plotFold_R); }
Scripts PlotCNV() { return ToString(src_r_plotCNV_R); }
Scripts PlotLinear() { return ToString(src_r_plotLinear_R); }
Scripts PlotConjoint() { return ToString(src_r_plotConjoint_R); }
Scripts PlotAllele() { return ToString(src_r_plotAllele_R); }
Scripts PlotKAllele() { return ToString(src_r_plotKAllele_R); }
Scripts PlotLogistic() { return ToString(src_r_plotLogistic_R); }
Scripts RnaAlign() { return ToString(data_manuals_RnaAlign_txt); }
Scripts RnaReport() { return ToString(data_manuals_RnaReport_txt); }
Scripts RnaSubsample() { return ToString(data_manuals_RnaSubsample_txt); }
Scripts RnaAssembly() { return ToString(data_manuals_RnaAssembly_txt); }
Scripts RnaExpression() { return ToString(data_manuals_RnaExpression_txt); }
Scripts RnaFoldChange() { return ToString(data_manuals_RnaFoldChange_txt); }
Scripts VarTrim() { return ToString(data_manuals_VarTrim_txt); }
Scripts VarFlip() { return ToString(data_manuals_VarFlip_txt); }
Scripts VarCopy() { return ToString(data_manuals_VarCopy_txt); }
Scripts VarAlign() { return ToString(data_manuals_VarAlign_txt); }
Scripts VarKmer() { return ToString(data_manuals_VarKmer_txt); }
Scripts VarCalibrate() { return ToString(data_manuals_VarCalibrate_txt); }
Scripts VarGermline() { return ToString(data_manuals_VarGermline_txt); }
Scripts VarSomatic() { return ToString(data_manuals_VarSomatic_txt); }
Scripts VarConjoint() { return ToString(data_manuals_VarConjoint_txt); }
Scripts VarStructure() { return ToString(data_manuals_VarStructure_txt); }
Scripts MetaCoverage() { return ToString(data_manuals_MetaCoverage_txt); }
Scripts MetaSubsample() { return ToString(data_manuals_MetaSubsample_txt); }
Scripts MetaAssembly() { return ToString(data_manuals_MetaAssembly_txt); }
Scripts PlotTROC() { return ToString(src_r_plotTROC_R); }
Scripts PlotTLODR() { return ToString(src_r_plotTLODR_R); }
Scripts PlotVGROC() { return ToString(src_r_plotVGROC_R); }
Scripts PlotVCROC() { return ToString(src_r_plotVCROC_R); }
Scripts PythonReport() { return ToString(scripts_report_py); }
| 40.896552
| 79
| 0.769252
|
danielnavarrogomez
|
6e96facabae3ab4a3127b68592fbc7300e284c49
| 2,610
|
cpp
|
C++
|
src/lib/netlist/devices/nld_7493.cpp
|
mamedev/netedit
|
815723fc4772ee7f47558d1a63abc189a65e01b6
|
[
"BSD-3-Clause"
] | 3
|
2017-04-12T16:13:34.000Z
|
2021-02-24T03:42:19.000Z
|
src/lib/netlist/devices/nld_7493.cpp
|
mamedev/netedit
|
815723fc4772ee7f47558d1a63abc189a65e01b6
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/netlist/devices/nld_7493.cpp
|
mamedev/netedit
|
815723fc4772ee7f47558d1a63abc189a65e01b6
|
[
"BSD-3-Clause"
] | 7
|
2017-01-24T23:07:50.000Z
|
2021-01-28T04:10:59.000Z
|
// license:GPL-2.0+
// copyright-holders:Couriersud
/*
* nld_7493.c
*
*/
#include "nld_7493.h"
#include "nl_setup.h"
namespace netlist
{
namespace devices
{
NETLIB_OBJECT(7493ff)
{
NETLIB_CONSTRUCTOR(7493ff)
, m_I(*this, "CLK")
, m_Q(*this, "Q")
, m_reset(*this, "m_reset", 0)
, m_state(*this, "m_state", 0)
{
}
NETLIB_RESETI();
NETLIB_UPDATEI();
public:
logic_input_t m_I;
logic_output_t m_Q;
state_var_u8 m_reset;
state_var_u8 m_state;
};
NETLIB_OBJECT(7493)
{
NETLIB_CONSTRUCTOR(7493)
, m_R1(*this, "R1")
, m_R2(*this, "R2")
, A(*this, "A")
, B(*this, "B")
, C(*this, "C")
, D(*this, "D")
{
register_subalias("CLKA", A.m_I);
register_subalias("CLKB", B.m_I);
register_subalias("QA", A.m_Q);
register_subalias("QB", B.m_Q);
register_subalias("QC", C.m_Q);
register_subalias("QD", D.m_Q);
connect_late(C.m_I, B.m_Q);
connect_late(D.m_I, C.m_Q);
}
NETLIB_RESETI() { }
NETLIB_UPDATEI();
logic_input_t m_R1;
logic_input_t m_R2;
NETLIB_SUB(7493ff) A;
NETLIB_SUB(7493ff) B;
NETLIB_SUB(7493ff) C;
NETLIB_SUB(7493ff) D;
};
NETLIB_OBJECT_DERIVED(7493_dip, 7493)
{
NETLIB_CONSTRUCTOR_DERIVED(7493_dip, 7493)
{
register_subalias("1", B.m_I);
register_subalias("2", m_R1);
register_subalias("3", m_R2);
// register_subalias("4", ); --> NC
// register_subalias("5", ); --> VCC
// register_subalias("6", ); --> NC
// register_subalias("7", ); --> NC
register_subalias("8", C.m_Q);
register_subalias("9", B.m_Q);
// register_subalias("10", ); -. GND
register_subalias("11", D.m_Q);
register_subalias("12", A.m_Q);
// register_subalias("13", ); -. NC
register_subalias("14", A.m_I);
}
};
NETLIB_RESET(7493ff)
{
m_reset = 1;
m_state = 0;
m_I.set_state(logic_t::STATE_INP_HL);
}
NETLIB_UPDATE(7493ff)
{
constexpr netlist_time out_delay = NLTIME_FROM_NS(18);
if (m_reset)
{
m_state ^= 1;
m_Q.push(m_state, out_delay);
}
}
NETLIB_UPDATE(7493)
{
const netlist_sig_t r = m_R1() & m_R2();
if (r)
{
A.m_I.inactivate();
B.m_I.inactivate();
A.m_Q.push(0, NLTIME_FROM_NS(40));
B.m_Q.push(0, NLTIME_FROM_NS(40));
C.m_Q.push(0, NLTIME_FROM_NS(40));
D.m_Q.push(0, NLTIME_FROM_NS(40));
A.m_reset = B.m_reset = C.m_reset = D.m_reset = 0;
A.m_state = B.m_state = C.m_state = D.m_state = 0;
}
else
{
A.m_I.activate_hl();
B.m_I.activate_hl();
A.m_reset = B.m_reset = C.m_reset = D.m_reset = 1;
}
}
NETLIB_DEVICE_IMPL(7493)
NETLIB_DEVICE_IMPL(7493_dip)
} //namespace devices
} // namespace netlist
| 18.913043
| 56
| 0.628352
|
mamedev
|
6e9ea6e4b61a6d3da6cf48e4f2cf9a035fa43ea1
| 6,118
|
hpp
|
C++
|
cvlib/include/cvlib.hpp
|
Pol22/cvclasses18
|
94c3b398349c739dcbce5e02b0e9a277456cd85b
|
[
"MIT"
] | null | null | null |
cvlib/include/cvlib.hpp
|
Pol22/cvclasses18
|
94c3b398349c739dcbce5e02b0e9a277456cd85b
|
[
"MIT"
] | null | null | null |
cvlib/include/cvlib.hpp
|
Pol22/cvclasses18
|
94c3b398349c739dcbce5e02b0e9a277456cd85b
|
[
"MIT"
] | 1
|
2019-12-22T12:51:06.000Z
|
2019-12-22T12:51:06.000Z
|
/* Computer Vision Functions.
* @file
* @date 2018-09-05
* @author Anonymous
*/
#ifndef __CVLIB_HPP__
#define __CVLIB_HPP__
#include <opencv2/opencv.hpp>
namespace cvlib
{
/// \brief Split and merge algorithm for image segmentation
/// \param image, in - input image
/// \param stddev, in - threshold to treat regions as homogeneous
/// \return segmented image
cv::Mat split_and_merge(const cv::Mat& image, double stddev);
cv::Mat only_split(const cv::Mat& image, double stddev);
/// \brief Segment texuture on passed image according to sample in ROI
/// \param image, in - input image
/// \param roi, in - region with sample texture on passed image
/// \param eps, in - threshold parameter for texture's descriptor distance
/// \return binary mask with selected texture
cv::Mat select_texture(const cv::Mat& image, const cv::Rect& roi, double eps, void* data);
struct GMM
{
float weight = 0.0;
float mean[3] = { 0.0, 0.0, 0.0 }; // mean RGB
float variance = 0.0;
float significants = 0.0; // weight / variance = which Gaussians shoud be part of bg
};
/// \brief Motion Segmentation algorithm
class motion_segmentation : public cv::BackgroundSubtractor
{
public:
/// \brief ctor
motion_segmentation() {}
~motion_segmentation()
{
if (modes != nullptr)
delete[] modes;
}
void reinit();
void setVarThreshold(int threshold);
/// \see cv::BackgroundSubtractor::apply
void apply(cv::InputArray image, cv::OutputArray fgmask, double learningRate = -1) override;
/// \see cv::BackgroundSubtractor::BackgroundSubtractor
void getBackgroundImage(cv::OutputArray backgroundImage) const override
{
//backgroundImage.assign(bg_model_);
}
private:
void createModel(cv::Size size);
int substractPixel(long posPixel, const cv::Scalar pixelRGB, uchar& numModes);
float bg_threshold;
float m_variance;
GMM* modes; // gaussian mixture model
cv::Mat modes_per_pixel;
cv::Mat bg_model;
float alpha = 1.0 / 50;
unsigned number_of_frames = 2;
const int max_modes = 3;
static const int BACKGROUND = 0;
static const int FOREGROUND = 255;
};
/// \brief FAST corner detection algorithm
class corner_detector_fast : public cv::Feature2D
{
public:
corner_detector_fast();
/// \brief Fabrique method for creating FAST detector
static cv::Ptr<corner_detector_fast> create();
/// \see Feature2d::detect
virtual void detect(cv::InputArray image, CV_OUT std::vector<cv::KeyPoint>& keypoints, cv::InputArray mask = cv::noArray()) override;
/// \see Feature2d::compute
virtual void compute(cv::InputArray image, std::vector<cv::KeyPoint>& keypoints, cv::OutputArray descriptors) override;
/// \see Feature2d::detectAndCompute
virtual void detectAndCompute(cv::InputArray image, cv::InputArray mask, std::vector<cv::KeyPoint>& keypoints, cv::OutputArray descriptors,
bool useProvidedKeypoints = false) override;
/// \see Feature2d::getDefaultName
virtual cv::String getDefaultName() const override
{
return "FAST_Binary";
}
private:
int getShift(const int& index) const;
char checkDarkerOrBrighter(const uchar* pixel, const uchar* neighbour) const;
bool highSpeedTest(const uchar* pixel) const;
bool pointOnImage(const cv::Mat& image, const cv::Point2f& point);
int twoPointsTest(const cv::Mat& image, const cv::Point2f& point1, const cv::Point2f& point2, const int& num);
void binaryTest(const cv::Mat& image, const cv::Point2f& keypoint, int* descriptor);
// detector
static const int number_of_circle_pixels = 16;
static const int number_non_similar_pixels = 12;
static const uchar threshold = 30;
static const int roi_mask_size = 7;
char circle_pixels[number_of_circle_pixels + 1];
char int_circle_pixels[number_of_circle_pixels + number_non_similar_pixels + 1];
int width = 0;
int end_j;
int end_i;
// extractor
static const int S = 15;
static const int desc_length = 8; // 32 * 8 = 256
static const int all_length = desc_length * 32; // 256
cv::Point2f test_points1[all_length];
cv::Point2f test_points2[all_length];
cv::RNG rng;
};
/// \brief Descriptor matched based on ratio of SSD
class descriptor_matcher : public cv::DescriptorMatcher
{
public:
/// \brief ctor
descriptor_matcher(float ratio = 1.5) : ratio_(ratio) {}
/// \brief setup ratio threshold for SSD filtering
void set_ratio(float r)
{
ratio_ = r;
}
protected:
/// \see cv::DescriptorMatcher::knnMatchImpl
void knnMatchImpl(cv::InputArray queryDescriptors, std::vector<std::vector<cv::DMatch>>& matches, int k,
cv::InputArrayOfArrays masks = cv::noArray(), bool compactResult = false) override;
/// \see cv::DescriptorMatcher::radiusMatchImpl
void radiusMatchImpl(cv::InputArray queryDescriptors, std::vector<std::vector<cv::DMatch>>& matches, float maxDistance,
cv::InputArrayOfArrays masks = cv::noArray(), bool compactResult = false) override;
/// \see cv::DescriptorMatcher::isMaskSupported
bool isMaskSupported() const override
{
return false;
}
/// \see cv::DescriptorMatcher::isMaskSupported
cv::Ptr<cv::DescriptorMatcher> clone(bool emptyTrainData = false) const override
{
cv::Ptr<cv::DescriptorMatcher> copy = new descriptor_matcher(*this);
if (emptyTrainData)
{
copy->clear();
}
return copy;
}
private:
int hamming_distance(int* x1, int* x2);
float ratio_;
int desc_length = 0;
};
/// \brief Stitcher for merging images into big one
class Stitcher
{
public:
Stitcher() = default;
~Stitcher() { detector.release(); }
void setReference(cv::Mat& img);
cv::Mat stitch(cv::Mat& img);
private:
cv::Ptr<cvlib::corner_detector_fast> detector = cvlib::corner_detector_fast::create();
cvlib::descriptor_matcher matcher;
cv::Mat ref_img;
std::vector<cv::KeyPoint> ref_keypoints;
cv::Mat ref_descriptors;
static constexpr float max_distance = 100.0f;
};
} // namespace cvlib
#endif // __CVLIB_HPP__
| 31.374359
| 143
| 0.695652
|
Pol22
|
6ea1b3c0fb1d8209dbb6367eb49c38c79242a5ff
| 2,842
|
cpp
|
C++
|
source/playlunky/mod/fix_mod_structure.cpp
|
C-ffeeStain/Playlunky
|
c0df8a993712192fb44048c8542776ead110441d
|
[
"MIT"
] | null | null | null |
source/playlunky/mod/fix_mod_structure.cpp
|
C-ffeeStain/Playlunky
|
c0df8a993712192fb44048c8542776ead110441d
|
[
"MIT"
] | null | null | null |
source/playlunky/mod/fix_mod_structure.cpp
|
C-ffeeStain/Playlunky
|
c0df8a993712192fb44048c8542776ead110441d
|
[
"MIT"
] | null | null | null |
#include "unzip_mod.h"
#include "log.h"
#include "util/algorithms.h"
#include "util/regex.h"
static constexpr ctll::fixed_string s_FontRule{ ".*\\.fnb" };
static constexpr std::string_view s_FontTargetPath{ "Data/Fonts" };
static constexpr ctll::fixed_string s_ArenaLevelRule{ "dm.*\\.lvl" };
static constexpr ctll::fixed_string s_ArenaLevelTokRule{ ".*\\.tok" };
static constexpr std::string_view s_ArenaLevelTargetPath{ "Data/Levels/Arena" };
static constexpr ctll::fixed_string s_LevelRule{ ".*\\.lvl" };
static constexpr std::string_view s_LevelTargetPath{ "Data/Levels" };
static constexpr ctll::fixed_string s_OldTextureRule{ "ai\\.(DDS|png)" };
static constexpr std::string_view s_OldTextureTargetPath{ "Data/Textures/OldTextures" };
static constexpr ctll::fixed_string s_FullTextureRule{ ".*_full\\.(DDS|png)" };
static constexpr std::string_view s_FullTextureTargetPath{ "Data/Textures/Merged" };
static constexpr ctll::fixed_string s_TextureRule{ ".*\\.(DDS|png)" };
static constexpr std::string_view s_TextureTargetPath{ "Data/Textures" };
void FixModFolderStructure(const std::filesystem::path& mod_folder) {
namespace fs = std::filesystem;
struct PathMapping {
fs::path CurrentPath;
fs::path TargetPath;
};
std::vector<PathMapping> path_mappings;
const auto db_folder = mod_folder / ".db";
for (const auto& path : fs::recursive_directory_iterator(mod_folder)) {
if (fs::is_regular_file(path) && !algo::is_sub_path(path, db_folder)) {
const auto file_name = path.path().filename().string();
if (ctre::match<s_FontRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_FontTargetPath / file_name });
}
else if (ctre::match<s_ArenaLevelRule>(file_name) || ctre::match<s_ArenaLevelTokRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_ArenaLevelTargetPath / file_name });
}
else if (ctre::match<s_LevelRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_LevelTargetPath / file_name });
}
else if (ctre::match<s_OldTextureRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_OldTextureTargetPath / file_name });
}
else if (ctre::match<s_FullTextureRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_FullTextureTargetPath / file_name });
}
else if (ctre::match<s_TextureRule>(file_name)) {
path_mappings.push_back({ path, mod_folder / s_TextureTargetPath / file_name });
}
else {
path_mappings.push_back({ path, mod_folder / file_name });
}
}
}
for (auto& [current_path, target_path] : path_mappings) {
if (current_path != target_path) {
{
const auto target_parent_path = target_path.parent_path();
if (!fs::exists(target_parent_path)) {
fs::create_directories(target_parent_path);
}
}
fs::rename(current_path, target_path);
}
}
}
| 37.893333
| 102
| 0.724138
|
C-ffeeStain
|
6ea3c7dba877c577794b2a764d864917f79e3026
| 631
|
cpp
|
C++
|
Sculptor2_0/putbox.cpp
|
igorsergioJS/sculptor-2.0
|
c4224d8485dfb0305bb5ebc8c816c527c8c6f698
|
[
"MIT"
] | null | null | null |
Sculptor2_0/putbox.cpp
|
igorsergioJS/sculptor-2.0
|
c4224d8485dfb0305bb5ebc8c816c527c8c6f698
|
[
"MIT"
] | null | null | null |
Sculptor2_0/putbox.cpp
|
igorsergioJS/sculptor-2.0
|
c4224d8485dfb0305bb5ebc8c816c527c8c6f698
|
[
"MIT"
] | null | null | null |
#include "putbox.h"
PutBox::PutBox(int x0, int x1, int y0, int y1, int z0, int z1, float r, float g, float b, float a)
{
this->x0 = x0;
this->x1 = x1;
this->y0 = y0;
this->y1 = y1;
this->z0 = z0;
this->z1 = z1;
this->r = r;
this->g = g;
this->b = b;
this->a = a;
}
PutBox::~PutBox()
{
}
void PutBox::draw(Sculptor &t)
{
for(int i=x0;i<x1;i++)
{
for(int j=y0;j<y1;j++)
{
for(int k=z0;k<z1;k++)
{
t.setColor(r,g,b,a);
t.putVoxel(i,j,k);
}
}
}
}
| 17.527778
| 98
| 0.397781
|
igorsergioJS
|
6ea4430ee8412eaa0f0e3d093e9038a3ec51d343
| 1,118
|
cpp
|
C++
|
src/ServiceDescription.cpp
|
ruurdadema/dnssd
|
5c444ed901d177e57dd7f9338cf9466fa12f7794
|
[
"MIT"
] | null | null | null |
src/ServiceDescription.cpp
|
ruurdadema/dnssd
|
5c444ed901d177e57dd7f9338cf9466fa12f7794
|
[
"MIT"
] | 1
|
2022-02-25T19:03:49.000Z
|
2022-02-25T19:03:49.000Z
|
src/ServiceDescription.cpp
|
ruurdadema/dnssd
|
5c444ed901d177e57dd7f9338cf9466fa12f7794
|
[
"MIT"
] | null | null | null |
#include <dnssd/ServiceDescription.h>
#include <sstream>
using namespace dnssd;
std::string ServiceDescription::description() const noexcept
{
std::string txtRecordDescription;
for (auto& kv : txtRecord)
{
txtRecordDescription += kv.first;
txtRecordDescription += "=";
txtRecordDescription += kv.second;
txtRecordDescription += ", ";
}
std::string addressesDescription;
for (auto& interface : interfaces)
{
addressesDescription += "interface ";
addressesDescription += std::to_string(interface.first);
addressesDescription += ": ";
for (auto& addr : interface.second)
{
addressesDescription += addr;
addressesDescription += ", ";
}
}
std::stringstream output;
output
<< "fullname: " << fullname
<< ", name: " << name
<< ", type: " << type
<< ", domain: " << domain
<< ", hostTarget: " << hostTarget
<< ", port: " << port
<< ", txtRecord: " << txtRecordDescription
<< "addresses: " << addressesDescription;
return output.str();
}
| 23.787234
| 64
| 0.580501
|
ruurdadema
|
6ea61efaeacce9a946491e7f090cb47b8d85d3f0
| 3,576
|
hpp
|
C++
|
src/Client/GUI3/Widgets/Panels/AbstractPanel.hpp
|
AlexWayfer/RankCheck
|
cf3005a2ba6f66bd66f27e0e42ca6b0ccb907014
|
[
"Unlicense",
"MIT"
] | 10
|
2018-02-12T16:14:07.000Z
|
2022-03-19T15:08:29.000Z
|
src/Client/GUI3/Widgets/Panels/AbstractPanel.hpp
|
AlexWayfer/RankCheck
|
cf3005a2ba6f66bd66f27e0e42ca6b0ccb907014
|
[
"Unlicense",
"MIT"
] | 11
|
2018-02-08T16:46:49.000Z
|
2022-02-03T20:48:12.000Z
|
src/Client/GUI3/Widgets/Panels/AbstractPanel.hpp
|
AlexWayfer/RankCheck
|
cf3005a2ba6f66bd66f27e0e42ca6b0ccb907014
|
[
"Unlicense",
"MIT"
] | 3
|
2018-02-12T22:08:55.000Z
|
2021-06-24T16:29:17.000Z
|
#ifndef SRC_CLIENT_GUI3_WIDGETS_ABSTRACTPANEL_HPP_
#define SRC_CLIENT_GUI3_WIDGETS_ABSTRACTPANEL_HPP_
#include <Client/GUI3/Container.hpp>
#include <Client/GUI3/Events/Callback.hpp>
#include <Client/GUI3/Events/StateEvent.hpp>
#include <Client/GUI3/Types.hpp>
#include <SFML/System/Vector2.hpp>
#include <algorithm>
#include <memory>
#include <vector>
namespace gui3
{
struct EmptyPanelData
{
};
/**
* Simple container without automatic layout management.
*/
template<typename ExtraData = EmptyPanelData>
class AbstractPanel : public Container
{
public:
AbstractPanel() :
myWidgetScale(1, 1)
{
}
virtual ~AbstractPanel()
{
while (!myOwnedWidgets.empty())
{
dropOwnership(myOwnedWidgets.end() - 1);
}
}
protected:
/**
* Adds the widget to the container, leaving lifetime management up to the caller.
*
* Call this function inside the "add" function of subclasses.
*/
bool own(Ptr<Widget> widget)
{
if (takeOwnership(widget))
{
return addWidget(*widget);
}
else
{
return false;
}
}
/**
* Removes the widget from the container.
*
* If the widget is owned by this container, it is automatically deallocated.
*
* Call this function inside the "remove" function of subclasses.
*/
bool disown(Widget& widget)
{
if (removeWidget(widget))
{
return dropOwnership(widget);
}
else
{
return false;
}
}
/**
* Returns a pointer to a custom data structure holding information for a specific widget in the panel.
*/
ExtraData * getWidgetData(Widget & widget) const
{
auto it = findWidget(widget);
if (it == myOwnedWidgets.end() || it->widget.get() != &widget)
{
return nullptr;
}
return it->data.get();
}
private:
struct OwnedWidget
{
Ptr<Widget> widget;
std::unique_ptr<ExtraData> data;
CallbackHandle<StateEvent> callback;
};
bool takeOwnership(Ptr<Widget> widget)
{
if (widget == nullptr)
{
return false;
}
auto it = findWidget(*widget);
Widget* widgetPointer = widget.get();
if (it != myOwnedWidgets.end() && it->widget.get() == widgetPointer)
{
return false;
}
auto func = [this, widgetPointer](StateEvent event)
{
if (widgetPointer->getParent() != this)
{
dropOwnership(*widgetPointer);
}
};
OwnedWidget info;
info.widget = widget;
info.data = makeUnique<ExtraData>();
info.callback = widget->addStateCallback(std::move(func), StateEvent::ParentChanged, 0);
myOwnedWidgets.insert(it, std::move(info));
return true;
}
bool dropOwnership(Widget& widget)
{
auto it = findWidget(widget);
if (it == myOwnedWidgets.end() || it->widget.get() != &widget)
{
return false;
}
dropOwnership(it);
return true;
}
void dropOwnership(typename std::vector<OwnedWidget>::iterator it)
{
myDisownedWidgets.push_back(std::move(*it));
myOwnedWidgets.erase(it);
invokeLater([=]
{
myDisownedWidgets.clear();
});
}
typename std::vector<OwnedWidget>::iterator findWidget(Widget & widget)
{
return std::lower_bound(myOwnedWidgets.begin(), myOwnedWidgets.end(), &widget,
[](const OwnedWidget& left, Widget* right)
{
return left.widget.get() < right;
});
}
typename std::vector<OwnedWidget>::const_iterator findWidget(Widget & widget) const
{
return std::lower_bound(myOwnedWidgets.begin(), myOwnedWidgets.end(), &widget,
[](const OwnedWidget& left, Widget* right)
{
return left.widget.get() < right;
});
}
std::vector<OwnedWidget> myOwnedWidgets;
std::vector<OwnedWidget> myDisownedWidgets;
sf::Vector2f myWidgetScale;
};
}
#endif
| 19.021277
| 104
| 0.682606
|
AlexWayfer
|
6eaf4b56574eea425bc9c9e89831da13e21e93f2
| 62,518
|
cpp
|
C++
|
src/Prey/prey_baseweapons.cpp
|
AMS21/PreyRun
|
3efc9d70228bcfb8bc18f6ff23a05c8be1e45101
|
[
"MIT"
] | 2
|
2018-08-30T23:48:22.000Z
|
2021-04-07T19:16:18.000Z
|
src/Prey/prey_baseweapons.cpp
|
AMS21/PreyRun
|
3efc9d70228bcfb8bc18f6ff23a05c8be1e45101
|
[
"MIT"
] | null | null | null |
src/Prey/prey_baseweapons.cpp
|
AMS21/PreyRun
|
3efc9d70228bcfb8bc18f6ff23a05c8be1e45101
|
[
"MIT"
] | null | null | null |
#include "../idlib/precompiled.h"
#pragma hdrstop
#include "prey_local.h"
#define WEAPON_DEBUG if(g_debugWeapon.GetBool()) gameLocal.Warning
/***********************************************************************
hhWeapon
***********************************************************************/
const idEventDef EV_PlayAnimWhenReady( "playAnimWhenReady", "s" );
const idEventDef EV_Weapon_Aside( "<weaponAside>" );
const idEventDef EV_Weapon_EjectAltBrass( "ejectAltBrass" );
const idEventDef EV_Weapon_HasAmmo( "hasAmmo", "", 'd' );
const idEventDef EV_Weapon_HasAltAmmo( "hasAltAmmo", "", 'd' );
const idEventDef EV_Weapon_GetFireDelay( "getFireDelay", "", 'f' );
const idEventDef EV_Weapon_GetAltFireDelay( "getAltFireDelay", "", 'f' );
const idEventDef EV_Weapon_GetSpread( "getSpread", "", 'f' );
const idEventDef EV_Weapon_GetAltSpread( "getAltSpread", "", 'f' );
const idEventDef EV_Weapon_GetString( "getString", "s", 's' );
const idEventDef EV_Weapon_GetAltString( "getAltString", "s", 's' );
const idEventDef EV_Weapon_AddToAltClip( "addToAltClip", "f" );
const idEventDef EV_Weapon_AltAmmoInClip( "altAmmoInClip", "", 'f' );
const idEventDef EV_Weapon_AltAmmoAvailable( "altAmmoAvailable", "", 'f' );
const idEventDef EV_Weapon_AltClipSize( "altClipSize", "", 'f' );
const idEventDef EV_Weapon_FireAltProjectiles( "fireAltProjectiles" );
const idEventDef EV_Weapon_FireProjectiles( "fireProjectiles" );
const idEventDef EV_Weapon_WeaponAside( "weaponAside" ); // nla
const idEventDef EV_Weapon_WeaponPuttingAside( "weaponPuttingAside" ); // nla
const idEventDef EV_Weapon_WeaponUprighting( "weaponUprighting" ); // nla
const idEventDef EV_Weapon_IsAnimPlaying( "isAnimPlaying", "s", 'd' );
const idEventDef EV_Weapon_Raise( "<raise>" ); // nla - For the hands to post an event to raise the weapons
const idEventDef EV_Weapon_SetViewAnglesSensitivity( "setViewAnglesSensitivity", "f" );
const idEventDef EV_Weapon_UseAltAmmo( "useAltAmmo", "d" );
const idEventDef EV_Weapon_Hide( "hideWeapon" );
const idEventDef EV_Weapon_Show( "showWeapon" );
CLASS_DECLARATION( hhAnimatedEntity, hhWeapon )
EVENT( EV_Weapon_FireAltProjectiles, hhWeapon::Event_FireAltProjectiles )
EVENT( EV_Weapon_FireProjectiles, hhWeapon::Event_FireProjectiles )
EVENT( EV_PlayAnimWhenReady, hhWeapon::Event_PlayAnimWhenReady )
EVENT( EV_SpawnFxAlongBone, hhWeapon::Event_SpawnFXAlongBone )
EVENT( EV_Weapon_EjectAltBrass, hhWeapon::Event_EjectAltBrass )
EVENT( EV_Weapon_HasAmmo, hhWeapon::Event_HasAmmo )
EVENT( EV_Weapon_HasAltAmmo, hhWeapon::Event_HasAltAmmo )
EVENT( EV_Weapon_AddToAltClip, hhWeapon::Event_AddToAltClip )
EVENT( EV_Weapon_AltAmmoInClip, hhWeapon::Event_AltAmmoInClip )
EVENT( EV_Weapon_AltAmmoAvailable, hhWeapon::Event_AltAmmoAvailable )
EVENT( EV_Weapon_AltClipSize, hhWeapon::Event_AltClipSize )
EVENT( EV_Weapon_GetFireDelay, hhWeapon::Event_GetFireDelay )
EVENT( EV_Weapon_GetAltFireDelay, hhWeapon::Event_GetAltFireDelay )
EVENT( EV_Weapon_GetString, hhWeapon::Event_GetString )
EVENT( EV_Weapon_GetAltString, hhWeapon::Event_GetAltString )
EVENT( EV_Weapon_Raise, hhWeapon::Event_Raise )
EVENT( EV_Weapon_WeaponAside, hhWeapon::Event_Weapon_Aside )
EVENT( EV_Weapon_WeaponPuttingAside, hhWeapon::Event_Weapon_PuttingAside )
EVENT( EV_Weapon_WeaponUprighting, hhWeapon::Event_Weapon_Uprighting )
EVENT( EV_Weapon_IsAnimPlaying, hhWeapon::Event_IsAnimPlaying )
EVENT( EV_Weapon_SetViewAnglesSensitivity, hhWeapon::Event_SetViewAnglesSensitivity )
EVENT( EV_Weapon_Hide, hhWeapon::Event_HideWeapon )
EVENT( EV_Weapon_Show, hhWeapon::Event_ShowWeapon )
//idWeapon
EVENT( EV_Weapon_State, hhWeapon::Event_WeaponState )
EVENT( EV_Weapon_WeaponReady, hhWeapon::Event_WeaponReady )
EVENT( EV_Weapon_WeaponOutOfAmmo, hhWeapon::Event_WeaponOutOfAmmo )
EVENT( EV_Weapon_WeaponReloading, hhWeapon::Event_WeaponReloading )
EVENT( EV_Weapon_WeaponHolstered, hhWeapon::Event_WeaponHolstered )
EVENT( EV_Weapon_WeaponRising, hhWeapon::Event_WeaponRising )
EVENT( EV_Weapon_WeaponLowering, hhWeapon::Event_WeaponLowering )
EVENT( EV_Weapon_AddToClip, hhWeapon::Event_AddToClip )
EVENT( EV_Weapon_AmmoInClip, hhWeapon::Event_AmmoInClip )
EVENT( EV_Weapon_AmmoAvailable, hhWeapon::Event_AmmoAvailable )
EVENT( EV_Weapon_ClipSize, hhWeapon::Event_ClipSize )
EVENT( AI_PlayAnim, hhWeapon::Event_PlayAnim )
EVENT( AI_PlayCycle, hhWeapon::Event_PlayCycle )
EVENT( AI_AnimDone, hhWeapon::Event_AnimDone )
EVENT( EV_Weapon_Next, hhWeapon::Event_Next )
EVENT( EV_Weapon_Flashlight, hhWeapon::Event_Flashlight )
EVENT( EV_Weapon_EjectBrass, hhWeapon::Event_EjectBrass )
EVENT( EV_Weapon_GetOwner, hhWeapon::Event_GetOwner )
EVENT( EV_Weapon_UseAmmo, hhWeapon::Event_UseAmmo )
EVENT( EV_Weapon_UseAltAmmo, hhWeapon::Event_UseAltAmmo )
END_CLASS
/*
================
hhWeapon::hhWeapon
================
*/
hhWeapon::hhWeapon() {
owner = NULL;
worldModel = NULL;
thread = NULL;
//HUMANHEAD: aob
fireController = NULL;
altFireController = NULL;
fl.networkSync = true;
cameraShakeOffset.Zero(); //rww - had to move here to avoid den/nan/blah in spawn
//HUMANHEAD END
Clear();
}
/*
================
hhWeapon::Spawn
================
*/
void hhWeapon::Spawn() {
//idWeapon
if ( !gameLocal.isClient )
{
worldModel = static_cast< hhAnimatedEntity * >( gameLocal.SpawnEntityType( hhAnimatedEntity::Type, NULL ) );
worldModel.GetEntity()->fl.networkSync = true;
}
thread = new idThread();
thread->ManualDelete();
thread->ManualControl();
//idWeapon End
physicsObj.SetSelf( this );
physicsObj.SetClipModel( NULL, 1.0f );
physicsObj.SetOrigin( GetPhysics()->GetOrigin() );
physicsObj.SetAxis( GetPhysics()->GetAxis() );
SetPhysics( &physicsObj );
fl.solidForTeam = true;
// HUMANHEAD: aob
memset( &eyeTraceInfo, 0, sizeof(trace_t) );
eyeTraceInfo.fraction = 1.0f;
BecomeActive( TH_TICKER );
handedness = hhMath::hhMax<int>( 1, spawnArgs.GetInt("handedness", "1") );
fl.neverDormant = true;
// HUMANHEAD END
}
/*
================
hhWeapon::~hhWeapon()
================
*/
hhWeapon::~hhWeapon() {
SAFE_REMOVE( worldModel );
SAFE_REMOVE( thread );
SAFE_DELETE_PTR( fireController );
SAFE_DELETE_PTR( altFireController );
if ( nozzleFx && nozzleGlowHandle != -1 ) {
gameRenderWorld->FreeLightDef( nozzleGlowHandle );
}
}
/*
================
hhWeapon::SetOwner
================
*/
void hhWeapon::SetOwner( idPlayer *_owner ) {
if( !_owner || !_owner->IsType(hhPlayer::Type) ) {
owner = NULL;
return;
}
owner = static_cast<hhPlayer*>( _owner );
if( GetPhysics() && GetPhysics()->IsType(hhPhysics_StaticWeapon::Type) ) {
static_cast<hhPhysics_StaticWeapon*>(GetPhysics())->SetSelfOwner( owner.GetEntity() );
}
}
/*
================
hhWeapon::Save
================
*/
void hhWeapon::Save( idSaveGame *savefile ) const {
savefile->WriteInt( status );
savefile->WriteObject( thread );
savefile->WriteString( state );
savefile->WriteString( idealState );
savefile->WriteInt( animBlendFrames );
savefile->WriteInt( animDoneTime );
owner.Save( savefile );
worldModel.Save( savefile );
savefile->WriteStaticObject( physicsObj );
savefile->WriteObject( fireController );
savefile->WriteObject( altFireController );
savefile->WriteTrace( eyeTraceInfo );
savefile->WriteVec3( cameraShakeOffset );
savefile->WriteInt( handedness );
savefile->WriteVec3( pushVelocity );
savefile->WriteString( weaponDef->GetName() );
savefile->WriteString( icon );
savefile->WriteInt( kick_endtime );
savefile->WriteBool( lightOn );
savefile->WriteInt( zoomFov );
savefile->WriteInt( weaponAngleOffsetAverages );
savefile->WriteFloat( weaponAngleOffsetScale );
savefile->WriteFloat( weaponAngleOffsetMax );
savefile->WriteFloat( weaponOffsetTime );
savefile->WriteFloat( weaponOffsetScale );
savefile->WriteBool( nozzleFx );
//HUMANHEAD PCF mdl 05/04/06 - Don't save light handles
//savefile->WriteInt( nozzleGlowHandle );
savefile->WriteJoint( nozzleJointHandle.view );
savefile->WriteJoint( nozzleJointHandle.world );
savefile->WriteRenderLight( nozzleGlow );
savefile->WriteVec3( nozzleGlowColor );
savefile->WriteMaterial( nozzleGlowShader );
savefile->WriteFloat( nozzleGlowRadius );
savefile->WriteVec3( nozzleGlowOffset );
}
/*
================
hhWeapon::Restore
================
*/
void hhWeapon::Restore( idRestoreGame *savefile ) {
savefile->ReadInt( (int &)status );
savefile->ReadObject( reinterpret_cast<idClass*&>(thread) );
savefile->ReadString( state );
savefile->ReadString( idealState );
savefile->ReadInt( animBlendFrames );
savefile->ReadInt( animDoneTime );
//Re-link script fields
WEAPON_ATTACK.LinkTo( scriptObject, "WEAPON_ATTACK" );
WEAPON_RELOAD.LinkTo( scriptObject, "WEAPON_RELOAD" );
WEAPON_RAISEWEAPON.LinkTo( scriptObject, "WEAPON_RAISEWEAPON" );
WEAPON_LOWERWEAPON.LinkTo( scriptObject, "WEAPON_LOWERWEAPON" );
WEAPON_NEXTATTACK.LinkTo( scriptObject, "nextAttack" ); //HUMANHEAD rww
//HUMANHEAD: aob
WEAPON_ALTATTACK.LinkTo( scriptObject, "WEAPON_ALTATTACK" );
WEAPON_ASIDEWEAPON.LinkTo( scriptObject, "WEAPON_ASIDEWEAPON" );
WEAPON_ALTMODE.LinkTo( scriptObject, "WEAPON_ALTMODE" );
//HUMANHEAD END
owner.Restore( savefile );
worldModel.Restore( savefile );
savefile->ReadStaticObject( physicsObj );
RestorePhysics( &physicsObj );
savefile->ReadObject( reinterpret_cast< idClass *&> ( fireController ) );
savefile->ReadObject( reinterpret_cast< idClass *&> ( altFireController ) );
savefile->ReadTrace( eyeTraceInfo );
savefile->ReadVec3( cameraShakeOffset );
savefile->ReadInt( handedness );
savefile->ReadVec3( pushVelocity );
idStr objectname;
savefile->ReadString( objectname );
weaponDef = gameLocal.FindEntityDef( objectname, false );
if (!weaponDef) {
gameLocal.Error( "Unknown weaponDef: %s\n", objectname );
}
dict = &(weaponDef->dict);
savefile->ReadString( icon );
savefile->ReadInt( kick_endtime );
savefile->ReadBool( lightOn );
savefile->ReadInt( zoomFov );
savefile->ReadInt( weaponAngleOffsetAverages );
savefile->ReadFloat( weaponAngleOffsetScale );
savefile->ReadFloat( weaponAngleOffsetMax );
savefile->ReadFloat( weaponOffsetTime );
savefile->ReadFloat( weaponOffsetScale );
savefile->ReadBool( nozzleFx );
//HUMANHEAD PCF mdl 05/04/06 - Don't save light handles
//savefile->ReadInt( nozzleGlowHandle );
savefile->ReadJoint( nozzleJointHandle.view );
savefile->ReadJoint( nozzleJointHandle.world );
savefile->ReadRenderLight( nozzleGlow );
savefile->ReadVec3( nozzleGlowColor );
savefile->ReadMaterial( nozzleGlowShader );
savefile->ReadFloat( nozzleGlowRadius );
savefile->ReadVec3( nozzleGlowOffset );
}
/*
================
hhWeapon::Clear
================
*/
void hhWeapon::Clear( void ) {
DeconstructScriptObject();
scriptObject.Free();
WEAPON_ATTACK.Unlink();
WEAPON_RELOAD.Unlink();
WEAPON_RAISEWEAPON.Unlink();
WEAPON_LOWERWEAPON.Unlink();
WEAPON_NEXTATTACK.Unlink(); //HUMANHEAD rww
//HUMANHEAD: aob
WEAPON_ALTATTACK.Unlink();
WEAPON_ASIDEWEAPON.Unlink();
WEAPON_ALTMODE.Unlink();
SAFE_DELETE_PTR( fireController );
SAFE_DELETE_PTR( altFireController );
//HUMANEAD END
//memset( &renderEntity, 0, sizeof( renderEntity ) );
renderEntity.entityNum = entityNumber;
renderEntity.noShadow = true;
renderEntity.noSelfShadow = true;
renderEntity.customSkin = NULL;
// set default shader parms
renderEntity.shaderParms[ SHADERPARM_RED ] = 1.0f;
renderEntity.shaderParms[ SHADERPARM_GREEN ]= 1.0f;
renderEntity.shaderParms[ SHADERPARM_BLUE ] = 1.0f;
renderEntity.shaderParms[3] = 1.0f;
renderEntity.shaderParms[ SHADERPARM_TIMEOFFSET ] = 0.0f;
renderEntity.shaderParms[5] = 0.0f;
renderEntity.shaderParms[6] = 0.0f;
renderEntity.shaderParms[7] = 0.0f;
// nozzle fx
nozzleFx = false;
memset( &nozzleGlow, 0, sizeof( nozzleGlow ) );
nozzleGlowHandle = -1;
nozzleJointHandle.Clear();
memset( &refSound, 0, sizeof( refSound_t ) );
if ( owner.IsValid() ) {
// don't spatialize the weapon sounds
refSound.listenerId = owner->GetListenerId();
}
// clear out the sounds from our spawnargs since we'll copy them from the weapon def
const idKeyValue *kv = spawnArgs.MatchPrefix( "snd_" );
while( kv ) {
spawnArgs.Delete( kv->GetKey() );
kv = spawnArgs.MatchPrefix( "snd_" );
}
weaponDef = NULL;
dict = NULL;
kick_endtime = 0;
icon = "";
pushVelocity.Zero();
status = WP_HOLSTERED;
state = "";
idealState = "";
animBlendFrames = 0;
animDoneTime = 0;
lightOn = false;
zoomFov = 90;
weaponAngleOffsetAverages = 10; //initialize this to default number to prevent infinite loops
FreeModelDef();
}
/*
================
hhWeapon::InitWorldModel
================
*/
void hhWeapon::InitWorldModel( const idDict *dict ) {
idEntity *ent;
ent = worldModel.GetEntity();
if ( !ent || !dict ) {
return;
}
const char *model = dict->GetString( "model_world" );
const char *attach = dict->GetString( "joint_attach" );
if (gameLocal.isMultiplayer) { //HUMANHEAD rww - shadow default based on whether the player shadows
ent->GetRenderEntity()->noShadow = MP_PLAYERNOSHADOW_DEFAULT;
}
if ( model[0] && attach[0] ) {
ent->Show();
ent->SetModel( model );
ent->GetPhysics()->SetContents( 0 );
ent->GetPhysics()->SetClipModel( NULL, 1.0f );
ent->BindToJoint( owner.GetEntity(), attach, true );
ent->GetPhysics()->SetOrigin( vec3_origin );
ent->GetPhysics()->SetAxis( mat3_identity );
// supress model in player views, but allow it in mirrors and remote views
renderEntity_t *worldModelRenderEntity = ent->GetRenderEntity();
if ( worldModelRenderEntity ) {
worldModelRenderEntity->suppressSurfaceInViewID = owner->entityNumber+1;
worldModelRenderEntity->suppressShadowInViewID = owner->entityNumber+1;
worldModelRenderEntity->suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + owner->entityNumber;
}
} else {
ent->SetModel( "" );
ent->Hide();
}
}
/*
================
hhWeapon::GetWeaponDef
HUMANHEAD: aob - this should only be called after the weapon has just been created
================
*/
void hhWeapon::GetWeaponDef( const char *objectname ) {
//HUMANHEAD: aob - put logic in helper function
ParseDef( objectname );
//HUMANHEAD END
if( owner->inventory.weaponRaised[owner->GetWeaponNum(objectname)] || gameLocal.isMultiplayer )
ProcessEvent( &EV_Weapon_State, "Raise", 0 );
else {
ProcessEvent( &EV_Weapon_State, "NewRaise", 0 );
owner->inventory.weaponRaised[owner->GetWeaponNum(objectname)] = true;
}
}
/*
================
hhWeapon::ParseDef
HUMANHEAD: aob
================
*/
void hhWeapon::ParseDef( const char* objectname ) {
if( !objectname || !objectname[ 0 ] ) {
return;
}
if( !owner.IsValid() ) {
gameLocal.Error( "hhWeapon::ParseDef: no owner" );
}
weaponDef = gameLocal.FindEntityDef( objectname, false );
if (!weaponDef) {
gameLocal.Error( "Unknown weaponDef: %s\n", objectname );
}
dict = &(weaponDef->dict);
// setup the world model
InitWorldModel( dict );
if (!owner.IsValid() || !owner.GetEntity()) {
gameLocal.Error("NULL owner in hhWeapon::ParseDef!");
}
//HUMANHEAD: aob
const idDict* infoDict = gameLocal.FindEntityDefDict( dict->GetString("def_fireInfo"), false );
if( infoDict ) {
fireController = CreateFireController();
if( fireController ) {
fireController->Init( infoDict, this, owner.GetEntity() );
}
}
infoDict = gameLocal.FindEntityDefDict( dict->GetString("def_altFireInfo"), false );
if( infoDict ) {
altFireController = CreateAltFireController();
if( altFireController ) {
altFireController->Init( infoDict, this, owner.GetEntity() );
}
}
//HUMANHEAD END
icon = dict->GetString( "inv_icon" );
// copy the sounds from the weapon view model def into out spawnargs
const idKeyValue *kv = dict->MatchPrefix( "snd_" );
while( kv ) {
spawnArgs.Set( kv->GetKey(), kv->GetValue() );
kv = dict->MatchPrefix( "snd_", kv );
}
weaponAngleOffsetAverages = dict->GetInt( "weaponAngleOffsetAverages", "10" );
weaponAngleOffsetScale = dict->GetFloat( "weaponAngleOffsetScale", "0.1" );
weaponAngleOffsetMax = dict->GetFloat( "weaponAngleOffsetMax", "10" );
weaponOffsetTime = dict->GetFloat( "weaponOffsetTime", "400" );
weaponOffsetScale = dict->GetFloat( "weaponOffsetScale", "0.002" );
zoomFov = dict->GetInt( "zoomFov", "70" );
InitScriptObject( dict->GetString("scriptobject") );
nozzleFx = weaponDef->dict.GetBool( "nozzleFx", "0" );
nozzleGlowColor = weaponDef->dict.GetVector("nozzleGlowColor", "1 1 1");
nozzleGlowRadius = weaponDef->dict.GetFloat("nozzleGlowRadius", "10");
nozzleGlowOffset = weaponDef->dict.GetVector( "nozzleGlowOffset", "0 0 0" );
nozzleGlowShader = declManager->FindMaterial( weaponDef->dict.GetString( "mtr_nozzleGlowShader", "" ), false );
GetJointHandle( weaponDef->dict.GetString( "nozzleJoint", "" ), nozzleJointHandle );
//HUMANHEAD bjk
int clipAmmo = owner->inventory.clip[owner->GetWeaponNum(objectname)];
if ( ( clipAmmo < 0 ) || ( clipAmmo > fireController->ClipSize() ) ) {
// first time using this weapon so have it fully loaded to start
clipAmmo = fireController->ClipSize();
if ( clipAmmo > fireController->AmmoAvailable() ) {
clipAmmo = fireController->AmmoAvailable();
}
}
fireController->AddToClip(clipAmmo);
WEAPON_ALTMODE = owner->inventory.altMode[owner->GetWeaponNum(objectname)];
//HUMANHEAD END
Show();
}
/*
================
idWeapon::ShouldConstructScriptObjectAtSpawn
Called during idEntity::Spawn to see if it should construct the script object or not.
Overridden by subclasses that need to spawn the script object themselves.
================
*/
bool hhWeapon::ShouldConstructScriptObjectAtSpawn( void ) const {
return false;
}
/*
================
hhWeapon::InitScriptObject
================
*/
void hhWeapon::InitScriptObject( const char* objectType ) {
if( !objectType || !objectType[0] ) {
gameLocal.Error( "No scriptobject set on '%s'.", dict->GetString("classname") );
}
if( !idStr::Icmp(scriptObject.GetTypeName(), objectType) ) {
//Same script object, don't reload it
return;
}
// setup script object
if( !scriptObject.SetType(objectType) ) {
gameLocal.Error( "Script object '%s' not found on weapon '%s'.", objectType, dict->GetString("classname") );
}
WEAPON_ATTACK.LinkTo( scriptObject, "WEAPON_ATTACK" );
WEAPON_RELOAD.LinkTo( scriptObject, "WEAPON_RELOAD" );
WEAPON_RAISEWEAPON.LinkTo( scriptObject, "WEAPON_RAISEWEAPON" );
WEAPON_LOWERWEAPON.LinkTo( scriptObject, "WEAPON_LOWERWEAPON" );
WEAPON_NEXTATTACK.LinkTo( scriptObject, "nextAttack" ); //HUMANHEAD rww
//HUMANHEAD: aob
WEAPON_ALTATTACK.LinkTo( scriptObject, "WEAPON_ALTATTACK" );
WEAPON_ASIDEWEAPON.LinkTo( scriptObject, "WEAPON_ASIDEWEAPON" );
WEAPON_ALTMODE.LinkTo( scriptObject, "WEAPON_ALTMODE" );
//HUMANHEAD END
// call script object's constructor
ConstructScriptObject();
}
/***********************************************************************
GUIs
***********************************************************************/
/*
================
hhWeapon::Icon
================
*/
const char *hhWeapon::Icon( void ) const {
return icon;
}
/*
================
hhWeapon::UpdateGUI
================
*/
void hhWeapon::UpdateGUI() {
if ( !renderEntity.gui[0] ) {
return;
}
if ( status == WP_HOLSTERED ) {
return;
}
int ammoamount = AmmoAvailable();
int altammoamount = AltAmmoAvailable();
// show remaining ammo
renderEntity.gui[ 0 ]->SetStateInt( "ammoamount", ammoamount );
renderEntity.gui[ 0 ]->SetStateInt( "altammoamount", altammoamount );
renderEntity.gui[ 0 ]->SetStateBool( "ammolow", ammoamount > 0 && ammoamount <= LowAmmo() );
renderEntity.gui[ 0 ]->SetStateBool( "altammolow", altammoamount > 0 && altammoamount <= LowAltAmmo() );
renderEntity.gui[ 0 ]->SetStateBool( "ammoempty", ( ammoamount == 0 ) );
renderEntity.gui[ 0 ]->SetStateBool( "altammoempty", ( altammoamount == 0 ) );
renderEntity.gui[ 0 ]->SetStateInt( "clipammoAmount", AmmoInClip() );
renderEntity.gui[ 0 ]->SetStateInt( "clipaltammoAmount", AltAmmoInClip() );
renderEntity.gui[ 0 ]->StateChanged(gameLocal.time);
}
/***********************************************************************
Model and muzzleflash
***********************************************************************/
/*
================
hhWeapon::GetGlobalJointTransform
This returns the offset and axis of a weapon bone in world space, suitable for attaching models or lights
================
*/
bool hhWeapon::GetJointWorldTransform( const char* jointName, idVec3 &offset, idMat3 &axis ) {
weaponJointHandle_t handle;
GetJointHandle( jointName, handle );
return GetJointWorldTransform( handle, offset, axis );
}
/*
================
hhWeapon::GetGlobalJointTransform
This returns the offset and axis of a weapon bone in world space, suitable for attaching models or lights
================
*/
bool hhWeapon::GetJointWorldTransform( const weaponJointHandle_t& handle, idVec3 &offset, idMat3 &axis, bool muzzleOnly ) {
//FIXME: this seems to work but may need revisiting
//FIXME: totally forgot about mirrors and portals. This may not work.
if( (!pm_thirdPerson.GetBool() && owner == gameLocal.GetLocalPlayer()) || (gameLocal.GetLocalPlayer() && gameLocal.GetLocalPlayer()->spectating && gameLocal.GetLocalPlayer()->spectator == owner->entityNumber) || (gameLocal.isServer && !muzzleOnly)) { //rww - mp server should always create projectiles from the viewmodel
// view model
if ( hhAnimatedEntity::GetJointWorldTransform(handle.view, offset, axis) ) {
return true;
}
} else {
// world model
if ( worldModel.IsValid() && worldModel.GetEntity()->GetJointWorldTransform(handle.world, offset, axis) ) {
return true;
}
}
offset = GetOrigin();
axis = GetAxis();
return false;
}
/*
================
hhWeapon::GetJointHandle
HUMANHEAD: aob
================
*/
void hhWeapon::GetJointHandle( const char* jointName, weaponJointHandle_t& handle ) {
if( dict ) {
handle.view = GetAnimator()->GetJointHandle( jointName );
}
if( worldModel.IsValid() ) {
handle.world = worldModel->GetAnimator()->GetJointHandle( jointName );
}
}
/*
================
hhWeapon::SetPushVelocity
================
*/
void hhWeapon::SetPushVelocity( const idVec3 &pushVelocity ) {
this->pushVelocity = pushVelocity;
}
/***********************************************************************
State control/player interface
***********************************************************************/
/*
================
hhWeapon::Raise
================
*/
void hhWeapon::Raise( void ) {
WEAPON_RAISEWEAPON = true;
WEAPON_ASIDEWEAPON = false;
}
/*
================
hhWeapon::PutAway
================
*/
void hhWeapon::PutAway( void ) {
//hasBloodSplat = false;
WEAPON_LOWERWEAPON = true;
WEAPON_RAISEWEAPON = false; //HUMANHEAD bjk PCF 5-4-06 : fix for weapons being up after death
WEAPON_ASIDEWEAPON = false;
WEAPON_ATTACK = false;
WEAPON_ALTATTACK = false;
}
/*
================
hhWeapon::PutAside
================
*/
void hhWeapon::PutAside( void ) {
//HUMANHEAD bjk PCF (4-27-06) - no setting unnecessary weapon state
//WEAPON_LOWERWEAPON = false;
//WEAPON_RAISEWEAPON = false;
WEAPON_ASIDEWEAPON = true;
WEAPON_ATTACK = false;
WEAPON_ALTATTACK = false;
}
/*
================
hhWeapon::PutUpright
================
*/
void hhWeapon::PutUpright( void ) {
WEAPON_ASIDEWEAPON = false;
}
/*
================
hhWeapon::SnapDown
HUMANHEAD: aob
================
*/
void hhWeapon::SnapDown() {
ProcessEvent( &EV_Weapon_State, "Down", 0 );
}
/*
================
hhWeapon::SnapUp
HUMANHEAD: aob
================
*/
void hhWeapon::SnapUp() {
ProcessEvent( &EV_Weapon_State, "Up", 0 );
}
/*
================
hhWeapon::Reload
================
*/
void hhWeapon::Reload( void ) {
WEAPON_RELOAD = true;
}
/*
================
hhWeapon::HideWeapon
================
*/
void hhWeapon::HideWeapon( void ) {
Hide();
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Hide();
}
}
/*
================
hhWeapon::ShowWeapon
================
*/
void hhWeapon::ShowWeapon( void ) {
Show();
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Show();
}
}
/*
================
hhWeapon::HideWorldModel
================
*/
void hhWeapon::HideWorldModel( void ) {
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Hide();
}
}
/*
================
hhWeapon::ShowWorldModel
================
*/
void hhWeapon::ShowWorldModel( void ) {
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Show();
}
}
/*
================
hhWeapon::OwnerDied
================
*/
void hhWeapon::OwnerDied( void ) {
Hide();
if ( worldModel.GetEntity() ) {
worldModel.GetEntity()->Hide();
}
}
/*
================
hhWeapon::BeginAltAttack
================
*/
void hhWeapon::BeginAltAttack( void ) {
WEAPON_ALTATTACK = true;
//if ( status != WP_OUTOFAMMO ) {
// lastAttack = gameLocal.time;
//}
}
/*
================
hhWeapon::EndAltAttack
================
*/
void hhWeapon::EndAltAttack( void ) {
WEAPON_ALTATTACK = false;
}
/*
================
hhWeapon::BeginAttack
================
*/
void hhWeapon::BeginAttack( void ) {
//if ( status != WP_OUTOFAMMO ) {
// lastAttack = gameLocal.time;
//}
WEAPON_ATTACK = true;
}
/*
================
hhWeapon::EndAttack
================
*/
void hhWeapon::EndAttack( void ) {
if ( !WEAPON_ATTACK.IsLinked() ) {
return;
}
if ( WEAPON_ATTACK ) {
WEAPON_ATTACK = false;
}
}
/*
================
hhWeapon::isReady
================
*/
bool hhWeapon::IsReady( void ) const {
return !IsHidden() && ( ( status == WP_READY ) || ( status == WP_OUTOFAMMO ) );
}
/*
================
hhWeapon::IsReloading
================
*/
bool hhWeapon::IsReloading( void ) const {
return ( status == WP_RELOAD );
}
/*
================
hhWeapon::IsChangable
================
*/
bool hhWeapon::IsChangable( void ) const {
//HUMANHEAD: aob - same as IsReady except w/o IsHidden check
//Allows us to switch weapons while they are hidden
//Hope this doesn't fuck to many things
return ( ( status == WP_READY ) || ( status == WP_OUTOFAMMO ) );
}
/*
================
hhWeapon::IsHolstered
================
*/
bool hhWeapon::IsHolstered( void ) const {
return ( status == WP_HOLSTERED );
}
/*
================
hhWeapon::IsLowered
================
*/
bool hhWeapon::IsLowered( void ) const {
return ( status == WP_HOLSTERED ) || ( status == WP_LOWERING );
}
/*
================
hhWeapon::IsRising
================
*/
bool hhWeapon::IsRising( void ) const {
return ( status == WP_RISING );
}
/*
================
hhWeapon::IsAside
================
*/
bool hhWeapon::IsAside( void ) const {
return ( status == WP_ASIDE );
}
/*
================
hhWeapon::ShowCrosshair
================
*/
bool hhWeapon::ShowCrosshair( void ) const {
//HUMANHEAD: aob - added cinematic check
return !( state == idStr( WP_RISING ) || state == idStr( WP_LOWERING ) || state == idStr( WP_HOLSTERED ) ) && !owner->InCinematic();
}
/*
=====================
hhWeapon::DropItem
=====================
*/
idEntity* hhWeapon::DropItem( const idVec3 &velocity, int activateDelay, int removeDelay, bool died ) {
if ( !weaponDef || !worldModel.GetEntity() ) {
return NULL;
}
const char *classname = weaponDef->dict.GetString( "def_dropItem" );
if ( !classname[0] ) {
return NULL;
}
StopSound( SND_CHANNEL_BODY, !died ); //HUMANHEAD rww - on death, do not broadcast the stop, because the weapon itself is about to be removed
return idMoveableItem::DropItem( classname, worldModel.GetEntity()->GetPhysics()->GetOrigin(), worldModel.GetEntity()->GetPhysics()->GetAxis(), velocity, activateDelay, removeDelay );
}
/*
=====================
hhWeapon::CanDrop
=====================
*/
bool hhWeapon::CanDrop( void ) const {
if ( !weaponDef || !worldModel.GetEntity() ) {
return false;
}
const char *classname = weaponDef->dict.GetString( "def_dropItem" );
if ( !classname[ 0 ] ) {
return false;
}
return true;
}
/***********************************************************************
Script state management
***********************************************************************/
/*
=====================
hhWeapon::SetState
=====================
*/
void hhWeapon::SetState( const char *statename, int blendFrames ) {
const function_t *func;
func = scriptObject.GetFunction( statename );
if ( !func ) {
gameLocal.Error( "Can't find function '%s' in object '%s'", statename, scriptObject.GetTypeName() );
}
thread->CallFunction( this, func, true );
state = statename;
animBlendFrames = blendFrames;
if ( g_debugWeapon.GetBool() ) {
gameLocal.Printf( "%d: weapon state : %s\n", gameLocal.time, statename );
}
idealState = "";
}
/***********************************************************************
Visual presentation
***********************************************************************/
/*
================
hhWeapon::MuzzleRise
HUMANHEAD: aob
================
*/
void hhWeapon::MuzzleRise( idVec3 &origin, idMat3 &axis ) {
if( fireController ) {
fireController->CalculateMuzzleRise( origin, axis );
}
if( altFireController ) {
altFireController->CalculateMuzzleRise( origin, axis );
}
}
/*
================
hhWeapon::ConstructScriptObject
Called during idEntity::Spawn. Calls the constructor on the script object.
Can be overridden by subclasses when a thread doesn't need to be allocated.
================
*/
idThread *hhWeapon::ConstructScriptObject( void ) {
const function_t *constructor;
//HUMANHEAD: aob
if( !thread ) {
return thread;
}
//HUMANHEAD END
thread->EndThread();
// call script object's constructor
constructor = scriptObject.GetConstructor();
if ( !constructor ) {
gameLocal.Error( "Missing constructor on '%s' for weapon", scriptObject.GetTypeName() );
}
// init the script object's data
scriptObject.ClearObject();
thread->CallFunction( this, constructor, true );
thread->Execute();
return thread;
}
/*
================
hhWeapon::DeconstructScriptObject
Called during idEntity::~idEntity. Calls the destructor on the script object.
Can be overridden by subclasses when a thread doesn't need to be allocated.
Not called during idGameLocal::MapShutdown.
================
*/
void hhWeapon::DeconstructScriptObject( void ) {
const function_t *destructor;
if ( !thread ) {
return;
}
// don't bother calling the script object's destructor on map shutdown
if ( gameLocal.GameState() == GAMESTATE_SHUTDOWN ) {
return;
}
thread->EndThread();
// call script object's destructor
destructor = scriptObject.GetDestructor();
if ( destructor ) {
// start a thread that will run immediately and end
thread->CallFunction( this, destructor, true );
thread->Execute();
thread->EndThread();
}
// clear out the object's memory
scriptObject.ClearObject();
}
/*
================
hhWeapon::UpdateScript
================
*/
void hhWeapon::UpdateScript( void ) {
int count;
if ( !IsLinked() ) {
return;
}
// only update the script on new frames
if ( !gameLocal.isNewFrame ) {
return;
}
if ( idealState.Length() ) {
SetState( idealState, animBlendFrames );
}
// update script state, which may call Event_LaunchProjectiles, among other things
count = 10;
while( ( thread->Execute() || idealState.Length() ) && count-- ) {
// happens for weapons with no clip (like grenades)
if ( idealState.Length() ) {
SetState( idealState, animBlendFrames );
}
}
WEAPON_RELOAD = false;
}
/*
================
hhWeapon::PresentWeapon
================
*/
void hhWeapon::PresentWeapon( bool showViewModel ) {
UpdateScript();
//HUMANHEAD rww - added this gui owner logic here
bool allowGuiUpdate = true;
if ( owner.IsValid() && gameLocal.localClientNum != owner->entityNumber ) {
// if updating the hud for a followed client
if ( gameLocal.localClientNum >= 0 && gameLocal.entities[ gameLocal.localClientNum ] && gameLocal.entities[ gameLocal.localClientNum ]->IsType( idPlayer::Type ) ) {
idPlayer *p = static_cast< idPlayer * >( gameLocal.entities[ gameLocal.localClientNum ] );
if ( !p->spectating || p->spectator != owner->entityNumber ) {
allowGuiUpdate = false;
}
} else {
allowGuiUpdate = false;
}
}
if (allowGuiUpdate) {
UpdateGUI();
}
// update animation
UpdateAnimation();
// only show the surface in player view
renderEntity.allowSurfaceInViewID = owner->entityNumber+1;
// crunch the depth range so it never pokes into walls this breaks the machine gun gui
renderEntity.weaponDepthHack = true;
// present the model
if ( showViewModel ) {
Present();
} else {
FreeModelDef();
}
if ( worldModel.GetEntity() && worldModel.GetEntity()->GetRenderEntity() ) {
// deal with the third-person visible world model
// don't show shadows of the world model in first person
#ifdef HUMANHEAD
if ( gameLocal.isMultiplayer || (g_showPlayerShadow.GetBool() && pm_modelView.GetInteger() == 1) || pm_thirdPerson.GetBool()
|| (pm_modelView.GetInteger() == 2 && owner->health <= 0)) {
worldModel->GetRenderEntity()->suppressShadowInViewID = 0;
} else {
worldModel->GetRenderEntity()->suppressShadowInViewID = owner->entityNumber+1;
worldModel->GetRenderEntity()->suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + owner->entityNumber;
}
#else
// deal with the third-person visible world model
// don't show shadows of the world model in first person
if ( gameLocal.isMultiplayer || g_showPlayerShadow.GetBool() || pm_thirdPerson.GetBool() ) {
worldModel.GetEntity()->GetRenderEntity()->suppressShadowInViewID = 0;
} else {
worldModel.GetEntity()->GetRenderEntity()->suppressShadowInViewID = owner->entityNumber+1;
worldModel.GetEntity()->GetRenderEntity()->suppressShadowInLightID = LIGHTID_VIEW_MUZZLE_FLASH + owner->entityNumber;
}
}
#endif // HUMANHEAD pdm
}
// update the muzzle flash light, so it moves with the gun
//HUMANHEAD: aob
if( fireController ) {
fireController->UpdateMuzzleFlash();
}
if( altFireController ) {
altFireController->UpdateMuzzleFlash();
}
//HUMANHEAD END
UpdateNozzleFx(); // expensive
UpdateSound();
}
/*
================
hhWeapon::EnterCinematic
================
*/
void hhWeapon::EnterCinematic( void ) {
StopSound( SND_CHANNEL_ANY, false );
if ( IsLinked() ) {
SetState( "EnterCinematic", 0 );
thread->Execute();
WEAPON_ATTACK = false;
WEAPON_RELOAD = false;
// WEAPON_NETRELOAD = false;
// WEAPON_NETENDRELOAD = false;
WEAPON_RAISEWEAPON = false;
WEAPON_LOWERWEAPON = false;
}
//disabled = true;
LowerWeapon();
}
/*
================
hhWeapon::ExitCinematic
================
*/
void hhWeapon::ExitCinematic( void ) {
//disabled = false;
if ( IsLinked() ) {
SetState( "ExitCinematic", 0 );
thread->Execute();
}
RaiseWeapon();
}
/*
================
hhWeapon::NetCatchup
================
*/
void hhWeapon::NetCatchup( void ) {
if ( IsLinked() ) {
SetState( "NetCatchup", 0 );
thread->Execute();
}
}
/*
================
hhWeapon::GetClipBits
================
*/
int hhWeapon::GetClipBits(void) const {
return ASYNC_PLAYER_INV_CLIP_BITS;
}
/*
================
hhWeapon::GetZoomFov
================
*/
int hhWeapon::GetZoomFov( void ) {
return zoomFov;
}
/*
================
hhWeapon::GetWeaponAngleOffsets
================
*/
void hhWeapon::GetWeaponAngleOffsets( int *average, float *scale, float *max ) {
*average = weaponAngleOffsetAverages;
*scale = weaponAngleOffsetScale;
*max = weaponAngleOffsetMax;
}
/*
================
hhWeapon::GetWeaponTimeOffsets
================
*/
void hhWeapon::GetWeaponTimeOffsets( float *time, float *scale ) {
*time = weaponOffsetTime;
*scale = weaponOffsetScale;
}
/***********************************************************************
Ammo
**********************************************************************/
/*
================
hhWeapon::WriteToSnapshot
================
*/
void hhWeapon::WriteToSnapshot( idBitMsgDelta &msg ) const {
#if 0
//FIXME: need to add altFire stuff too
if( fireController ) {
msg.WriteBits( fireController->AmmoInClip(), GetClipBits() );
} else {
msg.WriteBits( 0, GetClipBits() );
}
msg.WriteBits(worldModel.GetSpawnId(), 32);
#else //rww - forget this silliness, let's do this the Right Way.
msg.WriteBits(owner.GetSpawnId(), 32);
msg.WriteBits(worldModel.GetSpawnId(), 32);
if (fireController) {
fireController->WriteToSnapshot(msg);
}
else { //rwwFIXME this is an ugly hack
msg.WriteBits(0, 32);
msg.WriteBits(0, 32);
msg.WriteBits(0, GetClipBits());
}
if (altFireController) {
altFireController->WriteToSnapshot(msg);
}
else { //rwwFIXME this is an ugly hack
msg.WriteBits(0, 32);
msg.WriteBits(0, 32);
msg.WriteBits(0, GetClipBits());
}
msg.WriteBits(WEAPON_ASIDEWEAPON, 1);
//HUMANHEAD PCF rww 05/09/06 - no need to sync these values
/*
msg.WriteBits(WEAPON_LOWERWEAPON, 1);
msg.WriteBits(WEAPON_RAISEWEAPON, 1);
*/
WriteBindToSnapshot(msg);
#endif
}
/*
================
hhWeapon::ReadFromSnapshot
================
*/
void hhWeapon::ReadFromSnapshot( const idBitMsgDelta &msg ) {
#if 0
//FIXME: need to add altFire stuff too
if( fireController ) {
fireController->AddToClip( msg.ReadBits(GetClipBits()) );
} else {
msg.ReadBits( GetClipBits() );
}
worldModel.SetSpawnId(msg.ReadBits(32));
#else
bool wmInit = false;
owner.SetSpawnId(msg.ReadBits(32));
if (worldModel.SetSpawnId(msg.ReadBits(32))) { //do this once we finally get the entity in the snapshot
wmInit = true;
}
//rwwFIXME this is a little hacky, i think. is there a way to do it in ::Spawn? but, the weapon doesn't know its owner at that point.
if (!dict) {
if (!owner.IsValid() || !owner.GetEntity()) {
gameLocal.Error("NULL owner in hhWeapon::ReadFromSnapshot!");
}
assert(owner.IsValid());
GetWeaponDef(spawnArgs.GetString("classname"));
//owner->ForceWeapon(this); it doesn't like this.
}
assert(fireController);
assert(altFireController);
if (wmInit) { //need to do this once the ent is valid on the client
InitWorldModel( dict );
GetJointHandle( weaponDef->dict.GetString( "nozzleJoint", "" ), nozzleJointHandle );
fireController->UpdateWeaponJoints();
altFireController->UpdateWeaponJoints();
}
fireController->ReadFromSnapshot(msg);
altFireController->ReadFromSnapshot(msg);
WEAPON_ASIDEWEAPON = !!msg.ReadBits(1);
//HUMANHEAD PCF rww 05/09/06 - no need to sync these values
/*
WEAPON_LOWERWEAPON = !!msg.ReadBits(1);
WEAPON_RAISEWEAPON = !!msg.ReadBits(1);
*/
ReadBindFromSnapshot(msg);
#endif
}
/*
================
hhWeapon::ClientPredictionThink
================
*/
void hhWeapon::ClientPredictionThink( void ) {
Think();
}
/***********************************************************************
Script events
***********************************************************************/
/*
hhWeapon::Event_Raise
*/
void hhWeapon::Event_Raise() {
Raise();
}
/*
===============
hhWeapon::Event_WeaponState
===============
*/
void hhWeapon::Event_WeaponState( const char *statename, int blendFrames ) {
const function_t *func;
func = scriptObject.GetFunction( statename );
if ( !func ) {
gameLocal.Error( "Can't find function '%s' in object '%s'", statename, scriptObject.GetTypeName() );
}
idealState = statename;
animBlendFrames = blendFrames;
thread->DoneProcessing();
}
/*
===============
hhWeapon::Event_WeaponReady
===============
*/
void hhWeapon::Event_WeaponReady( void ) {
status = WP_READY;
WEAPON_RAISEWEAPON = false;
//HUMANHEAD bjk PCF (4-27-06) - no setting unnecessary weapon state
//WEAPON_LOWERWEAPON = false;
//WEAPON_ASIDEWEAPON = false;
}
/*
===============
hhWeapon::Event_WeaponOutOfAmmo
===============
*/
void hhWeapon::Event_WeaponOutOfAmmo( void ) {
status = WP_OUTOFAMMO;
WEAPON_RAISEWEAPON = false;
//HUMANHEAD bjk PCF (4-27-06) - no setting unnecessary weapon state
//WEAPON_LOWERWEAPON = false;
//WEAPON_ASIDEWEAPON = false;
}
/*
===============
hhWeapon::Event_WeaponReloading
===============
*/
void hhWeapon::Event_WeaponReloading( void ) {
status = WP_RELOAD;
}
/*
===============
hhWeapon::Event_WeaponHolstered
===============
*/
void hhWeapon::Event_WeaponHolstered( void ) {
status = WP_HOLSTERED;
WEAPON_LOWERWEAPON = false;
}
/*
===============
hhWeapon::Event_WeaponRising
===============
*/
void hhWeapon::Event_WeaponRising( void ) {
status = WP_RISING;
WEAPON_LOWERWEAPON = false;
//HUMANHEAD bjk PCF (4-27-06) - no setting unnecessary weapon state
//WEAPON_ASIDEWEAPON = false;
owner->WeaponRisingCallback();
}
/*
===============
hhWeapon::Event_WeaponAside
===============
*/
void hhWeapon::Event_Weapon_Aside( void ) {
status = WP_ASIDE;
}
/*
===============
hhWeapon::Event_Weapon_PuttingAside
===============
*/
void hhWeapon::Event_Weapon_PuttingAside( void ) {
status = WP_PUTTING_ASIDE;
}
/*
===============
hhWeapon::Event_Weapon_Uprighting
===============
*/
void hhWeapon::Event_Weapon_Uprighting( void ) {
status = WP_UPRIGHTING;
}
/*
===============
hhWeapon::Event_WeaponLowering
===============
*/
void hhWeapon::Event_WeaponLowering( void ) {
status = WP_LOWERING;
WEAPON_RAISEWEAPON = false;
//HUMANHEAD: aob
WEAPON_ASIDEWEAPON = false;
//HUMANHEAD END
owner->WeaponLoweringCallback();
}
/*
===============
hhWeapon::Event_AddToClip
===============
*/
void hhWeapon::Event_AddToClip( int amount ) {
if( fireController ) {
fireController->AddToClip( amount );
}
}
/*
===============
hhWeapon::Event_AmmoInClip
===============
*/
void hhWeapon::Event_AmmoInClip( void ) {
int ammo = AmmoInClip();
idThread::ReturnFloat( ammo );
}
/*
===============
hhWeapon::Event_AmmoAvailable
===============
*/
void hhWeapon::Event_AmmoAvailable( void ) {
int ammoAvail = AmmoAvailable();
idThread::ReturnFloat( ammoAvail );
}
/*
===============
hhWeapon::Event_ClipSize
===============
*/
void hhWeapon::Event_ClipSize( void ) {
idThread::ReturnFloat( ClipSize() );
}
/*
===============
hhWeapon::Event_PlayAnim
===============
*/
void hhWeapon::Event_PlayAnim( int channel, const char *animname ) {
int anim = 0;
anim = GetAnimator()->GetAnim( animname );
if ( !anim ) {
//HUMANHEAD: aob
WEAPON_DEBUG( "missing '%s' animation on '%s'", animname, name.c_str() );
//HUMANHEAD END
GetAnimator()->Clear( channel, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
animDoneTime = 0;
} else {
//Show(); AOB - removed so we can use hidden weapons Hope this doesn't fuck to many things
GetAnimator()->PlayAnim( channel, anim, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
animDoneTime = GetAnimator()->CurrentAnim( channel )->GetEndTime();
if ( worldModel.GetEntity() ) {
anim = worldModel.GetEntity()->GetAnimator()->GetAnim( animname );
if ( anim ) {
worldModel.GetEntity()->GetAnimator()->PlayAnim( channel, anim, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
}
}
}
animBlendFrames = 0;
}
/*
===============
hhWeapon::Event_AnimDone
===============
*/
void hhWeapon::Event_AnimDone( int channel, int blendFrames ) {
if ( animDoneTime - FRAME2MS( blendFrames ) <= gameLocal.time ) {
idThread::ReturnInt( true );
} else {
idThread::ReturnInt( false );
}
}
/*
================
hhWeapon::Event_Next
================
*/
void hhWeapon::Event_Next( void ) {
// change to another weapon if possible
owner->NextBestWeapon();
}
/*
================
hhWeapon::Event_Flashlight
================
*/
void hhWeapon::Event_Flashlight( int enable ) {
/*
if ( enable ) {
lightOn = true;
MuzzleFlashLight();
} else {
lightOn = false;
muzzleFlashEnd = 0;
}
*/
}
/*
================
hhWeapon::Event_FireProjectiles
HUMANHEAD: aob
================
*/
void hhWeapon::Event_FireProjectiles() {
//HUMANHEAD: aob - moved logic to this helper function
LaunchProjectiles( fireController );
//HUMANHEAD END
}
/*
================
hhWeapon::Event_GetOwner
================
*/
void hhWeapon::Event_GetOwner( void ) {
idThread::ReturnEntity( owner.GetEntity() );
}
/*
===============
hhWeapon::Event_UseAmmo
===============
*/
void hhWeapon::Event_UseAmmo( int amount ) {
UseAmmo();
}
/*
===============
hhWeapon::Event_UseAltAmmo
===============
*/
void hhWeapon::Event_UseAltAmmo( int amount ) {
UseAltAmmo();
}
/*
================
hhWeapon::RestoreGUI
HUMANHEAD: aob
================
*/
void hhWeapon::RestoreGUI( const char* guiKey, idUserInterface** gui ) {
if( guiKey && guiKey[0] && gui ) {
AddRenderGui( dict->GetString(guiKey), gui, dict );
}
}
/*
================
hhWeapon::Think
================
*/
void hhWeapon::Think() {
if( thinkFlags & TH_TICKER ) {
if (owner.IsValid()) {
Ticker();
}
}
}
/*
================
hhWeapon::SpawnWorldModel
================
*/
idEntity* hhWeapon::SpawnWorldModel( const char* worldModelDict, idActor* _owner ) {
/*
assert( _owner && worldModelDict );
idEntity* pEntity = NULL;
idDict* pArgs = declManager->FindEntityDefDict( worldModelDict, false );
if( !pArgs ) { return NULL; }
idStr ownerWeaponBindBone = _owner->spawnArgs.GetString( "bone_weapon_bind" );
idStr attachBone = pArgs->GetString( "attach" );
if( attachBone.Length() && ownerWeaponBindBone.Length() ) {
pEntity = gameLocal.SpawnEntityType( idEntity::Type, pArgs );
HH_ASSERT( pEntity );
pEntity->GetPhysics()->SetContents( 0 );
pEntity->GetPhysics()->DisableClip();
pEntity->MoveJointToJoint( attachBone.c_str(), _owner, ownerWeaponBindBone.c_str() );
pEntity->AlignJointToJoint( attachBone.c_str(), _owner, ownerWeaponBindBone.c_str() );
pEntity->BindToJoint( _owner, ownerWeaponBindBone.c_str(), true );
// supress model in player views and in any views on the weapon itself
pEntity->renderEntity.suppressSurfaceInViewID = _owner->entityNumber + 1;
}
*/
return NULL;
}
/*
================
hhWeapon::SetModel
================
*/
void hhWeapon::SetModel( const char *modelname ) {
assert( modelname );
if ( modelDefHandle >= 0 ) {
gameRenderWorld->RemoveDecals( modelDefHandle );
}
hhAnimatedEntity::SetModel( modelname );
// hide the model until an animation is played
Hide();
}
/*
================
hhWeapon::FreeModelDef
================
*/
void hhWeapon::FreeModelDef() {
hhAnimatedEntity::FreeModelDef();
}
/*
================
hhWeapon::GetPhysicsToVisualTransform
================
*/
bool hhWeapon::GetPhysicsToVisualTransform( idVec3 &origin, idMat3 &axis ) {
bool bResult = hhAnimatedEntity::GetPhysicsToVisualTransform( origin, axis );
assert(!FLOAT_IS_NAN(cameraShakeOffset.x));
assert(!FLOAT_IS_NAN(cameraShakeOffset.y));
assert(!FLOAT_IS_NAN(cameraShakeOffset.z));
if( !cameraShakeOffset.Compare(vec3_zero, VECTOR_EPSILON) ) {
origin = (bResult) ? cameraShakeOffset + origin : cameraShakeOffset;
origin *= GetPhysics()->GetAxis().Transpose();
if( !bResult ) { axis = mat3_identity; }
return true;
}
return bResult;
}
/*
================
hhWeapon::GetMasterDefaultPosition
================
*/
void hhWeapon::GetMasterDefaultPosition( idVec3 &masterOrigin, idMat3 &masterAxis ) const {
idActor* actor = NULL;
idEntity* master = GetBindMaster();
if( master ) {
if( master->IsType(idActor::Type) ) {
actor = static_cast<idActor*>( master );
actor->DetermineOwnerPosition( masterOrigin, masterAxis );
masterOrigin = actor->ApplyLandDeflect( masterOrigin, 1.1f );
} else {
hhAnimatedEntity::GetMasterDefaultPosition( masterOrigin, masterAxis );
}
}
}
/*
================
hhWeapon::SetShaderParm
================
*/
void hhWeapon::SetShaderParm( int parmnum, float value ) {
hhAnimatedEntity::SetShaderParm(parmnum, value);
if ( worldModel.IsValid() ) {
worldModel->SetShaderParm(parmnum, value);
}
}
/*
================
hhWeapon::SetSkin
================
*/
void hhWeapon::SetSkin( const idDeclSkin *skin ) {
hhAnimatedEntity::SetSkin(skin);
if ( worldModel.IsValid() ) {
worldModel->SetSkin(skin);
}
}
/*
================
hhWeapon::PlayCycle
================
*/
void hhWeapon::Event_PlayCycle( int channel, const char *animname ) {
int anim;
anim = GetAnimator()->GetAnim( animname );
if ( !anim ) {
//HUMANHEAD: aob
WEAPON_DEBUG( "missing '%s' animation on '%s'", animname, name.c_str() );
//HUMANHEAD END
GetAnimator()->Clear( channel, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
animDoneTime = 0;
} else {
//Show();AOB - removed so we can use hidden weapons Hope this doesn't fuck to many things
// NLANOTE - Used to be CARandom
GetAnimator()->CycleAnim( channel, anim, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
animDoneTime = GetAnimator()->CurrentAnim( channel )->GetEndTime();
if ( worldModel.GetEntity() ) {
anim = worldModel.GetEntity()->GetAnimator()->GetAnim( animname );
// NLANOTE - Used to be CARandom
worldModel.GetEntity()->GetAnimator()->CycleAnim( channel, anim, gameLocal.GetTime(), FRAME2MS( animBlendFrames ) );
}
}
animBlendFrames = 0;
}
/*
================
hhWeapon::Event_IsAnimPlaying
================
*/
void hhWeapon::Event_IsAnimPlaying( const char *animname ) {
idThread::ReturnInt( animator.IsAnimPlaying(animname) );
}
/*
================
hhWeapon::Event_EjectBrass
================
*/
void hhWeapon::Event_EjectBrass() {
if( fireController ) {
fireController->EjectBrass();
}
}
/*
================
hhWeapon::Event_EjectAltBrass
================
*/
void hhWeapon::Event_EjectAltBrass() {
if( altFireController ) {
altFireController->EjectBrass();
}
}
/*
================
hhWeapon::Event_PlayAnimWhenReady
================
*/
void hhWeapon::Event_PlayAnimWhenReady( const char* animName ) {
/*
if( !IsReady() && (!dict || !dict->GetBool("pickupHasRaise") || !IsRaising()) ) {
CancelEvents( &EV_PlayAnimWhenReady );
PostEventSec( &EV_PlayAnimWhenReady, 0.5f, animName );
return;
}
PlayAnim( animName, 0, &EV_Weapon_Ready );
*/
}
/*
================
hhWeapon::Event_SpawnFXAlongBone
================
*/
void hhWeapon::Event_SpawnFXAlongBone( idList<idStr>* fxParms ) {
if ( !owner->CanShowWeaponViewmodel() || !fxParms ) {
return;
}
HH_ASSERT( fxParms->Num() == 2 );
hhFxInfo fxInfo;
fxInfo.UseWeaponDepthHack( true );
BroadcastFxInfoAlongBone( dict->GetString((*fxParms)[0].c_str()), (*fxParms)[1].c_str(), &fxInfo, NULL, false ); //rww - default to not broadcast from events
}
/*
==============================
hhWeapon::Event_FireAltProjectiles
==============================
*/
void hhWeapon::Event_FireAltProjectiles() {
LaunchProjectiles( altFireController );
}
// This is called once per frame to precompute where the weapon is pointing. This is used for determining if crosshairs should display as targetted as
// well as fire controllers to update themselves. This must be called before UpdateCrosshairs().
void hhWeapon::PrecomputeTraceInfo() {
// This is needed for fireControllers, even if there are no crosshairs
idVec3 eyePos = owner->GetEyePosition();
idMat3 weaponAxis = GetAxis();
float traceDist = 1024.0f; // was CM_MAX_TRACE_DIST
// Perform eye trace
gameLocal.clip.TracePoint( eyeTraceInfo, eyePos, eyePos + weaponAxis[0] * traceDist,
MASK_SHOT_BOUNDINGBOX | CONTENTS_GAME_PORTAL, owner.GetEntity() );
// CJR: If the trace hit a portal, then force it to trace the max distance, as if it's tracing through the portal
if ( eyeTraceInfo.fraction < 1.0f ) {
idEntity *ent = gameLocal.GetTraceEntity( eyeTraceInfo );
if ( ent->IsType( hhPortal::Type ) ) {
eyeTraceInfo.endpos = eyePos + weaponAxis[0] * traceDist;
eyeTraceInfo.fraction = 1.0f;
}
}
}
/*
==============================
hhWeapon::UpdateCrosshairs
==============================
*/
void hhWeapon::UpdateCrosshairs( bool &crosshair, bool &targeting ) {
idEntity* ent = NULL;
trace_t traceInfo;
crosshair = false;
targeting = false;
if (spawnArgs.GetBool("altModeWeapon")) {
if (WEAPON_ALTMODE) { // Moded weapon in alt-mode
if (altFireController) {
crosshair = altFireController->UsesCrosshair();
}
}
else { // Moded weapon in normal mode
if (fireController) {
crosshair = fireController->UsesCrosshair();
}
}
}
else { // Normal non-moded weapon
if (altFireController && altFireController->UsesCrosshair()) {
crosshair = true;
}
if (fireController && fireController->UsesCrosshair()) {
crosshair = true;
}
}
ent = NULL;
if( crosshair ) {
traceInfo = GetEyeTraceInfo();
if( traceInfo.fraction < 1.0f ) {
ent = gameLocal.GetTraceEntity(traceInfo);
}
targeting = ( ent && ent->fl.takedamage && !(ent->IsType( hhDoor::Type ) || ent->IsType( hhModelDoor::Type ) || ent->IsType( hhConsole::Type ) ) );
}
}
/*
==============================
hhWeapon::GetAmmoType
==============================
*/
ammo_t hhWeapon::GetAmmoType( void ) const {
return (fireController) ? fireController->GetAmmoType() : 0;
}
/*
==============================
hhWeapon::AmmoAvailable
==============================
*/
int hhWeapon::AmmoAvailable( void ) const {
return (fireController) ? fireController->AmmoAvailable() : 0;
}
/*
==============================
hhWeapon::AmmoInClip
==============================
*/
int hhWeapon::AmmoInClip( void ) const {
return (fireController) ? fireController->AmmoInClip() : 0;
}
/*
==============================
hhWeapon::ClipSize
==============================
*/
int hhWeapon::ClipSize( void ) const {
return (fireController) ? fireController->ClipSize() : 0;
}
/*
==============================
hhWeapon::AmmoRequired
==============================
*/
int hhWeapon::AmmoRequired( void ) const {
return (fireController) ? fireController->AmmoRequired() : 0;
}
/*
==============================
hhWeapon::LowAmmo
==============================
*/
int hhWeapon::LowAmmo() {
return (fireController) ? fireController->LowAmmo() : 0;
}
/*
==============================
hhWeapon::GetAltAmmoType
==============================
*/
ammo_t hhWeapon::GetAltAmmoType( void ) const {
return (altFireController) ? altFireController->GetAmmoType() : 0;
}
/*
==============================
hhWeapon::AltAmmoAvailable
==============================
*/
int hhWeapon::AltAmmoAvailable( void ) const {
return (altFireController) ? altFireController->AmmoAvailable() : 0;
}
/*
==============================
hhWeapon::AltAmmoInClip
==============================
*/
int hhWeapon::AltAmmoInClip( void ) const {
return (altFireController) ? altFireController->AmmoInClip() : 0;
}
/*
==============================
hhWeapon::AltClipSize
==============================
*/
int hhWeapon::AltClipSize( void ) const {
return (altFireController) ? altFireController->ClipSize() : 0;
}
/*
==============================
hhWeapon::AltAmmoRequired
==============================
*/
int hhWeapon::AltAmmoRequired( void ) const {
return (altFireController) ? altFireController->AmmoRequired() : 0;
}
/*
==============================
hhWeapon::LowAltAmmo
==============================
*/
int hhWeapon::LowAltAmmo() {
return (altFireController) ? altFireController->LowAmmo() : 0;
}
/*
==============================
hhWeapon::GetAltMode
HUMANHEAD bjk
==============================
*/
bool hhWeapon::GetAltMode() const {
return WEAPON_ALTMODE != 0;
}
/*
==============================
hhWeapon::UseAmmo
==============================
*/
void hhWeapon::UseAmmo() {
if (fireController) {
fireController->UseAmmo();
}
}
/*
==============================
hhWeapon::UseAltAmmo
==============================
*/
void hhWeapon::UseAltAmmo() {
if (altFireController) {
altFireController->UseAmmo();
}
}
/*
==============================
hhWeapon::CheckDeferredProjectiles
HUMANEAD: rww
==============================
*/
void hhWeapon::CheckDeferredProjectiles(void) {
if (fireController) {
fireController->CheckDeferredProjectiles();
}
if (altFireController) {
altFireController->CheckDeferredProjectiles();
}
}
/*
==============================
hhWeapon::LaunchProjectiles
HUMANEAD: aob
==============================
*/
void hhWeapon::LaunchProjectiles( hhWeaponFireController* controller ) {
if ( IsHidden() ) {
return;
}
// wake up nearby monsters
if ( !spawnArgs.GetBool( "silent_fire" ) ) {
gameLocal.AlertAI( owner.GetEntity() );
}
// set the shader parm to the time of last projectile firing,
// which the gun material shaders can reference for single shot barrel glows, etc
SetShaderParm( SHADERPARM_DIVERSITY, gameLocal.random.CRandomFloat() );
SetShaderParm( SHADERPARM_TIMEOFFSET, -MS2SEC( gameLocal.realClientTime ) );
float low = ((float)controller->AmmoAvailable()*controller->AmmoRequired())/controller->LowAmmo();
if( !controller->LaunchProjectiles(pushVelocity) ) {
return;
}
if (!gameLocal.isClient) { //HUMANHEAD rww - let everyone hear this sound, and broadcast it (so don't try to play it for client-projectile weapons)
if( controller->AmmoAvailable()*controller->AmmoRequired() <= controller->LowAmmo() && low > 1 && spawnArgs.FindKey("snd_lowammo")) {
StartSound( "snd_lowammo", SND_CHANNEL_ANY, 0, true, NULL );
}
}
controller->UpdateMuzzleKick();
// add the light for the muzzleflash
controller->MuzzleFlash();
//HUMANEHAD: aob
controller->WeaponFeedback();
//HUMANHEAD END
}
/*
===============
hhWeapon::SetViewAnglesSensitivity
HUMANHEAD: aob
===============
*/
void hhWeapon::SetViewAnglesSensitivity( float fov ) {
if( owner.IsValid() ) {
owner->SetViewAnglesSensitivity( fov / g_fov.GetFloat() );
}
}
/*
===============
hhWeapon::GetDict
HUMANHEAD: aob
===============
*/
const idDict* hhWeapon::GetDict( const char* objectname ) {
return gameLocal.FindEntityDefDict( objectname, false );
}
/*
===============
hhWeapon::GetFireInfoDict
HUMANHEAD: aob
===============
*/
const idDict* hhWeapon::GetFireInfoDict( const char* objectname ) {
const idDict* dict = GetDict( objectname );
if( !dict ) {
return NULL;
}
return gameLocal.FindEntityDefDict( dict->GetString("def_fireInfo"), false );
}
/*
===============
hhWeapon::GetAltFireInfoDict
HUMANHEAD: aob
===============
*/
const idDict* hhWeapon::GetAltFireInfoDict( const char* objectname ) {
const idDict* dict = GetDict( objectname );
if( !dict ) {
return NULL;
}
return gameLocal.FindEntityDefDict( dict->GetString("def_altFireInfo"), false );
}
void hhWeapon::Event_GetString(const char *key) {
if ( fireController ) {
idThread::ReturnString( fireController->GetString(key) );
}
}
void hhWeapon::Event_GetAltString(const char *key) {
if ( altFireController ) {
idThread::ReturnString( altFireController->GetString(key) );
}
}
/*
===============
hhWeapon::Event_AddToAltClip
===============
*/
void hhWeapon::Event_AddToAltClip( int amount ) {
HH_ASSERT( altFireController );
altFireController->AddToClip( amount );
}
/*
===============
hhWeapon::Event_AmmoInClip
===============
*/
void hhWeapon::Event_AltAmmoInClip( void ) {
HH_ASSERT( altFireController );
idThread::ReturnFloat( altFireController->AmmoInClip() );
}
/*
===============
hhWeapon::Event_AltAmmoAvailable
===============
*/
void hhWeapon::Event_AltAmmoAvailable( void ) {
HH_ASSERT( altFireController );
idThread::ReturnFloat( altFireController->AmmoAvailable() );
}
/*
===============
hhWeapon::Event_ClipSize
===============
*/
void hhWeapon::Event_AltClipSize( void ) {
HH_ASSERT( altFireController );
idThread::ReturnFloat( altFireController->ClipSize() );
}
/*
==============================
hhWeapon::Event_GetFireDelay
==============================
*/
void hhWeapon::Event_GetFireDelay() {
HH_ASSERT( fireController );
idThread::ReturnFloat( fireController->GetFireDelay() );
}
/*
==============================
hhWeapon::Event_GetAltFireDelay
==============================
*/
void hhWeapon::Event_GetAltFireDelay() {
HH_ASSERT( altFireController );
idThread::ReturnFloat( altFireController->GetFireDelay() );
}
/*
==============================
hhWeapon::Event_HasAmmo
==============================
*/
void hhWeapon::Event_HasAmmo() {
idThread::ReturnInt( fireController->HasAmmo() );
}
/*
==============================
hhWeapon::Event_HasAltAmmo
==============================
*/
void hhWeapon::Event_HasAltAmmo() {
idThread::ReturnInt( altFireController->HasAmmo() );
}
/*
===============
hhWeapon::Event_SetViewAnglesSensitivity
HUMANHEAD: aob
===============
*/
void hhWeapon::Event_SetViewAnglesSensitivity( float fov ) {
SetViewAnglesSensitivity( fov );
}
/*
================
hhWeapon::UpdateNozzleFx
================
*/
void hhWeapon::UpdateNozzleFx( void ) {
if ( !nozzleFx || !g_projectileLights.GetBool()) {
return;
}
if ( nozzleJointHandle.view == INVALID_JOINT ) {
return;
}
//
// vent light
//
if ( nozzleGlowHandle == -1 ) {
memset(&nozzleGlow, 0, sizeof(nozzleGlow));
if ( owner.IsValid() ) {
nozzleGlow.allowLightInViewID = owner->entityNumber+1;
}
nozzleGlow.pointLight = true;
nozzleGlow.noShadows = true;
nozzleGlow.lightRadius.x = nozzleGlowRadius;
nozzleGlow.lightRadius.y = nozzleGlowRadius;
nozzleGlow.lightRadius.z = nozzleGlowRadius;
nozzleGlow.shader = nozzleGlowShader;
GetJointWorldTransform( nozzleJointHandle, nozzleGlow.origin, nozzleGlow.axis );
nozzleGlow.origin += nozzleGlowOffset * nozzleGlow.axis;
nozzleGlowHandle = gameRenderWorld->AddLightDef(&nozzleGlow);
}
GetJointWorldTransform(nozzleJointHandle, nozzleGlow.origin, nozzleGlow.axis );
nozzleGlow.origin += nozzleGlowOffset * nozzleGlow.axis;
nozzleGlow.shaderParms[ SHADERPARM_RED ] = nozzleGlowColor.x;
nozzleGlow.shaderParms[ SHADERPARM_GREEN ] = nozzleGlowColor.y;
nozzleGlow.shaderParms[ SHADERPARM_BLUE ] = nozzleGlowColor.z;
// Copy parms from the weapon into this light
for( int i = 4; i < 8; i++ ) {
nozzleGlow.shaderParms[ i ] = GetRenderEntity()->shaderParms[ i ];
}
gameRenderWorld->UpdateLightDef(nozzleGlowHandle, &nozzleGlow);
}
void hhWeapon::Event_HideWeapon(void) {
HideWeapon();
}
void hhWeapon::Event_ShowWeapon(void) {
ShowWeapon();
}
/*
===============
hhWeapon::FillDebugVars
===============
*/
void hhWeapon::FillDebugVars(idDict *args, int page) {
idStr text;
switch(page) {
case 1:
args->SetBool("WEAPON_LOWERWEAPON", WEAPON_LOWERWEAPON != 0);
args->SetBool("WEAPON_RAISEWEAPON", WEAPON_RAISEWEAPON != 0);
args->SetBool("WEAPON_ASIDEWEAPON", WEAPON_ASIDEWEAPON != 0);
args->SetBool("WEAPON_ATTACK", WEAPON_ATTACK != 0);
args->SetBool("WEAPON_ALTATTACK", WEAPON_ALTATTACK != 0);
args->SetBool("WEAPON_ALTMODE", WEAPON_ALTMODE != 0);
args->SetBool("WEAPON_RELOAD", WEAPON_RELOAD != 0);
break;
}
}
| 24.749802
| 321
| 0.648869
|
AMS21
|
6eb0235879f977d48605c503d1bae02b99905776
| 1,543
|
cpp
|
C++
|
Centipede/GameComponents/Player.cpp
|
anunez97/centipede
|
871bb505c7726dfa4b16caeb0f5b9c2d0e2660f8
|
[
"MIT"
] | null | null | null |
Centipede/GameComponents/Player.cpp
|
anunez97/centipede
|
871bb505c7726dfa4b16caeb0f5b9c2d0e2660f8
|
[
"MIT"
] | null | null | null |
Centipede/GameComponents/Player.cpp
|
anunez97/centipede
|
871bb505c7726dfa4b16caeb0f5b9c2d0e2660f8
|
[
"MIT"
] | null | null | null |
// Player
#include "Player.h"
#include "MushroomField.h"
#include "BlasterFactory.h"
#include "Settings.h"
#include "Grid.h"
#include "PlayerManager.h"
#include "KeyboardController.h"
#include "Blaster.h"
Player::Player()
:lives(3), score(0), pController(0), pBlaster(0), wave(1)
{
pGrid = new Grid;
pField = new MushroomField;
pField->SetGrid(pGrid);
}
Player::~Player()
{
delete pGrid;
delete pField;
}
void Player::SetController(Controller* c)
{
pController = c;
}
void Player::Initialize()
{
pField->Initialize();
pBlaster = BlasterFactory::CreateBlaster(
sf::Vector2f(WindowManager::Window().getDefaultView().getSize().x / 2.0f, Grid::gridtoPixels(Settings::BROWBORDER)), this);
pController->SetBlaster(pBlaster);
pController->Enable();
lives--;
}
void Player::Deinitialize()
{
pField->Deinitialize();
pController->Disable();
pBlaster->MarkForDestroy();
}
void Player::SetWave(int w)
{
wave = w;
}
MushroomField* Player::GetField()
{
return pField;
}
Blaster* Player::GetBlaster()
{
return pBlaster;
}
Grid* Player::GetGrid()
{
return pGrid;
}
int Player::GetScore()
{
return score;
}
int Player::GetWave()
{
return wave;
}
int Player::GetLives()
{
return lives;
}
void Player::AddScore(int val)
{
score += val;
}
void Player::AddLife()
{
lives++;
}
void Player::PlayerDeath()
{
BlasterFactory::PlayerDeath();
pController->Disable();
pController->SetBlaster(0);
PlayerManager::SwitchPlayer();
}
| 15.585859
| 126
| 0.652625
|
anunez97
|
6eb04f751f7d32c88637bc22fb504b39e1237eb9
| 21,193
|
cpp
|
C++
|
src/UI/Reports/FactoryReport.cpp
|
gogoprog/OPHD
|
70604dda83042ef9124728bebeaa70eb57f3dfca
|
[
"BSD-3-Clause"
] | null | null | null |
src/UI/Reports/FactoryReport.cpp
|
gogoprog/OPHD
|
70604dda83042ef9124728bebeaa70eb57f3dfca
|
[
"BSD-3-Clause"
] | null | null | null |
src/UI/Reports/FactoryReport.cpp
|
gogoprog/OPHD
|
70604dda83042ef9124728bebeaa70eb57f3dfca
|
[
"BSD-3-Clause"
] | null | null | null |
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
#include "FactoryReport.h"
#include "../../Constants.h"
#include "../../FontManager.h"
#include "../../StructureManager.h"
#include "../../Things/Structures/SurfaceFactory.h"
#include "../../Things/Structures/SeedFactory.h"
#include "../../Things/Structures/UndergroundFactory.h"
#include <array>
using namespace NAS2D;
static int SORT_BY_PRODUCT_POSITION = 0;
static int STATUS_LABEL_POSITION = 0;
static int WIDTH_RESOURCES_REQUIRED_LABEL = 0;
static Rectangle_2d FACTORY_LISTBOX;
static Rectangle_2d DETAIL_PANEL;
static Font* FONT = nullptr;
static Font* FONT_BOLD = nullptr;
static Font* FONT_MED = nullptr;
static Font* FONT_MED_BOLD = nullptr;
static Font* FONT_BIG = nullptr;
static Font* FONT_BIG_BOLD = nullptr;
static Factory* SELECTED_FACTORY = nullptr;
static Image* FACTORY_SEED = nullptr;
static Image* FACTORY_AG = nullptr;
static Image* FACTORY_UG = nullptr;
static Image* FACTORY_IMAGE = nullptr;
std::array<Image*, PRODUCT_COUNT> PRODUCT_IMAGE_ARRAY;
static Image* _PRODUCT_NONE = nullptr;
static std::string FACTORY_STATUS;
static const std::string RESOURCES_REQUIRED = "Resources Required";
static ProductType SELECTED_PRODUCT_TYPE = PRODUCT_NONE;
/**
* C'tor
*/
FactoryReport::FactoryReport()
{
init();
}
/**
* D'tor
*/
FactoryReport::~FactoryReport()
{
delete FACTORY_SEED;
delete FACTORY_AG;
delete FACTORY_UG;
delete _PRODUCT_NONE;
SELECTED_FACTORY = nullptr;
for (auto img : PRODUCT_IMAGE_ARRAY) { delete img; }
}
/**
* Sets up UI positions.
*/
void FactoryReport::init()
{
FONT = Utility<FontManager>::get().font(constants::FONT_PRIMARY, constants::FONT_PRIMARY_NORMAL);
FONT_BOLD = Utility<FontManager>::get().font(constants::FONT_PRIMARY_BOLD, constants::FONT_PRIMARY_NORMAL);
FONT_MED = Utility<FontManager>::get().font(constants::FONT_PRIMARY, constants::FONT_PRIMARY_MEDIUM);
FONT_MED_BOLD = Utility<FontManager>::get().font(constants::FONT_PRIMARY_BOLD, constants::FONT_PRIMARY_MEDIUM);
FONT_BIG = Utility<FontManager>::get().font(constants::FONT_PRIMARY, constants::FONT_PRIMARY_HUGE);
FONT_BIG_BOLD = Utility<FontManager>::get().font(constants::FONT_PRIMARY_BOLD, constants::FONT_PRIMARY_HUGE);
FACTORY_SEED = new Image("ui/interface/factory_seed.png");
FACTORY_AG = new Image("ui/interface/factory_ag.png");
FACTORY_UG = new Image("ui/interface/factory_ug.png");
/// \todo Decide if this is the best place to have these images live or if it should be done at program start.
PRODUCT_IMAGE_ARRAY.fill(nullptr);
PRODUCT_IMAGE_ARRAY[PRODUCT_DIGGER] = new Image("ui/interface/product_robodigger.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_DOZER] = new Image("ui/interface/product_robodozer.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_MINER] = new Image("ui/interface/product_robominer.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_EXPLORER] = new Image("ui/interface/product_roboexplorer.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_TRUCK] = new Image("ui/interface/product_truck.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_ROAD_MATERIALS] = new Image("ui/interface/product_road_materials.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_MAINTENANCE_PARTS] = new Image("ui/interface/product_maintenance_parts.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_CLOTHING] = new Image("ui/interface/product_clothing.png");
PRODUCT_IMAGE_ARRAY[PRODUCT_MEDICINE] = new Image("ui/interface/product_medicine.png");
_PRODUCT_NONE = new Image("ui/interface/product_none.png");
add(&lstFactoryList, 10, 63);
lstFactoryList.selectionChanged().connect(this, &FactoryReport::lstFactoryListSelectionChanged);
add(&btnShowAll, 10, 10);
btnShowAll.size(75, 20);
btnShowAll.type(Button::BUTTON_TOGGLE);
btnShowAll.toggle(true);
btnShowAll.text("All");
btnShowAll.click().connect(this, &FactoryReport::btnShowAllClicked);
add(&btnShowSurface, 87, 10);
btnShowSurface.size(75, 20);
btnShowSurface.type(Button::BUTTON_TOGGLE);
btnShowSurface.text("Surface");
btnShowSurface.click().connect(this, &FactoryReport::btnShowSurfaceClicked);
add(&btnShowUnderground, 164, 10);
btnShowUnderground.size(75, 20);
btnShowUnderground.type(Button::BUTTON_TOGGLE);
btnShowUnderground.text("Underground");
btnShowUnderground.click().connect(this, &FactoryReport::btnShowUndergroundClicked);
add(&btnShowActive, 10, 33);
btnShowActive.size(75, 20);
btnShowActive.type(Button::BUTTON_TOGGLE);
btnShowActive.text("Active");
btnShowActive.click().connect(this, &FactoryReport::btnShowActiveClicked);
add(&btnShowIdle, 87, 33);
btnShowIdle.size(75, 20);
btnShowIdle.type(Button::BUTTON_TOGGLE);
btnShowIdle.text("Idle");
btnShowIdle.click().connect(this, &FactoryReport::btnShowIdleClicked);
add(&btnShowDisabled, 164, 33);
btnShowDisabled.size(75, 20);
btnShowDisabled.type(Button::BUTTON_TOGGLE);
btnShowDisabled.text("Disabled");
btnShowDisabled.click().connect(this, &FactoryReport::btnShowDisabledClicked);
int position_x = Utility<Renderer>::get().width() - 110;
add(&btnIdle, position_x, 35);
btnIdle.type(Button::BUTTON_TOGGLE);
btnIdle.size(140, 30);
btnIdle.text("Idle");
btnIdle.click().connect(this, &FactoryReport::btnIdleClicked);
add(&btnClearProduction, position_x, 75);
btnClearProduction.size(140, 30);
btnClearProduction.text("Clear Production");
btnClearProduction.click().connect(this, &FactoryReport::btnClearProductionClicked);
add(&btnTakeMeThere, position_x, 115);
btnTakeMeThere.size(140, 30);
btnTakeMeThere.text(constants::BUTTON_TAKE_ME_THERE);
btnTakeMeThere.click().connect(this, &FactoryReport::btnTakeMeThereClicked);
add(&btnApply, 0, 0);
btnApply.size(140, 30);
btnApply.text("Apply");
btnApply.click().connect(this, &FactoryReport::btnApplyClicked);
add(&cboFilterByProduct, 250, 33);
cboFilterByProduct.size(200, 20);
cboFilterByProduct.addItem(constants::NONE, PRODUCT_NONE);
cboFilterByProduct.addItem(constants::CLOTHING, PRODUCT_CLOTHING);
cboFilterByProduct.addItem(constants::MAINTENANCE_SUPPLIES, PRODUCT_MAINTENANCE_PARTS);
cboFilterByProduct.addItem(constants::MEDICINE, PRODUCT_MEDICINE);
cboFilterByProduct.addItem(constants::ROBODIGGER, PRODUCT_DIGGER);
cboFilterByProduct.addItem(constants::ROBODOZER, PRODUCT_DOZER);
cboFilterByProduct.addItem(constants::ROBOEXPLORER, PRODUCT_EXPLORER);
cboFilterByProduct.addItem(constants::ROBOMINER, PRODUCT_MINER);
cboFilterByProduct.addItem(constants::ROAD_MATERIALS, PRODUCT_ROAD_MATERIALS);
cboFilterByProduct.addItem(constants::TRUCK, PRODUCT_TRUCK);
cboFilterByProduct.selectionChanged().connect(this, &FactoryReport::cboFilterByProductSelectionChanged);
add(&lstProducts, cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width() + 20, rect().y() + 230);
txtProductDescription.font(constants::FONT_PRIMARY, constants::FONT_PRIMARY_NORMAL);
txtProductDescription.height(128);
txtProductDescription.textColor(0, 185, 0);
txtProductDescription.text("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.");
SORT_BY_PRODUCT_POSITION = cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width() - FONT->width("Filter by Product");
WIDTH_RESOURCES_REQUIRED_LABEL = FONT_MED_BOLD->width(RESOURCES_REQUIRED);
Control::resized().connect(this, &FactoryReport::resized);
fillLists();
}
/**
* Override of the interface provided by ReportInterface class.
*
* \note Pointer
*/
void FactoryReport::selectStructure(Structure* structure)
{
lstFactoryList.currentSelection(dynamic_cast<Factory*>(structure));
}
void FactoryReport::clearSelection()
{
lstFactoryList.clearSelection();
SELECTED_FACTORY = nullptr;
}
/**
* Pass-through function to simulate clicking on the Show All button.
*/
void FactoryReport::refresh()
{
btnShowAllClicked();
}
/**
* Fills the factory list with all available factories.
*/
void FactoryReport::fillLists()
{
SELECTED_FACTORY = nullptr;
lstFactoryList.clearItems();
for (auto factory : Utility<StructureManager>::get().structureList(Structure::CLASS_FACTORY))
{
lstFactoryList.addItem(static_cast<Factory*>(factory));
}
checkFactoryActionControls();
}
/**
* Fills the factory list based on product type.
*/
void FactoryReport::fillFactoryList(ProductType type)
{
SELECTED_FACTORY = nullptr;
lstFactoryList.clearItems();
for (auto f : Utility<StructureManager>::get().structureList(Structure::CLASS_FACTORY))
{
Factory* factory = static_cast<Factory*>(f);
if (factory->productType() == type)
{
lstFactoryList.addItem(factory);
}
}
checkFactoryActionControls();
}
/**
* Fills the factory list based on surface/subterranean
*/
void FactoryReport::fillFactoryList(bool surface)
{
SELECTED_FACTORY = nullptr;
lstFactoryList.clearItems();
for (auto f : Utility<StructureManager>::get().structureList(Structure::CLASS_FACTORY))
{
Factory* factory = static_cast<Factory*>(f);
if (surface && (factory->name() == constants::SURFACE_FACTORY || factory->name() == constants::SEED_FACTORY))
{
lstFactoryList.addItem(factory);
}
else if (!surface && factory->name() == constants::UNDERGROUND_FACTORY)
{
lstFactoryList.addItem(factory);
}
}
checkFactoryActionControls();
}
/**
* Fills the factory list based on structure state.
*/
void FactoryReport::fillFactoryList(Structure::StructureState state)
{
SELECTED_FACTORY = nullptr;
lstFactoryList.clearItems();
for (auto f : Utility<StructureManager>::get().structureList(Structure::CLASS_FACTORY))
{
if (f->state() == state)
{
lstFactoryList.addItem(static_cast<Factory*>(f));
}
}
lstFactoryList.setSelection(0);
checkFactoryActionControls();
}
/**
* Sets visibility for factory action controls.
*/
void FactoryReport::checkFactoryActionControls()
{
bool actionControlVisible = !lstFactoryList.empty();
btnIdle.visible(actionControlVisible);
btnClearProduction.visible(actionControlVisible);
btnTakeMeThere.visible(actionControlVisible);
btnApply.visible(actionControlVisible);
lstProducts.visible(actionControlVisible);
if (actionControlVisible) { lstFactoryList.setSelection(0); }
}
/**
*
*/
void FactoryReport::resized(Control* c)
{
FACTORY_LISTBOX.x(positionX() + 10);
FACTORY_LISTBOX.y(cboFilterByProduct.positionY() + cboFilterByProduct.height() + 10);
FACTORY_LISTBOX.width(cboFilterByProduct.positionX() + cboFilterByProduct.width() - 10);
FACTORY_LISTBOX.height(height() - 74);
lstFactoryList.size(FACTORY_LISTBOX.width(), FACTORY_LISTBOX.height());
DETAIL_PANEL(cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width() + 20,
rect().y() + 10,
rect().width() - (cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width()) - 30,
rect().y() + rect().height() - 69);
STATUS_LABEL_POSITION = DETAIL_PANEL.x() + FONT_MED_BOLD->width("Status") + 158;
int position_x = rect().width() - 150;
btnIdle.position(position_x, btnIdle.positionY());
btnClearProduction.position(position_x, btnClearProduction.positionY());
btnTakeMeThere.position(position_x, btnTakeMeThere.positionY());
btnApply.position(position_x, rect().height() + 8);
lstProducts.size(DETAIL_PANEL.width() / 3, DETAIL_PANEL.height() - 219);
lstProducts.selectionChanged().connect(this, &FactoryReport::lstProductsSelectionChanged);
txtProductDescription.position(lstProducts.positionX() + lstProducts.width() + 158, lstProducts.positionY());
txtProductDescription.width(rect().width() - txtProductDescription.positionX() - 30);
}
/**
* This has been overridden to handle some UI elements that need
* special handling.
*/
void FactoryReport::visibilityChanged(bool visible)
{
if (!SELECTED_FACTORY) { return; }
Structure::StructureState _state = SELECTED_FACTORY->state();
btnApply.visible(visible && (_state == Structure::OPERATIONAL || _state == Structure::IDLE));
checkFactoryActionControls();
}
/**
*
*/
void FactoryReport::filterButtonClicked(bool clearCbo)
{
btnShowAll.toggle(false);
btnShowSurface.toggle(false);
btnShowUnderground.toggle(false);
btnShowActive.toggle(false);
btnShowIdle.toggle(false);
btnShowDisabled.toggle(false);
if (clearCbo) { cboFilterByProduct.clearSelection(); }
}
/**
*
*/
void FactoryReport::btnShowAllClicked()
{
filterButtonClicked(true);
btnShowAll.toggle(true);
fillLists();
}
/**
*
*/
void FactoryReport::btnShowSurfaceClicked()
{
filterButtonClicked(true);
btnShowSurface.toggle(true);
fillFactoryList(true);
}
/**
*
*/
void FactoryReport::btnShowUndergroundClicked()
{
filterButtonClicked(true);
btnShowUnderground.toggle(true);
fillFactoryList(false);
}
/**
*
*/
void FactoryReport::btnShowActiveClicked()
{
filterButtonClicked(true);
btnShowActive.toggle(true);
fillFactoryList(Structure::OPERATIONAL);
}
/**
*
*/
void FactoryReport::btnShowIdleClicked()
{
filterButtonClicked(true);
btnShowIdle.toggle(true);
fillFactoryList(Structure::IDLE);
}
/**
*
*/
void FactoryReport::btnShowDisabledClicked()
{
filterButtonClicked(true);
btnShowDisabled.toggle(true);
fillFactoryList(Structure::DISABLED);
}
/**
*
*/
void FactoryReport::btnIdleClicked()
{
SELECTED_FACTORY->forceIdle(btnIdle.toggled());
FACTORY_STATUS = structureStateDescription(SELECTED_FACTORY->state());
}
/**
*
*/
void FactoryReport::btnClearProductionClicked()
{
SELECTED_FACTORY->productType(PRODUCT_NONE);
lstProducts.clearSelection();
cboFilterByProductSelectionChanged();
}
/**
*
*/
void FactoryReport::btnTakeMeThereClicked()
{
takeMeThereCallback()(SELECTED_FACTORY);
}
/**
*
*/
void FactoryReport::btnApplyClicked()
{
SELECTED_FACTORY->productType(SELECTED_PRODUCT_TYPE);
cboFilterByProductSelectionChanged();
}
/**
*
*/
void FactoryReport::lstFactoryListSelectionChanged()
{
SELECTED_FACTORY = lstFactoryList.selectedFactory();
if (!SELECTED_FACTORY)
{
checkFactoryActionControls();
return;
}
/// \fixme Ugly
if (SELECTED_FACTORY->name() == constants::SEED_FACTORY) { FACTORY_IMAGE = FACTORY_SEED; }
else if (SELECTED_FACTORY->name() == constants::SURFACE_FACTORY) { FACTORY_IMAGE = FACTORY_AG; }
else if (SELECTED_FACTORY->name() == constants::UNDERGROUND_FACTORY) { FACTORY_IMAGE = FACTORY_UG; }
FACTORY_STATUS = structureStateDescription(SELECTED_FACTORY->state());
btnIdle.toggle(SELECTED_FACTORY->state() == Structure::IDLE);
btnIdle.enabled(SELECTED_FACTORY->state() == Structure::OPERATIONAL || SELECTED_FACTORY->state() == Structure::IDLE);
btnClearProduction.enabled(SELECTED_FACTORY->state() == Structure::OPERATIONAL || SELECTED_FACTORY->state() == Structure::IDLE);
lstProducts.dropAllItems();
if (SELECTED_FACTORY->state() != Structure::DESTROYED)
{
const Factory::ProductionTypeList& _pl = SELECTED_FACTORY->productList();
for (auto item : _pl)
{
lstProducts.addItem(productDescription(item), static_cast<int>(item));
}
}
lstProducts.clearSelection();
lstProducts.setSelectionByName(productDescription(SELECTED_FACTORY->productType()));
SELECTED_PRODUCT_TYPE = SELECTED_FACTORY->productType();
Structure::StructureState _state = SELECTED_FACTORY->state();
btnApply.visible(_state == Structure::OPERATIONAL || _state == Structure::IDLE);
}
/**
*
*/
void FactoryReport::lstProductsSelectionChanged()
{
SELECTED_PRODUCT_TYPE = static_cast<ProductType>(lstProducts.selectionTag());
}
/**
*
*/
void FactoryReport::cboFilterByProductSelectionChanged()
{
if (cboFilterByProduct.currentSelection() == constants::NO_SELECTION) { return; }
filterButtonClicked(false);
fillFactoryList(static_cast<ProductType>(cboFilterByProduct.selectionTag()));
}
/**
*
*/
void FactoryReport::drawDetailPane(Renderer& r)
{
Color_4ub text_color(0, 185, 0, 255);
r.drawImage(*FACTORY_IMAGE, DETAIL_PANEL.x(), DETAIL_PANEL.y() + 25);
r.drawText(*FONT_BIG_BOLD, SELECTED_FACTORY->name(), DETAIL_PANEL.x(), DETAIL_PANEL.y() - 8, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT_MED_BOLD, "Status", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 20, text_color.red(), text_color.green(), text_color.blue());
if (SELECTED_FACTORY->disabled() || SELECTED_FACTORY->destroyed()) { text_color(255, 0, 0, 255); }
r.drawText(*FONT_MED, FACTORY_STATUS, STATUS_LABEL_POSITION, DETAIL_PANEL.y() + 20, text_color.red(), text_color.green(), text_color.blue());
text_color(0, 185, 0, 255);
r.drawText(*FONT_MED_BOLD, RESOURCES_REQUIRED, DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 60, text_color.red(), text_color.green(), text_color.blue());
// MINERAL RESOURCES
r.drawText(*FONT_BOLD, "Common Metals", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 80, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT_BOLD, "Common Minerals", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 95, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT_BOLD, "Rare Metals", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 110, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT_BOLD, "Rare Minerals", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 125, text_color.red(), text_color.green(), text_color.blue());
const ProductionCost& _pc = productCost(SELECTED_FACTORY->productType());
r.drawText(*FONT, std::to_string(_pc.commonMetals()), DETAIL_PANEL.x() + 138 + WIDTH_RESOURCES_REQUIRED_LABEL - FONT->width(std::to_string(_pc.commonMetals())), DETAIL_PANEL.y() + 80, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT, std::to_string(_pc.commonMinerals()), DETAIL_PANEL.x() + 138 + WIDTH_RESOURCES_REQUIRED_LABEL - FONT->width(std::to_string(_pc.commonMinerals())), DETAIL_PANEL.y() + 95, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT, std::to_string(_pc.rareMetals()), DETAIL_PANEL.x() + 138 + WIDTH_RESOURCES_REQUIRED_LABEL - FONT->width(std::to_string(_pc.rareMetals())), DETAIL_PANEL.y() + 110, text_color.red(), text_color.green(), text_color.blue());
r.drawText(*FONT, std::to_string(_pc.rareMinerals()), DETAIL_PANEL.x() + 138 + WIDTH_RESOURCES_REQUIRED_LABEL - FONT->width(std::to_string(_pc.rareMinerals())), DETAIL_PANEL.y() + 125, text_color.red(), text_color.green(), text_color.blue());
// POPULATION
SELECTED_FACTORY->populationAvailable()[0] == SELECTED_FACTORY->populationRequirements()[0] ? text_color(0, 185, 0, 255) : text_color(255, 0, 0, 255);
r.drawText(*FONT_BOLD, "Workers", DETAIL_PANEL.x() + 138, DETAIL_PANEL.y() + 140, text_color.red(), text_color.green(), text_color.blue());
std::string _scratch = string_format("%i / %i", SELECTED_FACTORY->populationAvailable()[0], SELECTED_FACTORY->populationRequirements()[0]);
r.drawText(*FONT, _scratch, DETAIL_PANEL.x() + 138 + WIDTH_RESOURCES_REQUIRED_LABEL - FONT->width(_scratch), DETAIL_PANEL.y() + 140, text_color.red(), text_color.green(), text_color.blue());
}
/**
*
*/
void FactoryReport::drawProductPane(Renderer& r)
{
r.drawText(*FONT_BIG_BOLD, "Production", DETAIL_PANEL.x(), DETAIL_PANEL.y() + 180, 0, 185, 0);
int position_x = DETAIL_PANEL.x() + lstProducts.width() + 20;
if (SELECTED_PRODUCT_TYPE != PRODUCT_NONE)
{
r.drawText(*FONT_BIG_BOLD, productDescription(SELECTED_PRODUCT_TYPE), position_x, DETAIL_PANEL.y() + 180, 0, 185, 0);
r.drawImage(*PRODUCT_IMAGE_ARRAY[SELECTED_PRODUCT_TYPE], position_x, lstProducts.positionY());
txtProductDescription.update();
}
if (SELECTED_FACTORY->productType() == PRODUCT_NONE) { return; }
r.drawText(*FONT_BIG_BOLD, "Progress", position_x, DETAIL_PANEL.y() + 358, 0, 185, 0);
r.drawText(*FONT_MED, "Building " + productDescription(SELECTED_FACTORY->productType()), position_x, DETAIL_PANEL.y() + 393, 0, 185, 0);
float percent = 0.0f;
if (SELECTED_FACTORY->productType() != PRODUCT_NONE) { percent = static_cast<float>(SELECTED_FACTORY->productionTurnsCompleted()) / static_cast<float>(SELECTED_FACTORY->productionTurnsToComplete()); }
drawBasicProgressBar(position_x, DETAIL_PANEL.y() + 413, rect().width() - position_x - 10, 30, percent, 4);
std::string _turns = string_format("%i / %i", SELECTED_FACTORY->productionTurnsCompleted(), SELECTED_FACTORY->productionTurnsToComplete());
r.drawText(*FONT_MED_BOLD, "Turns", position_x, DETAIL_PANEL.y() + 449, 0, 185, 0);
r.drawText(*FONT_MED, _turns, rect().width() - FONT_MED->width(_turns) - 10, DETAIL_PANEL.y() + 449, 0, 185, 0);
}
/**
*
*/
void FactoryReport::update()
{
if (!visible()) { return; }
Renderer& r = Utility<Renderer>::get();
r.drawLine(cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width() + 10, rect().y() + 10, cboFilterByProduct.rect().x() + cboFilterByProduct.rect().width() + 10, rect().y() + rect().height() - 10, 0, 185, 0);
r.drawText(*FONT, "Filter by Product", SORT_BY_PRODUCT_POSITION, rect().y() + 10, 0, 185, 0);
if (SELECTED_FACTORY)
{
drawDetailPane(r);
drawProductPane(r);
}
UIContainer::update();
}
| 32.806502
| 477
| 0.750106
|
gogoprog
|
6eb137bdfbd0fc38213efd55d1944c4146b05242
| 2,776
|
hpp
|
C++
|
src/parser/symbols/letterlike.hpp
|
cpp-niel/mfl
|
d22d698b112b95d102150d5f3a5f35d8eb7fb0f3
|
[
"MIT"
] | 4
|
2021-04-02T02:52:05.000Z
|
2021-12-11T00:42:35.000Z
|
src/parser/symbols/letterlike.hpp
|
cpp-niel/mfl
|
d22d698b112b95d102150d5f3a5f35d8eb7fb0f3
|
[
"MIT"
] | null | null | null |
src/parser/symbols/letterlike.hpp
|
cpp-niel/mfl
|
d22d698b112b95d102150d5f3a5f35d8eb7fb0f3
|
[
"MIT"
] | null | null | null |
#pragma once
#include "mfl/code_point.hpp"
#include <array>
#include <utility>
namespace mfl::parser
{
constexpr auto letterlike_symbols = std::array<std::pair<const char*, code_point>, 93>{{
{"AA", 0x00c5},
{"AE", 0x00c6},
{"BbbC", 0x2102},
{"BbbN", 0x2115},
{"BbbP", 0x2119},
{"BbbQ", 0x211a},
{"BbbR", 0x211d},
{"BbbZ", 0x2124},
{"Finv", 0x2132},
{"Game", 0x2141},
{"Im", 0x2111},
{"L", 0x0141},
{"O", 0x00d8},
{"OE", 0x0152},
{"P", 0x00b6},
{"Re", 0x211c},
{"S", 0x00a7},
{"Thorn", 0x00de},
{"Upsilon", 0x03a5},
{"ae", 0x00e6},
{"aleph", 0x2135},
{"backprime", 0x2035},
{"backslash", 0x005c},
{"beth", 0x2136},
{"blacksquare", 0x25a0},
{"cent", 0x00a2},
{"checkmark", 0x2713},
{"circledR", 0x00ae},
{"circledS", 0x24c8},
{"clubsuit", 0x2663},
{"clubsuitopen", 0x2667},
{"copyright", 0x00a9},
{"daleth", 0x2138},
{"danger", 0x26a0},
{"degree", 0x00b0},
{"diamondsuit", 0x2662},
{"digamma", 0x03dd},
{"ell", 0x2113},
{"emptyset", 0x2205},
{"eth", 0x00f0},
{"exists", 0x2203},
{"flat", 0x266d},
{"forall", 0x2200},
{"frakC", 0x212d},
{"frakZ", 0x2128},
{"gimel", 0x2137},
{"hbar", 0x0127},
{"heartsuit", 0x2661},
{"hslash", 0x210f},
{"i", 0x0131},
{"imath", 0x0131},
{"infty", 0x221e},
{"jmath", 0x0237},
{"l", 0x0142},
{"lambdabar", 0x019b},
{"macron", 0x00af},
{"maltese", 0x2720},
{"mho", 0x2127},
{"nabla", 0x2207},
{"natural", 0x266e},
{"nexists", 0x2204},
{"o", 0x00f8},
{"oe", 0x0153},
{"partial", 0x2202},
{"perthousand", 0x2030},
{"prime", 0x2032},
{"scrB", 0x212c},
{"scrE", 0x2130},
{"scrF", 0x2131},
{"scrH", 0x210b},
{"scrI", 0x2110},
{"scrL", 0x2112},
{"scrM", 0x2133},
{"scrR", 0x211b},
{"scre", 0x212f},
{"scrg", 0x210a},
{"scro", 0x2134},
{"sharp", 0x266f},
{"spadesuit", 0x2660},
{"spadesuitopen", 0x2664},
{"ss", 0x00df},
{"sterling", 0x00a3},
{"surd", 0x221a},
{"textasciiacute", 0x00b4},
{"textasciicircum", 0x005e},
{"textasciigrave", 0x0060},
{"textasciitilde", 0x007e},
{"thorn", 0x00fe},
{"underbar", 0x0331},
{"varkappa", 0x03f0},
{"varnothing", 0x2205},
{"wp", 0x2118},
{"yen", 0x00a5},
}};
}
| 26.188679
| 92
| 0.440562
|
cpp-niel
|
6eb333ffd0637682d57f8119b1498e63397f860e
| 2,727
|
cpp
|
C++
|
Plugins/Experimental/Experimentals/SuppressPlayerLoginInfo.cpp
|
Mefi100/unified
|
b12a6cc27f291ff779d5ce1226c180ba3f3db800
|
[
"MIT"
] | 1
|
2021-07-13T19:21:57.000Z
|
2021-07-13T19:21:57.000Z
|
Plugins/Experimental/Experimentals/SuppressPlayerLoginInfo.cpp
|
Mefi100/unified
|
b12a6cc27f291ff779d5ce1226c180ba3f3db800
|
[
"MIT"
] | null | null | null |
Plugins/Experimental/Experimentals/SuppressPlayerLoginInfo.cpp
|
Mefi100/unified
|
b12a6cc27f291ff779d5ce1226c180ba3f3db800
|
[
"MIT"
] | null | null | null |
#include "Experimentals/SuppressPlayerLoginInfo.hpp"
#include "API/CNWSPlayer.hpp"
#include "API/CNWSMessage.hpp"
#include "API/Functions.hpp"
#include "API/Globals.hpp"
#include "API/Constants.hpp"
namespace Experimental {
using namespace NWNXLib;
using namespace NWNXLib::API;
static NWNXLib::Hooks::Hook s_SendServerToPlayerPlayerList_AddHook;
static NWNXLib::Hooks::Hook s_SendServerToPlayerPlayerList_AllHook;
static NWNXLib::Hooks::Hook s_SendServerToPlayerPlayerList_DeleteHook;
SuppressPlayerLoginInfo::SuppressPlayerLoginInfo()
{
s_SendServerToPlayerPlayerList_AddHook = Hooks::HookFunction(
API::Functions::_ZN11CNWSMessage32SendServerToPlayerPlayerList_AddEjP10CNWSPlayer,
(void*)&SendServerToPlayerPlayerList_AddHook, Hooks::Order::Late);
s_SendServerToPlayerPlayerList_AllHook = Hooks::HookFunction(
API::Functions::_ZN11CNWSMessage32SendServerToPlayerPlayerList_AllEP10CNWSPlayer,
(void*)&SendServerToPlayerPlayerList_AllHook, Hooks::Order::Late);
s_SendServerToPlayerPlayerList_DeleteHook = Hooks::HookFunction(
API::Functions::_ZN11CNWSMessage35SendServerToPlayerPlayerList_DeleteEjP10CNWSPlayer,
(void*)&SendServerToPlayerPlayerList_DeleteHook, Hooks::Order::Late);
static auto s_ReplacedFunc = Hooks::HookFunction(API::Functions::_ZN11CNWSMessage49HandlePlayerToServerPlayModuleCharacterList_StartEP10CNWSPlayer,
(void*)&HandlePlayerToServerPlayModuleCharacterList_StartHook, Hooks::Order::Final);
}
int32_t SuppressPlayerLoginInfo::SendServerToPlayerPlayerList_AddHook(CNWSMessage *pThis, uint32_t nPlayerId, CNWSPlayer *pNewPlayer)
{
return nPlayerId == Constants::PLAYERID_ALL_GAMEMASTERS ? s_SendServerToPlayerPlayerList_AddHook->CallOriginal<int32_t>(pThis, nPlayerId, pNewPlayer) : false;
}
int32_t SuppressPlayerLoginInfo::SendServerToPlayerPlayerList_AllHook(CNWSMessage *pThis, CNWSPlayer *pPlayer)
{
return pPlayer->m_nPlayerID == Constants::PLAYERID_ALL_GAMEMASTERS ? s_SendServerToPlayerPlayerList_AllHook->CallOriginal<int32_t>(pThis, pPlayer) : false;
}
int32_t SuppressPlayerLoginInfo::SendServerToPlayerPlayerList_DeleteHook(CNWSMessage *pThis, uint32_t nPlayerId, CNWSPlayer *pNewPlayer)
{
return nPlayerId == Constants::PLAYERID_ALL_GAMEMASTERS ? s_SendServerToPlayerPlayerList_DeleteHook->CallOriginal<int32_t>(pThis, nPlayerId, pNewPlayer) : false;
}
int32_t SuppressPlayerLoginInfo::HandlePlayerToServerPlayModuleCharacterList_StartHook(
CNWSMessage* pThis, CNWSPlayer* pPlayer)
{
if (pThis->MessageReadOverflow(true) || pThis->MessageReadUnderflow(true))
return false;
pPlayer->m_bPlayModuleListingCharacters = true;
return true;
}
}
| 45.45
| 165
| 0.807847
|
Mefi100
|
6eb6fe112022e783839e132a269c3f48b17ebea5
| 2,993
|
hpp
|
C++
|
physic.hpp
|
Bethoth/SComputer
|
ce3547a0b7065f4422050ca03f3b05c50dee1772
|
[
"MIT"
] | null | null | null |
physic.hpp
|
Bethoth/SComputer
|
ce3547a0b7065f4422050ca03f3b05c50dee1772
|
[
"MIT"
] | null | null | null |
physic.hpp
|
Bethoth/SComputer
|
ce3547a0b7065f4422050ca03f3b05c50dee1772
|
[
"MIT"
] | null | null | null |
#pragma once
#include <array>
#include <string>
#include <cmath>
#include <optional>
#include "maths.hpp"
using std::stod;
namespace physic {
const double G = 6.67e-11;
std::optional<double> voluminal_mass(const std::string& rho, const std::string& mass, const std::string& volume) {
const bool rho_is_searched = rho == "searched";
const bool mass_is_searched = mass == "searched";
const bool volume_is_searched = volume == "searched";
if (rho_is_searched && !mass_is_searched && !volume_is_searched) {
double int_mass = stod(mass);
double int_volume = stod(volume);
return std::round((int_mass / int_volume) * options::rounder) / options::rounder;
}
else if (mass_is_searched && !rho_is_searched && !volume_is_searched) {
double int_rho = stod(rho);
double int_volume = stod(volume);
return std::round((int_rho * int_volume) * options::rounder) / options::rounder;
}
else if (volume_is_searched && !rho_is_searched && !mass_is_searched) {
double int_rho = stod(rho);
double int_mass = stod(mass);
return std::round((int_mass / int_rho) * options::rounder) / options::rounder;
}
return {};
}
std::optional<double> gravitational_force(const std::string& F, const std::string& mass_a, const std::string& mass_b, const std::string& distance) {
const bool F_is_searched = F == "searched";
const bool mass_a_is_searched = mass_a == "searched";
const bool mass_b_is_searched = mass_b == "searched";
const bool distance_is_searched = distance == "searched";
if (F_is_searched && !mass_a_is_searched && !mass_b_is_searched && !distance_is_searched) {
double int_mass_a = stod(mass_a);
double int_mass_b = stod(mass_b);
double int_distance = stod(distance);
return std::round((G * (int_mass_a * int_mass_b) / std::pow(int_distance, 2)) * options::rounder) / options::rounder;
}
else if (distance_is_searched && !mass_a_is_searched && !mass_b_is_searched && !F_is_searched) {
double int_F = stod(F);
double int_mass_a = stod(mass_a);
double int_mass_b = stod(mass_b);
return std::round(std::sqrt((G * int_mass_a * int_mass_b) / int_F) * options::rounder) / options::rounder;
}
else if (mass_a_is_searched && !distance_is_searched && !mass_b_is_searched && !F_is_searched) {
double int_F = stod(F);
double int_distance = stod(distance);
double int_mass_b = stod(mass_b);
return std::round(((int_F * std::pow(int_distance, 2)) / (G * int_mass_b)) * options::rounder) / options::rounder;
}
else if (mass_b_is_searched && !distance_is_searched && !mass_a_is_searched && !F_is_searched) {
double int_F = stod(F);
double int_distance = stod(distance);
double int_mass_a = stod(mass_a);
return std::round(((int_F * std::pow(int_distance, 2)) / (G * int_mass_a)) * options::rounder) / options::rounder;
}
return {};
}
std::array<std::string, 2> figures = { "Voluminal mass", "Gravitational force" };
int figures_size = std::tuple_size<std::array<std::string, 2>>::value;
}
| 39.906667
| 149
| 0.696625
|
Bethoth
|
6ebd6a92172b5081434b69543f6a97c823542698
| 5,565
|
cpp
|
C++
|
Partmod/free_space_manager.cpp
|
Null665/partmod
|
11f2b90c745e27bdb47b105e0bf45834c62d3527
|
[
"BSD-3-Clause"
] | 1
|
2017-02-12T15:10:38.000Z
|
2017-02-12T15:10:38.000Z
|
Partmod/free_space_manager.cpp
|
Null665/partmod
|
11f2b90c745e27bdb47b105e0bf45834c62d3527
|
[
"BSD-3-Clause"
] | 1
|
2016-06-03T18:20:16.000Z
|
2016-10-10T22:22:41.000Z
|
Partmod/free_space_manager.cpp
|
Null665/partmod
|
11f2b90c745e27bdb47b105e0bf45834c62d3527
|
[
"BSD-3-Clause"
] | null | null | null |
#include "free_space_manager.h"
#include "disk.h"
#include "disk_exception.h"
#include <algorithm>
using namespace std;
bool cmp_frs(FREE_SPACE a,FREE_SPACE b)
{
return a.begin_sector < b.begin_sector;
}
void FreeSpaceManager::sort_vectors()
{
sort(free_space.begin(),free_space.end(),cmp_frs);
}
FreeSpaceManager::~FreeSpaceManager()
{
free_space.clear();
free_space.resize(0);
}
uint32_t FreeSpaceManager::CountFreeSpaces()
{
return free_space.size();
}
const FREE_SPACE &FreeSpaceManager::GetFreeSpace(uint32_t f)
{
if(f>CountFreeSpaces())
throw DiskException(ERR_OUT_OF_BOUNDS);
return free_space[f];
}
//
// FINALLY THIS SHIT WORKS!!!
//
void FreeSpaceManager::FindFreeSpace(PartitionManager *partman,uint64_t num_sect,int bps,int spt)
{
free_space.clear();
uint64_t NSECT_MB=MB/bps; // Numbert of disk sectors in megabyte
bool found_gpt;
try
{
partman->GetPartition(0).flags&PART_MBR_GPT ? found_gpt=true : found_gpt=false;
}
catch(...) {found_gpt=false;}
if(found_gpt)
find_in(partman,num_sect,0,PART_PRIMARY | PART_EXTENDED | PART_MBR_GPT,0,FREE_UNALLOCATED,NSECT_MB,1);
else
find_in(partman,num_sect,0,PART_PRIMARY | PART_EXTENDED | PART_MBR_GPT,0,FREE_UNALLOCATED,NSECT_MB,1); //spt
if(partman->CountPartitions(PART_EXTENDED)!=0)
find_in(partman,num_sect,PART_EXTENDED,PART_LOGICAL,spt,FREE_EXTENDED,NSECT_MB);
if(partman->CountPartitions(PART_MBR_GPT)!=0)
find_in(partman,num_sect,PART_MBR_GPT,PART_GPT,spt,FREE_GPT,NSECT_MB);
this->sort_vectors();
return;
}
void FreeSpaceManager::find_in(PartitionManager *partman,
uint64_t num_sect, // Number of sectors on disk
uint32_t parent_flag, // Parent flag: (optional)PART_EXTENDED, PART_MBR_GPT
uint32_t child_flag, // Child flag: PART_LOGICAL, PART_GPT
uint32_t sect_between, // Number of sectors between partition and the free space
uint32_t free_space_type, // FREE_EXTENDED, FREE_GPT, FREE_UNALLOCATED
uint32_t resolution, // Min size of the free space
uint32_t reserved_space // Number of reseved sectors at the beginning of disk
)
{
GEN_PART part_curr,part_next;
FREE_SPACE tmp;
// Special case:
// there are no partitions and we need to find unallocated space
if(partman->CountPartitions()==0 && parent_flag==0)
{
tmp.begin_sector=reserved_space;
tmp.length=num_sect-tmp.begin_sector;
tmp.type=FREE_UNALLOCATED;
free_space.push_back(tmp);
return;
}
// there are no partitions and we are trying to find free space on something else (PART_EXTENDED or PART_MBR_GPT)
else if(partman->CountPartitions()==0 && parent_flag!=0)
{
return;
}
for(unsigned i=0,j=1;i<partman->CountPartitions()-1,j<partman->CountPartitions(); i++,j++)
{
part_curr=partman->GetPartition(i);
if( !(part_curr.flags&child_flag))
continue;
part_next=partman->GetPartition(j);
if( !(part_next.flags&child_flag))
{
i--;
continue;
}
tmp.begin_sector=part_curr.begin_sector+part_curr.length;
tmp.length=part_next.begin_sector-tmp.begin_sector;
tmp.type=free_space_type;
if(tmp.length>resolution)
{
tmp.begin_sector+=sect_between;
tmp.length-=sect_between;
free_space.push_back(tmp);
}
}
// ----------
GEN_PART part_parent,last_logical;
bool found=false;
if(parent_flag==0)
{
part_parent.begin_sector=reserved_space;
part_parent.length=num_sect-part_parent.begin_sector;
}
else
{
for(unsigned i=0;i<partman->CountPartitions();i++)
if(partman->GetPartition(i).flags&parent_flag)
{
part_parent=partman->GetPartition(i);
found=true;
break;
}
if(!found)
return;
}
found=false;
for(unsigned i=0;i<partman->CountPartitions();i++)
if(partman->GetPartition(i).flags&child_flag)
{
last_logical=partman->GetPartition(i);
found=true;
}
if(found==false)
{
tmp.begin_sector=part_parent.begin_sector;
tmp.length=part_parent.length;
tmp.type=free_space_type;
if(tmp.length>resolution)
{
tmp.begin_sector+=sect_between;
tmp.length-=sect_between;
free_space.push_back(tmp);
}
}
else
{
// Find free space between the parent and last child partition
tmp.begin_sector=last_logical.begin_sector+last_logical.length;
tmp.length= (part_parent.begin_sector+part_parent.length)-tmp.begin_sector;
tmp.type=free_space_type;
if(tmp.length>resolution)
{
tmp.begin_sector+=sect_between;
tmp.length-=sect_between;
free_space.push_back(tmp);
}
// Find free space between the parent and first child partition
GEN_PART first_logical;
for(unsigned i=0;i<partman->CountPartitions();i++)
if(partman->GetPartition(i).flags&child_flag)
{
first_logical=partman->GetPartition(i);
break;
}
tmp.begin_sector=part_parent.begin_sector;
tmp.length= first_logical.begin_sector-tmp.begin_sector;
tmp.type=free_space_type;
if(tmp.length>resolution)
{
tmp.begin_sector+=sect_between;
tmp.length-=sect_between;
free_space.push_back(tmp);
}
}
}
| 25.527523
| 116
| 0.654447
|
Null665
|
6ebff0ee1d9f67afa95d19050693d78b9c8d6a70
| 1,828
|
cpp
|
C++
|
tests/src/Helpers/TestRoutes.cpp
|
nemu-framework/core
|
dea0ab4382684d0efc7f387e8a69a51a170c9305
|
[
"MIT"
] | null | null | null |
tests/src/Helpers/TestRoutes.cpp
|
nemu-framework/core
|
dea0ab4382684d0efc7f387e8a69a51a170c9305
|
[
"MIT"
] | 3
|
2022-03-26T12:52:32.000Z
|
2022-03-28T19:35:21.000Z
|
tests/src/Helpers/TestRoutes.cpp
|
nemu-framework/core
|
dea0ab4382684d0efc7f387e8a69a51a170c9305
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2019 Xavier Leclercq
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 "TestRoutes.h"
TestRoutes::TestRoutes()
: m_visitedRoutes(std::make_shared<std::vector<std::string>>())
{
setDefaultRoute(Nemu::Route("",
[](const Nemu::WebRequest& request, Nemu::WebResponseBuilder& response, void* handlerData)
{
response.setStatus(404);
TestRoutes* routes = reinterpret_cast<TestRoutes*>(handlerData);
std::lock_guard<std::mutex> guard(routes->m_visitedRoutesMutex);
routes->m_visitedRoutes->push_back(request.URI());
},
std::shared_ptr<TestRoutes>(this, [](TestRoutes*) {})));
}
const std::vector<std::string>& TestRoutes::visitedRoutes() const
{
return *m_visitedRoutes;
}
| 41.545455
| 98
| 0.715536
|
nemu-framework
|
6ec84435134d26540a86ea3ea7a58b7de7f6e4dd
| 1,472
|
hpp
|
C++
|
include/threepp/math/float_view.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
include/threepp/math/float_view.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
include/threepp/math/float_view.hpp
|
maidamai0/threepp
|
9b50e2c0f2a7bb3ebfd3ffeef61dbefcd54c7071
|
[
"MIT"
] | null | null | null |
#ifndef THREEPP_FLOAT_VIEW_HPP
#define THREEPP_FLOAT_VIEW_HPP
#include <functional>
#include <utility>
#include <optional>
namespace threepp {
class float_view {
public:
float value{};
float operator()() const {
return value;
}
float_view &operator=(float v) {
this->value = v;
if (f_) f_.value()();
return *this;
}
float_view &operator*=(float f) {
value *= f;
if (f_) f_.value()();
return *this;
}
float_view &operator/=(float f) {
value /= f;
if (f_) f_.value()();
return *this;
}
float_view &operator+=(float f) {
value += f;
if (f_) f_.value()();
return *this;
}
float_view &operator-=(float f) {
value -= f;
if (f_) f_.value()();
return *this;
}
float_view &operator++() {
value++;
if (f_) f_.value()();
return *this;
}
float_view &operator--() {
value--;
if (f_) f_.value()();
return *this;
}
private:
std::optional<std::function<void()>> f_;
void setCallback(std::function<void()> f) {
f_ = std::move(f);
}
friend class Euler;
};
}// namespace threepp
#endif//THREEPP_FLOAT_VIEW_HPP
| 18.871795
| 51
| 0.44837
|
maidamai0
|
6ecd27327e29418e36ffd3b391dc26babac7cdd4
| 8,330
|
cpp
|
C++
|
hash/appl_hash_test.cpp
|
fboucher9/appl
|
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
|
[
"MIT"
] | null | null | null |
hash/appl_hash_test.cpp
|
fboucher9/appl
|
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
|
[
"MIT"
] | null | null | null |
hash/appl_hash_test.cpp
|
fboucher9/appl
|
bb90398cf9985d4cc0a2a079c4d49d891108e6d1
|
[
"MIT"
] | null | null | null |
/* See LICENSE for license details */
/*
*/
#include <stdio.h>
#include <string.h>
#include <appl.h>
#include <hash/appl_hash_test.h>
#include <misc/appl_unused.h>
/*
*/
struct appl_hash_test_node
{
struct appl_list
o_list;
/* -- */
char const *
p_string;
int
i_string_len;
#define PADDING (APPL_SIZEOF_PTR + APPL_SIZEOF_INT)
#include <misc/appl_padding.h>
}; /* struct appl_hash_test_node */
union appl_hash_test_node_ptr
{
struct appl_list *
p_list;
struct appl_hash_test_node *
p_hash_test_node;
};
/*
*/
static
int
appl_hash_test_compare_string(
void * const
p_context,
void const * const
p_key,
unsigned long int const
i_key_len,
struct appl_list * const
p_list)
{
int
i_compare_result;
union appl_hash_test_node_ptr
o_hash_test_node_ptr;
struct appl_hash_test_node const *
p_hash_test_node;
appl_unused(
p_context,
i_key_len);
o_hash_test_node_ptr.p_list =
p_list;
p_hash_test_node =
o_hash_test_node_ptr.p_hash_test_node;
i_compare_result =
strcmp(
p_hash_test_node->p_string,
static_cast<char const *>(
p_key));
return
i_compare_result;
} /* appl_hash_test_compare_string() */
/*
*/
static
unsigned long int
appl_hash_test_index_string(
void * const
p_context,
void const * const
p_key,
unsigned long int const
i_key_len)
{
appl_unused(
p_context,
i_key_len);
unsigned char const * const
p_uchar =
static_cast<unsigned char const *>(
p_key);
return
*(
p_uchar);
} /* appl_hash_test_index_string() */
/*
*/
static
enum appl_status
appl_hash_test_create_node(
struct appl_context * const
p_context,
char const * const
p_string,
struct appl_hash_test_node * * const
r_node)
{
enum appl_status
e_status;
struct appl_hash_test_node *
p_node;
e_status =
appl_heap_alloc_structure(
p_context,
&(
p_node));
if (
appl_status_ok
== e_status)
{
appl_list_init(
&(
p_node->o_list));
p_node->p_string =
p_string;
p_node->i_string_len =
static_cast<int>(
strlen(
p_string));
*(
r_node) =
p_node;
}
return
e_status;
} /* appl_hash_test_create_node() */
/*
*/
static
void
appl_hash_test_destroy_node(
struct appl_context * const
p_context,
struct appl_hash_test_node * const
p_node)
{
void *
p_placement;
appl_size_t
i_placement_length;
p_placement =
static_cast<void *>(
p_node);
i_placement_length =
sizeof(
struct appl_hash_test_node);
appl_list_join(
&(
p_node->o_list),
&(
p_node->o_list));
appl_heap_free(
p_context,
i_placement_length,
p_placement);
} /* appl_hash_test_destroy_node() */
/*
*/
static
void
appl_hash_test_dump_callback(
void * const
p_context,
struct appl_list * const
p_list)
{
struct appl_hash_test_node *
p_node;
appl_unused(
p_context);
p_node =
reinterpret_cast<struct appl_hash_test_node *>(
p_list);
printf(
"[%s]\n",
p_node->p_string);
} /* appl_hash_test_dump_callback() */
/*
*/
static
void
appl_hash_test_dump(
struct appl_hash * const
p_hash)
{
appl_hash_iterate(
p_hash,
&(
appl_hash_test_dump_callback),
static_cast<void *>(
p_hash));
} /* appl_hash_test_dump() */
/*
Function: appl_hash_test()
Description:
Test of appl_hash module.
*/
void
appl_hash_test_1(
struct appl_context * const
p_context)
{
{
enum appl_status
e_status;
struct appl_hash *
p_hash;
struct appl_hash_descriptor
o_hash_descriptor;
o_hash_descriptor.p_compare =
&(
appl_hash_test_compare_string);
o_hash_descriptor.p_index =
&(
appl_hash_test_index_string);
o_hash_descriptor.i_max_index =
16ul;
e_status =
appl_hash_create(
p_context,
&(
o_hash_descriptor),
&(
p_hash));
if (
appl_status_ok
== e_status)
{
{
struct appl_object *
p_object;
p_object =
appl_hash_parent(
p_hash);
appl_unused(
p_object);
}
static char const g_good_key1[] = "felix";
static char const g_good_key2[] = "falafel";
static char const g_bad_key[] = "bad";
/* create some nodes */
struct appl_hash_test_node *
p_node1;
e_status =
appl_hash_test_create_node(
p_context,
g_good_key1,
&(
p_node1));
if (
appl_status_ok
== e_status)
{
/* insert into hash table */
appl_hash_insert(
p_hash,
static_cast<void const *>(
p_node1->p_string),
static_cast<unsigned long int>(
p_node1->i_string_len),
&(
p_node1->o_list));
struct appl_hash_test_node *
p_node2;
e_status =
appl_hash_test_create_node(
p_context,
g_good_key2,
&(
p_node2));
if (
appl_status_ok
== e_status)
{
appl_hash_insert(
p_hash,
static_cast<void const *>(
p_node2->p_string),
static_cast<unsigned long int>(
p_node2->i_string_len),
&(
p_node2->o_list));
/* Verify */
appl_hash_test_dump(
p_hash);
// Lookup good and bad
{
struct appl_list *
p_lookup_result;
appl_hash_lookup(
p_hash,
g_good_key1,
static_cast<unsigned long int>(sizeof(g_good_key1) - 1),
&(
p_lookup_result));
appl_hash_lookup(
p_hash,
g_good_key2,
static_cast<unsigned long int>(sizeof(g_good_key2) - 1),
&(
p_lookup_result));
appl_hash_lookup(
p_hash,
g_bad_key,
static_cast<unsigned long int>(sizeof(g_bad_key) - 1),
&(
p_lookup_result));
}
appl_hash_test_destroy_node(
p_context,
p_node2);
}
appl_hash_test_destroy_node(
p_context,
p_node1);
}
/* locate nodes */
/* remove nodes */
/* iterate */
appl_hash_destroy(
p_hash);
}
}
} /* appl_hash_test() */
/* end-of-file: appl_hash_test.c */
| 19.739336
| 84
| 0.460384
|
fboucher9
|
6ed2838e809f41f084155b727183638f3ee85b12
| 287
|
cpp
|
C++
|
628.三个数的最大乘积/maximumProduct.cpp
|
YichengZhong/Top-Interview-Questions
|
124828d321f482a0eaa30012b3706267487bfd24
|
[
"MIT"
] | 1
|
2019-10-21T14:40:39.000Z
|
2019-10-21T14:40:39.000Z
|
628.三个数的最大乘积/maximumProduct.cpp
|
YichengZhong/Top-Interview-Questions
|
124828d321f482a0eaa30012b3706267487bfd24
|
[
"MIT"
] | null | null | null |
628.三个数的最大乘积/maximumProduct.cpp
|
YichengZhong/Top-Interview-Questions
|
124828d321f482a0eaa30012b3706267487bfd24
|
[
"MIT"
] | 1
|
2020-11-04T07:33:34.000Z
|
2020-11-04T07:33:34.000Z
|
class Solution {
public:
int maximumProduct(vector<int>& nums) {
sort(nums.begin(),nums.end());
int first=nums[0]*nums[1]*nums[nums.size()-1];
int second=nums[nums.size()-1]*nums[nums.size()-2]*nums[nums.size()-3];
return max(first,second);
}
};
| 26.090909
| 79
| 0.585366
|
YichengZhong
|
6ed3e03729815f12c9f7265a696a4b63af6dbb5b
| 291
|
hpp
|
C++
|
include/unordered_map/details/align_helper.hpp
|
Wizermil/unordered_map
|
4d60bf16384b7ea9db1d43d8b15313f8752490ee
|
[
"MIT"
] | null | null | null |
include/unordered_map/details/align_helper.hpp
|
Wizermil/unordered_map
|
4d60bf16384b7ea9db1d43d8b15313f8752490ee
|
[
"MIT"
] | null | null | null |
include/unordered_map/details/align_helper.hpp
|
Wizermil/unordered_map
|
4d60bf16384b7ea9db1d43d8b15313f8752490ee
|
[
"MIT"
] | null | null | null |
#pragma once
#include "unordered_map/details/config.hpp"
#include "unordered_map/details/type.hpp"
namespace wiz::details {
WIZ_HIDE_FROM_ABI constexpr usize next_aligned(usize sz, usize a_minus_one) noexcept { return (sz + a_minus_one) & ~a_minus_one; }
} // namespace wiz::details
| 26.454545
| 134
| 0.762887
|
Wizermil
|
6ed439ae01ec6187b401af8f78ee13a8a24300a5
| 10,283
|
cpp
|
C++
|
src/FealStream.cpp
|
ruben2020/leaf
|
2927582ad2f6af0f683ad4e73a80c79f997857fa
|
[
"Apache-2.0"
] | null | null | null |
src/FealStream.cpp
|
ruben2020/leaf
|
2927582ad2f6af0f683ad4e73a80c79f997857fa
|
[
"Apache-2.0"
] | null | null | null |
src/FealStream.cpp
|
ruben2020/leaf
|
2927582ad2f6af0f683ad4e73a80c79f997857fa
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2021 ruben2020 https://github.com/ruben2020
*
* Licensed under the Apache License, Version 2.0
* with LLVM Exceptions (the "License");
* you may not use this file except in compliance with the License.
* You can find a copy of the License in the LICENSE file.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
*/
#include "feal.h"
#if defined (_WIN32)
#define BUFCAST(x) (char *) x
#define CLOSESOCKET(x) closesocket(x)
#else
#define BUFCAST(x) (void *) x
#define CLOSESOCKET(x) close(x)
#endif
feal::EventId_t feal::EvtIncomingConn::getId(void)
{
return getIdOfType<EvtIncomingConn>();
}
feal::EventId_t feal::EvtDataReadAvail::getId(void)
{
return getIdOfType<EvtDataReadAvail>();
}
feal::EventId_t feal::EvtDataWriteAvail::getId(void)
{
return getIdOfType<EvtDataWriteAvail>();
}
feal::EventId_t feal::EvtClientShutdown::getId(void)
{
return getIdOfType<EvtClientShutdown>();
}
feal::EventId_t feal::EvtServerShutdown::getId(void)
{
return getIdOfType<EvtServerShutdown>();
}
feal::EventId_t feal::EvtConnectedToServer::getId(void)
{
return getIdOfType<EvtConnectedToServer>();
}
feal::EventId_t feal::EvtConnectionShutdown::getId(void)
{
return getIdOfType<EvtConnectionShutdown>();
}
void feal::StreamGeneric::shutdownTool(void)
{
disconnect_and_reset();
}
feal::errenum feal::StreamGeneric::create_and_bind(feal::ipaddr* fa)
{
errenum res = FEAL_OK;
int ret;
if (fa == nullptr) return res;
sockaddr_ip su;
memset(&su, 0, sizeof(su));
ret = ipaddr_feal2posix(fa, &su);
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
sockfd = socket(fa->family, SOCK_STREAM, 0);
if (sockfd == FEAL_INVALID_SOCKET)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
socklen_t length = sizeof(su.in);
if (fa->family == feal::ipaddr::INET6)
{
setipv6only(sockfd);
length = sizeof(su.in6);
}
setnonblocking(sockfd);
ret = ::bind(sockfd, &(su.sa), length);
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
return res;
}
#if defined(unix) || defined(__unix__) || defined(__unix)
feal::errenum feal::StreamGeneric::create_and_bind(struct sockaddr_un* su)
{
errenum res = FEAL_OK;
int ret;
if (su == nullptr) return res;
sockfd = socket(su->sun_family, SOCK_STREAM, 0);
if (sockfd == FEAL_INVALID_SOCKET)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
setnonblocking(sockfd);
socklen_t length = sizeof(su->sun_family) + strlen(su->sun_path) + 1;
ret = bind(sockfd, (const struct sockaddr*) su, length);
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
return res;
}
#endif
feal::errenum feal::StreamGeneric::recv(void *buf,
uint32_t len, int32_t* bytes, feal::socket_t fd)
{
errenum res = FEAL_OK;
if (fd == FEAL_INVALID_SOCKET) fd = sockfd;
ssize_t numbytes = ::recv(fd, BUFCAST(buf), (size_t) len, MSG_DONTWAIT);
#if defined (_WIN32)
do_client_read_start(fd);
#endif
if (numbytes == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
if (bytes) *bytes = (int32_t) numbytes;
return res;
}
feal::errenum feal::StreamGeneric::send(void *buf,
uint32_t len, int32_t* bytes, feal::socket_t fd)
{
errenum res = FEAL_OK;
if (fd == FEAL_INVALID_SOCKET) fd = sockfd;
ssize_t numbytes = ::send(fd, BUFCAST(buf), (size_t) len, MSG_DONTWAIT);
if (numbytes == FEAL_SOCKET_ERROR)
{
if ((FEAL_GETSOCKETERRNO == EAGAIN)||(FEAL_GETSOCKETERRNO == EWOULDBLOCK))
{
do_send_avail_notify(fd);
}
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
if (bytes) *bytes = (int32_t) numbytes;
return res;
}
feal::errenum feal::StreamGeneric::disconnect_client(feal::socket_t client_sockfd)
{
errenum res = FEAL_OK;
mapReaders.erase(client_sockfd);
if (do_client_shutdown(client_sockfd) == -1)
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
feal::errenum feal::StreamGeneric::disconnect_and_reset(void)
{
for (auto it=mapReaders.begin(); it!=mapReaders.end(); ++it)
do_client_shutdown(it->first);
mapReaders.clear();
errenum res = FEAL_OK;
if (do_full_shutdown() == -1)
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
if (serverThread.joinable()) serverThread.join();
if (connectThread.joinable()) connectThread.join();
return res;
}
feal::errenum feal::StreamGeneric::getpeername(feal::ipaddr* fa, feal::socket_t fd)
{
errenum res = FEAL_OK;
if (fd == FEAL_INVALID_SOCKET) fd = sockfd;
sockaddr_ip su;
memset(&su, 0, sizeof(su));
socklen_t length = sizeof(su);
int ret = ::getpeername(fd, &(su.sa), &length);
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
if (fa) ipaddr_posix2feal(&su, fa);
return res;
}
#if defined(unix) || defined(__unix__) || defined(__unix)
feal::errenum feal::StreamGeneric::getpeername(struct sockaddr_un* su, feal::socket_t fd)
{
errenum res = FEAL_OK;
struct sockaddr_un an;
if (fd == -1) fd = sockfd;
socklen_t length = sizeof(an);
int ret = ::getpeername(fd, (struct sockaddr*) su, &length);
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
return res;
}
feal::errenum feal::StreamGeneric::getpeereid(uid_t* euid, gid_t* egid)
{
return getpeereid(sockfd, euid, egid);
}
feal::errenum feal::StreamGeneric::getpeereid(feal::socket_t fd, uid_t* euid, gid_t* egid)
{
errenum res = FEAL_OK;
int ret;
#if defined (__linux__)
socklen_t len;
struct ucred ucred;
len = sizeof(struct ucred);
ret = getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &len);
if (ret != FEAL_SOCKET_ERROR)
{
*euid = (uid_t) ucred.uid;
*egid = (gid_t) ucred.gid;
}
#else
ret = ::getpeereid(fd, euid, egid);
#endif
if (ret == FEAL_SOCKET_ERROR)
{
res = static_cast<errenum>(FEAL_GETSOCKETERRNO);
return res;
}
return res;
}
#endif
void feal::StreamGeneric::serverLoopLauncher(StreamGeneric *p)
{
if (p) p->serverLoop();
}
void feal::StreamGeneric::connectLoopLauncher(StreamGeneric *p)
{
if (p) p->connectLoop();
}
int feal::StreamGeneric::accept_new_conn(void)
{
sockaddr_ip su;
memset(&su, 0, sizeof(su));
socklen_t socklength = sizeof(su);
socket_t sock_conn_fd = accept(sockfd, &(su.sa), &socklength);
std::shared_ptr<EvtIncomingConn> incomingevt = std::make_shared<EvtIncomingConn>();
incomingevt.get()->client_sockfd = sock_conn_fd;
if (sock_conn_fd == FEAL_INVALID_SOCKET)
{
incomingevt.get()->errnum = static_cast<errenum>(FEAL_GETSOCKETERRNO);
}
else
{
incomingevt.get()->errnum = FEAL_OK;
}
receiveEvent(incomingevt);
return sock_conn_fd;
}
void feal::StreamGeneric::client_read_avail(feal::socket_t client_sockfd)
{
std::shared_ptr<EvtDataReadAvail> evt = std::make_shared<EvtDataReadAvail>();
evt.get()->sockfd = client_sockfd;
evt.get()->datalen = datareadavaillen(client_sockfd);
auto it = mapReaders.find(client_sockfd);
if (it != mapReaders.end())
{
std::weak_ptr<Actor> wkact = it->second;
if (wkact.expired() == false)
{
std::shared_ptr<Actor> act = wkact.lock();
act.get()->receiveEvent(evt);
}
}
}
void feal::StreamGeneric::client_write_avail(feal::socket_t client_sockfd)
{
std::shared_ptr<EvtDataWriteAvail> evt = std::make_shared<EvtDataWriteAvail>();
evt.get()->sockfd = client_sockfd;
auto it = mapReaders.find(client_sockfd);
if (it != mapReaders.end())
{
std::weak_ptr<Actor> wkact = it->second;
if (wkact.expired() == false)
{
std::shared_ptr<Actor> act = wkact.lock();
act.get()->receiveEvent(evt);
}
}
}
void feal::StreamGeneric::client_shutdown(feal::socket_t client_sockfd)
{
std::shared_ptr<EvtClientShutdown> evtclshutdown = std::make_shared<EvtClientShutdown>();
evtclshutdown.get()->client_sockfd = client_sockfd;
auto it = mapReaders.find(client_sockfd);
if (it != mapReaders.end())
{
std::weak_ptr<Actor> wkact = it->second;
if (wkact.expired() == false)
{
std::shared_ptr<Actor> act = wkact.lock();
act.get()->receiveEvent(evtclshutdown);
}
}
mapReaders.erase(client_sockfd);
}
void feal::StreamGeneric::server_shutdown(void)
{
std::shared_ptr<EvtServerShutdown> evt = std::make_shared<EvtServerShutdown>();
receiveEvent(evt);
}
void feal::StreamGeneric::connected_to_server(feal::socket_t fd)
{
std::shared_ptr<EvtConnectedToServer> evt = std::make_shared<EvtConnectedToServer>();
evt.get()->server_sockfd = fd;
receiveEvent(evt);
}
void feal::StreamGeneric::connection_read_avail(void)
{
std::shared_ptr<EvtDataReadAvail> evt = std::make_shared<EvtDataReadAvail>();
evt.get()->sockfd = sockfd;
evt.get()->datalen = datareadavaillen(sockfd);
receiveEvent(evt);
}
void feal::StreamGeneric::connection_write_avail(void)
{
std::shared_ptr<EvtDataWriteAvail> evt = std::make_shared<EvtDataWriteAvail>();
evt.get()->sockfd = sockfd;
receiveEvent(evt);
}
void feal::StreamGeneric::connection_shutdown(void)
{
std::shared_ptr<EvtConnectionShutdown> evt = std::make_shared<EvtConnectionShutdown>();
receiveEvent(evt);
}
void feal::StreamGeneric::receiveEvent(std::shared_ptr<Event> pevt){(void)pevt;}
| 27.791892
| 93
| 0.664495
|
ruben2020
|
6ed43db9683a69209dcd8456a6ebf6cc857b15a7
| 1,383
|
cpp
|
C++
|
engine/Engine/src/game/parameter/ParameterType.cpp
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | null | null | null |
engine/Engine/src/game/parameter/ParameterType.cpp
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | 10
|
2018-03-20T21:32:16.000Z
|
2018-04-23T19:42:59.000Z
|
engine/Engine/src/game/parameter/ParameterType.cpp
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | null | null | null |
#include "ghpch.h"
#include "ParameterType.h"
#include "core/Pointer.h"
namespace Ghurund {
using namespace ::DirectX;
const ParameterType ParameterType::INT = ParameterType(ParameterTypeEnum::INT, "int", sizeof(int));
const ParameterType ParameterType::INT2 = ParameterType(ParameterTypeEnum::INT2, "int2", sizeof(XMINT2));
const ParameterType ParameterType::FLOAT = ParameterType(ParameterTypeEnum::FLOAT, "float", sizeof(float));
const ParameterType ParameterType::FLOAT2 = ParameterType(ParameterTypeEnum::FLOAT2, "float2", sizeof(XMFLOAT2));
const ParameterType ParameterType::FLOAT3 = ParameterType(ParameterTypeEnum::FLOAT3, "float3", sizeof(XMFLOAT3));
const ParameterType ParameterType::MATRIX = ParameterType(ParameterTypeEnum::MATRIX, "matrix", sizeof(XMFLOAT4X4));
const ParameterType ParameterType::COLOR = ParameterType(ParameterTypeEnum::COLOR, "color", sizeof(XMFLOAT4));
const ParameterType ParameterType::TEXTURE = ParameterType(ParameterTypeEnum::TEXTURE, "texture", sizeof(Pointer*));
const EnumValues<ParameterTypeEnum, ParameterType> ParameterType::VALUES = {
&ParameterType::INT,
&ParameterType::INT2,
&ParameterType::FLOAT,
&ParameterType::FLOAT2,
&ParameterType::FLOAT3,
&ParameterType::MATRIX,
&ParameterType::COLOR,
&ParameterType::TEXTURE
};
}
| 49.392857
| 120
| 0.735358
|
Kartikeyapan598
|
6ed6f82f450ae78f18aa2c743cdf90f9bd3435f9
| 452
|
hpp
|
C++
|
Axis.Mint/foundation/definitions/ElementBlockSyntax.hpp
|
renato-yuzup/axis-fem
|
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
|
[
"MIT"
] | 2
|
2021-07-23T08:49:54.000Z
|
2021-07-29T22:07:30.000Z
|
Axis.Mint/foundation/definitions/ElementBlockSyntax.hpp
|
renato-yuzup/axis-fem
|
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
|
[
"MIT"
] | null | null | null |
Axis.Mint/foundation/definitions/ElementBlockSyntax.hpp
|
renato-yuzup/axis-fem
|
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
|
[
"MIT"
] | null | null | null |
#pragma once
#include "foundation/Axis.Mint.hpp"
#include "AxisString.hpp"
namespace axis { namespace foundation { namespace definitions {
class AXISMINT_API ElementBlockSyntax
{
private:
ElementBlockSyntax(void);
public:
~ElementBlockSyntax(void);
static const axis::String::char_type * BlockName;
static const axis::String::char_type * SetIdAttributeName;
friend class AxisInputLanguage;
};
} } } // namespace axis::foundation::definitions
| 21.52381
| 63
| 0.776549
|
renato-yuzup
|
6edc886b9560de46f95509370ffe6ef1d84e329f
| 1,562
|
hpp
|
C++
|
library/felix/maxflow.hpp
|
fffelix-huang/CP
|
ed7b481a6643bee1b6d89dec0be89aea205114ca
|
[
"MIT"
] | 1
|
2021-12-16T13:57:11.000Z
|
2021-12-16T13:57:11.000Z
|
library/felix/maxflow.hpp
|
fffelix-huang/CP
|
ed7b481a6643bee1b6d89dec0be89aea205114ca
|
[
"MIT"
] | null | null | null |
library/felix/maxflow.hpp
|
fffelix-huang/CP
|
ed7b481a6643bee1b6d89dec0be89aea205114ca
|
[
"MIT"
] | null | null | null |
#ifndef FELIX_MAXFLOW_HPP
#define FELIX_MAXFLOW_HPP 1
#include <vector>
#include <queue>
#include <numeric>
namespace felix {
template<class T>
class mf_graph {
public:
struct Edge {
int to;
T cap;
Edge(int _to, T _cap) : to(_to), cap(_cap) {}
};
static constexpr T inf = std::numeric_limits<T>::max() / 3 - 5;
int n;
std::vector<Edge> e;
std::vector<std::vector<int>> g;
std::vector<int> cur, h;
mf_graph(int _n) : n(_n), g(_n) {}
void add_edge(int u, int v, T c) {
debug() << show(u) show(v) show(c);
g[u].push_back(e.size());
e.emplace_back(v, c);
g[v].push_back(e.size());
e.emplace_back(u, 0);
}
bool bfs(int s, int t) {
h.assign(n, -1);
std::queue<int> que;
h[s] = 0;
que.push(s);
while(!que.empty()) {
int u = que.front();
que.pop();
for(int i : g[u]) {
int v = e[i].to;
T c = e[i].cap;
if(c > 0 && h[v] == -1) {
h[v] = h[u] + 1;
if(v == t) {
return true;
}
que.push(v);
}
}
}
return false;
}
T dfs(int u, int t, T f) {
if(u == t) {
return f;
}
T r = f;
for(int &i = cur[u]; i < int(g[u].size()); ++i) {
int j = g[u][i];
int v = e[j].to;
T c = e[j].cap;
if(c > 0 && h[v] == h[u] + 1) {
T a = dfs(v, t, std::min(r, c));
e[j].cap -= a;
e[j ^ 1].cap += a;
r -= a;
if (r == 0) {
return f;
}
}
}
return f - r;
}
T flow(int s, int t) {
T ans = 0;
while(bfs(s, t)) {
cur.assign(n, 0);
ans += dfs(s, t, inf);
}
return ans;
}
};
} // namespace felix
#endif // FELIX_MAXFLOW_HPP
| 16.617021
| 64
| 0.495519
|
fffelix-huang
|
6ede0060d2d169dbf4110b4f333770a7d3a75050
| 1,905
|
cpp
|
C++
|
numpy_benchmarks/benchmarks/periodic_dist.cpp
|
adriendelsalle/numpy-benchmarks
|
5c09448d045726b347e868756f9e1b004d0876ea
|
[
"BSD-3-Clause"
] | 33
|
2015-03-18T23:16:55.000Z
|
2021-12-17T11:00:01.000Z
|
numpy_benchmarks/benchmarks/periodic_dist.cpp
|
adriendelsalle/numpy-benchmarks
|
5c09448d045726b347e868756f9e1b004d0876ea
|
[
"BSD-3-Clause"
] | 8
|
2015-04-17T15:14:15.000Z
|
2021-02-24T13:34:55.000Z
|
numpy_benchmarks/benchmarks/periodic_dist.cpp
|
adriendelsalle/numpy-benchmarks
|
5c09448d045726b347e868756f9e1b004d0876ea
|
[
"BSD-3-Clause"
] | 12
|
2015-04-17T12:24:31.000Z
|
2021-01-27T08:06:01.000Z
|
#include "xtensor/xnoalias.hpp"
#include "xtensor/xtensor.hpp"
#include "xtensor/xarray.hpp"
#include "xtensor/xrandom.hpp"
#include "xtensor/xview.hpp"
#include "xtensor/xfixed.hpp"
#include "xtensor/xpad.hpp"
#include "xtensor/xindex_view.hpp"
#define FORCE_IMPORT_ARRAY
#include "xtensor-python/pyarray.hpp"
#include "xtensor-python/pytensor.hpp"
using namespace xt;
template<typename X, typename Y, typename Z>
auto periodic_dist(X const& x, Y const& y, Z const& z, long L, bool periodicX, bool periodicY, bool periodicZ)
{
auto N = x.size();
using shape_type = decltype(N);
xarray<double> xtemp = tile(x, N);
xtemp.reshape({N, N});
xtensor<double, 2> dx = xtemp - transpose(xtemp);
xarray<double> ytemp = tile(y, N);
ytemp.reshape({N, N});
xtensor<double, 2> dy = ytemp - transpose(ytemp);
xarray<double> ztemp = tile(z, N);
ztemp.reshape({N, N});
xtensor<double, 2> dz = ztemp - transpose(ztemp);
if(periodicX) {
filter(dx, dx>L/2) = filter(dx, dx > L/2) - L;
filter(dx, dx<-L/2) = filter(dx, dx < -L/2) + L;
}
if(periodicY) {
filter(dy, dy>L/2) = filter(dy, dy > L/2) - L;
filter(dy, dy<-L/2) = filter(dy, dy < -L/2) + L;
}
if(periodicZ) {
filter(dz, dz>L/2) = filter(dz, dz > L/2) - L;
filter(dz, dz<-L/2) = filter(dz, dz < -L/2) + L;
}
xtensor<double, 2> d = sqrt(square(dx) + square(dy) + square(dz));
filter(d, equal(d, 0)) = -1;
return std::make_tuple(d, dx, dy, dz);
}
std::tuple<pytensor<double, 2>, pytensor<double, 2>, pytensor<double, 2>, pytensor<double, 2>>
py_periodic_dist(pytensor<double, 1> const& x, pytensor<double, 1> const& y, pytensor<double, 1> const& z, long L, bool periodicX, bool periodicY, bool periodicZ)
{
return periodic_dist(x, y, z, L, periodicX, periodicY, periodicZ);
}
PYBIND11_MODULE(xtensor_periodic_dist, m)
{
import_numpy();
m.def("periodic_dist", py_periodic_dist);
}
| 27.608696
| 162
| 0.655118
|
adriendelsalle
|
6ee2a7582bd29f96c6ec8838d399081ce4086521
| 2,170
|
cpp
|
C++
|
test/huge_page_test.cpp
|
WeipingQu/memkind
|
f1c4ac9efd17e45b5bd669023a018e8b47bda398
|
[
"BSD-3-Clause"
] | null | null | null |
test/huge_page_test.cpp
|
WeipingQu/memkind
|
f1c4ac9efd17e45b5bd669023a018e8b47bda398
|
[
"BSD-3-Clause"
] | null | null | null |
test/huge_page_test.cpp
|
WeipingQu/memkind
|
f1c4ac9efd17e45b5bd669023a018e8b47bda398
|
[
"BSD-3-Clause"
] | null | null | null |
// SPDX-License-Identifier: BSD-2-Clause
/* Copyright (C) 2016 - 2020 Intel Corporation. */
#include "common.h"
#include "allocator_perf_tool/HugePageUnmap.hpp"
#include "allocator_perf_tool/HugePageOrganizer.hpp"
#include "TimerSysTime.hpp"
#include "Thread.hpp"
/*
* This test was created because of the munmap() fail in jemalloc.
* There are two root causes of the error:
* - kernel bug (munmap() fails when the size is not aligned)
* - heap Manager doesn’t provide size aligned to 2MB pages for munmap()
* Test allocates 2000MB using Huge Pages (50threads*10operations*4MBalloc_size),
* but it needs extra Huge Pages due to overhead caused by heap management.
*/
class HugePageTest: public :: testing::Test
{
protected:
void run()
{
unsigned mem_operations_num = 10;
size_t threads_number = 50;
bool touch_memory = true;
size_t size_1MB = 1024*1024;
size_t alignment = 2*size_1MB;
size_t alloc_size = 4*size_1MB;
std::vector<Thread *> threads;
std::vector<Task *> tasks;
TimerSysTime timer;
timer.start();
// This bug occurs more frequently under stress of multithreaded allocations.
for (int i=0; i<threads_number; i++) {
Task *task = new HugePageUnmap(mem_operations_num, touch_memory, alignment,
alloc_size, HBW_PAGESIZE_2MB);
tasks.push_back(task);
threads.push_back(new Thread(task));
}
float elapsed_time = timer.getElapsedTime();
ThreadsManager threads_manager(threads);
threads_manager.start();
threads_manager.barrier();
threads_manager.release();
//task release
for (int i=0; i<tasks.size(); i++) {
delete tasks[i];
}
RecordProperty("threads_number", threads_number);
RecordProperty("memory_operations_per_thread", mem_operations_num);
RecordProperty("elapsed_time", elapsed_time);
}
};
// Test passes when there is no crash.
TEST_F(HugePageTest, test_TC_MEMKIND_ext_UNMAP_HUGE_PAGE)
{
HugePageOrganizer huge_page_organizer(1024);
run();
}
| 31
| 87
| 0.660369
|
WeipingQu
|
6ee5312f3b09eac6769a296dcd6b0f44d8eeb5d6
| 2,461
|
cpp
|
C++
|
dev/spark/Gem/Code/Utils/Filter.cpp
|
chrisinajar/spark
|
3c6b30592c00bc38738cc3aaca2144edfc6cc8b2
|
[
"AML"
] | 2
|
2020-08-20T03:40:24.000Z
|
2021-02-07T20:31:43.000Z
|
dev/spark/Gem/Code/Utils/Filter.cpp
|
chrisinajar/spark
|
3c6b30592c00bc38738cc3aaca2144edfc6cc8b2
|
[
"AML"
] | null | null | null |
dev/spark/Gem/Code/Utils/Filter.cpp
|
chrisinajar/spark
|
3c6b30592c00bc38738cc3aaca2144edfc6cc8b2
|
[
"AML"
] | 5
|
2020-08-27T20:44:18.000Z
|
2021-08-21T22:54:11.000Z
|
#include "spark_precompiled.h"
#include "Filter.h"
#include <AzCore/Serialization/SerializeContext.h>
#include <AzCore/Serialization/EditContext.h>
namespace spark
{
static AZStd::stack<FilterResult*> resultsStack;
void FilterResult::FilterResultScriptConstructor(FilterResult* self, AZ::ScriptDataContext& dc)
{
if (dc.GetNumArguments() == 0)
{
*self = FilterResult();
return;
}
else if (dc.GetNumArguments() >= 1)
{
new(self) FilterResult{ };
if (dc.IsNumber(0))
{
int type = 0;
dc.ReadArg(0, type);
self->action = (FilterResult::FilterAction)type;
if (!resultsStack.empty()) {
//when there are multiple handler of the same filter, do the thing only if the priority is greater or equal
auto &top = resultsStack.top();
if (self->action >= top->action)
{
top->action = self->action;
top->ScriptConstructor(dc);
}
}
return;
}
}
dc.GetScriptContext()->Error(AZ::ScriptContext::ErrorType::Error, true, "Invalid arguments passed to FilterResult().");
new(self) FilterResult();
}
void FilterResult::Reflect(AZ::ReflectContext* reflection)
{
if (auto serializationContext = azrtti_cast<AZ::SerializeContext*>(reflection))
{
serializationContext->Class<FilterResult>()
->Version(1)
->Field("action", &FilterResult::action);
}
if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(reflection))
{
behaviorContext->Class<FilterResult>("FilterResult")
->Attribute(AZ::Script::Attributes::Storage, AZ::Script::Attributes::StorageType::Value)
->Attribute(AZ::Script::Attributes::ConstructorOverride, &FilterResultScriptConstructor)
->Enum<(int)FilterResult::FILTER_IGNORE>("FILTER_IGNORE")
->Enum<(int)FilterResult::FILTER_PREVENT>("FILTER_PREVENT")
->Enum<(int)FilterResult::FILTER_MODIFY>("FILTER_MODIFY")
->Enum<(int)FilterResult::FILTER_FORCE>("FILTER_FORCE")
;
}
}
void FilterResult::Push()
{
resultsStack.push(this);
}
void FilterResult::Pop()
{
AZ_Assert(!resultsStack.empty(), "FilterResult::Pop() called, but stack is empty!");
AZ_Assert(resultsStack.top()==this, "FilterResult::Pop() called, but the top of the stack does not match!");
resultsStack.pop();
}
AZStd::stack<FilterResult*>& FilterResult::GetStack()
{
return resultsStack;
}
FilterResult* FilterResult::GetStackTop()
{
return resultsStack.empty() ? nullptr : resultsStack.top();
}
}
| 25.371134
| 121
| 0.686306
|
chrisinajar
|
6ee9f5eff929c9c70575f862fcd112847b4376d9
| 977
|
cpp
|
C++
|
main_server/src/entities/hourly_rate/hourly_rate.cpp
|
GrassoMichele/uPark
|
d96310c165c3efa9b0251c51ababe06639c4570a
|
[
"MIT"
] | null | null | null |
main_server/src/entities/hourly_rate/hourly_rate.cpp
|
GrassoMichele/uPark
|
d96310c165c3efa9b0251c51ababe06639c4570a
|
[
"MIT"
] | null | null | null |
main_server/src/entities/hourly_rate/hourly_rate.cpp
|
GrassoMichele/uPark
|
d96310c165c3efa9b0251c51ababe06639c4570a
|
[
"MIT"
] | null | null | null |
#include "hourly_rate.hpp"
HourlyRate::HourlyRate(){}
HourlyRate::HourlyRate(int id) : id(id) {}
HourlyRate::HourlyRate(int id, float amount): id(id), amount(amount) {}
void HourlyRate::setId(int id){
this->id = id;
}
void HourlyRate::setAmount(float amount){
this->amount = amount;
}
int HourlyRate::getId() const{
return id;
}
float HourlyRate::getAmount() const{
return amount;
}
HourlyRate& HourlyRate::operator= (const HourlyRate& h1){
id = h1.id;
amount = h1.amount;
return *this;
}
bool operator== (const HourlyRate& h1, const HourlyRate& h2)
{
return h1.id == h2.id;
}
std::ostream& operator<<(std::ostream& os, const HourlyRate& h)
{
os << "HourlyRate - Id: " << h.id << ", Amount: " << h.amount << std::endl;
return os;
}
// HourlyRateException::HourlyRateException(const std::string & message):_message(message) {}
// const char * HourlyRateException::what() const throw() {
// return _message.c_str();
// }
| 20.787234
| 93
| 0.651996
|
GrassoMichele
|
6eebb790af7bd43fe9d2373147c269e0b47407b7
| 1,013
|
cpp
|
C++
|
TestExcel/pageMargins.cpp
|
antonyenergy-dev/QXlsx
|
865c0de9f8bf019100b90ef2528422d55ee92206
|
[
"MIT"
] | 1
|
2020-01-03T14:00:29.000Z
|
2020-01-03T14:00:29.000Z
|
TestExcel/pageMargins.cpp
|
antonyenergy-dev/QXlsx
|
865c0de9f8bf019100b90ef2528422d55ee92206
|
[
"MIT"
] | null | null | null |
TestExcel/pageMargins.cpp
|
antonyenergy-dev/QXlsx
|
865c0de9f8bf019100b90ef2528422d55ee92206
|
[
"MIT"
] | 1
|
2021-04-03T23:11:39.000Z
|
2021-04-03T23:11:39.000Z
|
// pageMargins.cpp
#include <QtGlobal>
#include <QObject>
#include <QString>
#include <QDebug>
#include "xlsxdocument.h"
#include "xlsxchartsheet.h"
#include "xlsxcellrange.h"
#include "xlsxchart.h"
#include "xlsxrichstring.h"
#include "xlsxworkbook.h"
using namespace QXlsx;
#include <cstdio>
#include <iostream>
// using namespace std;
int pageMargin(bool isTest);
int pages()
{
pageMargin(true);
return 0;
}
int pageMargin(bool isTest)
{
if (!isTest)
return (-1);
// TODO:
/*
Document xlsx;
xlsx.write("A1", "Hello QtXlsx!"); // current file is utf-8 character-set.
xlsx.write("A2", 12345);
xlsx.write("A3", "=44+33"); // cell value is 77.
xlsx.write("A4", true);
xlsx.write("A5", "http://qt-project.org");
xlsx.write("A6", QDate(2013, 12, 27));
xlsx.write("A7", QTime(6, 30));
if (!xlsx.saveAs("WriteExcel.xlsx"))
{
qDebug() << "[WriteExcel] failed to save excel file";
return (-2);
}
*/
return 0;
}
| 17.77193
| 78
| 0.611056
|
antonyenergy-dev
|
6ef036e9eae822b44864ca9595b31fa50868afd6
| 12,437
|
cpp
|
C++
|
Editor/LevelEditor/DOShuffle.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:19.000Z
|
2022-03-26T17:00:19.000Z
|
Editor/LevelEditor/DOShuffle.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | null | null | null |
Editor/LevelEditor/DOShuffle.cpp
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:21.000Z
|
2022-03-26T17:00:21.000Z
|
//---------------------------------------------------------------------------
#include "stdafx.h"
#pragma hdrstop
#include "DOShuffle.h"
#include "ChoseForm.h"
#include "ImageThumbnail.h"
#include "xr_trims.h"
#include "Library.h"
#include "DOOneColor.h"
#include "EditObject.h"
#include "Scene.h"
#include "DetailObjects.h"
#include "D3DUtils.h"
#include "PropertiesDetailObject.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TfrmDOShuffle *TfrmDOShuffle::form=0;
static DDVec DOData;
SDOData::SDOData(){
DOData.push_back(this);
}
//---------------------------------------------------------------------------
// Constructors
//---------------------------------------------------------------------------
bool __fastcall TfrmDOShuffle::Run(){
VERIFY(!form);
form = new TfrmDOShuffle(0);
// show
return (form->ShowModal()==mrOk);
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::FormShow(TObject *Sender)
{
bColorIndModif = false;
GetInfo();
}
//---------------------------------------------------------------------------
void TfrmDOShuffle::GetInfo(){
// init
tvItems->IsUpdating = true;
tvItems->Selected = 0;
tvItems->Items->Clear();
// fill
CDetailManager* DM=Scene.m_DetailObjects;
VERIFY(DM);
// objects
for (DOIt d_it=DM->m_Objects.begin(); d_it!=DM->m_Objects.end(); d_it++){
SDOData* dd = new SDOData;
dd->m_RefName = (*d_it)->GetName();
dd->m_fMinScale = (*d_it)->m_fMinScale;
dd->m_fMaxScale = (*d_it)->m_fMaxScale;
dd->m_fDensityFactor = (*d_it)->m_fDensityFactor;
dd->m_dwFlags = (*d_it)->m_dwFlags;
AddItem(0,(*d_it)->GetName(),(void*)dd);
}
// indices
ColorIndexPairIt S = DM->m_ColorIndices.begin();
ColorIndexPairIt E = DM->m_ColorIndices.end();
ColorIndexPairIt it= S;
for(; it!=E; it++){
TfrmOneColor* OneColor = new TfrmOneColor(0);
color_indices.push_back(OneColor);
OneColor->Parent = form->sbDO;
OneColor->ShowIndex(this);
OneColor->mcColor->Brush->Color = (TColor)rgb2bgr(it->first);
for (d_it=it->second.begin(); d_it!=it->second.end(); d_it++)
OneColor->AppendObject((*d_it)->GetName());
}
// redraw
tvItems->IsUpdating = false;
}
void TfrmDOShuffle::ApplyInfo(){
CDetailManager* DM=Scene.m_DetailObjects;
VERIFY(DM);
bool bNeedUpdate = false;
// update objects
DM->MarkAllObjectsAsDel();
for ( TElTreeItem* node = tvItems->Items->GetFirstNode(); node; node = node->GetNext()){
CDetail* DO = DM->FindObjectByName(AnsiString(node->Text).c_str());
if (DO) DO->m_bMarkDel = false;
else{
DO = DM->AppendObject(AnsiString(node->Text).c_str());
bNeedUpdate = true;
}
// update data
SDOData* DD = (SDOData*)node->Data;
DO->m_fMinScale = DD->m_fMinScale;
DO->m_fMaxScale = DD->m_fMaxScale;
DO->m_fDensityFactor= DD->m_fDensityFactor;
DO->m_dwFlags = DD->m_dwFlags;
}
if (DM->RemoveObjects(true)) bNeedUpdate=true;
// update indices
DM->RemoveColorIndices();
for (DWORD k=0; k<color_indices.size(); k++){
TfrmOneColor* OneColor = color_indices[k];
DWORD clr = bgr2rgb(OneColor->mcColor->Brush->Color);
for ( TElTreeItem* node = OneColor->tvDOList->Items->GetFirstNode(); node; node = node->GetNext())
DM->AppendIndexObject(clr,AnsiString(node->Text).c_str(),false);
}
if (bNeedUpdate||bColorIndModif){
ELog.DlgMsg(mtInformation,"Object list changed. Update objects needed!");
DM->InvalidateSlots();
}
}
//---------------------------------------------------------------------------
// implementation
//---------------------------------------------------------------------------
__fastcall TfrmDOShuffle::TfrmDOShuffle(TComponent* Owner)
: TForm(Owner)
{
DEFINE_INI(fsStorage);
}
//---------------------------------------------------------------------------
TElTreeItem* TfrmDOShuffle::FindItem(const char* s)
{
for ( TElTreeItem* node = tvItems->Items->GetFirstNode(); node; node = node->GetNext())
if (node->Data && (AnsiString(node->Text) == s)) return node;
return 0;
}
//---------------------------------------------------------------------------
TElTreeItem* TfrmDOShuffle::AddItem(TElTreeItem* node, const char* name, void* obj)
{
TElTreeItem* obj_node = tvItems->Items->AddChildObject(node, name, obj);
obj_node->ParentStyle = false;
obj_node->Bold = false;
return obj_node;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebOkClick(TObject *Sender)
{
ApplyInfo();
Close();
ModalResult = mrOk;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebCancelClick(TObject *Sender)
{
Close();
ModalResult = mrCancel;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::FormKeyDown(TObject *Sender, WORD &Key,
TShiftState Shift)
{
if (Key==VK_ESCAPE) ebCancel->Click();
if (Key==VK_RETURN) ebOk->Click();
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::FormClose(TObject *Sender, TCloseAction &Action)
{
for (DDIt it=DOData.begin(); it!=DOData.end(); it++)
_DELETE(*it);
DOData.clear();
for (DWORD k=0; k<color_indices.size(); k++)
_DELETE(color_indices[k]);
color_indices.clear();
_DELETE(m_Thm);
if (ModalResult==mrOk)
Scene.m_DetailObjects->InvalidateCache();
Action = caFree;
form = 0;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsItemFocused(TObject *Sender)
{
TElTreeItem* Item = tvItems->Selected;
_DELETE(m_Thm);
if (Item&&Item->Data){
AnsiString nm = Item->Text;
m_Thm = new EImageThumbnail(nm.c_str(),EImageThumbnail::EITObject);
SDOData* dd = (SDOData*)Item->Data;
lbItemName->Caption = "\""+dd->m_RefName+"\"";
AnsiString temp; temp.sprintf("Density: %1.2f\nScale: [%3.1f, %3.1f)\nNo waving: %s",dd->m_fDensityFactor,dd->m_fMinScale,dd->m_fMaxScale,(dd->m_dwFlags&DO_NO_WAVING)?"on":"off");
lbInfo->Caption = temp;
}else{
lbItemName->Caption = "-";
lbInfo->Caption = "-";
}
if (m_Thm&&m_Thm->Valid()) pbImagePaint(Sender);
else pbImage->Repaint();
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::pbImagePaint(TObject *Sender)
{
if (m_Thm) m_Thm->Draw(paImage,pbImage,true);
}
//---------------------------------------------------------------------------
bool __fastcall LookupFunc(TElTreeItem* Item, void* SearchDetails){
char s1 = *(char*)SearchDetails;
char s2 = *AnsiString(Item->Text).c_str();
return (s1==tolower(s2));
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsKeyPress(TObject *Sender, char &Key)
{
TElTreeItem* node = tvItems->Items->LookForItemEx(tvItems->Selected,-1,false,false,false,&Key,LookupFunc);
if (!node) node = tvItems->Items->LookForItemEx(0,-1,false,false,false,&Key,LookupFunc);
if (node){
tvItems->Selected = node;
tvItems->EnsureVisible(node);
}
}
//---------------------------------------------------------------------------
static TElTreeItem* DragItem=0;
void __fastcall TfrmDOShuffle::tvMultiDragDrop(TObject *Sender,
TObject *Source, int X, int Y)
{
TElTreeItem* node = ((TElTree*)Sender)->GetItemAtY(Y);
if (node)
DragItem->MoveToIns(0,node->Index);
DragItem = 0;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvMultiDragOver(TObject *Sender,
TObject *Source, int X, int Y, TDragState State, bool &Accept)
{
Accept = false;
TElTreeItem* node = ((TElTree*)Sender)->GetItemAtY(Y);
if ((Sender==Source)&&(node!=DragItem)) Accept=true;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvMultiStartDrag(TObject *Sender,
TDragObject *&DragObject)
{
DragItem = ((TElTree*)Sender)->Selected;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebAddObjectClick(TObject *Sender)
{
LPCSTR S = TfrmChoseItem::SelectObject(true,0,0);
if (S){
AStringVec lst;
SequenceToList(lst, S);
for (AStringIt s_it=lst.begin(); s_it!=lst.end(); s_it++)
if (!FindItem(s_it->c_str())){
if (tvItems->Items->Count>=dm_max_objects){
ELog.DlgMsg(mtInformation,"Maximum detail objects in scene '%d'",dm_max_objects);
return;
}
SDOData* dd = new SDOData;
dd->m_RefName = s_it->c_str();
dd->m_fMinScale = 0.5f;
dd->m_fMaxScale = 2.f;
dd->m_fDensityFactor= 1.f;
dd->m_dwFlags = 0;
AddItem(0,s_it->c_str(),(void*)dd);
}
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebDelObjectClick(TObject *Sender)
{
if (tvItems->Selected){
ModifColorInd();
for (DWORD k=0; k<color_indices.size(); k++)
color_indices[k]->RemoveObject(tvItems->Selected->Text);
tvItems->Selected->Delete();
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebAppendIndexClick(TObject *Sender)
{
ModifColorInd();
color_indices.push_back(new TfrmOneColor(0));
color_indices.back()->Parent = sbDO;
color_indices.back()->ShowIndex(this);
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::RemoveColorIndex(TfrmOneColor* p){
form->ModifColorInd();
form->color_indices.erase(find(form->color_indices.begin(),form->color_indices.end(),p));
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebMultiClearClick(TObject *Sender)
{
ModifColorInd();
for (DWORD k=0; k<color_indices.size(); k++)
_DELETE(color_indices[k]);
color_indices.clear();
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsDragDrop(TObject *Sender,
TObject *Source, int X, int Y)
{
TfrmOneColor* OneColor = (TfrmOneColor*)((TElTree*)Source)->Parent;
if (OneColor&&OneColor->FDragItem){
OneColor->FDragItem->Delete();
ModifColorInd();
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsDragOver(TObject *Sender,
TObject *Source, int X, int Y, TDragState State, bool &Accept)
{
Accept = false;
if (Source == tvItems) return;
TElTreeItem* node;
Accept = true;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsStartDrag(TObject *Sender,
TDragObject *&DragObject)
{
FDragItem = tvItems->ItemFocused;
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::ebDOPropertiesClick(TObject *Sender)
{
if (tvItems->Selected&&tvItems->Selected->Data){
bool bChange;
DDVec lst;
lst.push_back(((SDOData*)tvItems->Selected->Data));
TElTreeItem* node = tvItems->Selected;
if (frmPropertiesSectorRun(lst,bChange)==mrOk){
tvItems->Selected = 0;
tvItems->Selected = node;
}
}
}
//---------------------------------------------------------------------------
void __fastcall TfrmDOShuffle::tvItemsDblClick(TObject *Sender)
{
ebDOProperties->Click();
}
//---------------------------------------------------------------------------
| 34.451524
| 183
| 0.508
|
ixray-team
|
6ef4630fb60252ff3ead8fda9d590727def2f723
| 5,886
|
cpp
|
C++
|
source/Win32/XCondition.cpp
|
MultiSight/multisight-xsdk
|
02268e1aeb1313cfb2f9515d08d131a4389e49f2
|
[
"BSL-1.0"
] | null | null | null |
source/Win32/XCondition.cpp
|
MultiSight/multisight-xsdk
|
02268e1aeb1313cfb2f9515d08d131a4389e49f2
|
[
"BSL-1.0"
] | null | null | null |
source/Win32/XCondition.cpp
|
MultiSight/multisight-xsdk
|
02268e1aeb1313cfb2f9515d08d131a4389e49f2
|
[
"BSL-1.0"
] | null | null | null |
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// XSDK
// Copyright (c) 2015 Schneider Electric
//
// Use, modification, and distribution is subject to the Boost Software License,
// Version 1.0 (See accompanying file LICENSE).
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "XSDK/XCondition.h"
#include "XSDK/Errors.h"
#include "XSDK/TimeUtils.h"
#include "XSDK/XMonoClock.h"
#define MICROS_IN_SECOND 1000000
using namespace XSDK;
XCondition::XCondition( XMutex& lok ) :
_lok( lok ),
_numWaitingThreads( 0 )
{
InitializeCriticalSection( &_threadCountLock );
// We have to use both types of Win32 events to get the exact behavior we
// expect from a POSIX condition variable. We use an auto-reset event for
// the signal() call so only a single thread is woken up. We rely on the
// "stickyness" of a manual-reset event to properly implement broadcast().
_events[SIGNAL] = CreateEvent( NULL, false, false, NULL ); // auto-reset event
_events[BROADCAST] = CreateEvent( NULL, true, false, NULL ); // manual-reset event
if( _events[SIGNAL] == NULL || _events[BROADCAST] == NULL )
X_THROW(( "Unable to allocate Win32 event objects." ));
}
XCondition::~XCondition() throw()
{
if( _events[SIGNAL] )
CloseHandle( _events[SIGNAL] );
if( _events[BROADCAST] )
CloseHandle( _events[BROADCAST] );
DeleteCriticalSection( &_threadCountLock );
}
void XCondition::Wait()
{
// We keep track of the number of waiting threads so we can guarantee that
// all waiting threads are woken up by a broadcast() call.
EnterCriticalSection( &_threadCountLock );
_numWaitingThreads++;
LeaveCriticalSection( &_threadCountLock );
// Release the lock before waiting... this is standard POSIX condition
// semantics.
_lok.Release();
// NOTE: We avoid the "lost wakeup" bug common in many Win32 condition
// implementations because we are using a manual-reset event. If we were
// only using an auto-reset event, it would be possible to lose a signal
// right here due to a race condition.
// Wait for either event to be signaled.
DWORD result = WaitForMultipleObjects( MAX_EVENTS, _events, false, INFINITE );
if( ( result < WAIT_OBJECT_0 ) || ( result > WAIT_OBJECT_0 + MAX_EVENTS ) )
{
X_THROW(( "An error occurred what waiting for the Win32 event objects. Errorcode = 0x%08X.",
GetLastError() ));
}
// The following code is only required for the broadcast(). Basically, if
// broadcast was called AND we are the last waiting thread, then reset the
// manual-reset event.
EnterCriticalSection( &_threadCountLock );
_numWaitingThreads--;
bool lastThreadWaiting = ( result == WAIT_OBJECT_0 + BROADCAST ) && ( _numWaitingThreads == 0 );
LeaveCriticalSection( &_threadCountLock );
if( lastThreadWaiting )
ResetEvent( _events[BROADCAST] );
// Reacquire the lock before returning... again, this is standard POSIX
// condition semantics.
_lok.Acquire();
}
//bool XCondition::WaitUntil( time_t secondsAbsolute, time_t microsecondsAbsolute )
bool XCondition::WaitUntil( uint64_t then )
{
//
// NOTE: See the Wait() method for more details about how this works
// on Windows.
//
EnterCriticalSection( &_threadCountLock );
_numWaitingThreads++;
LeaveCriticalSection( &_threadCountLock );
// Convert the absolute wait timeout into a relative time. Windows wait
// functions only operate on relative time (in milliseconds).
int timeoutMS = (int)(ConvertTimeScale( then - XMonoClock::GetTime(), XMonoClock::GetFrequency(), 1000 ));
if( timeoutMS < 0 )
timeoutMS = 0;
bool timedOut = false;
_lok.Release();
DWORD result = WaitForMultipleObjects( MAX_EVENTS, _events, false, (DWORD)timeoutMS );
if( result == WAIT_TIMEOUT )
timedOut = true;
if( !timedOut && ( ( result < WAIT_OBJECT_0 ) || ( result > WAIT_OBJECT_0 + MAX_EVENTS ) ) )
{
X_THROW(( "An error occurred what waiting for the Win32 event objects. Errorcode = 0x%08X.",
GetLastError() ));
}
EnterCriticalSection( &_threadCountLock );
_numWaitingThreads--;
bool lastThreadWaiting = ( result == WAIT_OBJECT_0 + BROADCAST ) && ( _numWaitingThreads == 0 );
LeaveCriticalSection( &_threadCountLock );
if( lastThreadWaiting )
ResetEvent( _events[BROADCAST] );
_lok.Acquire();
return timedOut;
}
void XCondition::Signal()
{
EnterCriticalSection( &_threadCountLock );
bool threadsWaiting = _numWaitingThreads > 0;
LeaveCriticalSection( &_threadCountLock );
if( threadsWaiting )
SetEvent( _events[SIGNAL] );
}
void XCondition::Broadcast()
{
EnterCriticalSection( &_threadCountLock );
bool threadsWaiting = _numWaitingThreads > 0;
LeaveCriticalSection( &_threadCountLock );
if( threadsWaiting )
SetEvent( _events[BROADCAST] );
}
uint64_t XCondition::FutureMonotonicTime( time_t secondsAbsolute, time_t microsecondsAbsolute )
{
struct timeval future = { secondsAbsolute, microsecondsAbsolute };
struct timeval now;
x_gettimeofday( &now );
struct timeval delta;
timersub( &future, &now, &delta );
const double deltaSeconds = (((double)((delta.tv_sec * MICROS_IN_SECOND) + delta.tv_usec)) / MICROS_IN_SECOND);
return XMonoClock::GetTime() + (uint64_t)(deltaSeconds * XMonoClock::GetFrequency());
}
uint64_t XCondition::FutureMonotonicTime( XDuration timeFromNow )
{
const double deltaSeconds = ((double)timeFromNow.Total(HNSECS)) / convert(SECONDS, HNSECS, 1);
return deltaSeconds > 0 ? XMonoClock::GetTime() + (uint64_t)(deltaSeconds * XMonoClock::GetFrequency())
: XMonoClock::GetTime();
}
| 33.634286
| 115
| 0.666157
|
MultiSight
|
6ef4e0df22cae77eefa9664ef8696f04eb88ce9e
| 722
|
hpp
|
C++
|
include/back_off.hpp
|
cblauvelt/connection-pool
|
ea6e6fd1b4bea750fa694e10e36a53a3f0d0456d
|
[
"MIT"
] | null | null | null |
include/back_off.hpp
|
cblauvelt/connection-pool
|
ea6e6fd1b4bea750fa694e10e36a53a3f0d0456d
|
[
"MIT"
] | 7
|
2022-02-02T04:57:24.000Z
|
2022-03-20T23:07:02.000Z
|
include/back_off.hpp
|
cblauvelt/connection-pool
|
ea6e6fd1b4bea750fa694e10e36a53a3f0d0456d
|
[
"MIT"
] | 1
|
2021-09-19T17:55:20.000Z
|
2021-09-19T17:55:20.000Z
|
#pragma once
#include <chrono>
#include <random>
#include <stdexcept>
#include "types.hpp"
namespace cpool {
inline milliseconds
timer_delay(uint8_t num_retries,
std::chrono::milliseconds maximum_backoff = 32s) {
// prevent int rollover
int retries = std::min(num_retries, (uint8_t)29);
std::random_device
rd; // Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> distrib(1, 500);
milliseconds retry_time =
seconds((int)std::pow(2, retries)) + milliseconds(distrib(gen));
return std::min(retry_time, maximum_backoff);
}
} // namespace cpool
| 24.896552
| 80
| 0.693906
|
cblauvelt
|
6ef57bddc556034f284838f43f68d0cfdece60b1
| 4,861
|
cpp
|
C++
|
src/Engine/Platform/Thread.cpp
|
SapphireEngine/Engine
|
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
|
[
"MIT"
] | 2
|
2020-02-03T04:58:17.000Z
|
2021-03-13T06:03:52.000Z
|
src/Engine/Platform/Thread.cpp
|
SapphireEngine/Engine
|
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
|
[
"MIT"
] | null | null | null |
src/Engine/Platform/Thread.cpp
|
SapphireEngine/Engine
|
bf5a621ac45d76a2635b804c0d8b023f1114d8f5
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Thread.h"
//=============================================================================
SE_NAMESPACE_BEGIN
#if SE_PLATFORM_WINDOWS
//-----------------------------------------------------------------------------
bool Mutex::Init(uint32_t spinCount, const char *name)
{
return InitializeCriticalSectionAndSpinCount((CRITICAL_SECTION*)&handle, (DWORD)spinCount);
}
//-----------------------------------------------------------------------------
void Mutex::Destroy()
{
CRITICAL_SECTION* cs = (CRITICAL_SECTION*)&handle;
DeleteCriticalSection(cs);
handle = {};
}
//-----------------------------------------------------------------------------
void Mutex::Acquire()
{
EnterCriticalSection((CRITICAL_SECTION*)&handle);
}
//-----------------------------------------------------------------------------
bool Mutex::TryAcquire()
{
return TryEnterCriticalSection((CRITICAL_SECTION*)&handle);
}
//-----------------------------------------------------------------------------
void Mutex::Release()
{
LeaveCriticalSection((CRITICAL_SECTION*)&handle);
}
//-----------------------------------------------------------------------------
bool ConditionVariable::Init(const char *name)
{
handle = (CONDITION_VARIABLE*)conf_calloc(1, sizeof(CONDITION_VARIABLE));
InitializeConditionVariable((PCONDITION_VARIABLE)handle);
return true;
}
//-----------------------------------------------------------------------------
void ConditionVariable::Destroy()
{
conf_free(handle);
}
//-----------------------------------------------------------------------------
void ConditionVariable::Wait(const Mutex &mutex, uint32_t ms)
{
SleepConditionVariableCS((PCONDITION_VARIABLE)handle, (PCRITICAL_SECTION)&mutex.handle, ms);
}
//-----------------------------------------------------------------------------
void ConditionVariable::WakeOne()
{
WakeConditionVariable((PCONDITION_VARIABLE)handle);
}
//-----------------------------------------------------------------------------
void ConditionVariable::WakeAll()
{
WakeAllConditionVariable((PCONDITION_VARIABLE)handle);
}
//-----------------------------------------------------------------------------
ThreadID Thread::mainThreadID;
//-----------------------------------------------------------------------------
void Thread::SetMainThread()
{
mainThreadID = GetCurrentThreadID();
}
//-----------------------------------------------------------------------------
ThreadID Thread::GetCurrentThreadID()
{
return GetCurrentThreadId();
}
//-----------------------------------------------------------------------------
char* thread_name()
{
__declspec(thread) static char name[MAX_THREAD_NAME_LENGTH + 1];
return name;
}
//-----------------------------------------------------------------------------
void Thread::GetCurrentThreadName(char *buffer, int size)
{
if ( const char* name = thread_name() )
snprintf(buffer, (size_t)size, "%s", name);
else
buffer[0] = 0;
}
//-----------------------------------------------------------------------------
void Thread::SetCurrentThreadName(const char *name)
{
strcpy_s(thread_name(), MAX_THREAD_NAME_LENGTH + 1, name);
}
//-----------------------------------------------------------------------------
bool Thread::IsMainThread()
{
return GetCurrentThreadID() == mainThreadID;
}
//-----------------------------------------------------------------------------
DWORD WINAPI ThreadFunctionStatic(void *data)
{
ThreadDesc* pDesc = (ThreadDesc*)data;
pDesc->func(pDesc->data);
return 0;
}
//-----------------------------------------------------------------------------
void Thread::Sleep(unsigned mSec)
{
::Sleep(mSec);
}
//-----------------------------------------------------------------------------
// threading class (Static functions)
unsigned int Thread::GetNumCPUCores()
{
_SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
return systemInfo.dwNumberOfProcessors;
}
//-----------------------------------------------------------------------------
ThreadHandle CreateThread(ThreadDesc *desc)
{
ThreadHandle handle = ::CreateThread(0, 0, ThreadFunctionStatic, desc, 0, 0);
__assume(handle != NULL);
return handle;
}
//-----------------------------------------------------------------------------
void DestroyThread(ThreadHandle handle)
{
__assume(handle != NULL);
WaitForSingleObject((HANDLE)handle, INFINITE);
CloseHandle((HANDLE)handle);
handle = 0;
}
//-----------------------------------------------------------------------------
void JoinThread(ThreadHandle handle)
{
WaitForSingleObject((HANDLE)handle, INFINITE);
}
//-----------------------------------------------------------------------------
void Sleep(uint32_t mSec)
{
::Sleep((DWORD)mSec);
}
//-----------------------------------------------------------------------------
#endif
SE_NAMESPACE_END
//=============================================================================
| 33.524138
| 93
| 0.424193
|
SapphireEngine
|
6ef59d31bba551d565b1b536bdda1656c7381f6b
| 1,871
|
cpp
|
C++
|
snippets/0x03/d_copyctor.cpp
|
pblan/fha-cpp
|
5008f54133cf4913f0ca558a3817b01b10d04494
|
[
"CECILL-B"
] | null | null | null |
snippets/0x03/d_copyctor.cpp
|
pblan/fha-cpp
|
5008f54133cf4913f0ca558a3817b01b10d04494
|
[
"CECILL-B"
] | null | null | null |
snippets/0x03/d_copyctor.cpp
|
pblan/fha-cpp
|
5008f54133cf4913f0ca558a3817b01b10d04494
|
[
"CECILL-B"
] | null | null | null |
// author: a.voss@fh-aachen.de
#include <iostream>
using std::cout;
using std::endl;
class address {
int id;
public:
address() : id{0} { // (A)
cout << "-a| ctor(), id=" << id << endl;
}
address(int id) : id{id} { // (B)
cout << "-b| ctor(int), id=" << id << endl;
}
address(const address& a) : id{a.id+1} { // (C)
cout << "-c| ctor(address&), id=" << id << endl;
}
~address() {
cout << "-d| dtor(), id=" << id << endl;
}
};
address a(-1); // (D)
int main()
{
cout << endl << "--- " << __FILE__ << " ---" << endl << endl;
cout << "01| start" << endl;
address a0;
address a1(1);
address a2(a1);
address a3=a2; // (E)
address a4{a3}; // (F)
cout << "02| ende" << endl;
cout << endl << "--- " << __FILE__ << " ---" << endl << endl;
return 0;
} // (G)
/* Kommentierung
*
* (A) Standard-ctor, Verwendung ohne Argumente (auch ohne Klammern),
* siehe 'a0' in 'main'.
*
* (B) ctor mit 'int'-Argument, siehe 'a1' in 'main'.
*
* (C) ctor mit 'address'-Argument, siehe 'a2' in 'main'. Dies ist der
* sogenannte Kopierkonstruktor (copy-ctor), er initialisiert die
* Instant anhand des Arguments, d.h. häufig kopiert er den Inhalt.
*
* (D) Eine globale Variable, man beachte den Zeitpunkt der Aufrufe
* ctor und dtor.
*
* (E) Das sieht aus wie eine Zuweisung, tatsächlich ist es aber der
* copy-ctor.
*
* (F) In diesem Fall wie (E), der copy-ctor.
*
* (G) dtor der globalen Variablen.
*
*/
| 26.352113
| 72
| 0.435061
|
pblan
|
6efc04af7e71c2c6aef92cce088b860c1b483427
| 17,430
|
cpp
|
C++
|
tests/cuda2.2/tests/SobelFilter/SobelFilter.cpp
|
florianjacob/gpuocelot
|
fa63920ee7c5f9a86e264cd8acd4264657cbd190
|
[
"BSD-3-Clause"
] | 221
|
2015-03-29T02:05:49.000Z
|
2022-03-25T01:45:36.000Z
|
tests/cuda2.2/tests/SobelFilter/SobelFilter.cpp
|
mprevot/gpuocelot
|
d9277ef05a110e941aef77031382d0260ff115ef
|
[
"BSD-3-Clause"
] | 106
|
2015-03-29T01:28:42.000Z
|
2022-02-15T19:38:23.000Z
|
tests/cuda2.2/tests/SobelFilter/SobelFilter.cpp
|
mprevot/gpuocelot
|
d9277ef05a110e941aef77031382d0260ff115ef
|
[
"BSD-3-Clause"
] | 83
|
2015-07-10T23:09:57.000Z
|
2022-03-25T03:01:00.000Z
|
/*
* Copyright 1993-2009 NVIDIA Corporation. All rights reserved.
*
* NOTICE TO USER:
*
* This source code is subject to NVIDIA ownership rights under U.S. and
* international Copyright laws. Users and possessors of this source code
* are hereby granted a nonexclusive, royalty-free license to use this code
* in individual and commercial software.
*
* NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE
* CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR
* IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH
* REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
* IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL,
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
* OR PERFORMANCE OF THIS SOURCE CODE.
*
* U.S. Government End Users. This source code is a "commercial item" as
* that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of
* "commercial computer software" and "commercial computer software
* documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995)
* and is provided to the U.S. Government only as a commercial end item.
* Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through
* 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the
* source code with only those rights set forth herein.
*
* Any use of this source code in individual and commercial software must
* include, in the user documentation and internal comments to the code,
* the above Disclaimer and U.S. Government End Users Notice.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <GL/glew.h>
#if defined(__APPLE__) || defined(MACOSX)
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <cuda_runtime.h>
#include <cutil_inline.h>
#include <cutil_gl_inline.h>
#include <cuda_gl_interop.h>
#include <rendercheck_gl.h>
#include "SobelFilter_kernels.h"
//
// Cuda example code that implements the Sobel edge detection
// filter. This code works for 8-bit monochrome images.
//
// Use the '-' and '=' keys to change the scale factor.
//
// Other keys:
// I: display image
// T: display Sobel edge detection (computed solely with texture)
// S: display Sobel edge detection (computed with texture and shared memory)
void cleanup(void);
void initializeData(char *file) ;
#define MAX_EPSILON_ERROR 5.0f
static char *sSDKsample = "CUDA Sobel Edge-Detection";
// Define the files that are to be save and the reference images for validation
const char *sOriginal[] =
{
"lena_orig.pgm",
"lena_shared.pgm",
"lena_shared_tex.pgm",
NULL
};
const char *sOriginal_ppm[] =
{
"lena_orig.ppm",
"lena_shared.ppm",
"lena_shared_tex.ppm",
NULL
};
const char *sReference[] =
{
"ref_orig.pgm",
"ref_shared.pgm",
"ref_shared_tex.pgm",
NULL
};
const char *sReference_ppm[] =
{
"ref_orig.ppm",
"ref_shared.ppm",
"ref_shared_tex.ppm",
NULL
};
static int wWidth = 512; // Window width
static int wHeight = 512; // Window height
static int imWidth = 0; // Image width
static int imHeight = 0; // Image height
// Code to handle Auto verification
const int frameCheckNumber = 4;
int fpsCount = 0; // FPS count for averaging
int fpsLimit = 8; // FPS limit for sampling
unsigned int frameCount = 0;
unsigned int g_TotalErrors = 0;
bool g_Verify = false, g_AutoQuit = false;
unsigned int timer;
unsigned int g_Bpp;
unsigned int g_Index = 0;
bool g_bQAReadback = false;
bool g_bOpenGLQA = false;
bool g_bFBODisplay = false;
// Display Data
static GLuint pbo_buffer = 0; // Front and back CA buffers
static GLuint texid = 0; // Texture for display
unsigned char * pixels = NULL; // Image pixel data on the host
float imageScale = 1.f; // Image exposure
enum SobelDisplayMode g_SobelDisplayMode;
// CheckFBO/BackBuffer class objects
CheckRender *g_CheckRender = NULL;
bool bQuit = false;
extern "C" void runAutoTest(int argc, char **argv);
#define OFFSET(i) ((char *)NULL + (i))
#define MAX(a,b) ((a > b) ? a : b)
void AutoQATest()
{
if (g_CheckRender && g_CheckRender->IsQAReadback()) {
char temp[256];
g_SobelDisplayMode = (SobelDisplayMode)g_Index;
sprintf(temp, "%s Cuda Edge Detection (%s)", "AutoTest:", filterMode[g_SobelDisplayMode]);
glutSetWindowTitle(temp);
g_Index++;
if (g_Index > 2) {
g_Index = 0;
printf("Summary: %d errors!\n", g_TotalErrors);
printf("Test %s!\n", (g_TotalErrors==0) ? "PASSED" : "FAILED");
exit(0);
}
}
}
void computeFPS()
{
frameCount++;
fpsCount++;
if (fpsCount == fpsLimit-1) {
g_Verify = true;
}
if (fpsCount == fpsLimit) {
char fps[256];
float ifps = 1.f / (cutGetAverageTimerValue(timer) / 1000.f);
sprintf(fps, "%s Cuda Edge Detection (%s): %3.1f fps",
((g_CheckRender && g_CheckRender->IsQAReadback()) ? "AutoTest:" : ""),
filterMode[g_SobelDisplayMode], ifps);
glutSetWindowTitle(fps);
fpsCount = 0;
if (g_CheckRender && !g_CheckRender->IsQAReadback()) fpsLimit = (int)MAX(ifps, 1.f);
cutilCheckError(cutResetTimer(timer));
AutoQATest();
}
}
// This is the normal display path
void display(void)
{
cutilCheckError(cutStartTimer(timer));
// Sobel operation
Pixel *data = NULL;
cutilSafeCall(cudaGLMapBufferObject((void**)&data, pbo_buffer));
sobelFilter(data, imWidth, imHeight, g_SobelDisplayMode, imageScale );
cutilSafeCall(cudaGLUnmapBufferObject(pbo_buffer));
glClear(GL_COLOR_BUFFER_BIT);
glBindTexture(GL_TEXTURE_2D, texid);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo_buffer);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, imWidth, imHeight,
GL_LUMINANCE, GL_UNSIGNED_BYTE, OFFSET(0));
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glDisable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glBegin(GL_QUADS);
glVertex2f(0, 0); glTexCoord2f(0, 0);
glVertex2f(0, 1); glTexCoord2f(1, 0);
glVertex2f(1, 1); glTexCoord2f(1, 1);
glVertex2f(1, 0); glTexCoord2f(0, 1);
glEnd();
glBindTexture(GL_TEXTURE_2D, 0);
if (g_CheckRender && g_CheckRender->IsQAReadback() && g_Verify) {
printf("> (Frame %d) readback BackBuffer\n", frameCount);
g_CheckRender->readback( imWidth, imHeight );
g_CheckRender->savePPM ( sOriginal_ppm[g_Index], true, NULL );
if (!g_CheckRender->PPMvsPPM(sOriginal_ppm[g_Index], sReference_ppm[g_Index], MAX_EPSILON_ERROR, 0.15f)) {
g_TotalErrors++;
}
g_Verify = false;
}
glutSwapBuffers();
cutilCheckError(cutStopTimer(timer));
computeFPS();
glutPostRedisplay();
}
void idle(void) {
glutPostRedisplay();
}
void keyboard( unsigned char key, int /*x*/, int /*y*/)
{
char temp[256];
switch( key) {
case 27:
exit (0);
break;
case '-':
imageScale -= 0.1f;
printf("brightness = %4.2f\n", imageScale);
break;
case '=':
imageScale += 0.1f;
printf("brightness = %4.2f\n", imageScale);
break;
case 'i':
case 'I':
g_SobelDisplayMode = SOBELDISPLAY_IMAGE;
sprintf(temp, "Cuda Edge Detection (%s)", filterMode[g_SobelDisplayMode]);
glutSetWindowTitle(temp);
break;
case 's':
case 'S':
g_SobelDisplayMode = SOBELDISPLAY_SOBELSHARED;
sprintf(temp, "Cuda Edge Detection (%s)", filterMode[g_SobelDisplayMode]);
glutSetWindowTitle(temp);
break;
case 't':
case 'T':
g_SobelDisplayMode = SOBELDISPLAY_SOBELTEX;
sprintf(temp, "Cuda Edge Detection (%s)", filterMode[g_SobelDisplayMode]);
glutSetWindowTitle(temp);
default: break;
}
glutPostRedisplay();
}
void reshape(int x, int y) {
glViewport(0, 0, x, y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, 1, 0, 1, 0, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glutPostRedisplay();
}
void cleanup(void) {
cutilSafeCall(cudaGLUnregisterBufferObject(pbo_buffer));
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
glDeleteBuffers(1, &pbo_buffer);
glDeleteTextures(1, &texid);
deleteTexture();
if (g_CheckRender) {
delete g_CheckRender; g_CheckRender = NULL;
}
cutilCheckError(cutDeleteTimer(timer));
}
void initializeData(char *file) {
GLint bsize;
unsigned int w, h;
size_t file_length= strlen(file);
if (!strcmp(&file[file_length-3], "pgm")) {
if (cutLoadPGMub(file, &pixels, &w, &h) != CUTTrue) {
printf("Failed to load image file: %s\n", file);
exit(-1);
}
g_Bpp = 1;
} else if (!strcmp(&file[file_length-3], "ppm")) {
if (cutLoadPPM4ub(file, &pixels, &w, &h) != CUTTrue) {
printf("Failed to load image file: %s\n", file);
exit(-1);
}
g_Bpp = 4;
} else {
cudaThreadExit();
exit(-1);
}
imWidth = (int)w; imHeight = (int)h;
setupTexture(imWidth, imHeight, pixels, g_Bpp);
memset(pixels, 0x0, g_Bpp * sizeof(Pixel) * imWidth * imHeight);
if (!g_bQAReadback) {
// use OpenGL Path
glGenBuffers(1, &pbo_buffer);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo_buffer);
glBufferData(GL_PIXEL_UNPACK_BUFFER,
g_Bpp * sizeof(Pixel) * imWidth * imHeight,
pixels, GL_STREAM_DRAW);
glGetBufferParameteriv(GL_PIXEL_UNPACK_BUFFER, GL_BUFFER_SIZE, &bsize);
if ((GLuint)bsize != (g_Bpp * sizeof(Pixel) * imWidth * imHeight)) {
printf("Buffer object (%d) has incorrect size (%d).\n", (unsigned)pbo_buffer, (unsigned)bsize);
cudaThreadExit();
exit(-1);
}
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
cutilSafeCall(cudaGLRegisterBufferObject(pbo_buffer));
glGenTextures(1, &texid);
glBindTexture(GL_TEXTURE_2D, texid);
glTexImage2D(GL_TEXTURE_2D, 0, ((g_Bpp==1) ? GL_LUMINANCE : GL_BGRA),
imWidth, imHeight, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);
glBindTexture(GL_TEXTURE_2D, 0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
}
}
void loadDefaultImage( char* loc_exec) {
printf("Reading image: lena.pgm\n");
const char* image_filename = "lena.pgm";
char* image_path = cutFindFilePath(image_filename, loc_exec);
if (image_path == 0) {
printf( "Reading image failed.\n");
exit(EXIT_FAILURE);
}
initializeData( image_path );
cutFree( image_path );
}
void printHelp()
{
printf("\nUsage: SobelFilter <options>\n");
printf("\t\t-fbo (render using FBO display path)\n");
printf("\t\t-qatest (automatic validation)\n");
printf("\t\t-file = filename.pgm (image files for input)\n\n");
bQuit = true;
}
void initGL(int argc, char** argv)
{
glutInit( &argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutInitWindowSize(wWidth, wHeight);
glutCreateWindow("Cuda Edge Detection");
glewInit();
if (g_bFBODisplay) {
if (!glewIsSupported( "GL_VERSION_2_0 GL_ARB_fragment_program GL_EXT_framebuffer_object" )) {
fprintf(stderr, "Error: failed to get minimal extensions for demo\n");
fprintf(stderr, "This sample requires:\n");
fprintf(stderr, " OpenGL version 2.0\n");
fprintf(stderr, " GL_ARB_fragment_program\n");
fprintf(stderr, " GL_EXT_framebuffer_object\n");
cudaThreadExit();
exit(-1);
}
} else {
if (!glewIsSupported( "GL_VERSION_1_5 GL_ARB_vertex_buffer_object GL_ARB_pixel_buffer_object" )) {
fprintf(stderr, "Error: failed to get minimal extensions for demo\n");
fprintf(stderr, "This sample requires:\n");
fprintf(stderr, " OpenGL version 1.5\n");
fprintf(stderr, " GL_ARB_vertex_buffer_object\n");
fprintf(stderr, " GL_ARB_pixel_buffer_object\n");
cudaThreadExit();
exit(-1);
}
}
}
void runAutoTest(int argc, char **argv)
{
printf("[%s] (automated testing w/ readback)\n", sSDKsample);
if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") ) {
cutilDeviceInit(argc, argv);
} else {
cudaSetDevice( cutGetMaxGflopsDeviceId() );
}
if (argc > 1) {
char *filename;
if (cutGetCmdLineArgumentstr(argc, (const char **)argv, "file", &filename)) {
initializeData(filename);
}
} else {
loadDefaultImage( argv[0]);
}
g_CheckRender = new CheckBackBuffer(imWidth, imHeight, sizeof(Pixel), false);
g_CheckRender->setExecPath(argv[0]);
Pixel *d_result;
cutilSafeCall( cudaMalloc( (void **)&d_result, imWidth*imHeight*sizeof(Pixel)) );
while (g_SobelDisplayMode <= 2)
{
printf("AutoTest: %s <%s>\n", sSDKsample, filterMode[g_SobelDisplayMode]);
sobelFilter(d_result, imWidth, imHeight, g_SobelDisplayMode, imageScale );
cutilSafeCall( cudaThreadSynchronize() );
cudaMemcpy(g_CheckRender->imageData(), d_result, imWidth*imHeight*sizeof(Pixel), cudaMemcpyDeviceToHost);
g_CheckRender->savePGM(sOriginal[g_Index], false, NULL);
if (!g_CheckRender->PGMvsPGM(sOriginal[g_Index], sReference[g_Index], MAX_EPSILON_ERROR, 0.15f)) {
g_TotalErrors++;
}
g_Index++;
g_SobelDisplayMode = (SobelDisplayMode)g_Index;
}
cutilSafeCall( cudaFree( d_result ) );
delete g_CheckRender;
if (!g_TotalErrors)
printf("TEST PASSED!\n");
else
printf("TEST FAILED!\n");
}
int main(int argc, char** argv)
{
if (!cutCheckCmdLineFlag(argc, (const char **)argv, "noqatest") ||
cutCheckCmdLineFlag(argc, (const char **)argv, "noprompt"))
{
g_bQAReadback = true;
fpsLimit = frameCheckNumber;
}
if (argc > 1) {
if (cutCheckCmdLineFlag(argc, (const char **)argv, "help")) {
printHelp();
}
if (cutCheckCmdLineFlag(argc, (const char **)argv, "glverify"))
{
g_bOpenGLQA = true;
fpsLimit = frameCheckNumber;
}
if (cutCheckCmdLineFlag(argc, (const char **)argv, "fbo")) {
g_bFBODisplay = true;
fpsLimit = frameCheckNumber;
}
}
if (g_bQAReadback)
{
runAutoTest(argc, argv);
} else {
// First initialize OpenGL context, so we can properly set the GL for CUDA.
// This is necessary in order to achieve optimal performance with OpenGL/CUDA interop.
initGL( argc, argv );
// use command-line specified CUDA device, otherwise use device with highest Gflops/s
if( cutCheckCmdLineFlag(argc, (const char**)argv, "device") ) {
cutilGLDeviceInit(argc, argv);
} else {
cudaGLSetGLDevice (cutGetMaxGflopsDeviceId() );
}
int device;
struct cudaDeviceProp prop;
cudaGetDevice( &device );
cudaGetDeviceProperties( &prop, device );
if( !strncmp( "Tesla", prop.name, 5 ) ){
printf("This sample needs a card capable of OpenGL and display.\n");
printf("Please choose a different device with the -device=x argument.\n");
cudaThreadExit();
cutilExit(argc, argv);
}
cutilCheckError(cutCreateTimer(&timer));
cutilCheckError(cutResetTimer(timer));
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
glutReshapeFunc(reshape);
glutIdleFunc(idle);
if (g_bOpenGLQA) {
loadDefaultImage( argv[0] );
}
if (argc > 1) {
char *filename;
if (cutGetCmdLineArgumentstr(argc, (const char **)argv, "file", &filename)) {
initializeData(filename);
}
} else {
loadDefaultImage( argv[0]);
}
// If code is not printing the USage, then we execute this path.
if (!bQuit) {
if (g_bOpenGLQA) {
g_CheckRender = new CheckBackBuffer(wWidth, wHeight, 4);
g_CheckRender->setPixelFormat(GL_BGRA);
g_CheckRender->setExecPath(argv[0]);
g_CheckRender->EnableQAReadback(true);
}
printf("I: display image\n");
printf("T: display Sobel edge detection (computed with tex)\n");
printf("S: display Sobel edge detection (computed with tex+shared memory)\n");
printf("Use the '-' and '=' keys to change the brightness.\n");
fflush(stdout);
atexit(cleanup);
glutMainLoop();
}
}
cudaThreadExit();
cutilExit(argc, argv);
}
| 31.014235
| 114
| 0.635571
|
florianjacob
|
6efc5d7fe01f241b9c0715c28e342bdbc9a6e094
| 9,872
|
hpp
|
C++
|
Source/Math/Matrix4.hpp
|
frobro98/Musa
|
6e7dcd5d828ca123ce8f43d531948a6486428a3d
|
[
"MIT"
] | null | null | null |
Source/Math/Matrix4.hpp
|
frobro98/Musa
|
6e7dcd5d828ca123ce8f43d531948a6486428a3d
|
[
"MIT"
] | null | null | null |
Source/Math/Matrix4.hpp
|
frobro98/Musa
|
6e7dcd5d828ca123ce8f43d531948a6486428a3d
|
[
"MIT"
] | null | null | null |
// Copyright 2020, Nathan Blane
#pragma once
#include "Math/Vector4.hpp"
#include "Math/MathDefinitions.hpp"
#include "Math/MathAPI.hpp"
struct Quat;
// TODO - Make the set and constructor methods be free floating methods that
// return a constructed matrix of that type
class MATH_API Matrix4
{
public:
static const Matrix4 Identity;
public:
Matrix4();
explicit Matrix4(const Vector4& row0, const Vector4& row1, const Vector4& row2, const Vector4& row3);
explicit Matrix4(MatrixSpecialType specialEnum);
explicit Matrix4(MatrixTransType transEnum, const Vector4& transVec);
explicit Matrix4(MatrixTransType transEnum, f32 x, f32 y, f32 z);
explicit Matrix4(RotType rotationEnum, f32 angle);
explicit Matrix4(Rot3AxisType multiAxisEnum, f32 xAngleRad, f32 yAngleRad, f32 zAngleRad);
explicit Matrix4(RotAxisAngleType axisEnum, const Vector4& vect, f32 angleRads);
explicit Matrix4(RotOrientType orientEnum, const Vector4& dof, const Vector4& up);
explicit Matrix4(MatrixScaleType scaleEnum, const Vector4& scaleVec);
explicit Matrix4(MatrixScaleType scaleEnum, f32 sx, f32 sy, f32 sz);
Matrix4(const Quat& q);
// Setting specific matrix types
void Set(MatrixTransType transEnum, const Vector4& transVec);
void Set(MatrixTransType transEnum, f32 x, f32 y, f32 z);
void Set(RotType rotationEnum, f32 angle);
void Set(Rot3AxisType axisEnum, f32 xRad, f32 yRad, f32 zRad);
void Set(RotAxisAngleType axisEnum, const Vector4& vect, f32 angleRads);
void Set(RotOrientType orientEnum, const Vector4& dof, const Vector4& up);
void Set(const struct Quat& q);
void Set(MatrixScaleType scaleEnum, const Vector4& scaleVec);
void Set(MatrixScaleType scaleEnum, f32 sx, f32 sy, f32 sz);
void Set(MatrixSpecialType specialEnum);
void Set(const Vector4 &axis, f32 angle);
// Setting matrix
void Set(const Vector4& row0, const Vector4& row1, const Vector4& row2, const Vector4& row3);
void Set(MatrixRowType rowEnum, const Vector4& rowVec);
// Get row of matrix
Vector4 Get(MatrixRowType rowEnum) const;
// Matrix operations
// Determinant
f32 Determinant() const;
// Inverse
void Inverse();
Matrix4 GetInverse() const;
// Transpose
void Transpose();
Matrix4 GetTranspose() const;
bool IsIdentity(f32 epsilon = Math::InternalTolerence) const;
bool IsEqual(const Matrix4& m, f32 epsilon = Math::InternalTolerence) const;
Matrix4 operator+() const;
Matrix4 operator-() const;
Matrix4 operator+(const Matrix4& m) const;
Matrix4 operator-(const Matrix4& m) const;
Matrix4 operator*(const Matrix4& m) const;
Matrix4 operator*(f32 s) const;
Matrix4& operator+=(const Matrix4& m);
Matrix4& operator-=(const Matrix4& m);
Matrix4& operator*=(const Matrix4& m);
Matrix4& operator*=(f32 s);
//friend MATH_API Vector3 operator*(const Vector3& v, const Matrix4& m);
friend MATH_API Vector4 operator*(const Vector4& v, const Matrix4& m);
friend MATH_API Matrix4 operator*(f32 s, const Matrix4& m);
friend MATH_API Vector4& operator*=(Vector4& v, const Matrix4& m);
friend MATH_API bool operator==(const Matrix4& lhs, const Matrix4& rhs)
{
return lhs.IsEqual(rhs);
}
friend MATH_API bool operator!=(const Matrix4& lhs, const Matrix4& rhs)
{
return !lhs.IsEqual(rhs);
}
forceinline f32& m0();
forceinline f32& m1();
forceinline f32& m2();
forceinline f32& m3();
forceinline f32& m4();
forceinline f32& m6();
forceinline f32& m7();
forceinline f32& m8();
forceinline f32& m9();
forceinline f32& m5();
forceinline f32& m10();
forceinline f32& m11();
forceinline f32& m12();
forceinline f32& m13();
forceinline f32& m14();
forceinline f32& m15();
forceinline const f32& m0() const;
forceinline const f32& m1() const;
forceinline const f32& m2() const;
forceinline const f32& m3() const;
forceinline const f32& m4() const;
forceinline const f32& m5() const;
forceinline const f32& m6() const;
forceinline const f32& m7() const;
forceinline const f32& m8() const;
forceinline const f32& m9() const;
forceinline const f32& m10() const;
forceinline const f32& m11() const;
forceinline const f32& m12() const;
forceinline const f32& m13() const;
forceinline const f32& m14() const;
forceinline const f32& m15() const;
forceinline f32& operator[](m0_enum);
forceinline f32& operator[](m1_enum);
forceinline f32& operator[](m2_enum);
forceinline f32& operator[](m3_enum);
forceinline f32& operator[](m4_enum);
forceinline f32& operator[](m5_enum);
forceinline f32& operator[](m6_enum);
forceinline f32& operator[](m7_enum);
forceinline f32& operator[](m8_enum);
forceinline f32& operator[](m9_enum);
forceinline f32& operator[](m10_enum);
forceinline f32& operator[](m11_enum);
forceinline f32& operator[](m12_enum);
forceinline f32& operator[](m13_enum);
forceinline f32& operator[](m14_enum);
forceinline f32& operator[](m15_enum);
forceinline const f32& operator[](m0_enum) const;
forceinline const f32& operator[](m1_enum) const;
forceinline const f32& operator[](m2_enum) const;
forceinline const f32& operator[](m3_enum) const;
forceinline const f32& operator[](m4_enum) const;
forceinline const f32& operator[](m5_enum) const;
forceinline const f32& operator[](m6_enum) const;
forceinline const f32& operator[](m7_enum) const;
forceinline const f32& operator[](m8_enum) const;
forceinline const f32& operator[](m9_enum) const;
forceinline const f32& operator[](m10_enum) const;
forceinline const f32& operator[](m11_enum) const;
forceinline const f32& operator[](m12_enum) const;
forceinline const f32& operator[](m13_enum) const;
forceinline const f32& operator[](m14_enum) const;
forceinline const f32& operator[](m15_enum) const;
private:
// 00, 01, 02, 03
Vector4 v0;
// 10, 11, 12, 13
Vector4 v1;
// 20, 21, 22, 23
Vector4 v2;
// 30, 31, 32, 33
Vector4 v3;
};
f32& Matrix4::m0()
{
return v0.x;
}
forceinline f32& Matrix4::m1()
{
return v0.y;
}
forceinline f32& Matrix4::m2()
{
return v0.z;
}
forceinline f32& Matrix4::m3()
{
return v0.w;
}
forceinline f32& Matrix4::m4()
{
return v1.x;
}
forceinline f32& Matrix4::m5()
{
return v1.y;
}
forceinline f32& Matrix4::m6()
{
return v1.z;
}
forceinline f32& Matrix4::m7()
{
return v1.w;
}
forceinline f32& Matrix4::m8()
{
return v2.x;
}
forceinline f32& Matrix4::m9()
{
return v2.y;
}
forceinline f32& Matrix4::m10()
{
return v2.z;
}
forceinline f32& Matrix4::m11()
{
return v2.w;
}
forceinline f32& Matrix4::m12()
{
return v3.x;
}
forceinline f32& Matrix4::m13()
{
return v3.y;
}
forceinline f32& Matrix4::m14()
{
return v3.z;
}
forceinline f32& Matrix4::m15()
{
return v3.w;
}
forceinline const f32& Matrix4::m0() const
{
return v0.x;
}
forceinline const f32& Matrix4::m1() const
{
return v0.y;
}
forceinline const f32& Matrix4::m2() const
{
return v0.z;
}
forceinline const f32& Matrix4::m3() const
{
return v0.w;
}
forceinline const f32& Matrix4::m4() const
{
return v1.x;
}
forceinline const f32& Matrix4::m5() const
{
return v1.y;
}
forceinline const f32& Matrix4::m6() const
{
return v1.z;
}
forceinline const f32& Matrix4::m7() const
{
return v1.w;
}
forceinline const f32& Matrix4::m8() const
{
return v2.x;
}
forceinline const f32& Matrix4::m9() const
{
return v2.y;
}
forceinline const f32& Matrix4::m10() const
{
return v2.z;
}
forceinline const f32& Matrix4::m11() const
{
return v2.w;
}
forceinline const f32& Matrix4::m12() const
{
return v3.x;
}
forceinline const f32& Matrix4::m13() const
{
return v3.y;
}
forceinline const f32& Matrix4::m14() const
{
return v3.z;
}
forceinline const f32& Matrix4::m15() const
{
return v3.w;
}
forceinline f32& Matrix4::operator[](m0_enum)
{
return v0.x;
}
forceinline f32& Matrix4::operator[](m1_enum)
{
return v0.y;
}
forceinline f32& Matrix4::operator[](m2_enum)
{
return v0.z;
}
forceinline f32& Matrix4::operator[](m3_enum)
{
return v0.w;
}
forceinline f32& Matrix4::operator[](m4_enum)
{
return v1.x;
}
forceinline f32& Matrix4::operator[](m5_enum)
{
return v1.y;
}
forceinline f32& Matrix4::operator[](m6_enum)
{
return v1.z;
}
forceinline f32& Matrix4::operator[](m7_enum)
{
return v1.w;
}
forceinline f32& Matrix4::operator[](m8_enum)
{
return v2.x;
}
forceinline f32& Matrix4::operator[](m9_enum)
{
return v2.y;
}
forceinline f32& Matrix4::operator[](m10_enum)
{
return v2.z;
}
forceinline f32& Matrix4::operator[](m11_enum)
{
return v2.w;
}
forceinline f32& Matrix4::operator[](m12_enum)
{
return v3.x;
}
forceinline f32& Matrix4::operator[](m13_enum)
{
return v3.y;
}
forceinline f32& Matrix4::operator[](m14_enum)
{
return v3.z;
}
forceinline f32& Matrix4::operator[](m15_enum)
{
return v3.w;
}
forceinline const f32& Matrix4::operator[](m0_enum) const
{
return v0.x;
}
forceinline const f32& Matrix4::operator[](m1_enum) const
{
return v0.y;
}
forceinline const f32& Matrix4::operator[](m2_enum) const
{
return v0.z;
}
forceinline const f32& Matrix4::operator[](m3_enum) const
{
return v0.w;
}
forceinline const f32& Matrix4::operator[](m4_enum) const
{
return v1.x;
}
forceinline const f32& Matrix4::operator[](m5_enum) const
{
return v1.y;
}
forceinline const f32& Matrix4::operator[](m6_enum) const
{
return v1.z;
}
forceinline const f32& Matrix4::operator[](m7_enum) const
{
return v1.w;
}
forceinline const f32& Matrix4::operator[](m8_enum) const
{
return v2.x;
}
forceinline const f32& Matrix4::operator[](m9_enum) const
{
return v2.y;
}
forceinline const f32& Matrix4::operator[](m10_enum) const
{
return v2.z;
}
forceinline const f32& Matrix4::operator[](m11_enum) const
{
return v2.w;
}
forceinline const f32& Matrix4::operator[](m12_enum) const
{
return v3.x;
}
forceinline const f32& Matrix4::operator[](m13_enum) const
{
return v3.y;
}
forceinline const f32& Matrix4::operator[](m14_enum) const
{
return v3.z;
}
forceinline const f32& Matrix4::operator[](m15_enum) const
{
return v3.w;
}
| 19.863179
| 102
| 0.718395
|
frobro98
|
6efe513761ea1954ddbf39cedcbdab45bba6b1bb
| 63
|
hpp
|
C++
|
making coffee/coffee.hpp
|
mattersievers/cpp_basics
|
53ca6528ef65af55e4dc2c93f7d2f12ccd6747bc
|
[
"Apache-2.0"
] | null | null | null |
making coffee/coffee.hpp
|
mattersievers/cpp_basics
|
53ca6528ef65af55e4dc2c93f7d2f12ccd6747bc
|
[
"Apache-2.0"
] | null | null | null |
making coffee/coffee.hpp
|
mattersievers/cpp_basics
|
53ca6528ef65af55e4dc2c93f7d2f12ccd6747bc
|
[
"Apache-2.0"
] | null | null | null |
std::string make_coffee(bool milk = false, bool sugar = false);
| 63
| 63
| 0.746032
|
mattersievers
|
6efe6a2198b44083901f948149b2f993ef00259b
| 5,537
|
cc
|
C++
|
mesh_estimate/src/stereo/inverse_depth_meas_model.cc
|
pangfumin/okvis_depth_mesh
|
a6c95a723796b3d9f14db7ec925bb7c046c81039
|
[
"BSD-3-Clause"
] | 3
|
2018-09-20T01:41:27.000Z
|
2020-06-03T15:13:20.000Z
|
mesh_estimate/src/stereo/inverse_depth_meas_model.cc
|
pangfumin/okvis_depth_mesh
|
a6c95a723796b3d9f14db7ec925bb7c046c81039
|
[
"BSD-3-Clause"
] | null | null | null |
mesh_estimate/src/stereo/inverse_depth_meas_model.cc
|
pangfumin/okvis_depth_mesh
|
a6c95a723796b3d9f14db7ec925bb7c046c81039
|
[
"BSD-3-Clause"
] | null | null | null |
/**
* This file is part of FLaME.
* Copyright (C) 2017 W. Nicholas Greene (wng@csail.mit.edu)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*
* @file inverse_depth_meas_model.cc
* @author W. Nicholas Greene
* @date 2016-07-19 21:03:02 (Tue)
*/
#include "flame/stereo/inverse_depth_meas_model.h"
#include <stdio.h>
#include "flame/utils/assert.h"
#include "flame/utils/image_utils.h"
namespace flame {
namespace stereo {
InverseDepthMeasModel::InverseDepthMeasModel(const Eigen::Matrix3f& K0,
const Eigen::Matrix3f& K0inv,
const Eigen::Matrix3f& K1,
const Eigen::Matrix3f& K1inv,
const Params& params) :
inited_geo_(false),
inited_imgs_(false),
params_(params),
img_ref_(),
img_cmp_(),
gradx_ref_(),
grady_ref_(),
gradx_cmp_(),
grady_cmp_(),
T_ref_to_cmp_(),
epigeo_(K0, K0inv, K1, K1inv) {}
bool InverseDepthMeasModel::idepth(const cv::Point2f& u_ref,
const cv::Point2f& u_cmp,
float* mu, float* var) const {
FLAME_ASSERT(inited_geo_ && inited_imgs_);
// Compute the inverse depth mean.
cv::Point2f u_inf, epi;
float disp = epigeo_.disparity(u_ref, u_cmp, &u_inf, &epi);
// printf("epi = %f, %f\n", epi.x, epi.y);
// printf("disp = %f\n", disp);
if (disp < 1e-3) {
if (params_.verbose) {
fprintf(stderr, "IDepthMeasModel[ERROR]: NegativeDisparity: u_ref = (%f, %f), u_cmp = (%f, %f), u_inf = (%f, %f), disp = %f\n",
u_ref.x, u_ref.y, u_cmp.x, u_cmp.y, u_inf.x, u_inf.y, disp);
}
// No dispariy = idepth information.
*mu = 0.0f;
*var = 1e10;
return false;
}
*mu = epigeo_.disparityToInverseDepth(u_ref, u_inf, epi, disp);
if (*mu < 0.0f) {
if (params_.verbose) {
fprintf(stderr, "IDepthMeasModel[ERROR]: NegativeIDepth: u_ref = (%f, %f), u_cmp = (%f, %f), u_inf = (%f, %f), disp = %f, idepth = %f\n",
u_ref.x, u_ref.y, u_cmp.x, u_cmp.y, u_inf.x, u_inf.y, disp, *mu);
}
// No depth information.
*mu = 0.0f;
*var = 1e10;
return false;
}
// Get the image gradient.
cv::Point2f offset(params_.win_size/2+1, params_.win_size/2+1);
float gx = utils::bilinearInterp<float, float>(gradx_cmp_,
u_cmp.x + offset.x,
u_cmp.y + offset.y);
float gy = utils::bilinearInterp<float, float>(grady_cmp_,
u_cmp.x + offset.x,
u_cmp.y + offset.y);
float gnorm = sqrt(gx * gx + gy * gy);
if (gnorm < 1e-3) {
if (params_.verbose) {
fprintf(stderr, "IDepthMeasModel[ERROR]: NoGradient: u_ref = (%f, %f), u_cmp = (%f, %f), u_inf = (%f, %f), disp = %f, idepth = %f, grad = (%f, %f)\n",
u_ref.x, u_ref.y, u_cmp.x, u_cmp.y, u_inf.x, u_inf.y, disp, *mu, gx, gy);
}
// No depth information.
*mu = 0.0f;
*var = 1e10;
return false;
}
float ngx = gx / gnorm;
float ngy = gy / gnorm;
// printf("grad = %f, %f\n", gx, gy);
// Compute geometry disparity variance.
float epi_dot_ngrad = ngx * epi.x + ngy * epi.y;
float geo_var = params_.epipolar_line_var / (epi_dot_ngrad * epi_dot_ngrad);
if (utils::fast_abs(epi_dot_ngrad) < 1e-3) {
if (params_.verbose) {
fprintf(stderr, "IDepthMeasModel[ERROR]: NoEpiDotGradient: u_ref = (%f, %f), u_cmp = (%f, %f), u_inf = (%f, %f), disp = %f, idepth = %f, grad = (%f, %f), epi = (%f, %f)\n",
u_ref.x, u_ref.y, u_cmp.x, u_cmp.y, u_inf.x, u_inf.y, disp, *mu, gx, gy, epi.x, epi.y);
}
// No depth information.
*mu = 0.0f;
*var = 1e10;
return false;
}
// Compute photometric disparity variance.
float epi_dot_grad = gx * epi.x + gy * epi.y;
float photo_var = 2 * params_.pixel_var / (epi_dot_grad * epi_dot_grad);
// Compute disparity to inverse depth scaling factor.
float disp_min = disp - disp / 10;
float disp_max = disp + disp / 10;
float idepth_min = epigeo_.disparityToInverseDepth(u_ref, u_inf, epi, disp_min);
float idepth_max = epigeo_.disparityToInverseDepth(u_ref, u_inf, epi, disp_max);
float alpha = (idepth_max - idepth_min) / (disp_max - disp_min);
float meas_var = alpha * alpha * (geo_var + photo_var);
FLAME_ASSERT(!std::isnan(meas_var));
FLAME_ASSERT(!std::isinf(meas_var));
// printf("var1 = %f\n", meas_var);
// float angle = Eigen::AngleAxisf(T_ref_to_cmp_.unit_quaternion()).angle();
// float baseline = T_ref_to_cmp_.translation().squaredNorm();
// meas_var = 0.000001f / baseline + 0.0001f / cos(angle);
*var = meas_var;
// printf("var2 = %f\n", meas_var);
return true;
}
} // namespace stereo
} // namespace flame
| 33.969325
| 178
| 0.590392
|
pangfumin
|
3e01ac8d1067bf9c01e97f36acbc934061ca3af3
| 160
|
hxx
|
C++
|
src/Providers/UNIXProviders/SoftwareFeatureSAPImplementation/UNIX_SoftwareFeatureSAPImplementation_TRU64.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | 1
|
2020-10-12T09:00:09.000Z
|
2020-10-12T09:00:09.000Z
|
src/Providers/UNIXProviders/SoftwareFeatureSAPImplementation/UNIX_SoftwareFeatureSAPImplementation_TRU64.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
src/Providers/UNIXProviders/SoftwareFeatureSAPImplementation/UNIX_SoftwareFeatureSAPImplementation_TRU64.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
#ifdef PEGASUS_OS_TRU64
#ifndef __UNIX_SOFTWAREFEATURESAPIMPLEMENTATION_PRIVATE_H
#define __UNIX_SOFTWAREFEATURESAPIMPLEMENTATION_PRIVATE_H
#endif
#endif
| 13.333333
| 57
| 0.88125
|
brunolauze
|
3e026e598383d4eb052638fb6a25a51b3efd37d1
| 787
|
hpp
|
C++
|
includes/Graphics/DebugInfoManager.hpp
|
razerx100/Gaia
|
4e58cbb00d5f8b5d1c27fae461c6136ff54bee9b
|
[
"MIT"
] | null | null | null |
includes/Graphics/DebugInfoManager.hpp
|
razerx100/Gaia
|
4e58cbb00d5f8b5d1c27fae461c6136ff54bee9b
|
[
"MIT"
] | null | null | null |
includes/Graphics/DebugInfoManager.hpp
|
razerx100/Gaia
|
4e58cbb00d5f8b5d1c27fae461c6136ff54bee9b
|
[
"MIT"
] | null | null | null |
#ifndef __DXGI_INFO_MANAGER_HPP__
#define __DXGI_INFO_MANAGER_HPP__
#include <CleanWin.hpp>
#include <wrl.h>
#include <vector>
#include <string>
#include <d3d12.h>
using Microsoft::WRL::ComPtr;
class DebugInfoManager {
public:
DebugInfoManager();
~DebugInfoManager() = default;
DebugInfoManager(const DebugInfoManager&) = delete;
DebugInfoManager& operator=(const DebugInfoManager&) = delete;
void Set() noexcept;
std::vector<std::string> GetMessages() const;
ComPtr<ID3D12InfoQueue> m_pInfoQueue;
private:
std::uint64_t m_next;
#ifdef _DEBUG
public:
static void SetDebugInfoManager(ID3D12Device5* device) noexcept;
static DebugInfoManager& GetDebugInfoManager() noexcept;
private:
static DebugInfoManager s_InfoManager;
#endif
};
#endif
| 23.147059
| 66
| 0.753494
|
razerx100
|
3e03d0985df695dacaabfaf01baafb51955e176a
| 30,372
|
cpp
|
C++
|
SparCraft/bwapidata/include/UpgradeType.cpp
|
iali17/TheDon
|
f21cae2357835e7a21ebf351abb6bb175f67540c
|
[
"MIT"
] | null | null | null |
SparCraft/bwapidata/include/UpgradeType.cpp
|
iali17/TheDon
|
f21cae2357835e7a21ebf351abb6bb175f67540c
|
[
"MIT"
] | null | null | null |
SparCraft/bwapidata/include/UpgradeType.cpp
|
iali17/TheDon
|
f21cae2357835e7a21ebf351abb6bb175f67540c
|
[
"MIT"
] | null | null | null |
#include <string>
#include <map>
#include <set>
#include <BWAPI/UpgradeType.h>
#include <BWAPI/Race.h>
#include <BWAPI/UnitType.h>
#include <Util/Foreach.h>
#include "Common.h"
namespace BWAPI
{
bool initializingUpgradeType = true;
class UpgradeTypeInternal
{
public:
UpgradeTypeInternal() {valid = false;}
void set(const char* name, int mineralPriceBase, int mineralPriceFactor, int gasPriceBase, int gasPriceFactor, int upgradeTimeBase, int upgradeTimeFactor, BWAPI::UnitType whatUpgrades, Race race, BWAPI::UnitType whatUses, int maxRepeats)
{
if (initializingUpgradeType)
{
this->name = name;
this->mineralPriceBase = mineralPriceBase;
this->mineralPriceFactor = mineralPriceFactor;
this->gasPriceBase = gasPriceBase;
this->gasPriceFactor = gasPriceFactor;
this->upgradeTimeBase = upgradeTimeBase;
this->upgradeTimeFactor = upgradeTimeFactor;
this->whatUpgrades = whatUpgrades;
this->race = race;
if (whatUses != UnitTypes::None)
this->whatUses.insert(whatUses);
this->maxRepeats = maxRepeats;
this->valid = true;
}
}
std::string name;
int mineralPriceBase;
int mineralPriceFactor;
int gasPriceBase;
int gasPriceFactor;
int upgradeTimeBase;
int upgradeTimeFactor;
BWAPI::UnitType whatUpgrades;
Race race;
int maxRepeats;
std::set<BWAPI::UnitType> whatUses;
bool valid;
};
UpgradeTypeInternal upgradeTypeData[63];
std::map<std::string, UpgradeType> upgradeTypeMap;
std::set< UpgradeType > upgradeTypeSet;
namespace UpgradeTypes
{
const UpgradeType Terran_Infantry_Armor(0);
const UpgradeType Terran_Vehicle_Plating(1);
const UpgradeType Terran_Ship_Plating(2);
const UpgradeType Zerg_Carapace(3);
const UpgradeType Zerg_Flyer_Carapace(4);
const UpgradeType Protoss_Ground_Armor(5);
const UpgradeType Protoss_Air_Armor(6);
const UpgradeType Terran_Infantry_Weapons(7);
const UpgradeType Terran_Vehicle_Weapons(8);
const UpgradeType Terran_Ship_Weapons(9);
const UpgradeType Zerg_Melee_Attacks(10);
const UpgradeType Zerg_Missile_Attacks(11);
const UpgradeType Zerg_Flyer_Attacks(12);
const UpgradeType Protoss_Ground_Weapons(13);
const UpgradeType Protoss_Air_Weapons(14);
const UpgradeType Protoss_Plasma_Shields(15);
const UpgradeType U_238_Shells(16);
const UpgradeType Ion_Thrusters(17);
const UpgradeType Titan_Reactor(19);
const UpgradeType Ocular_Implants(20);
const UpgradeType Moebius_Reactor(21);
const UpgradeType Apollo_Reactor(22);
const UpgradeType Colossus_Reactor(23);
const UpgradeType Ventral_Sacs(24);
const UpgradeType Antennae(25);
const UpgradeType Pneumatized_Carapace(26);
const UpgradeType Metabolic_Boost(27);
const UpgradeType Adrenal_Glands(28);
const UpgradeType Muscular_Augments(29);
const UpgradeType Grooved_Spines(30);
const UpgradeType Gamete_Meiosis(31);
const UpgradeType Metasynaptic_Node(32);
const UpgradeType Singularity_Charge(33);
const UpgradeType Leg_Enhancements(34);
const UpgradeType Scarab_Damage(35);
const UpgradeType Reaver_Capacity(36);
const UpgradeType Gravitic_Drive(37);
const UpgradeType Sensor_Array(38);
const UpgradeType Gravitic_Boosters(39);
const UpgradeType Khaydarin_Amulet(40);
const UpgradeType Apial_Sensors(41);
const UpgradeType Gravitic_Thrusters(42);
const UpgradeType Carrier_Capacity(43);
const UpgradeType Khaydarin_Core(44);
const UpgradeType Argus_Jewel(47);
const UpgradeType Argus_Talisman(49);
const UpgradeType Caduceus_Reactor(51);
const UpgradeType Chitinous_Plating(52);
const UpgradeType Anabolic_Synthesis(53);
const UpgradeType Charon_Boosters(54);
const UpgradeType None(61);
const UpgradeType Unknown(62);
void init()
{
upgradeTypeData[Terran_Infantry_Armor.getID()].set("Terran Infantry Armor" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Terran_Engineering_Bay , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Terran_Vehicle_Plating.getID()].set("Terran Vehicle Plating" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Terran_Armory , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Terran_Ship_Plating.getID()].set("Terran Ship Plating" , 150, 75 , 150, 75 , 4000, 480, UnitTypes::Terran_Armory , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Zerg_Carapace.getID()].set("Zerg Carapace" , 150, 75 , 150, 75 , 4000, 480, UnitTypes::Zerg_Evolution_Chamber , Races::Zerg , UnitTypes::None , 3);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].set("Zerg Flyer Carapace" , 150, 75 , 150, 75 , 4000, 480, UnitTypes::Zerg_Spire , Races::Zerg , UnitTypes::None , 3);
upgradeTypeData[Protoss_Ground_Armor.getID()].set("Protoss Ground Armor" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Protoss_Forge , Races::Protoss, UnitTypes::None , 3);
upgradeTypeData[Protoss_Air_Armor.getID()].set("Protoss Air Armor" , 150, 75 , 150, 75 , 4000, 480, UnitTypes::Protoss_Cybernetics_Core , Races::Protoss, UnitTypes::None , 3);
upgradeTypeData[Terran_Infantry_Weapons.getID()].set("Terran Infantry Weapons", 100, 75 , 100, 75 , 4000, 480, UnitTypes::Terran_Engineering_Bay , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Terran_Vehicle_Weapons.getID()].set("Terran Vehicle Weapons" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Terran_Armory , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Terran_Ship_Weapons.getID()].set("Terran Ship Weapons" , 100, 50 , 100, 50 , 4000, 480, UnitTypes::Terran_Armory , Races::Terran , UnitTypes::None , 3);
upgradeTypeData[Zerg_Melee_Attacks.getID()].set("Zerg Melee Attacks" , 100, 50 , 100, 50 , 4000, 480, UnitTypes::Zerg_Evolution_Chamber , Races::Zerg , UnitTypes::None , 3);
upgradeTypeData[Zerg_Missile_Attacks.getID()].set("Zerg Missile Attacks" , 100, 50 , 100, 50 , 4000, 480, UnitTypes::Zerg_Evolution_Chamber , Races::Zerg , UnitTypes::None , 3);
upgradeTypeData[Zerg_Flyer_Attacks.getID()].set("Zerg Flyer Attacks" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Zerg_Spire , Races::Zerg , UnitTypes::None , 3);
upgradeTypeData[Protoss_Ground_Weapons.getID()].set("Protoss Ground Weapons" , 100, 50 , 100, 50 , 4000, 480, UnitTypes::Protoss_Forge , Races::Protoss, UnitTypes::None , 3);
upgradeTypeData[Protoss_Air_Weapons.getID()].set("Protoss Air Weapons" , 100, 75 , 100, 75 , 4000, 480, UnitTypes::Protoss_Cybernetics_Core , Races::Protoss, UnitTypes::None , 3);
upgradeTypeData[Protoss_Plasma_Shields.getID()].set("Protoss Plasma Shields" , 200, 100, 200, 100, 4000, 480, UnitTypes::Protoss_Forge , Races::Protoss, UnitTypes::None , 3);
upgradeTypeData[U_238_Shells.getID()].set("U-238 Shells" , 150, 0 , 150, 0 , 1500, 0 , UnitTypes::Terran_Academy , Races::Terran , UnitTypes::Terran_Marine , 1);
upgradeTypeData[Ion_Thrusters.getID()].set("Ion Thrusters" , 100, 0 , 100, 0 , 1500, 0 , UnitTypes::Terran_Machine_Shop , Races::Terran , UnitTypes::Terran_Vulture , 1);
upgradeTypeData[Titan_Reactor.getID()].set("Titan Reactor" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Terran_Science_Facility , Races::Terran , UnitTypes::Terran_Science_Vessel, 1);
upgradeTypeData[Ocular_Implants.getID()].set("Ocular Implants" , 100, 0 , 100, 0 , 2500, 0 , UnitTypes::Terran_Covert_Ops , Races::Terran , UnitTypes::Terran_Ghost , 1);
upgradeTypeData[Moebius_Reactor.getID()].set("Moebius Reactor" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Terran_Covert_Ops , Races::Terran , UnitTypes::Terran_Ghost , 1);
upgradeTypeData[Apollo_Reactor.getID()].set("Apollo Reactor" , 200, 0 , 200, 0 , 2500, 0 , UnitTypes::Terran_Control_Tower , Races::Terran , UnitTypes::Terran_Wraith , 1);
upgradeTypeData[Colossus_Reactor.getID()].set("Colossus Reactor" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Terran_Physics_Lab , Races::Terran , UnitTypes::Terran_Battlecruiser , 1);
upgradeTypeData[Ventral_Sacs.getID()].set("Ventral Sacs" , 200, 0 , 200, 0 , 2400, 0 , UnitTypes::Zerg_Lair , Races::Zerg , UnitTypes::Zerg_Overlord , 1);
upgradeTypeData[Antennae.getID()].set("Antennae" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Zerg_Lair , Races::Zerg , UnitTypes::Zerg_Overlord , 1);
upgradeTypeData[Pneumatized_Carapace.getID()].set("Pneumatized Carapace" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Zerg_Lair , Races::Zerg , UnitTypes::Zerg_Overlord , 1);
upgradeTypeData[Metabolic_Boost.getID()].set("Metabolic Boost" , 100, 0 , 100, 0 , 1500, 0 , UnitTypes::Zerg_Spawning_Pool , Races::Zerg , UnitTypes::Zerg_Zergling , 1);
upgradeTypeData[Adrenal_Glands.getID()].set("Adrenal Glands" , 200, 0 , 200, 0 , 1500, 0 , UnitTypes::Zerg_Spawning_Pool , Races::Zerg , UnitTypes::Zerg_Zergling , 1);
upgradeTypeData[Muscular_Augments.getID()].set("Muscular Augments" , 150, 0 , 150, 0 , 1500, 0 , UnitTypes::Zerg_Hydralisk_Den , Races::Zerg , UnitTypes::Zerg_Hydralisk , 1);
upgradeTypeData[Grooved_Spines.getID()].set("Grooved Spines" , 150, 0 , 150, 0 , 1500, 0 , UnitTypes::Zerg_Hydralisk_Den , Races::Zerg , UnitTypes::Zerg_Hydralisk , 1);
upgradeTypeData[Gamete_Meiosis.getID()].set("Gamete Meiosis" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Zerg_Queens_Nest , Races::Zerg , UnitTypes::Zerg_Queen , 1);
upgradeTypeData[Metasynaptic_Node.getID()].set("Metasynaptic Node" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Zerg_Defiler_Mound , Races::Zerg , UnitTypes::Zerg_Defiler , 1);
upgradeTypeData[Singularity_Charge.getID()].set("Singularity Charge" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Protoss_Cybernetics_Core , Races::Protoss, UnitTypes::Protoss_Dragoon , 1);
upgradeTypeData[Leg_Enhancements.getID()].set("Leg Enhancements" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Protoss_Citadel_of_Adun , Races::Protoss, UnitTypes::Protoss_Zealot , 1);
upgradeTypeData[Scarab_Damage.getID()].set("Scarab Damage" , 200, 0 , 200, 0 , 2500, 0 , UnitTypes::Protoss_Robotics_Support_Bay, Races::Protoss, UnitTypes::Protoss_Scarab , 1);
upgradeTypeData[Reaver_Capacity.getID()].set("Reaver Capacity" , 200, 0 , 200, 0 , 2500, 0 , UnitTypes::Protoss_Robotics_Support_Bay, Races::Protoss, UnitTypes::Protoss_Reaver , 1);
upgradeTypeData[Gravitic_Drive.getID()].set("Gravitic Drive" , 200, 0 , 200, 0 , 2500, 0 , UnitTypes::Protoss_Robotics_Support_Bay, Races::Protoss, UnitTypes::Protoss_Shuttle , 1);
upgradeTypeData[Sensor_Array.getID()].set("Sensor Array" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Protoss_Observatory , Races::Protoss, UnitTypes::Protoss_Observer , 1);
upgradeTypeData[Gravitic_Boosters.getID()].set("Gravitic Boosters" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Protoss_Observatory , Races::Protoss, UnitTypes::Protoss_Observer , 1);
upgradeTypeData[Khaydarin_Amulet.getID()].set("Khaydarin Amulet" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Protoss_Templar_Archives , Races::Protoss, UnitTypes::Protoss_High_Templar , 1);
upgradeTypeData[Apial_Sensors.getID()].set("Apial Sensors" , 100, 0 , 100, 0 , 2500, 0 , UnitTypes::Protoss_Fleet_Beacon , Races::Protoss, UnitTypes::Protoss_Scout , 1);
upgradeTypeData[Gravitic_Thrusters.getID()].set("Gravitic Thrusters" , 200, 0 , 200, 0 , 2500, 0 , UnitTypes::Protoss_Fleet_Beacon , Races::Protoss, UnitTypes::Protoss_Scout , 1);
upgradeTypeData[Carrier_Capacity.getID()].set("Carrier Capacity" , 100, 0 , 100, 0 , 1500, 0 , UnitTypes::Protoss_Fleet_Beacon , Races::Protoss, UnitTypes::Protoss_Carrier , 1);
upgradeTypeData[Khaydarin_Core.getID()].set("Khaydarin Core" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Protoss_Arbiter_Tribunal , Races::Protoss, UnitTypes::Protoss_Arbiter , 1);
upgradeTypeData[Argus_Jewel.getID()].set("Argus Jewel" , 100, 0 , 100, 0 , 2500, 0 , UnitTypes::Protoss_Fleet_Beacon , Races::Protoss, UnitTypes::Protoss_Corsair , 1);
upgradeTypeData[Argus_Talisman.getID()].set("Argus Talisman" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Protoss_Templar_Archives , Races::Protoss, UnitTypes::Protoss_Dark_Archon , 1);
upgradeTypeData[Caduceus_Reactor.getID()].set("Caduceus Reactor" , 150, 0 , 150, 0 , 2500, 0 , UnitTypes::Terran_Academy , Races::Terran , UnitTypes::Terran_Medic , 1);
upgradeTypeData[Chitinous_Plating.getID()].set("Chitinous Plating" , 150, 0 , 150, 0 , 2000, 0 , UnitTypes::Zerg_Ultralisk_Cavern , Races::Zerg , UnitTypes::Zerg_Ultralisk , 1);
upgradeTypeData[Anabolic_Synthesis.getID()].set("Anabolic Synthesis" , 200, 0 , 200, 0 , 2000, 0 , UnitTypes::Zerg_Ultralisk_Cavern , Races::Zerg , UnitTypes::Zerg_Ultralisk , 1);
upgradeTypeData[Charon_Boosters.getID()].set("Charon Boosters" , 100, 0 , 100, 0 , 2000, 0 , UnitTypes::Terran_Machine_Shop , Races::Terran , UnitTypes::Terran_Goliath , 1);
upgradeTypeData[None.getID()].set("None" , 0 , 0 , 0 , 0 , 0 , 0 , UnitTypes::None , Races::None , UnitTypes::None , 0);
upgradeTypeData[Unknown.getID()].set("Unknown" , 0 , 0 , 0 , 0 , 0 , 0 , UnitTypes::None , Races::Unknown, UnitTypes::None , 0);
upgradeTypeData[Terran_Infantry_Armor.getID()].whatUses.insert(UnitTypes::Terran_Firebat);
upgradeTypeData[Terran_Infantry_Armor.getID()].whatUses.insert(UnitTypes::Terran_Ghost);
upgradeTypeData[Terran_Infantry_Armor.getID()].whatUses.insert(UnitTypes::Terran_Marine);
upgradeTypeData[Terran_Infantry_Armor.getID()].whatUses.insert(UnitTypes::Terran_Medic);
upgradeTypeData[Terran_Infantry_Armor.getID()].whatUses.insert(UnitTypes::Terran_SCV);
upgradeTypeData[Terran_Vehicle_Plating.getID()].whatUses.insert(UnitTypes::Terran_Goliath);
upgradeTypeData[Terran_Vehicle_Plating.getID()].whatUses.insert(UnitTypes::Terran_Siege_Tank_Siege_Mode);
upgradeTypeData[Terran_Vehicle_Plating.getID()].whatUses.insert(UnitTypes::Terran_Siege_Tank_Tank_Mode);
upgradeTypeData[Terran_Vehicle_Plating.getID()].whatUses.insert(UnitTypes::Terran_Vulture);
upgradeTypeData[Terran_Ship_Plating.getID()].whatUses.insert(UnitTypes::Terran_Battlecruiser);
upgradeTypeData[Terran_Ship_Plating.getID()].whatUses.insert(UnitTypes::Terran_Dropship);
upgradeTypeData[Terran_Ship_Plating.getID()].whatUses.insert(UnitTypes::Terran_Science_Vessel);
upgradeTypeData[Terran_Ship_Plating.getID()].whatUses.insert(UnitTypes::Terran_Valkyrie);
upgradeTypeData[Terran_Ship_Plating.getID()].whatUses.insert(UnitTypes::Terran_Wraith);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Broodling);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Defiler);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Drone);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Hydralisk);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Infested_Terran);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Larva);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Lurker);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Ultralisk);
upgradeTypeData[Zerg_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Zergling);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Devourer);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Guardian);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Mutalisk);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Overlord);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Queen);
upgradeTypeData[Zerg_Flyer_Carapace.getID()].whatUses.insert(UnitTypes::Zerg_Scourge);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Archon);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Dark_Archon);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Dark_Templar);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Dragoon);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_High_Templar);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Probe);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Reaver);
upgradeTypeData[Protoss_Ground_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Zealot);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Arbiter);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Carrier);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Corsair);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Interceptor);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Observer);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Scout);
upgradeTypeData[Protoss_Air_Armor.getID()].whatUses.insert(UnitTypes::Protoss_Shuttle);
upgradeTypeData[Terran_Infantry_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Firebat);
upgradeTypeData[Terran_Infantry_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Ghost);
upgradeTypeData[Terran_Infantry_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Marine);
upgradeTypeData[Terran_Vehicle_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Goliath);
upgradeTypeData[Terran_Vehicle_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Siege_Tank_Siege_Mode);
upgradeTypeData[Terran_Vehicle_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Siege_Tank_Tank_Mode);
upgradeTypeData[Terran_Vehicle_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Vulture);
upgradeTypeData[Terran_Ship_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Battlecruiser);
upgradeTypeData[Terran_Ship_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Valkyrie);
upgradeTypeData[Terran_Ship_Weapons.getID()].whatUses.insert(UnitTypes::Terran_Wraith);
upgradeTypeData[Zerg_Melee_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Broodling);
upgradeTypeData[Zerg_Melee_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Ultralisk);
upgradeTypeData[Zerg_Melee_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Zergling);
upgradeTypeData[Zerg_Missile_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Hydralisk);
upgradeTypeData[Zerg_Missile_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Lurker);
upgradeTypeData[Zerg_Flyer_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Devourer);
upgradeTypeData[Zerg_Flyer_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Guardian);
upgradeTypeData[Zerg_Flyer_Attacks.getID()].whatUses.insert(UnitTypes::Zerg_Mutalisk);
upgradeTypeData[Protoss_Ground_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Dark_Templar);
upgradeTypeData[Protoss_Ground_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Dragoon);
upgradeTypeData[Protoss_Ground_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Zealot);
upgradeTypeData[Protoss_Air_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Arbiter);
upgradeTypeData[Protoss_Air_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Corsair);
upgradeTypeData[Protoss_Air_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Interceptor);
upgradeTypeData[Protoss_Air_Weapons.getID()].whatUses.insert(UnitTypes::Protoss_Scout);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Arbiter);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Arbiter_Tribunal);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Archon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Assimilator);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Carrier);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Citadel_of_Adun);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Corsair);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Cybernetics_Core);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Dark_Archon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Dark_Templar);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Dragoon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Fleet_Beacon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Forge);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Gateway);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_High_Templar);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Interceptor);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Nexus);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Observatory);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Observer);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Photon_Cannon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Probe);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Pylon);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Reaver);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Robotics_Facility);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Robotics_Support_Bay);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Scarab);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Scout);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Shield_Battery);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Shuttle);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Stargate);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Templar_Archives);
upgradeTypeData[Protoss_Plasma_Shields.getID()].whatUses.insert(UnitTypes::Protoss_Zealot);
upgradeTypeSet.insert(Terran_Infantry_Armor);
upgradeTypeSet.insert(Terran_Vehicle_Plating);
upgradeTypeSet.insert(Terran_Ship_Plating);
upgradeTypeSet.insert(Zerg_Carapace);
upgradeTypeSet.insert(Zerg_Flyer_Carapace);
upgradeTypeSet.insert(Protoss_Ground_Armor);
upgradeTypeSet.insert(Protoss_Air_Armor);
upgradeTypeSet.insert(Terran_Infantry_Weapons);
upgradeTypeSet.insert(Terran_Vehicle_Weapons);
upgradeTypeSet.insert(Terran_Ship_Weapons);
upgradeTypeSet.insert(Zerg_Melee_Attacks);
upgradeTypeSet.insert(Zerg_Missile_Attacks);
upgradeTypeSet.insert(Zerg_Flyer_Attacks);
upgradeTypeSet.insert(Protoss_Ground_Weapons);
upgradeTypeSet.insert(Protoss_Air_Weapons);
upgradeTypeSet.insert(Protoss_Plasma_Shields);
upgradeTypeSet.insert(U_238_Shells);
upgradeTypeSet.insert(Ion_Thrusters);
upgradeTypeSet.insert(Titan_Reactor);
upgradeTypeSet.insert(Ocular_Implants);
upgradeTypeSet.insert(Moebius_Reactor);
upgradeTypeSet.insert(Apollo_Reactor);
upgradeTypeSet.insert(Colossus_Reactor);
upgradeTypeSet.insert(Ventral_Sacs);
upgradeTypeSet.insert(Antennae);
upgradeTypeSet.insert(Pneumatized_Carapace);
upgradeTypeSet.insert(Metabolic_Boost);
upgradeTypeSet.insert(Adrenal_Glands);
upgradeTypeSet.insert(Muscular_Augments);
upgradeTypeSet.insert(Grooved_Spines);
upgradeTypeSet.insert(Gamete_Meiosis);
upgradeTypeSet.insert(Metasynaptic_Node);
upgradeTypeSet.insert(Singularity_Charge);
upgradeTypeSet.insert(Leg_Enhancements);
upgradeTypeSet.insert(Scarab_Damage);
upgradeTypeSet.insert(Reaver_Capacity);
upgradeTypeSet.insert(Gravitic_Drive);
upgradeTypeSet.insert(Sensor_Array);
upgradeTypeSet.insert(Gravitic_Boosters);
upgradeTypeSet.insert(Khaydarin_Amulet);
upgradeTypeSet.insert(Apial_Sensors);
upgradeTypeSet.insert(Gravitic_Thrusters);
upgradeTypeSet.insert(Carrier_Capacity);
upgradeTypeSet.insert(Khaydarin_Core);
upgradeTypeSet.insert(Argus_Jewel);
upgradeTypeSet.insert(Argus_Talisman);
upgradeTypeSet.insert(Caduceus_Reactor);
upgradeTypeSet.insert(Chitinous_Plating);
upgradeTypeSet.insert(Anabolic_Synthesis);
upgradeTypeSet.insert(Charon_Boosters);
upgradeTypeSet.insert(None);
upgradeTypeSet.insert(Unknown);
foreach(UpgradeType i, upgradeTypeSet)
{
std::string name = i.getName();
fixName(&name);
upgradeTypeMap.insert(std::make_pair(name, i));
}
initializingUpgradeType = false;
}
}
UpgradeType::UpgradeType()
{
this->id = UpgradeTypes::None.id;
}
UpgradeType::UpgradeType(int id)
{
this->id = id;
if (!initializingUpgradeType && (id < 0 || id >= 63 || !upgradeTypeData[id].valid) )
this->id = UpgradeTypes::Unknown.id;
}
UpgradeType::UpgradeType(const UpgradeType& other)
{
this->id = other.id;
}
UpgradeType& UpgradeType::operator=(const UpgradeType& other)
{
this->id = other.id;
return *this;
}
bool UpgradeType::operator==(const UpgradeType& other) const
{
return this->id == other.id;
}
bool UpgradeType::operator!=(const UpgradeType& other) const
{
return this->id != other.id;
}
bool UpgradeType::operator<(const UpgradeType& other) const
{
return this->id < other.id;
}
int UpgradeType::getID() const
{
return this->id;
}
std::string UpgradeType::getName() const
{
return upgradeTypeData[this->id].name;
}
Race UpgradeType::getRace() const
{
return upgradeTypeData[this->id].race;
}
int UpgradeType::mineralPrice() const
{
return upgradeTypeData[this->id].mineralPriceBase;
}
int UpgradeType::mineralPriceFactor() const
{
return upgradeTypeData[this->id].mineralPriceFactor;
}
int UpgradeType::gasPrice() const
{
return upgradeTypeData[this->id].gasPriceBase;
}
int UpgradeType::gasPriceFactor() const
{
return upgradeTypeData[this->id].gasPriceFactor;
}
int UpgradeType::upgradeTime() const
{
return upgradeTypeData[this->id].upgradeTimeBase;
}
int UpgradeType::upgradeTimeFactor() const
{
return upgradeTypeData[this->id].upgradeTimeFactor;
}
UnitType UpgradeType::whatUpgrades() const
{
return upgradeTypeData[this->id].whatUpgrades;
}
const std::set<UnitType>& UpgradeType::whatUses() const
{
return upgradeTypeData[this->id].whatUses;
}
int UpgradeType::maxRepeats() const
{
return upgradeTypeData[this->id].maxRepeats;
}
UpgradeType UpgradeTypes::getUpgradeType(std::string name)
{
fixName(&name);
std::map<std::string, UpgradeType>::iterator i = upgradeTypeMap.find(name);
if (i == upgradeTypeMap.end())
return UpgradeTypes::Unknown;
return (*i).second;
}
std::set<UpgradeType>& UpgradeTypes::allUpgradeTypes()
{
return upgradeTypeSet;
}
}
| 72.314286
| 244
| 0.690307
|
iali17
|
3e086ad85c6c673c77ac740a029a3b6fabc19c7c
| 3,327
|
cpp
|
C++
|
ImageVis3D/UI/BrowseData.cpp
|
JensDerKrueger/ImageVis3D
|
699ab32132c899b7ea227bc87a9de80768ab879f
|
[
"MIT"
] | null | null | null |
ImageVis3D/UI/BrowseData.cpp
|
JensDerKrueger/ImageVis3D
|
699ab32132c899b7ea227bc87a9de80768ab879f
|
[
"MIT"
] | null | null | null |
ImageVis3D/UI/BrowseData.cpp
|
JensDerKrueger/ImageVis3D
|
699ab32132c899b7ea227bc87a9de80768ab879f
|
[
"MIT"
] | null | null | null |
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2008 Scientific Computing and Imaging Institute,
University of Utah.
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.
*/
//! File : BrowseData.cpp
//! Author : Jens Krueger
//! SCI Institute
//! University of Utah
//! Date : September 2008
//
//! Copyright (C) 2008 SCI Institute
#include "BrowseData.h"
#include <QtCore/QFileInfo>
#include <ui_SettingsDlg.h>
#include "../Tuvok/LuaScripting/LuaScripting.h"
using namespace std;
BrowseData::BrowseData(MasterController& masterController, QDialog* pleaseWaitDialog, QString strDir, QWidget* parent, Qt::WindowFlags flags) :
QDialog(parent, flags),
m_MasterController(masterController),
m_bDataFound(false),
m_strDir(strDir),
m_iSelected(0)
{
setupUi(this);
m_bDataFound = FillTable(pleaseWaitDialog);
}
BrowseData::~BrowseData() {
this->m_dirInfo.clear();
}
void BrowseData::showEvent ( QShowEvent * ) {
}
void BrowseData::accept() {
// find out which dataset is selected
for (size_t i = 0;i < m_vRadioButtons.size();i++) {
if (m_vRadioButtons[i]->isChecked()) {
m_iSelected = i;
break;
}
}
QDialog::accept();
}
void BrowseData::SetBrightness(int iScale) {
for (size_t i = 0;i < m_vRadioButtons.size();i++)
m_vRadioButtons[i]->SetBrightness(float(iScale));
}
bool BrowseData::FillTable(QDialog* pleaseWaitDialog)
{
shared_ptr<LuaScripting> ss(m_MasterController.LuaScript());
m_dirInfo = ss->cexecRet<vector<shared_ptr<FileStackInfo>>>(
"tuvok.io.scanDirectory", m_strDir.toStdWString());
m_vRadioButtons.clear();
for (size_t iStackID = 0;iStackID < m_dirInfo.size();iStackID++) {
QDataRadioButton *pStackElement;
pStackElement = new QDataRadioButton(m_dirInfo[iStackID],frame);
pStackElement->setMinimumSize(QSize(0, 80));
pStackElement->setChecked(iStackID==0);
pStackElement->setIconSize(QSize(80, 80));
verticalLayout_DICOM->addWidget(pStackElement);
m_vRadioButtons.push_back(pStackElement);
}
if (pleaseWaitDialog != NULL) pleaseWaitDialog->close();
return !m_dirInfo.empty();
}
| 31.386792
| 144
| 0.701232
|
JensDerKrueger
|
3e0932793cd541b17d107d1d47c468a3170b96e2
| 1,517
|
cpp
|
C++
|
client/UDPClient.cpp
|
connest/BerkeleySockets
|
e3facc13150409483ab91ec373609715ac832602
|
[
"MIT"
] | null | null | null |
client/UDPClient.cpp
|
connest/BerkeleySockets
|
e3facc13150409483ab91ec373609715ac832602
|
[
"MIT"
] | null | null | null |
client/UDPClient.cpp
|
connest/BerkeleySockets
|
e3facc13150409483ab91ec373609715ac832602
|
[
"MIT"
] | null | null | null |
#include "UDPClient.h"
#include <iostream>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
UDPClient::UDPClient(const std::string &address, short port)
: IClient(address, port)
{
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port);
}
UDPClient::~UDPClient()
{
std::cout << "Close the UDP client..." <<std::endl;
if(sockfd > 0)
close(sockfd);
}
int UDPClient::init()
{
int res = getBindAddress();
if(res)
return -1;
res = bindSocket();
if(res)
return -2;
return 0;
}
int UDPClient::recv(char *buffer, int maxlength)
{
int length = recvfrom(sockfd, buffer, maxlength, 0, NULL, NULL);
if(length < 0) {
std::cerr<<"Read error"<<std::endl;
return -1;
}
buffer[length] = 0;
return length;
}
int UDPClient::send(const std::string &request)
{
return sendto(sockfd, request.data(), request.length(), 0,
(struct sockaddr*)&server_address, sizeof(server_address));
}
int UDPClient::getBindAddress()
{
int res = inet_pton(AF_INET, address.data(), &server_address.sin_addr);
if(res <= 0) {
std::cerr<<"inet_pton error occured" <<std::endl;
return -1;
}
return 0;
}
int UDPClient::bindSocket()
{
sockfd = socket(PF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
std::cerr<<"Error : Could not create socket" <<std::endl;
return -1;
}
return 0;
}
| 19.960526
| 77
| 0.607119
|
connest
|
3e09e4dd05661b82fafb4fc33c6a746ea5544951
| 310
|
cpp
|
C++
|
src/xray/shader_compiler/sources/shader_compiler_library_linkage.cpp
|
ixray-team/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | 3
|
2021-10-30T09:36:14.000Z
|
2022-03-26T17:00:06.000Z
|
src/xray/shader_compiler/sources/shader_compiler_library_linkage.cpp
|
acidicMercury8/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | null | null | null |
src/xray/shader_compiler/sources/shader_compiler_library_linkage.cpp
|
acidicMercury8/ixray-2.0
|
85c3a544175842323fc82f42efd96c66f0fc5abb
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:08.000Z
|
2022-03-26T17:00:08.000Z
|
////////////////////////////////////////////////////////////////////////////
// Created : 18.05.2010
// Author : Armen Abroyan
// Copyright (C) GSC Game World - 2010
////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include <xray/core/library_linkage.h>
| 34.444444
| 77
| 0.325806
|
ixray-team
|
3e0b7f9e60c94d9507bd52cf0afd05ba81479e02
| 201
|
hpp
|
C++
|
unicode_back/character_categories/punctuation_dash.hpp
|
do-m-en/random_regex_string
|
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
|
[
"BSL-1.0"
] | null | null | null |
unicode_back/character_categories/punctuation_dash.hpp
|
do-m-en/random_regex_string
|
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
|
[
"BSL-1.0"
] | null | null | null |
unicode_back/character_categories/punctuation_dash.hpp
|
do-m-en/random_regex_string
|
7ded2dcf7c03122a68e66b5db6f94403e8c9c690
|
[
"BSL-1.0"
] | null | null | null |
#ifndef UNICODE_PUNCTUATION_DASH_HPP_INCLUDED
#define UNICODE_PUNCTUATION_DASH_HPP_INCLUDED
namespace unicode {
// Pd
class punctuation_dash
{
};
}
#endif // UNICODE_PUNCTUATION_DASH_HPP_INCLUDED
| 13.4
| 47
| 0.830846
|
do-m-en
|
3e0debffd5950077536d0e6189e7c788e3474386
| 15,480
|
hpp
|
C++
|
include/hlsv/hlsv_reflect.hpp
|
mossseank/HLSV
|
5725b842ec629536a4156321ac27c926ad063590
|
[
"MIT"
] | null | null | null |
include/hlsv/hlsv_reflect.hpp
|
mossseank/HLSV
|
5725b842ec629536a4156321ac27c926ad063590
|
[
"MIT"
] | null | null | null |
include/hlsv/hlsv_reflect.hpp
|
mossseank/HLSV
|
5725b842ec629536a4156321ac27c926ad063590
|
[
"MIT"
] | null | null | null |
/*
* The HLSV project and all associated files and assets, including this file, are licensed under the MIT license, the
* text of which can be found in the LICENSE file at the root of this project, and is available online at
* (https://opensource.org/licenses/MIT). In the event of redistribution of this code, this header, or the text of
* the license itself, must not be removed from the source files or assets in which they appear.
* Copyright (c) 2019 Sean Moss [moss.seank@gmail.com]
*/
// This file declares the public reflection API functionality
#pragma once
#include "hlsv.hpp"
#include <vector>
/* Import/Export Macros */
#if !defined(HLSV_STATIC)
# if defined(HLSV_COMPILER_MSVC)
# if defined(_HLSV_BUILD)
# define _EXPORT __declspec(dllexport)
# else
# define _EXPORT __declspec(dllimport)
# endif // defined(_HLSV_BUILD)
# else
# define _EXPORT __attribute__((__visibility__("default")))
# endif // defined(HLSV_COMPILER_MSVC)
#else
# define _EXPORT
#endif // !defined(HLSV_STATIC)
namespace hlsv
{
// The types of shaders
enum class ShaderType : uint8
{
Graphics = 0 // The shader operates in the graphics pipeline
}; // enum class ShaderType
// Shader stages (as a bitset of flags), contains flags for all shader types, but the types shouldn't be mixed
enum class ShaderStages : uint8
{
None = 0x00, // Represents a bitset of no stages
/// Graphics Stages
Vertex = 0x01, // The vertex stage for graphics shaders
TessControl = 0x02, // The tessellation control stage for graphics shaders
TessEval = 0x04, // The tessellation evaluation stage for graphics shaders
Geometry = 0x08, // The geometry stage for graphics shaders
Fragment = 0x10, // The fragment stage for graphics shaders
MinGraphics = 0x11, // A bitset representing the minimal set of stages required for a "complete" graphics shader
AllGraphics = 0x1F // A bitset representing all graphics shader stages
}; // enum class ShaderStages
/* ShaderStages Operators */
inline ShaderStages operator | (ShaderStages l, ShaderStages r) { return (ShaderStages)((uint8)l | (uint8)r); }
inline ShaderStages& operator |= (ShaderStages& l, ShaderStages r) { l = l | r; return l; }
inline ShaderStages operator ^ (ShaderStages l, ShaderStages r) { return (ShaderStages)((uint8)l & ~(uint8)r); }
inline ShaderStages& operator ^= (ShaderStages& l, ShaderStages r) { l = l ^ r; return l; }
inline bool operator & (ShaderStages l, ShaderStages r) { return (ShaderStages)((uint8)l & (uint8)r) == r; }
// Represents a record about a specific primitive HLSV type
struct _EXPORT HLSVType final
{
public:
// A listing of the primitive types
enum PrimType : uint8
{
Void = 0, // The special "nothing" type, only valid as a function return type (void)
Error = 255, // A value used internally to represent a type error, this value will not appear in valid shaders
/// Scalar/Vector Value Types
Bool = 1, // A scalar boolean value (bool)
Bool2 = 2, // A 2-component boolean vector (bvec2)
Bool3 = 3, // A 3-component boolean vector (bvec3)
Bool4 = 4, // A 4-component boolean vector (bvec4)
Int = 5, // A scalar 32-bit signed integer value (int)
Int2 = 6, // A 2-component 32-bit signed integer vector (ivec2)
Int3 = 7, // A 3-component 32-bit signed integer vector (ivec3)
Int4 = 8, // A 4-component 32-bit signed integer vector (ivec4)
UInt = 9, // A scalar 32-bit unsigned integer value (uint)
UInt2 = 10, // A 2-component 32-bit unsigned integer vector (uvec2)
UInt3 = 11, // A 3-component 32-bit unsigned integer vector (uvec3)
UInt4 = 12, // A 4-component 32-bit unsigned integer vector (uvec4)
Float = 13, // A scalar 32-bit floating point value (float)
Float2 = 14, // A 2-component 32-bit floating point vector (vec2)
Float3 = 15, // A 3-component 32-bit floating point vector (vec3)
Float4 = 16, // A 4-component 32-bit floating point vector (vec4)
/// Matrix Value Types
Mat2 = 150, // A square 2x2 matrix of 32-bit floating point values (mat2)
Mat3 = 151, // A square 3x3 matrix of 32-bit floating point values (mat3)
Mat4 = 152, // A square 4x4 matrix of 32-bit floating point values (mat4)
/// Handle Types
Tex1D = 200, // A 1-dimensional combined image/sampler (tex1D)
Tex2D = 201, // A 2-dimensional combined image/sampler (tex2D)
Tex3D = 202, // A 3-dimensional combined image/sampler (tex3D)
TexCube = 203, // A cube-map combined image/sampler (texCube)
Tex1DArray = 204, // An array of 1-dimensional combined image/samplers (tex1DArray)
Tex2DArray = 205, // An array of 2-dimensional combined image/samplers (tex2DArray)
Image1D = 206, // A 1-dimensional non-sampled storage image (image1D)
Image2D = 207, // A 2-dimensional non-sampled storage image (image2D)
Image3D = 208, // A 3-dimensional non-sampled storage image (image3D)
Image1DArray = 209, // An array of 1-dimensional non-sampled storage images (image1DArray)
Image2DArray = 210, // An array of 2-dimensional non-sampled storage images (image2DArray)
SubpassInput = 211, // A texture resource that is being used as a subpass input within a renderpass
};
private:
static const PrimType VECTOR_TYPE_START = Bool;
static const PrimType VECTOR_TYPE_END = Float4;
static const PrimType MATRIX_TYPE_START = Mat2;
static const PrimType MATRIX_TYPE_END = Mat4;
static const PrimType HANDLE_TYPE_START = Tex1D;
static const PrimType HANDLE_TYPE_END = SubpassInput;
static const PrimType TEXTURE_TYPE_START = Tex1D;
static const PrimType TEXTURE_TYPE_END = Tex2DArray;
static const PrimType IMAGE_TYPE_START = Image1D;
static const PrimType IMAGE_TYPE_END = Image2DArray;
public:
PrimType type; // The base primitive type
bool is_array; // If the type is an array
uint8 count; // The number of elements in the type, will be 1 for non-arrays, and the array size for array types
union
{
uint8 subpass_input_index; // The index of the subpass input resource
PrimType image_format; // The texel format of the storage image
} extra; // Contains extra information about the type, the members will be valid only for certain types
// IMPORTANT: THIS VALUE SHOULD NOT BE LARGER THAN A BYTE, OR ELSE BINARY REFLECTION WILL BREAK
public:
HLSVType() :
type{ Void }, is_array{ false }, count{ 1 }, extra{ 0 }
{ }
HLSVType(PrimType type) :
type{ type }, is_array{ false }, count{ 1 }, extra{ 0 }
{ }
HLSVType(PrimType type, uint8 array_size) :
type{ type }, is_array{ true }, count{ array_size }, extra{ 0 }
{ }
HLSVType(PrimType type, PrimType fmt) :
type{ type }, is_array{ false }, count{ 1 }, extra{ fmt }
{ }
HLSVType& operator = (PrimType type) {
this->type = type;
is_array = false;
count = 1;
extra = { 0 };
return *this;
}
inline bool is_error() const { return type == Error; } // Gets if the type represents a type error
inline bool is_value_type() const { return IsValueType(type); }
inline bool is_scalar_type() const { return IsScalarType(type); }
inline bool is_vector_type() const { return IsVectorType(type); }
inline bool is_matrix_type() const { return IsMatrixType(type); }
inline bool is_handle_type() const { return IsHandleType(type); }
inline bool is_texture_type() const { return IsTextureType(type); }
inline bool is_image_type() const { return IsImageType(type); }
inline uint8 get_component_count() const { return GetComponentCount(type); }
inline PrimType get_component_type() const { return GetComponentType(type); }
inline string get_type_str() const { return GetTypeStr(type); }
inline uint32 get_slot_size() const { return GetSlotSize(*this); }
inline bool is_integer_type() const { return IsIntegerType(type); }
inline bool is_floating_point_type() const { return IsFloatingPointType(type); }
inline bool is_boolean_type() const { return IsBooleanType(type); }
inline static bool IsValueType(enum PrimType t) {
return (t >= VECTOR_TYPE_START && t <= VECTOR_TYPE_END) || (t >= MATRIX_TYPE_START && t <= MATRIX_TYPE_END);
}
inline static bool IsScalarType(enum PrimType t) {
return (t >= VECTOR_TYPE_START && t <= VECTOR_TYPE_END) && ((t % 4) == 1);
}
inline static bool IsVectorType(enum PrimType t) {
return (t >= VECTOR_TYPE_START && t <= VECTOR_TYPE_END) && ((t % 4) != 1);
}
inline static bool IsMatrixType(enum PrimType t) {
return (t >= MATRIX_TYPE_START && t <= MATRIX_TYPE_END);
}
inline static bool IsHandleType(enum PrimType t) {
return (t >= HANDLE_TYPE_START && t <= HANDLE_TYPE_END);
}
inline static bool IsTextureType(enum PrimType t) {
return (t >= TEXTURE_TYPE_START && t <= TEXTURE_TYPE_END);
}
inline static bool IsImageType(enum PrimType t) {
return (t >= IMAGE_TYPE_START && t <= IMAGE_TYPE_END);
}
inline static uint8 GetComponentCount(enum PrimType t) {
if (IsHandleType(t)) return 1u;
if (IsMatrixType(t)) return (t == Mat2) ? 4u : (t == Mat3) ? 9u : 16u;
return (((t - 1) % 4) + 1);
}
static PrimType GetComponentType(enum PrimType type);
static string GetTypeStr(enum PrimType t);
static uint32 GetSlotSize(HLSVType type);
inline static bool IsIntegerType(enum PrimType t) {
auto gc = GetComponentType(t);
return IsValueType(t) && (gc != Float) && (gc != Bool);
}
inline static bool IsFloatingPointType(enum PrimType t) {
return IsValueType(t) && (GetComponentType(t) == Float);
}
inline static bool IsBooleanType(enum PrimType t) {
return IsValueType(t) && (GetComponentType(t) == Bool);
}
inline static PrimType GetMostPromotedType(enum PrimType l, enum PrimType r) {
auto lc = GetComponentType(l);
auto rc = GetComponentType(r);
return lc > rc ? lc : rc;
}
inline static PrimType MakeVectorType(enum PrimType comp, uint8 count) {
return (PrimType)(comp + (count - 1));
}
}; // struct HLSVType
/* HLSVType Operators */
inline bool operator == (HLSVType l, HLSVType r) {
return l.type == r.type && l.is_array == r.is_array && l.count == r.count && l.extra.subpass_input_index == r.extra.subpass_input_index;
}
inline bool operator != (HLSVType l, HLSVType r) {
return l.type != r.type || l.is_array != r.is_array || l.count != r.count || l.extra.subpass_input_index != r.extra.subpass_input_index;
}
inline bool operator == (HLSVType l, enum HLSVType::PrimType r) { return l.type == r; }
inline bool operator != (HLSVType l, enum HLSVType::PrimType r) { return l.type != r; }
// Contains information about a vertex attribute in a shader
struct _EXPORT Attribute final
{
string name; // The attribute name
HLSVType type; // The attribute type information
uint8 location; // The binding location of the attribute
uint8 slot_count; // The number of binding slots taken by the attribute
Attribute(const string& name, HLSVType type, uint8 l, uint8 sc) :
name{ name }, type{ type }, location{ l }, slot_count{ sc }
{ }
}; // struct Attribute
// Contains information about a fragment output in a shader
struct _EXPORT Output final
{
string name; // The output name
HLSVType type; // The output type information
uint8 location; // The binding slot for the output
Output(const string& name, HLSVType type, uint8 l) :
name{ name }, type{ type }, location{ l }
{ }
}; // struct Output
// Contains information about a shader uniform
struct _EXPORT Uniform final
{
string name;
HLSVType type;
uint8 set;
uint8 binding;
struct
{
uint8 index; // The index of the uniform block that this uniform belongs to, if applicable
uint16 offset; // The offset of the uniform within its block, in bytes
uint16 size; // The size of the uniform within its block, in bytes
} block; // Contains block information, only valid for value-type uniforms inside of blocks
Uniform(const string& name, HLSVType type, uint8 s, uint8 b, uint8 bl, uint16 o, uint16 sz) :
name{ name }, type{ type }, set{ s }, binding{ b }, block{ bl, o, sz }
{ }
}; // struct Uniform
// Contains information about a shader uniform block
struct _EXPORT UniformBlock final
{
uint8 set;
uint8 binding;
uint16 size; // Total size of the block in bytes
bool packed; // If the members in the block are tightly packed
std::vector<uint8> members; // The indices into the reflection uniforms array for the members of this block
UniformBlock(uint8 s, uint8 b) :
set{ s }, binding{ b }, size{ 0 }, packed{ false }, members{ }
{ }
}; // struct UniformBlock
// Contains information about a push constant
struct _EXPORT PushConstant final
{
string name;
HLSVType type;
uint16 offset;
uint16 size;
PushConstant(const string& name, HLSVType type, uint16 o, uint16 s) :
name{ name }, type{ type }, offset{ o }, size{ s }
{ }
}; // struct PushConstant
// Contains information about a specialization constant
struct _EXPORT SpecConstant final
{
string name;
HLSVType type;
uint8 index;
uint16 size;
union
{
float f; // The default floating point value
int32 si; // The default signed integer value
uint32 ui; // The default unsigned integer value
} default_value; // The default value for the spec constant
SpecConstant(const string& name, HLSVType type, uint8 i, uint16 s) :
name{ name }, type{ type }, index{ i }, size{ s }, default_value{ 0u }
{ }
}; // struct SpecConstant
// The core reflection type that contains all reflection information about an HSLV shader
class _EXPORT ReflectionInfo final
{
public:
uint32 tool_version; // The version of the compiler that compiled the shader
uint32 shader_version; // The minimum feature version specified by the shader
ShaderType shader_type; // The type of the shader
ShaderStages stages; // The stages that are present in the shader
std::vector<Attribute> attributes; // The vertex attributes for the shader
std::vector<Output> outputs; // The fragment outputs for the shader
std::vector<Uniform> uniforms; // The uniforms for the shader
std::vector<UniformBlock> blocks; // The uniform blocks for the shader
std::vector<PushConstant> push_constants; // The push constants for the shader
std::vector<SpecConstant> spec_constants; // The specialization constants for the shader
bool push_constants_packed; // If the push constants are tightly packed
uint16 push_constants_size; // The total size of the push constant block, in bytes
public:
ReflectionInfo(ShaderType type, uint32 tv, uint32 sv);
~ReflectionInfo();
// Sorts the member vectors by binding location, info objects generated by the API will be pre-sorted
void sort();
inline bool is_graphics() const { return shader_type == ShaderType::Graphics; }
inline bool has_push_constants() const { return push_constants.size() > 0; }
// Gets the highest binding slot that is occupied by the vertex attributes of the shader
uint32 get_highest_attr_slot() const;
// Gets the uniform at the given set and binding, or nullptr if there is not one
const Uniform* get_uniform_at(uint32 set, uint32 binding) const;
// Gets the subpass input for the given index, or nullptr if there is not one
const Uniform* get_subpass_input(uint32 index) const;
}; // class ReflectionInfo
} // namespace hlsv
// Cleanup the non-public macros
#undef _EXPORT
| 43
| 138
| 0.702261
|
mossseank
|
3e137481138fdf09e3991cecdf367f1246be62c3
| 1,225
|
cpp
|
C++
|
tests/Droplet_tests.cpp
|
padinadrian/droplet
|
921415b5fed5a19fa5d7131a79713c2e574ca0d6
|
[
"Apache-2.0"
] | null | null | null |
tests/Droplet_tests.cpp
|
padinadrian/droplet
|
921415b5fed5a19fa5d7131a79713c2e574ca0d6
|
[
"Apache-2.0"
] | null | null | null |
tests/Droplet_tests.cpp
|
padinadrian/droplet
|
921415b5fed5a19fa5d7131a79713c2e574ca0d6
|
[
"Apache-2.0"
] | null | null | null |
/**
* Author: Adrian Padin (padin.adrian@gmail.com)
* Date: 2020/03/16
*/
/* ===== Includes ===== */
#include <gtest/gtest.h>
extern "C" {
#include "Droplet.h"
#include "BackgroundMap.h"
#include "data/maps/droplet_level1_bg.c"
}
/* ===== Tests ===== */
TEST(Position, DropletCheckMovement)
{
// Initialize map
BackgroundMap level1_map;
level1_map.map_data = DropletBackgroundLevel1;
level1_map.width = DropletBackgroundLevel1Width;
level1_map.height = DropletBackgroundLevel1Height;
// Droplet starting point on grid
Position droplet_grid_pos = {1, 10};
// Droplet can move right, but not up, down, or left
EXPECT_TRUE(
DropletCheckMovement(
J_RIGHT,
&droplet_grid_pos,
&level1_map
)
);
EXPECT_FALSE(
DropletCheckMovement(
J_UP,
&droplet_grid_pos,
&level1_map
)
);
EXPECT_FALSE(
DropletCheckMovement(
J_DOWN,
&droplet_grid_pos,
&level1_map
)
);
EXPECT_FALSE(
DropletCheckMovement(
J_LEFT,
&droplet_grid_pos,
&level1_map
)
);
}
| 21.12069
| 56
| 0.568163
|
padinadrian
|
3e1527f339c5acd7412cd6a7a35cb08a7ecef28a
| 3,959
|
cpp
|
C++
|
UI/GameHUD/Widget/Widget_PlayerSlowMotion.cpp
|
Bornsoul/Revenger_JoyContinue
|
599716970ca87a493bf3a959b36de0b330b318f1
|
[
"MIT"
] | null | null | null |
UI/GameHUD/Widget/Widget_PlayerSlowMotion.cpp
|
Bornsoul/Revenger_JoyContinue
|
599716970ca87a493bf3a959b36de0b330b318f1
|
[
"MIT"
] | null | null | null |
UI/GameHUD/Widget/Widget_PlayerSlowMotion.cpp
|
Bornsoul/Revenger_JoyContinue
|
599716970ca87a493bf3a959b36de0b330b318f1
|
[
"MIT"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "Widget_PlayerSlowMotion.h"
#include "../../Core/WidgetAni_Mng.h"
#include "Runtime/UMG/Public/Animation/WidgetAnimation.h"
#include "Kismet/KismetMathLibrary.h"
void UWidget_PlayerSlowMotion::NativeConstruct()
{
Super::NativeConstruct();
m_pGage = Cast<UImage>(GetWidgetFromName(TEXT("Gage")));
if (m_pGage == nullptr)
{
ULOG(TEXT("Error UProgressBar"));
}
m_pGageValueText = Cast<UTextBlock>(GetWidgetFromName(TEXT("GageValue")));
if (m_pGageValueText == nullptr)
{
ULOG(TEXT("Error UTextBlock"));
}
m_pWidgetAni = NewObject<UWidgetAni_Mng>();
if (m_pWidgetAni != nullptr)
{
m_pWidgetAni->Init(this);
}
else
{
ULOG(TEXT("WidgetAniMng is nullptr"));
return;
}
m_pMaterialInstance = Cast<UMaterialInterface >(m_pGage->Brush.GetResourceObject());
if (m_pMaterialInstance == nullptr)
{
ULOG(TEXT("Error m_pMaterialInstance"));
}
else
{
m_pMaterialDynamic = UMaterialInstanceDynamic::Create(m_pMaterialInstance, nullptr);
if (m_pMaterialDynamic == nullptr)
{
ULOG(TEXT("Error UMaterialInstanceDynamic"));
}
else
{
m_pGage->Brush.SetResourceObject(m_pMaterialDynamic);
}
}
ChangeSlowState(static_cast<int32>(E_State_SlowTime::E_SLOW_NONE));
}
void UWidget_PlayerSlowMotion::NativeTick(const FGeometry& MyGeometry, float InDeltaTime)
{
Super::NativeTick(MyGeometry, InDeltaTime);
switch (m_eSlowState)
{
case static_cast<int32>(E_State_SlowTime::E_SLOW_NONE) :
SlowTick_None(InDeltaTime);
break;
case static_cast<int32>(E_State_SlowTime::E_SLOW_START) :
SlowTick_Start(InDeltaTime);
break;
case static_cast<int32>(E_State_SlowTime::E_SLOW_END) :
SlowTick_End(InDeltaTime);
break;
}
if ( m_fValue <= 0.0f )
m_bEmptySlow = true;
else if ( m_fValue > 0.1f )
m_bEmptySlow = false;
if (m_fCurrValue_Front <= 0.0f)
m_fCurrValue_Front = 0.0f;
m_fCurrValue_Front = FMath::FInterpTo(m_fCurrValue_Front, m_fPerValue, InDeltaTime, 7.0f);
if (m_pGage != nullptr)
m_pMaterialDynamic->SetScalarParameterValue(FName(TEXT("ProgressBar")), m_fCurrValue_Front);
FString sText = FString::Printf(TEXT("%d%%"), static_cast<int32>(m_fPerValue*100));// FString::FromInt(sAA) + "%";
if ( m_pGageValueText != nullptr)
m_pGageValueText->SetText(FText::FromString(sText));
}
void UWidget_PlayerSlowMotion::SetInit(float fGage)
{
m_fPerValue = fGage;
m_fValue = fGage;
m_fCurrValue_Front = fGage;
m_bUseSlow = false;
m_bEmptySlow = false;
GetRootWidget()->SetVisibility(ESlateVisibility::Hidden);
}
void UWidget_PlayerSlowMotion::SetShow(bool bShow)
{
if (bShow)
{
if (m_eSlowState == static_cast<int32>(E_State_SlowTime::E_SLOW_NONE))
m_pWidgetAni->SetPlayAnimation("SlowShow");
}
else
{
m_pWidgetAni->SetPlayAnimation("SlowHide");
}
}
void UWidget_PlayerSlowMotion::SetPercent(float fValue)
{
if (m_fPerValue <= 0.0f)
{
m_fPerValue = 0.0f;
}
if (m_fPerValue >= 1.0f)
{
m_fPerValue = 1.0f;
}
m_fPerValue = fValue;
}
void UWidget_PlayerSlowMotion::ChangeSlowState(int32 eState)
{
if ( eState == static_cast<int32>(E_State_SlowTime::E_SLOW_START))
GetRootWidget()->SetVisibility(ESlateVisibility::Visible);
m_eSlowState = eState;
}
void UWidget_PlayerSlowMotion::SlowTick_None(float fDeltaTime)
{
if (m_bUseSlow)
{
SetShow(false);
m_bUseSlow = false;
}
m_fValue = 1.0f;
SetPercent(m_fValue);
}
void UWidget_PlayerSlowMotion::SlowTick_Start(float fDeltaTime)
{
if (m_fValue <= 0.0f)
{
m_fValue = 0.0f;
ChangeSlowState(static_cast<int32>(E_State_SlowTime::E_SLOW_END));
return;
}
m_bUseSlow = true;
m_fValue -= m_fUseSpeed * fDeltaTime;
SetPercent(m_fValue);
}
void UWidget_PlayerSlowMotion::SlowTick_End(float fDeltaTime)
{
if (m_fValue >= 1.0f)
{
m_fValue = 1.0f;
ChangeSlowState(static_cast<int32>(E_State_SlowTime::E_SLOW_NONE));
return;
}
m_fValue += m_fFullSpeed * fDeltaTime;
SetPercent(m_fValue);
}
| 21.994444
| 115
| 0.735034
|
Bornsoul
|
3e1cd3e9a033fa1b10782747b2d1d830fd9ec04f
| 1,048
|
cpp
|
C++
|
Editor/Source/Misc/EditorSelection.cpp
|
jkorn2324/jkornEngine
|
5822f2a311ed62e6ca495919872f0f436d300733
|
[
"MIT"
] | null | null | null |
Editor/Source/Misc/EditorSelection.cpp
|
jkorn2324/jkornEngine
|
5822f2a311ed62e6ca495919872f0f436d300733
|
[
"MIT"
] | null | null | null |
Editor/Source/Misc/EditorSelection.cpp
|
jkorn2324/jkornEngine
|
5822f2a311ed62e6ca495919872f0f436d300733
|
[
"MIT"
] | null | null | null |
#include "EditorPCH.h"
#include "EditorSelection.h"
#include "EditorCamera.h"
namespace Editor
{
static Engine::Entity s_selectedEntity;
static bool OnEntityCreated_EditorSelection(Engine::EntityCreatedEvent& event)
{
return true;
}
static bool OnEntityDestroyed_EditorSelection(Engine::EntityDestroyedEvent& event)
{
if (event.entity == s_selectedEntity)
{
s_selectedEntity = event.entity;
}
return true;
}
Engine::Entity EditorSelection::GetSelectedEntity()
{
return s_selectedEntity;
}
void EditorSelection::SetSelectedEntity(const Engine::Entity& entity)
{
s_selectedEntity = entity;
}
bool EditorSelection::HasSelectedEntity() { return s_selectedEntity.IsValid(); }
void EditorSelection::OnEvent(Engine::Event& event)
{
Engine::EventDispatcher dispatcher(event);
dispatcher.Invoke<Engine::EntityCreatedEvent>(
BIND_STATIC_EVENT_FUNCTION(OnEntityCreated_EditorSelection));
dispatcher.Invoke<Engine::EntityDestroyedEvent>(
BIND_STATIC_EVENT_FUNCTION(OnEntityDestroyed_EditorSelection));
}
}
| 23.288889
| 83
| 0.77958
|
jkorn2324
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.