hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
76ae2c05042d464bd907ab21b1c03582f2c8b85a
2,001
cpp
C++
Sources/Internal/Platform/TemplateAndroid/JniExtensions.cpp
reven86/dava.engine
ca47540c8694668f79774669b67d874a30188c20
[ "BSD-3-Clause" ]
5
2020-02-11T12:04:17.000Z
2022-01-30T10:18:29.000Z
Sources/Internal/Platform/TemplateAndroid/JniExtensions.cpp
reven86/dava.engine
ca47540c8694668f79774669b67d874a30188c20
[ "BSD-3-Clause" ]
null
null
null
Sources/Internal/Platform/TemplateAndroid/JniExtensions.cpp
reven86/dava.engine
ca47540c8694668f79774669b67d874a30188c20
[ "BSD-3-Clause" ]
4
2019-11-28T19:24:34.000Z
2021-08-24T19:12:50.000Z
#include "JniExtensions.h" #if !defined(__DAVAENGINE_COREV2__) #if defined(__DAVAENGINE_ANDROID__) #include "Platform/TemplateAndroid/CorePlatformAndroid.h" #include "UI/UIControlSystem.h" #include "Math/Rect.h" #include "Logger/Logger.h" #include "Debug/DVAssert.h" namespace DAVA { JniExtension::JniExtension() { CorePlatformAndroid* core = static_cast<CorePlatformAndroid*>(Core::Instance()); AndroidSystemDelegate* delegate = core->GetAndroidSystemDelegate(); vm = delegate->GetVM(); } JniExtension::~JniExtension() { } void JniExtension::SetJavaClass(JNIEnv* env, const char* className, jclass* gJavaClass, const char** gJavaClassName) { *gJavaClass = static_cast<jclass>(env->NewGlobalRef(env->FindClass(className))); if (gJavaClassName) *gJavaClassName = className; } jmethodID JniExtension::GetMethodID(const char* methodName, const char* paramCode) const { jclass javaClass = GetJavaClass(); DVASSERT(javaClass && "Not initialized Java class"); if (!javaClass) return 0; jmethodID mid = GetEnvironment()->GetStaticMethodID(javaClass, methodName, paramCode); if (!mid) { Logger::Error("get method id of %s.%s%s error ", GetJavaClassName(), methodName, paramCode); } return mid; } JNIEnv* JniExtension::GetEnvironment() const { // right way to take JNIEnv // JNIEnv is valid only for the thread where it was gotten. // we shouldn't store JNIEnv. JNIEnv* env; if (JNI_EDETACHED == vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6)) { Logger::Error("runtime_error(Thread is not attached to JNI)"); } return env; }; Rect JniExtension::V2P(const Rect& srcRect) const { Vector2 offset = UIControlSystem::Instance()->vcs->GetPhysicalDrawOffset(); Rect rect = UIControlSystem::Instance()->vcs->ConvertVirtualToPhysical(srcRect); rect += offset; return rect; } } //namespace DAVA #endif // __DAVAENGINE_ANDROID__ #endif // __DAVAENGINE_COREV2__
26.328947
116
0.709645
reven86
76b1445040b47301c1d5ceb15e854fd7590c3876
574
cpp
C++
3/3/35.cpp
Jamxscape/LearnCPlusPlus
9770af743a2f6e9267421ff8fec93eb9d81c1f14
[ "Apache-2.0" ]
null
null
null
3/3/35.cpp
Jamxscape/LearnCPlusPlus
9770af743a2f6e9267421ff8fec93eb9d81c1f14
[ "Apache-2.0" ]
null
null
null
3/3/35.cpp
Jamxscape/LearnCPlusPlus
9770af743a2f6e9267421ff8fec93eb9d81c1f14
[ "Apache-2.0" ]
null
null
null
// // 35.cpp // 3 // // Created by 马元 on 2016/12/25. // Copyright © 2016年 MaYuan. All rights reserved. //大家提到LTC都佩服的不行,不过,如果竞赛只有这一个题目,我敢保证你和他绝对在一个水平线上你的任务是:计算方程x^2+y^2+z^2= num的一个正整数解。Input输入数据包含多个测试实例,每个实例占一行,仅仅包含一个小于等于10000的正整数num。Output对于每组测试数据,请按照x,y,z递增的顺序输出它的一个最小正整数解,每个实例的输出占一行,题目保证所有测试数据都有解。 #include <iostream> using namespace std; int main35() { int num,x,y,z; cin>>num; for(x=0;x<num;x++) for(y=0;y<num;y++) for(z=0;z<num;z++) if(x*x+y*y+z*z==num)cout<<x<<" "<<y<<" "<<z<<endl; cout<<endl; return 0; }
26.090909
196
0.627178
Jamxscape
76b2c5fdc93414e954ec805be777754828ea48ef
739
cpp
C++
src/VK/SemaphoreWrapper.cpp
razerx100/Terra
a30738149cb07325283c2da9ac7972f079cb4dbc
[ "MIT" ]
null
null
null
src/VK/SemaphoreWrapper.cpp
razerx100/Terra
a30738149cb07325283c2da9ac7972f079cb4dbc
[ "MIT" ]
null
null
null
src/VK/SemaphoreWrapper.cpp
razerx100/Terra
a30738149cb07325283c2da9ac7972f079cb4dbc
[ "MIT" ]
null
null
null
#include <SemaphoreWrapper.hpp> #include <VKThrowMacros.hpp> SemaphoreWrapper::SemaphoreWrapper(VkDevice device, size_t count) : m_deviceRef(device), m_semaphores(count) { VkSemaphoreCreateInfo semaphoreInfo = {}; semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; VkResult result; for (size_t index = 0u; index < count; ++index) VK_THROW_FAILED(result, vkCreateSemaphore(device, &semaphoreInfo, nullptr, &m_semaphores[index]) ); } SemaphoreWrapper::~SemaphoreWrapper() noexcept { for (const auto semaphore : m_semaphores) vkDestroySemaphore(m_deviceRef, semaphore, nullptr); } VkSemaphore SemaphoreWrapper::GetSemaphore(size_t index) const noexcept { return m_semaphores[index]; }
29.56
76
0.759134
razerx100
76b2d918729e127a4b073b29b126d91cd5f6e0d2
1,049
cpp
C++
Chapter_3/p3_16.cpp
aalogancheney/CPlusPlus_For_Everyone
251247cf1f1ca169826179379831192fadfaa5f9
[ "MIT" ]
null
null
null
Chapter_3/p3_16.cpp
aalogancheney/CPlusPlus_For_Everyone
251247cf1f1ca169826179379831192fadfaa5f9
[ "MIT" ]
null
null
null
Chapter_3/p3_16.cpp
aalogancheney/CPlusPlus_For_Everyone
251247cf1f1ca169826179379831192fadfaa5f9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::string; void ClearInputDisplayMessage(const string& message) { cout << message << endl; cin.clear(); string ignore; getline(cin, ignore); } int main(int argc, char *argv[]) { cout << "Enter the employees name: "; string name; getline(cin, name); while(cin.fail()) { ClearInputDisplayMessage("Please enter a valid name: "); getline(cin, name); } cout << "Enter the employees hourly wage: "; double wage; cin >> wage; while(cin.fail()) { ClearInputDisplayMessage("Please enter a valid wage: "); cin >> wage; } cout << "How many hours did " << name << " work last week? "; double hours; cin >> hours; while(cin.fail()) { ClearInputDisplayMessage("Please enter a valid number of hours: "); cin >> hours; } double totalPay = 0; if(hours > 40) { totalPay += wage * 40 + wage * 1.5 * (hours - 40); } else { totalPay += wage * hours; } cout << name << "'s Paycheck: " << totalPay << endl; return 0; }
16.919355
69
0.632984
aalogancheney
76b4b622cd484e8969d77bfa2d4b292a7158258f
2,880
hpp
C++
src/io/FileWriterInterface.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
2
2018-07-04T16:44:04.000Z
2021-01-03T07:26:27.000Z
src/io/FileWriterInterface.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
src/io/FileWriterInterface.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
/** \defgroup Output Output module * @{ <img src="output.png"> @} */ #pragma once #include <vector> #include <string> #include "AMDiS_fwd.hpp" #include "Mesh.hpp" namespace AMDiS { class FileWriterInterface { public: FileWriterInterface() : filename(""), appendIndex(0), indexLength(5), indexDecimals(3), createSubDir(-1), tsModulo(1), timeModulo(-1.0), lastWriteTime(-1.0), traverseLevel(-1), traverseFlag(Mesh::CALL_LEAF_EL), writeElement(NULL) {} virtual ~FileWriterInterface() {} /** \brief * Interface. Must be overridden in subclasses. * \param time time index of solution std::vector. * \param force enforces the output operation for the last timestep. */ virtual void writeFiles(AdaptInfo& adaptInfo, bool force, int level = -1, Flag traverseFlag = Mesh::CALL_LEAF_EL, bool (*writeElem)(ElInfo*) = NULL) = 0; /// Test whether timestep should be written virtual bool doWriteTimestep(AdaptInfo& adaptInfo, bool force); std::string getFilename() { return filename; } void setFilename(std::string n) { filename = n; } void setWriteModulo(int tsModulo_ = 1, double timeModulo_ = -1.0) { tsModulo = tsModulo_; timeModulo = timeModulo_; } void setTraverseProperties(int level, Flag flag, bool (*writeElem)(ElInfo*)) { traverseLevel = level; traverseFlag |= flag; writeElement = writeElem; } protected: /// Reads all file writer dependend parameters from the init file. virtual void readParameters(std::string name); /// create a filename that includes the timestep and possibly a processor ID in parallel mode #ifdef HAVE_PARALLEL_DOMAIN_AMDIS void getFilename(AdaptInfo& adaptInfo, std::string& fn, std::string& paraFilename, std::string& postfix); #else void getFilename(AdaptInfo& adaptInfo, std::string& fn); #endif /// Used filename prefix. std::string filename; /// 0: Don't append time index to filename prefix. /// 1: Append time index to filename prefix. int appendIndex; /// Total length of appended time index. int indexLength; /// Number of decimals in time index. int indexDecimals; /// create a subdirectory where to put the files int createSubDir; /// Timestep modulo: write only every tsModulo-th timestep! int tsModulo; /// Time modulo: write at first iteration after lastWriteTime + timeModulo double timeModulo; double lastWriteTime; /// Traverse properties int traverseLevel; Flag traverseFlag; bool (*writeElement)(ElInfo*); }; } // end namespace AMDiS
25.263158
109
0.621875
spraetor
76b4efc373f16d2ffbb1f048bf2b579d8d95c96f
2,746
cpp
C++
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/constants/rmm.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
5
2019-11-11T07:57:26.000Z
2022-03-28T08:26:53.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/constants/rmm.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
3
2019-09-05T21:47:07.000Z
2019-09-17T18:10:45.000Z
Contrib-Intel/RSD-PSME-RMM/common/agent-framework/src/module/constants/rmm.cpp
opencomputeproject/Rack-Manager
e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a
[ "MIT" ]
11
2019-07-20T00:16:32.000Z
2022-01-11T14:17:48.000Z
/*! * @copyright * Copyright (c) 2017-2019 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * * @file rmm.cpp * @brief Contains RMM constants used all over the model * */ #include "agent-framework/module/constants/rmm.hpp" namespace agent_framework { namespace model { namespace literals { constexpr const char Fan::STATUS[]; constexpr const char Fan::CURRENT_SPEED[]; constexpr const char Fan::FRU_INFO[]; constexpr const char Fan::OEM[]; constexpr const char Fan::FAN[]; constexpr const char Fan::PHYSICAL_CONTEXT[]; constexpr const char Fan::CURRENT_SPEED_UNITS[]; constexpr const char ThermalZone::ZONE[]; constexpr const char ThermalZone::STATUS[]; constexpr const char ThermalZone::VOLUMETRIC_AIRFLOW_CFM[]; constexpr const char ThermalZone::DESIRED_SPEED_PWM[]; constexpr const char ThermalZone::COLLECTIONS[]; constexpr const char ThermalZone::OEM[]; constexpr const char Psu::PSU[]; constexpr const char Psu::STATUS[]; constexpr const char Psu::FRU_INFO[]; constexpr const char Psu::OEM[]; constexpr const char Psu::POWER_SUPPLY_TYPE[]; constexpr const char Psu::LINE_INPUT_VOLTAGE_TYPE[]; constexpr const char Psu::LINE_INPUT_VOLTAGE_VOLTS[]; constexpr const char Psu::FIRMWARE_VERSION[]; constexpr const char Psu::LAST_POWER_OUTPUT_WATTS[]; constexpr const char Psu::POWER_CAPACITY_WATTS[]; constexpr const char Psu::INDICATOR_LED[]; constexpr const char Psu::REQUESTED_STATE[]; constexpr const char PowerZone::ZONE[]; constexpr const char PowerZone::STATUS[]; constexpr const char PowerZone::POWER_ALLOCATED[]; constexpr const char PowerZone::POWER_REQUESTED[]; constexpr const char PowerZone::POWER_AVAILABLE[]; constexpr const char PowerZone::POWER_CONSUMED[]; constexpr const char PowerZone::POWER_CAPACITY[]; constexpr const char PowerZone::COLLECTIONS[]; constexpr const char PowerZone::OEM[]; constexpr const char ChassisSensor::SENSOR[]; constexpr const char ChassisSensor::STATUS[]; constexpr const char ChassisSensor::READING[]; constexpr const char ChassisSensor::PHYSICAL_CONTEXT[]; constexpr const char ChassisSensor::READING_UNITS[]; constexpr const char ChassisSensor::SENSOR_NUMBER[]; constexpr const char ChassisSensor::OEM[]; } } }
34.325
75
0.776766
opencomputeproject
76b777a4b45c88e0548d0939d5c537fbebce4b59
269
cpp
C++
src/ComponentSet.cpp
Konijnendijk/Meadows-ECS
5ee2619481086edaabcfa235e2455686cb854901
[ "BSL-1.0", "MIT" ]
1
2017-11-22T11:39:25.000Z
2017-11-22T11:39:25.000Z
src/ComponentSet.cpp
Konijnendijk/Meadows-ECS
5ee2619481086edaabcfa235e2455686cb854901
[ "BSL-1.0", "MIT" ]
null
null
null
src/ComponentSet.cpp
Konijnendijk/Meadows-ECS
5ee2619481086edaabcfa235e2455686cb854901
[ "BSL-1.0", "MIT" ]
null
null
null
#include "ComponentSet.h" using namespace Meadows; ComponentSet::ComponentSet() : componentBitSet(ComponentRegistry::getNumRegisteredComponents()) { } ComponentSet::~ComponentSet() { for (Component* component : components) { delete(component); } }
17.933333
97
0.717472
Konijnendijk
76bc393e21a080577c2bc57cc5ae93e4b500e791
535
cpp
C++
spoj/HOTELS.cpp
amarlearning/CodeForces
6625d3be21cb6a78b88c7521860d1da263e77121
[ "Unlicense" ]
3
2016-02-20T12:14:51.000Z
2016-03-18T20:09:36.000Z
spoj/HOTELS.cpp
amarlearning/Codeforces
6625d3be21cb6a78b88c7521860d1da263e77121
[ "Unlicense" ]
null
null
null
spoj/HOTELS.cpp
amarlearning/Codeforces
6625d3be21cb6a78b88c7521860d1da263e77121
[ "Unlicense" ]
2
2018-07-26T21:00:42.000Z
2019-11-30T19:33:57.000Z
/* Author : Amar Prakash Pandey contact : http://amarpandey.me */ #include <bits/stdc++.h> #define ll long long #define MAX 1000005 using namespace std; ll int A[MAX]; int main(int argc, char const *argv[]) { ll int N, M, sum = 0; scanf("%lld %lld", &N, &M); for (ll int i = 0; i < N; ++i) { scanf("%lld", &A[i]); } ll int l = 0, r = 0, ans = 0; while(l < N) { while(r < N && (sum + A[r]) <= M) { sum += A[r]; r++; } ans = max(ans, sum); sum -= A[l]; l++; } printf("%lld\n", ans); return 0; }
12.738095
40
0.506542
amarlearning
76be93f1975379ff4d2dbd50e15a7220270d08af
304
cpp
C++
cc/tests/test1/submit.cpp
DragoonKiller/bruteforces
e6283b18c692a3726e7e52a6a60e64ddc903da91
[ "MIT" ]
null
null
null
cc/tests/test1/submit.cpp
DragoonKiller/bruteforces
e6283b18c692a3726e7e52a6a60e64ddc903da91
[ "MIT" ]
null
null
null
cc/tests/test1/submit.cpp
DragoonKiller/bruteforces
e6283b18c692a3726e7e52a6a60e64ddc903da91
[ "MIT" ]
null
null
null
static void this_is_a_function_in_brute_gen_in_all_hpp() { } static void this_is_a_function_in_bits_hpp() { } #include <bits/stdc++.h> static void this_is_another_function_in_bits_hpp() { } #include <chrono> static void this_is_a_function_outof_brute_gen_in_all_hpp() { } int main() { return 0; }
21.714286
63
0.776316
DragoonKiller
76c2f4df9cb8a71855172fdb7ebc46cab2b57915
8,603
cpp
C++
src/ui/SciControl/CScintillaController.cpp
masmullin2000/codeassistor
82389e16dda7be522ee5370aae441724da2e9cf2
[ "BSD-4-Clause" ]
null
null
null
src/ui/SciControl/CScintillaController.cpp
masmullin2000/codeassistor
82389e16dda7be522ee5370aae441724da2e9cf2
[ "BSD-4-Clause" ]
null
null
null
src/ui/SciControl/CScintillaController.cpp
masmullin2000/codeassistor
82389e16dda7be522ee5370aae441724da2e9cf2
[ "BSD-4-Clause" ]
null
null
null
/** title info */ #include "CScintillaController.h" #include "ScintillaSend.h" #include "common_defs.h" /* colourizing defines */ #if PLATFORM == MAC #define DEF_KEYW_1 "#FF627E" #define DEF_KEYW_2 "#FF00FF" #define DEF_NUM "#0000FF" #define DEF_OP "#0000FF" #define DEF_STRING "#EE9A4D" #define DEF_STRING_EOL "#D4A9EE" #define DEF_CHAR "#0022FF" #define DEF_PREPRO "#C35617" #define DEF_IDENT "#000000" #define DEF_COMMENT "#777777" #define DEF_COMMENT_2 "#444444" #define DEF_MARGIN "#DADADA" #define DEF_LINE_NO "#CFCFCF" #else #define DEF_KEYW_1 "#FF627E" #define DEF_KEYW_2 "#FF00FF" #define DEF_NUM "#AAAAFF" #define DEF_OP "#DDAADD" #define DEF_STRING "#EE9A4D" #define DEF_STRING_EOL "#D4A9EE" #define DEF_CHAR "#0022FF" #define DEF_PREPRO "#C35617" #define DEF_IDENT "#999988" #define DEF_COMMENT "#777777" #define DEF_COMMENT_2 "#444444" #define DEF_MARGIN "#323232" #define DEF_LINE_NO "#434343" #endif #define TAB_WIDTH 2 CScintillaController* CScintillaController::_me = NULL; /* The CScintillaController is a singleton */ ScintillaController* CScintillaController::getInstance() { if( !_me ) _me = new CScintillaController(); return _me; } void CScintillaController::setDefaultEditor ( void* sci, fileType_t subtype ) { ScintillaSend* send = ScintillaSend::getInstance(); const char* keywordsToUse = NULL; const char* secondaryKeywordsToUse = CStdLibrary; ScintillaController::setDefaultEditor(sci,subtype); #if PLATFORM != MAC send->set(sci,SCI_STYLESETBACK,STYLE_DEFAULT,0); send->set(sci,SCI_STYLESETFORE,STYLE_DEFAULT,0); send->set(sci,SCI_SETCARETFORE,255,0); send->set(sci,SCI_STYLECLEARALL,0,0); #endif // CPP is used, this is also good for ObjC/Java/C send->set(sci,SCI_SETLEXER,SCLEX_CPP,0); send->set(sci,SCI_SETSTYLEBITS,send->get(sci,SCI_GETSTYLEBITSNEEDED),0); // tabs are replaced with spaces, tabs are 2 spaces wide send->set(sci,SCI_SETUSETABS,0,0); send->set(sci,SCI_SETTABWIDTH,TAB_WIDTH,0); switch( subtype ) { case CFILE: keywordsToUse = CKeywords; break; case CPPFILE: keywordsToUse = CppKeywords; break; case OBJCFILE: keywordsToUse = ObjCKeywords; break; case OBJCPPFILE: keywordsToUse = ObjCppKeywords; break; case HDFILE: keywordsToUse = HKeywords; break; case JFILE: keywordsToUse = JKeywords; secondaryKeywordsToUse = JClasses; break; default: keywordsToUse = "error"; } send->set(sci,SCI_SETKEYWORDS,0,(void*)keywordsToUse); send->set(sci,SCI_SETKEYWORDS,1,(void*)secondaryKeywordsToUse); for( int i = 0; i <= SCE_C_USERLITERAL; i++ ) send->set(sci,SCI_STYLESETFORE,i,"#FFFFFF",true); send->set(sci,SCI_SETSELFORE,true,255|255<<8|255<<16); send->set(sci,SCI_SETSELBACK,true,64|64<<8|64<<16); // set the font for strings (ie "this is a string" ) as itali send->set(sci,SCI_STYLESETFONT,SCE_C_STRING,ITALIC_STRING); send->set(sci,SCI_STYLESETITALIC,SCE_C_STRING,1); send->set(sci,SCI_STYLESETBOLD,SCE_C_STRING,1); send->set(sci,SCI_STYLESETSIZE,SCE_C_STRING,INITIAL_TEXT_SIZE); // colourizing // keywords send->set(sci,SCI_STYLESETFORE,SCE_C_WORD,DEF_KEYW_1,true); send->set(sci,SCI_STYLESETFORE,SCE_C_WORD|0x40,DEF_COMMENT,true); // c standard lib send->set(sci,SCI_STYLESETFORE,SCE_C_WORD2,DEF_KEYW_2,true); send->set(sci,SCI_STYLESETFORE,SCE_C_WORD2|0x40,DEF_COMMENT,true); // numbers send->set(sci,SCI_STYLESETFORE,SCE_C_NUMBER,DEF_NUM,true); send->set(sci,SCI_STYLESETFORE,SCE_C_NUMBER|0x40,DEF_COMMENT,true); // operators/operations send->set(sci,SCI_STYLESETFORE,SCE_C_OPERATOR,DEF_OP,true); send->set(sci,SCI_STYLESETFORE,SCE_C_OPERATOR|0x40,DEF_COMMENT,true); // strings send->set(sci,SCI_STYLESETFORE,SCE_C_STRING,DEF_STRING,true); send->set(sci,SCI_STYLESETFORE,SCE_C_STRING|0x40,DEF_COMMENT,true); send->set(sci,SCI_STYLESETFORE,SCE_C_STRINGEOL,DEF_STRING_EOL,true); send->set(sci,SCI_STYLESETFORE,SCE_C_STRINGEOL|0x40,DEF_COMMENT,true); // 'a' characters send->set(sci,SCI_STYLESETFORE,SCE_C_CHARACTER,DEF_CHAR,true); send->set(sci,SCI_STYLESETFORE,SCE_C_CHARACTER|0x40,DEF_COMMENT,true); // preprocessors #define/#include send->set(sci,SCI_STYLESETFORE,SCE_C_PREPROCESSOR,DEF_PREPRO,true); send->set(sci,SCI_STYLESETFORE,SCE_C_PREPROCESSOR|0x40,DEF_COMMENT,true); // identifiers aka everything else send->set(sci,SCI_STYLESETFORE,SCE_C_IDENTIFIER,DEF_IDENT,true); send->set(sci,SCI_STYLESETFORE,SCE_C_IDENTIFIER|0x40,DEF_COMMENT,true); // comments send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENT,DEF_COMMENT,true); send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENTLINE,DEF_COMMENT,true); send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENTDOC,DEF_COMMENT,true); send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENTLINEDOC,DEF_COMMENT,true); send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENTDOCKEYWORD,DEF_COMMENT_2,true); send->set(sci,SCI_STYLESETFORE,SCE_C_COMMENTDOCKEYWORDERROR,DEF_COMMENT_2,true); // send->set(sci,SCI_STYLESETFORE,SCE_C_GLOBALCLASS,"#FFFFFF",true); // Line numbering send->set(sci,SCI_STYLESETFORE,STYLE_LINENUMBER,DEF_IDENT,true); send->set(sci,SCI_STYLESETBACK,STYLE_LINENUMBER,DEF_LINE_NO,true); send->set(sci,SCI_SETMARGINTYPEN,0,SC_MARGIN_NUMBER); send->set(sci,SCI_SETMARGINWIDTHN,0,48); // long lines send->set(sci,SCI_SETEDGEMODE,1,0); send->set(sci,SCI_SETEDGECOLUMN,80,0); // folding send->set(sci,SCI_SETFOLDMARGINCOLOUR,true,DEF_MARGIN,true); send->set(sci,SCI_SETFOLDMARGINHICOLOUR,true,DEF_MARGIN,true); send->set(sci,SCI_SETMARGINWIDTHN,1,18); send->set(sci,SCI_SETFOLDFLAGS,SC_FOLDFLAG_LINEAFTER_CONTRACTED,0); send->set(sci,SCI_SETPROPERTY,"fold","1"); send->set(sci,SCI_SETPROPERTY,"fold.compact","0"); send->set(sci,SCI_SETPROPERTY,"fold.at.else","1"); send->set(sci,SCI_SETPROPERTY,"fold.preprocessor","1"); // these new preprocessor features aren't working out so well for me send->set(sci,SCI_SETPROPERTY,"lexer.cpp.track.preprocessor","0"); send->set(sci,SCI_SETPROPERTY,"lexer.cpp.update.preprocessor","0"); send->set(sci,SCI_SETMARGINTYPEN, 1, SC_MARGIN_SYMBOL); send->set(sci,SCI_SETMARGINMASKN, 1, SC_MASK_FOLDERS); send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDEROPEN, SC_MARK_ARROWDOWN); send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDER, SC_MARK_ARROW); send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDERSUB, SC_MARK_EMPTY); send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDERTAIL, SC_MARK_EMPTY); send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDEREND, SC_MARK_EMPTY); send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDEROPENMID, SC_MARK_EMPTY); send->set(sci,SCI_MARKERDEFINE, SC_MARKNUM_FOLDERMIDTAIL, SC_MARK_EMPTY); } /* Copyright (c) 2010, Michael Mullin <masmullin@gmail.com> 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. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by Michael Mullin <masmullin@gmail.com>. 4. Neither the name of Michael Mullin 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 MICHAEL MULLIN ''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 MICHAEL MULLIN 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. */
37.404348
84
0.749622
masmullin2000
76c84ac58ffc95d332730ba9586637136a402d87
4,225
cpp
C++
ZEDModel.cpp
balder2046/WorldViewer
088f7bfdbf3a4ac8ca82f301c26969e1b4db40f0
[ "MIT" ]
null
null
null
ZEDModel.cpp
balder2046/WorldViewer
088f7bfdbf3a4ac8ca82f301c26969e1b4db40f0
[ "MIT" ]
null
null
null
ZEDModel.cpp
balder2046/WorldViewer
088f7bfdbf3a4ac8ca82f301c26969e1b4db40f0
[ "MIT" ]
null
null
null
#include <GL/glew.h> #include <glm/detail/type_mat.hpp> #include <glm/gtc/type_ptr.hpp> #include "ZEDModel.hpp" #include "glm/glm.hpp" void CheckGLError(); Zed3D::Zed3D() { body_io.clear(); path_mem.clear(); vaoID = 0; vboID = 0; darktriID = 0; allumtriID = 0; } Zed3D::~Zed3D() { body_io.clear(); path_mem.clear(); } void Zed3D::setPath(sl::Transform &Path,std::vector<sl::Translation> path_history) { } void Zed3D::draw(glm::mat4 &pm) { shader.Use(); glBindVertexArray(vaoID); glBindBuffer(GL_ARRAY_BUFFER,vboID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,darktriID); glUniform4f(shader("ObjColor"),DARK_COLOR.r,DARK_COLOR.g,DARK_COLOR.g,1.0f); glDrawElements(GL_TRIANGLES,NB_DARK_TRIANGLES * 3,GL_UNSIGNED_SHORT,0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,allumtriID); // const GLubyte *buf = gluErrorString(code); glUniformMatrix4fv(shader("MVP"), 1, GL_FALSE, glm::value_ptr(pm)); glUniform4f(shader("ObjColor"),ALLUMINIUM_COLOR.r,ALLUMINIUM_COLOR.g,ALLUMINIUM_COLOR.b,1.0f); glDrawElements(GL_TRIANGLES, NB_ALLUMINIUM_TRIANGLES * 3, GL_UNSIGNED_SHORT, 0); glBindVertexArray(0); shader.UnUse(); return; // glPopMatrix(); } struct Vertex_t { float x; float y; float z; unsigned int color; }; void Zed3D::init() { sl::Transform path; GLuint tt; glGenVertexArrays(1,&vaoID); glBindVertexArray(vaoID); glGenBuffers(1,&vboID); glBindBuffer(GL_ARRAY_BUFFER,vboID); std::vector<Vertex_t> vertexs; int vertcount = sizeof(verticesZed) / sizeof(float) / 3; vertexs.resize(vertcount); for (int i = 0; i < vertcount; ++i) { vertexs[i].x = verticesZed[3 * i] * 100.0f; vertexs[i].y = verticesZed[3 * i + 1] * 100.0f; vertexs[i].z = verticesZed[3 * i + 2] * 100.0f; } unsigned int darkcolor,alluminiumcolor; darkcolor = glm::packUnorm4x8(glm::vec4(DARK_COLOR.r, DARK_COLOR.g, DARK_COLOR.b,1.0f)); alluminiumcolor = glm::packUnorm4x8(glm::vec4(ALLUMINIUM_COLOR.r, ALLUMINIUM_COLOR.g, ALLUMINIUM_COLOR.b,1.0f)); for (int i = 0; i < NB_ALLUMINIUM_TRIANGLES * 3; i += 3) { for (int j = 0; j < 3; j++) { double3color tmp; int index = alluminiumTriangles[i + j] - 1; vertexs[index].color = alluminiumcolor; } } for (int i = 0; i < NB_DARK_TRIANGLES * 3; i += 3) { for (int j = 0; j < 3; j++) { int index = darkTriangles[i + j] - 1; vertexs[index].color = darkcolor; } } glBufferData(GL_ARRAY_BUFFER,sizeof(Vertex_t) * vertexs.size() ,&vertexs[0],GL_STATIC_DRAW); glGenBuffers(1,&darktriID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,darktriID); std::vector<short> indexs; indexs.resize(NB_DARK_TRIANGLES * 3); for (int i = 0; i < NB_DARK_TRIANGLES * 3; i++) { indexs[i] = (short)darkTriangles[i] - 1; } glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(short) * indexs.size(),&indexs[0],GL_STATIC_DRAW); glGenBuffers(1,&allumtriID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,allumtriID); indexs.resize(NB_ALLUMINIUM_TRIANGLES * 3); for (int i = 0; i < NB_ALLUMINIUM_TRIANGLES * 3; ++i) { indexs[i] = (short)alluminiumTriangles[i] - 1; } glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(short) * indexs.size(), &indexs[0], GL_STATIC_DRAW); shader.LoadFromFile(GL_VERTEX_SHADER, "shaders/shader.vert"); shader.LoadFromFile(GL_FRAGMENT_SHADER, "shaders/shader.frag"); //compile and link shader shader.CreateAndLinkProgram(); shader.Use(); //add attributes and uniforms shader.AddAttribute("vVertex"); shader.AddUniform("MVP"); shader.AddUniform("ObjColor"); shader.UnUse(); glVertexAttribPointer(0,3,GL_FLOAT,GL_FALSE,sizeof(Vertex_t),(const void *)offsetof(Vertex_t,x)); glEnableVertexAttribArray(0); glVertexAttribPointer(1,4,GL_BYTE,GL_TRUE,sizeof(Vertex_t),(const void *)offsetof(Vertex_t,color)); glEnableVertexAttribArray(1); glBindVertexArray(0); // setPath(path, path_mem); }
31.296296
117
0.641657
balder2046
76c8aee4977befd247672662a0830efb72cbde0c
10,425
cpp
C++
source/printf.cpp
Rohansi/RaspberryPi
8cc24fa49ae7842ee7a9df954fe9672d32826a4b
[ "MIT" ]
3
2015-12-27T21:41:09.000Z
2017-03-28T14:29:09.000Z
source/printf.cpp
Rohansi/RaspberryPi
8cc24fa49ae7842ee7a9df954fe9672d32826a4b
[ "MIT" ]
null
null
null
source/printf.cpp
Rohansi/RaspberryPi
8cc24fa49ae7842ee7a9df954fe9672d32826a4b
[ "MIT" ]
2
2016-01-06T21:26:42.000Z
2021-02-18T16:47:25.000Z
// // Created by Daniel Lindberg on 2015-11-29. // #include <limits.h> #include "string.h" #include "printf.h" #define MAX_INTEGER_SIZE 65 #define FLAG_LEFT_ADJUST 0x01 #define FLAG_ALWAYS_SIGN 0x02 #define FLAG_PREPEND_SPACE 0x04 #define FLAG_ALTERNATIVE 0x08 #define FLAG_PAD_WITH_ZERO 0x10 #define INPUT_TYPE_hh 0 #define INPUT_TYPE_h 1 #define INPUT_TYPE_none 2 #define INPUT_TYPE_l 3 #define INPUT_TYPE_ll 4 #define INPUT_TYPE_j 5 #define INPUT_TYPE_z 6 #define INPUT_TYPE_t 7 #define INPUT_TYPE_L 8 typedef struct { char *buffer; char *buffer_end; } printf_state_t; typedef struct { int flags; size_t min_width; size_t precision; int input_type; int format; } printf_format_t; static size_t render_integer(char *buffer, int base, char ten, unsigned long long int val) { size_t index = MAX_INTEGER_SIZE - 1; buffer[index--] = '\0'; if (base > 10) { do { int mod = (int)(val % base); if (mod < 10) { buffer[index--] = (char)('0' + mod); } else { buffer[index--] = (char)(ten + mod - 10); } val /= base; } while (val != 0); } else { do { buffer[index--] = (char)('0' + val % base); val /= base; } while (val != 0); } return index + 1; } static inline const char *read_format_integer(const char *format) { if (*format == '*') { return format + 1; } while (*format >= '0' && *format <= '9') { format++; } return format; } static inline int parse_format_integer(const char *beg, const char *end) { int result = 0; int multiplier = 1; while (end != beg) { end--; result += multiplier * (*end - '0'); multiplier *= 10; } return result; } static inline void output_char(printf_state_t *state, char c) { if (state->buffer != state->buffer_end) { *state->buffer++ = c; } } static inline void output_n_chars(printf_state_t *state, char c, size_t n) { size_t left = state->buffer_end - state->buffer; n = n > left ? left : n; while (n--) { *state->buffer++ = c; } } static inline void output_string(printf_state_t *state, const char *str, size_t n) { size_t left = state->buffer_end - state->buffer; n = n > left ? left : n; while (n--) { *state->buffer++ = *str++; } } static void write_string(printf_state_t *state, printf_format_t fmt, const char *val) { size_t len = strlen(val); size_t pad = 0; if (fmt.precision != UINT_MAX && len > fmt.precision) { len = (size_t)fmt.precision; } if (len < fmt.min_width) { pad = fmt.min_width - len; } if (!(fmt.flags & FLAG_LEFT_ADJUST)) { output_n_chars(state, ' ', pad); } output_string(state, val, len); if (fmt.flags & FLAG_LEFT_ADJUST) { output_n_chars(state, ' ', pad); } } static void write_signed(printf_state_t *state, printf_format_t fmt, long long int val) { char sign = '\0'; char buffer[MAX_INTEGER_SIZE]; size_t index; size_t length; size_t padding = 0; size_t extra_zeroes = 0; if (fmt.precision == 0 && val == 0) { index = MAX_INTEGER_SIZE - 1; length = 0; buffer[MAX_INTEGER_SIZE - 1] = '\0'; } else { if (val < 0) { index = render_integer(buffer, 10, 'a', -val); } else { index = render_integer(buffer, 10, 'a', val); } length = MAX_INTEGER_SIZE - index - 1; } if (fmt.precision != UINT_MAX && length < fmt.precision) { extra_zeroes = fmt.precision - length; length += extra_zeroes; } if (val < 0 || fmt.flags & FLAG_PREPEND_SPACE || fmt.flags & FLAG_ALWAYS_SIGN) { length += 1; } if (length < fmt.min_width) { padding = fmt.min_width - length; } if (val < 0) { sign = '-'; } else if (fmt.flags & FLAG_ALWAYS_SIGN) { sign = '+'; } else if (fmt.flags & FLAG_PREPEND_SPACE) { sign = ' '; } if (!(fmt.flags & FLAG_LEFT_ADJUST)) { output_n_chars(state, ' ', padding); } if (sign != '\0') { output_char(state, sign); } output_n_chars(state, '0', extra_zeroes); output_string(state, buffer + index, MAX_INTEGER_SIZE - index - 1); if (fmt.flags & FLAG_LEFT_ADJUST) { output_n_chars(state, ' ', padding); } } static void write_unsigned(printf_state_t *state, printf_format_t fmt, unsigned long long int val) { int base = 10; char ten = 'a'; char buffer[MAX_INTEGER_SIZE]; size_t index; size_t length; size_t padding = 0; size_t extra_zeroes = 0; if (fmt.format == 'o') { base = 8; } else if (fmt.format == 'x') { base = 16; } else if (fmt.format == 'X') { base = 16; ten = 'A'; } index = render_integer(buffer, base, ten, val); length = MAX_INTEGER_SIZE - index - 1; if (fmt.format == 'o' && fmt.flags & FLAG_ALTERNATIVE) { if (buffer[index] != '0') { size_t extra_zero = length + 1; fmt.precision = fmt.precision < extra_zero ? extra_zero : fmt.precision; } } else if (fmt.precision == 0 && val == 0) { index = MAX_INTEGER_SIZE - 1; length = 0; buffer[MAX_INTEGER_SIZE - 1] = '\0'; } if (fmt.precision != UINT_MAX && length < fmt.precision) { extra_zeroes = fmt.precision - length; length += extra_zeroes; } if (val != 0 && base == 16 && fmt.flags & FLAG_ALTERNATIVE) { length += 2; } if (length < fmt.min_width) { padding = fmt.min_width - length; } if (!(fmt.flags & FLAG_LEFT_ADJUST)) { output_n_chars(state, ' ', padding); } if (val != 0 && base == 16 && fmt.flags & FLAG_ALTERNATIVE) { output_char(state, '0'); output_char(state, (char) fmt.format); } output_n_chars(state, '0', extra_zeroes); output_string(state, buffer + index, MAX_INTEGER_SIZE - index - 1); if (fmt.flags & FLAG_LEFT_ADJUST) { output_n_chars(state, ' ', padding); } } int vsnprintf(char *buffer, size_t bufsz, const char *format, va_list arg) { printf_state_t state; state.buffer = buffer; state.buffer_end = buffer + bufsz - 1; while (1) { char c = *format++; if (c == '\0') { break; } else if (c != '%') { output_char(&state, c); } else { printf_format_t fmt; fmt.flags = 0; // parse flags while (1) { switch (*format) { case '-': format++; fmt.flags |= FLAG_LEFT_ADJUST; continue; case '+': format++; fmt.flags |= FLAG_ALWAYS_SIGN; continue; case ' ': format++; fmt.flags |= FLAG_PREPEND_SPACE; continue; case '#': format++; fmt.flags |= FLAG_ALTERNATIVE; continue; case '0': format++; fmt.flags |= FLAG_PAD_WITH_ZERO; continue; } break; } // parse minimum width // TODO: duplicated code with precision const char *min_width_beg = format; format = read_format_integer(format); const char *min_width_end = format; fmt.min_width = *min_width_beg == '*' ? va_arg(arg, int) : parse_format_integer(min_width_beg, min_width_end); // parse precision (if there is one) if (*format != '.') { fmt.precision = UINT_MAX; } else { format++; const char *precision_beg = format; format = read_format_integer(format); const char *precision_end = format; fmt.precision = *precision_beg == '*' ? va_arg(arg, int) : parse_format_integer(precision_beg, precision_end); } // parse input type modifier switch (*format) { case 'h': format++; fmt.input_type = *format == 'h' ? INPUT_TYPE_hh : INPUT_TYPE_h; break; case 'l': format++; fmt.input_type = *format == 'l' ? INPUT_TYPE_ll : INPUT_TYPE_l; break; case 'j': format++; fmt.input_type = INPUT_TYPE_j; break; case 'z': format++; fmt.input_type = INPUT_TYPE_z; break; case 't': format++; fmt.input_type = INPUT_TYPE_t; break; case 'L': format++; fmt.input_type = INPUT_TYPE_L; break; default: fmt.input_type = INPUT_TYPE_none; break; } if (fmt.input_type == INPUT_TYPE_hh || fmt.input_type == INPUT_TYPE_ll) { format++; } char str_buf[2]; const char *str_val; long long int signed_val; unsigned long long int unsigned_val; fmt.format = *format++; switch (fmt.format) { case 'c': signed_val = va_arg(arg, int); str_buf[0] = (char)signed_val; str_buf[1] = '\0'; write_string(&state, fmt, str_buf); break; case 's': str_val = va_arg(arg, const char *); write_string(&state, fmt, str_val); break; case 'd': case 'i': signed_val = va_arg(arg, int); write_signed(&state, fmt, signed_val); break; case 'o': case 'x': case 'X': case 'u': unsigned_val = va_arg(arg, unsigned int); write_unsigned(&state, fmt, unsigned_val); break; case 'f': case 'F': case 'e': case 'E': case 'a': case 'A': case 'g': case 'G': case 'n': case 'p': // TODO: us break; } } } *state.buffer++ = '\0'; return (int)(state.buffer - buffer); } int snprintf(char *buffer, size_t bufsz, const char *format, ...) { va_list arg; va_start(arg, format); int ret = vsnprintf(buffer, bufsz, format, arg); va_end(arg); return ret; }
28.561644
126
0.526331
Rohansi
76c94f79b5ba8720a93381adb8428d974c59c32e
10,586
cc
C++
src/procps.cc
thlorenz/procps
b713185dc7b4c82d8cbc9f4be7e345f09df365bb
[ "MIT" ]
5
2016-02-14T11:03:22.000Z
2019-11-27T12:29:36.000Z
src/procps.cc
thlorenz/procps
b713185dc7b4c82d8cbc9f4be7e345f09df365bb
[ "MIT" ]
null
null
null
src/procps.cc
thlorenz/procps
b713185dc7b4c82d8cbc9f4be7e345f09df365bb
[ "MIT" ]
9
2017-08-31T11:03:02.000Z
2021-11-21T14:09:19.000Z
#include <node.h> #include <nan.h> #include "procps.h" #include "proc/sysinfo.h" #include "proc/whattime.h" #include <cassert> #include <time.h> #include <sys/time.h> using v8::FunctionTemplate; using v8::Handle; using v8::Local; using v8::Object; using v8::String; using v8::Number; using v8::Integer; using v8::Int32; using v8::Uint32; using v8::Array; using v8::Value; using v8::Function; #define MAX_PROCS 5000 #define MAX_SLABS 1000 /* * readproc */ /* * By default readproc will consider all processes as valid to parse * and return, but not actually fill in the cmdline, environ, and /proc/#/statm * derived memory fields. * * `flags' (a bitwise-or of PROC_* below) modifies the default behavior. * * The "fill" options will cause more of the proc_t to be filled in. * * The "filter" options all use the second argument as the pointer to a list of objects: * process status', process id's, user id's. * * The third argument is the length of the list (currently only used for lists of user * id's since uid_t supports no convenient termination sentinel.) */ static proc_t **get_proctab(uint32_t flags) { return readproctab(flags); } NAN_METHOD(Readproctab) { NanScope(); // our JS API ensures we always pass flags (defaults if none were given) Local<Integer> flags = args[0].As<Integer>(); assert(flags->IsUint32()); NanCallback *cb = new NanCallback(args[1].As<Function>()); proc_t **proctab = get_proctab(flags->Value()); int len = -1; while(*(proctab + (++len))); assert(len <= MAX_PROCS && "exceeded MAX_PROCS"); Local<Value> argv[MAX_PROCS]; for (int i = 0; i < len; i++) { Proc *proc = new Proc(proctab[i]); argv[i] = proc->Wrap(); } // Passing result by calling function with arguments instead of populating // and returning v8::Array since it's so much faster // This technique came from node: https://github.com/joyent/node/blob/5344d0c1034b28f9e6de914430d8c8436ad85105/src/node_file.cc#L326 // (thanks @trevnorris for explaining it to me) cb->Call(len, argv); NanReturnUndefined(); } /* * sysinfo */ NAN_METHOD(Sysinfo_Meminfo) { NanScope(); Local<Integer> shiftArg = args[0].As<Integer>(); assert(shiftArg->IsUint32()); unsigned long long shift = shiftArg->Value(); NanCallback *cb = new NanCallback(args[1].As<Function>()); meminfo(); #define X(field) NanNew<Uint32>((uint32_t) ((unsigned long long)(field) << 10) >> shift) Local<Value> argv[] = { /* all are unsigned long */ X(kb_main_buffers) , X(kb_main_cached) , X(kb_main_free) , X(kb_main_total) , X(kb_swap_free) , X(kb_swap_total) /* recently introduced */ , X(kb_high_free) , X(kb_high_total) , X(kb_low_free) , X(kb_low_total) /* 2.4.xx era */ , X(kb_active) , X(kb_inact_laundry) , X(kb_inact_dirty) , X(kb_inact_clean) , X(kb_inact_target) , X(kb_swap_cached) /* late 2.4 and 2.6+ only */ /* derived values */ , X(kb_swap_used) , X(kb_main_used) /* 2.5.41+ */ , X(kb_writeback) , X(kb_slab) , X(nr_reversemaps) , X(kb_committed_as) , X(kb_dirty) , X(kb_inactive) , X(kb_mapped) , X(kb_pagetables) }; #undef X cb->Call(sizeof(argv) / sizeof(argv[0]), argv); NanReturnUndefined(); } NAN_METHOD(Sysinfo_Vminfo) { NanScope(); NanCallback *cb = new NanCallback(args[0].As<Function>()); vminfo(); #define X(field) NanNew<Uint32>((uint32_t)field) Local<Value> argv[] = { /* all are unsigned long */ X(vm_nr_dirty) , X(vm_nr_writeback) , X(vm_nr_pagecache) , X(vm_nr_page_table_pages) , X(vm_nr_reverse_maps) , X(vm_nr_mapped) , X(vm_nr_slab) , X(vm_pgpgin) , X(vm_pgpgout) , X(vm_pswpin) , X(vm_pswpout) , X(vm_pgalloc) , X(vm_pgfree) , X(vm_pgactivate) , X(vm_pgdeactivate) , X(vm_pgfault) , X(vm_pgmajfault) , X(vm_pgscan) , X(vm_pgrefill) , X(vm_pgsteal) , X(vm_kswapd_steal) // next 3 as defined by the 2.5.52 kernel , X(vm_pageoutrun) , X(vm_allocstall) }; #undef X cb->Call(sizeof(argv) / sizeof(argv[0]), argv); NanReturnUndefined(); } NAN_METHOD(Sysinfo_Hertz) { NanScope(); /* Herz is globally defined in sysinfo.c */ NanReturnValue(NanNew<Uint32>((uint32_t) Hertz)); } NAN_METHOD(Sysinfo_Getstat) { jiff cpu_use, cpu_nic, cpu_sys, cpu_idl, cpu_iow, cpu_xxx, cpu_yyy, cpu_zzz; unsigned long pgpgin, pgpgout, pswpin, pswpout; unsigned int intr, ctxt; unsigned int running, blocked, btime, processes; NanScope(); NanCallback *cb = new NanCallback(args[0].As<Function>()); getstat(&cpu_use, &cpu_nic, &cpu_sys, &cpu_idl, &cpu_iow, &cpu_xxx, &cpu_yyy, &cpu_zzz, &pgpgin, &pgpgout, &pswpin, &pswpout, &intr, &ctxt, &running, &blocked, &btime, &processes); // FIXME: currently converting 64-bit unigned long long to 32-bit // this works as long as the machine we are looking up hasn't been up for a long time // need to figure out how to correct this by correctly passing 64-bit number to JS layer #define X(field) NanNew<Uint32>((uint32_t) field) Local<Value> argv[] = { X(cpu_use) , X(cpu_nic) , X(cpu_sys) , X(cpu_idl) , X(cpu_iow) , X(cpu_xxx) , X(cpu_yyy) , X(cpu_zzz) , X(pgpgin) , X(pgpgout) , X(pswpin) , X(pswpout) , X(intr) , X(ctxt) , X(running) , X(blocked) , X(btime) , X(processes) }; #undef X cb->Call(sizeof(argv) / sizeof(argv[0]), argv); NanReturnUndefined(); } NAN_METHOD(Sysinfo_GetDiskStat) { NanScope(); NanCallback *cb = new NanCallback(args[0].As<Function>()); disk_stat *disks; partition_stat *partitions; int ndisks = getdiskstat(&disks, &partitions); int npartitions = getpartitions_num(disks, ndisks); // disks Local<Array> wrapDisks = NanNew<Array>(ndisks); for (int i = 0; i < ndisks; i++) { DiskStat *stat = new DiskStat(disks[i]); wrapDisks->Set(i, stat->Wrap()); } // partitions Local<Array> wrapPartitions = NanNew<Array>(npartitions); for (int i = 0; i < npartitions; i++) { PartitionStat *stat = new PartitionStat(partitions[i]); wrapPartitions->Set(i, stat->Wrap()); } Local<Value> argv[] = { wrapDisks, wrapPartitions }; cb->Call(sizeof(argv) / sizeof(argv[0]), argv); NanReturnUndefined(); } // see deps/procps/uptime.c for how to determine uptime since NAN_METHOD(Sysinfo_Uptime) { NanScope(); NanCallback *cb = new NanCallback(args[0].As<Function>()); double uptime_secs, idle_secs; uptime(&uptime_secs, &idle_secs); Local<Value> argv[] = { NanNew<Number>(uptime_secs), NanNew<Number>(idle_secs) }; cb->Call(sizeof(argv) / sizeof(argv[0]), argv); NanReturnUndefined(); } NAN_METHOD(Sysinfo_UptimeSince) { NanScope(); NanCallback *cb = new NanCallback(args[0].As<Function>()); double now, uptime_secs, idle_secs; time_t up_since_secs; struct tm *up_since; struct timeval tim; /* Get the current time and convert it to a double */ gettimeofday(&tim, NULL); now = tim.tv_sec + (tim.tv_usec / 1000000.0); /* Get the uptime and calculate when that was */ uptime(&uptime_secs, &idle_secs); up_since_secs = (time_t) ((now - uptime_secs) + 0.5); /* Show this */ up_since = localtime(&up_since_secs); #define X(field) NanNew<Int32>((uint32_t) field) Local<Value> argv[] = { X(up_since->tm_year + 1900) , X(up_since->tm_mon + 1) , X(up_since->tm_mday) , X(up_since->tm_hour) , X(up_since->tm_min) , X(up_since->tm_sec) , X(up_since->tm_yday) , X(up_since->tm_wday) }; #undef X cb->Call(sizeof(argv) / sizeof(argv[0]), argv); NanReturnUndefined(); } NAN_METHOD(Sysinfo_UptimeString) { NanScope(); Local<Integer> human_readable = args[0].As<Integer>(); assert(human_readable->IsUint32()); NanCallback *cb = new NanCallback(args[1].As<Function>()); char* s = sprint_uptime(human_readable->Value()); Local<Value> argv[] = { NanNew<String>(s) }; cb->Call(1, argv); NanReturnUndefined(); } NAN_METHOD(Sysinfo_Loadavg) { NanScope(); NanCallback *cb = new NanCallback(args[0].As<Function>()); double av[3]; loadavg(&av[0], &av[1], &av[2]); #define X(field) NanNew<Number>(field) Local<Value> argv[] = { X(av[0]), X(av[1]), X(av[2]) }; #undef X cb->Call(sizeof(argv) / sizeof(argv[0]), argv); NanReturnUndefined(); } NAN_METHOD(Sysinfo_GetPidDigits) { NanScope(); NanCallback *cb = new NanCallback(args[0].As<Function>()); unsigned digits = get_pid_digits(); Local<Value> argv[] = { NanNew<Uint32>(digits) }; cb->Call(1, argv); NanReturnUndefined(); } NAN_METHOD(Sysinfo_GetSlabInfo) { NanScope(); NanCallback *cb = new NanCallback(args[0].As<Function>()); struct slab_cache *slabs; unsigned int nSlab = getslabinfo(&slabs); assert(nSlab <= MAX_SLABS && "exceeded MAX_SLABS"); Local<Value> argv[MAX_SLABS]; for (unsigned int i = 0; i < nSlab; i++) { SlabCache *sc = new SlabCache(slabs[i]); argv[i] = sc->Wrap(); } cb->Call(nSlab, argv); NanReturnUndefined(); } void init(Handle<Object> exports) { exports->Set(NanNew<String>("readproctab") , NanNew<FunctionTemplate>(Readproctab)->GetFunction()); exports->Set(NanNew<String>("sysinfo_meminfo") , NanNew<FunctionTemplate>(Sysinfo_Meminfo)->GetFunction()); exports->Set(NanNew<String>("sysinfo_vminfo") , NanNew<FunctionTemplate>(Sysinfo_Vminfo)->GetFunction()); exports->Set(NanNew<String>("sysinfo_Hertz") , NanNew<FunctionTemplate>(Sysinfo_Hertz)->GetFunction()); exports->Set(NanNew<String>("sysinfo_getstat") , NanNew<FunctionTemplate>(Sysinfo_Getstat)->GetFunction()); exports->Set(NanNew<String>("sysinfo_getdiskstat") , NanNew<FunctionTemplate>(Sysinfo_GetDiskStat)->GetFunction()); exports->Set(NanNew<String>("sysinfo_uptime") , NanNew<FunctionTemplate>(Sysinfo_Uptime)->GetFunction()); exports->Set(NanNew<String>("sysinfo_uptimesince") , NanNew<FunctionTemplate>(Sysinfo_UptimeSince)->GetFunction()); exports->Set(NanNew<String>("sysinfo_uptimestring") , NanNew<FunctionTemplate>(Sysinfo_UptimeString)->GetFunction()); exports->Set(NanNew<String>("sysinfo_loadavg") , NanNew<FunctionTemplate>(Sysinfo_Loadavg)->GetFunction()); exports->Set(NanNew<String>("sysinfo_getpiddigits") , NanNew<FunctionTemplate>(Sysinfo_GetPidDigits)->GetFunction()); exports->Set(NanNew<String>("sysinfo_getslabinfo") , NanNew<FunctionTemplate>(Sysinfo_GetSlabInfo)->GetFunction()); } NODE_MODULE(procps, init)
26.59799
134
0.665029
thlorenz
76cebccee3d56683320f6a612249e7a872d7c0ac
3,434
cpp
C++
willow/src/patterns/initaccumulatepattern.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/src/patterns/initaccumulatepattern.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/src/patterns/initaccumulatepattern.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2020 Graphcore Ltd. All rights reserved. #include <popart/error.hpp> #include <popart/graph.hpp> #include <popart/op/add.hpp> #include <popart/op/init.hpp> #include <popart/op/pad.hpp> #include <popart/patterns/initaccumulatepattern.hpp> #include <popart/patterns/patterns.hpp> #include <popart/tensor.hpp> #include <popart/tensorindex.hpp> #include <popart/tensors.hpp> namespace popart { bool InitAccumulatePattern::matches(Op *op) const { // Looking for element-wise binary op (two inputs checked). if (!op->isConvertibleTo<ElementWiseBinaryOp>() or op->input->n() != 2) { return false; } // Ignore ops for which inferTensorMappingToFrom has been modified already. if (!op->settings.inferTensorMappingToFrom.empty()) { return false; } const auto output = op->outTensor(AddOp::getOutIndex()); const auto arg0Idx = ElementWiseBinaryOp::getArg0InIndex(); const auto arg1Idx = ElementWiseBinaryOp::getArg1InIndex(); const auto arg0 = op->inTensor(arg0Idx); const auto arg1 = op->inTensor(arg1Idx); if (!arg0->hasProducer() || !arg1->hasProducer()) { return false; } // Is the arg0 producer an Init op? const auto arg0Producer = arg0->getProducer(); const auto arg0FromInit = arg0Producer->isConvertibleTo<InitOp>(); // Is the arg1 producer an Init op? const auto arg1Producer = arg1->getProducer(); const auto arg1FromInit = arg1Producer->isConvertibleTo<InitOp>(); // One and only one argument should be from an InitOp. if (!(arg0FromInit ^ arg1FromInit)) { return false; } // Check for inplace modification (arg0). uint32_t mods = 0; for (auto reg : op->modifies(arg0Idx)) { if (!reg.isEmpty()) { ++mods; } } const auto inplace0 = (mods > 0); // Check for inplace modification (arg1). mods = 0; for (auto reg : op->modifies(arg1Idx)) { if (!reg.isEmpty()) { ++mods; } } const auto inplace1 = (mods > 0); // Ignore op if either operand is modified inplace. if (inplace0 | inplace1) { return false; } uint32_t ewbConsumers = 0; uint32_t otherConsumers = 0; for (auto consumer : output->consumers.getOps()) { if (consumer->isConvertibleTo<ElementWiseBinaryOp>()) { ++ewbConsumers; } else { ++otherConsumers; } } // The output of this operation should be consumed by at least // one ElementWiseBinary op and no other op type. if (!ewbConsumers || otherConsumers) { return false; } return true; } std::vector<const Tensor *> InitAccumulatePattern::touches(Op *op) const { // This pattern affects the layout or relationship of both inputs. return {op->input->tensor(0), op->input->tensor(1)}; } bool InitAccumulatePattern::apply(Op *op) const { const auto arg0Idx = ElementWiseBinaryOp::getArg0InIndex(); const auto arg1Idx = ElementWiseBinaryOp::getArg1InIndex(); const auto arg0 = op->inTensor(arg0Idx); const auto arg0Producer = arg0->getProducer(); const auto arg0FromInit = arg0Producer->isConvertibleTo<InitOp>(); if (arg0FromInit) { // Infer Arg0 layout from Arg1. op->settings.inferTensorMappingToFrom.insert({arg0Idx, arg1Idx}); } else { // Infer Arg1 layout from Arg0. op->settings.inferTensorMappingToFrom.insert({arg1Idx, arg0Idx}); } return true; } namespace { static PatternCreator<InitAccumulatePattern> InitAccumulatePattern("InitAccumulate"); } } // namespace popart
28.147541
77
0.692196
gglin001
76d4f57531e01891535353830596594b082f7844
2,064
hpp
C++
include/boost/simd/arch/common/scalar/function/if_else_zero.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/arch/common/scalar/function/if_else_zero.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/arch/common/scalar/function/if_else_zero.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
//================================================================================================== /*! @file @copyright 2015 NumScale SAS @copyright 2015 J.T. Lapreste Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_IF_ELSE_ZERO_HPP_INCLUDED #define BOOST_SIMD_ARCH_COMMON_SCALAR_FUNCTION_IF_ELSE_ZERO_HPP_INCLUDED #include <boost/simd/constant/zero.hpp> #include <boost/simd/function/scalar/is_nez.hpp> #include <boost/dispatch/function/overload.hpp> #include <boost/config.hpp> namespace boost { namespace simd { namespace ext { BOOST_DISPATCH_OVERLOAD ( if_else_zero_ , (typename A0, typename A1) , bd::cpu_ , bd::scalar_< logical_<A0> > , bd::scalar_< bd::unspecified_<A1> > ) { BOOST_FORCEINLINE A1 operator() ( A0 a0, A1 const& a1) const BOOST_NOEXCEPT { return is_nez(a0) ? a1 : Zero<A1>(); } }; BOOST_DISPATCH_OVERLOAD ( if_else_zero_ , (typename A0, typename A1) , bd::cpu_ , bd::scalar_< bd::unspecified_<A0> > , bd::scalar_< bd::unspecified_<A1> > ) { BOOST_FORCEINLINE A1 operator() ( A0 const& a0, A1 const& a1) const BOOST_NOEXCEPT { return is_nez(a0) ? a1 : Zero<A1>(); } }; BOOST_DISPATCH_OVERLOAD ( if_else_zero_ , (typename A0) , bd::cpu_ , bd::scalar_< bd::bool_<A0> > , bd::scalar_< bd::bool_<A0> > ) { BOOST_FORCEINLINE bool operator() ( A0 a0, A0 a1) const BOOST_NOEXCEPT { return a0 ? a1 : false; } }; } } } #endif
31.753846
100
0.493702
yaeldarmon
76e3c01117eab50b90b46fcac940cf4a60f2d3f7
47,332
cxx
C++
PWG/muondep/AliMuonAccEffSubmitter.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWG/muondep/AliMuonAccEffSubmitter.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWG/muondep/AliMuonAccEffSubmitter.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include "AliMuonAccEffSubmitter.h" #include "AliAnalysisTriggerScalers.h" #include "AliCDBId.h" #include "AliCDBManager.h" #include "AliCDBStorage.h" #include "AliLog.h" #include "AliMuonOCDBSnapshotGenerator.h" #include "TFile.h" #include "TGrid.h" #include "TGridResult.h" #include "TMap.h" #include "TMath.h" #include "TObjString.h" #include "TROOT.h" #include "TString.h" #include "TSystem.h" #include <cassert> #include <fstream> #include <vector> using std::ifstream; /// \cond CLASSIMP ClassImp(AliMuonAccEffSubmitter); /// \endcond //______________________________________________________________________________ AliMuonAccEffSubmitter::AliMuonAccEffSubmitter(Bool_t localOnly) : AliMuonGridSubmitter(AliMuonGridSubmitter::kAccEff,localOnly), fRatio(-1.0), fFixedNofEvents(10000), fMaxEventsPerChunk(5000), fSplitMaxInputFileNumber(20), fLogOutToKeep(""), fRootOutToKeep(""), fExternalConfig(""), fSnapshotDir(""), fUseAODMerging(kFALSE) { /// default ctor SetupCommon(localOnly); AliWarning("Using default constructor : you will probably need to call a few Set methods to properly configure the object before getting it to do anything usefull"); } /// Normal constructor /// /// \param generator name of the generator to be used (see \ref SetGenerator) /// \param localOnly whether the generated files are meant to be used only locally (i.e. not on the Grid) /// \param generatorVersion optional speficiation to trigger the setup of some external libraries /// /// if generator contains "pythia8" and generatorVersion is given then /// the pythiaversion must represent the integer part XXX of the /// include directory $ALICE_ROOT/PYTHI8/pythiaXXX/include where the file /// Analysis.h is to be found. /// /// if generator contains "pythia6" then generatorVersion should be the /// X.YY part of libpythia6.X.YY.so // //______________________________________________________________________________ AliMuonAccEffSubmitter::AliMuonAccEffSubmitter(const char* generator, Bool_t localOnly, const char* generatorVersion) : AliMuonGridSubmitter(AliMuonGridSubmitter::kAccEff,localOnly), fRatio(-1.0), fFixedNofEvents(10000), fMaxEventsPerChunk(5000), fSplitMaxInputFileNumber(20), fLogOutToKeep(""), fRootOutToKeep(""), fExternalConfig(""), fSnapshotDir(""), fUseAODMerging(kFALSE) { SetupCommon(localOnly); if ( TString(generator).Contains("pythia8",TString::kIgnoreCase) ) { SetMaxEventsPerChunk(500); // 5000 is not reasonable with Pythia8 (and ITS+MUON...) SetCompactMode(2); // keep AOD as for the time being the filtering driven from AODtrain.C cannot // add SPD tracklets to muon AODs. SetVar("VAR_USE_ITS_RECO","1"); SetupPythia8(generatorVersion); SetVar("VAR_TRIGGER_CONFIGURATION","p-p"); } if ( TString(generator).Contains("pythia6",TString::kIgnoreCase) ) { SetMaxEventsPerChunk(500); // 5000 is not reasonable with Pythia6 (and ITS+MUON...) SetCompactMode(2); // keep AOD as for the time being the filtering driven from AODtrain.C cannot // add SPD tracklets to muon AODs. SetupPythia6(generatorVersion); SetVar("VAR_USE_ITS_RECO","1"); SetVar("VAR_TRIGGER_CONFIGURATION","p-p"); } if ( TString(generator).Contains("Powheg") ) { SetupCollision(5023); SetupPowheg("Z"); } SetGenerator(generator); } /// special mode to generate pseudo-ideal simulations /// in order to compute a quick acc x eff /// /// pseudo-ideal simulation means we : /// - use ideal pedestals (mean 0, sigma 1) /// - complete configuration (i.e. all manus are there) /// - raw/full alignment /// - do _not_ cut on the pad status, i.e. disregard occupancy, HV, LV or RejectList completely /// /// we use the real RecoParam, but with a patch to change the status mask to disregard above problems /// //______________________________________________________________________________ AliMuonAccEffSubmitter::AliMuonAccEffSubmitter(const char* generator, Bool_t localOnly, const char* pythia6version, Int_t numberOfEventsForPseudoIdealSimulation, Int_t maxEventsPerChunk) : AliMuonGridSubmitter(AliMuonGridSubmitter::kAccEff,localOnly) { AliWarning("THIS IS A SPECIAL MODE TO GENERATE PSEUDO-IDEAL SIMULATIONS !"); SetupCommon(localOnly); SetupPythia6(pythia6version); SetMaxEventsPerChunk(maxEventsPerChunk); SetGenerator(generator); ShouldOverwriteFiles(true); UseOCDBSnapshots(true); SetVar("VAR_USE_ITS_RECO","0"); SetVar("VAR_TRIGGER_CONFIGURATION","p-p"); SetCompactMode(0); SetAliPhysicsVersion("VO_ALICE@AliPhysics::v5-08-13o-01-1"); MakeNofEventsFixed(numberOfEventsForPseudoIdealSimulation); // 2015 pp // SetVar("VAR_SIM_ALIGNDATA","\"alien://folder=/alice/cern.ch/user/h/hupereir/CDB/LHC15Sim/Ideal\""); // SetVar("VAR_REC_ALIGNDATA","\"alien://folder=/alice/cern.ch/user/h/hupereir/CDB/LHC15Sim/Residual\""); SetVar("VAR_SIM_ALIGNDATA","\"alien://folder=/alice/cern.ch/user/j/jcastill/pp16wrk/LHC16_mcp1vsrealv2_tr_MisAlignCDB\""); SetVar("VAR_REC_ALIGNDATA","\"alien://folder=/alice/data/2016/OCDB\""); SetVar("VAR_MAKE_COMPACT_ESD","1"); } //______________________________________________________________________________ AliMuonAccEffSubmitter::~AliMuonAccEffSubmitter() { // dtor } ///______________________________________________________________________________ Bool_t AliMuonAccEffSubmitter::Generate(const char* jdlname) const { if ( TString(jdlname).Contains("merge",TString::kIgnoreCase) ) { return GenerateMergeJDL(jdlname); } else { return GenerateRunJDL(jdlname); } } ///______________________________________________________________________________ Bool_t AliMuonAccEffSubmitter::GenerateMergeJDL(const char* name) const { /// Create the JDL for merging jobs AliDebug(1,""); std::ostream* os = CreateJDLFile(name); if (!os) { return kFALSE; } Bool_t final = TString(name).Contains("final",TString::kIgnoreCase); (*os) << "# Generated merging jdl (production mode)" << std::endl << "# $1 = run number" << std::endl << "# $2 = merging stage" << std::endl << "# Stage_<n>.xml made via: find <OutputDir> *Stage<n-1>/*root_archive.zip" << std::endl; OutputToJDL(*os,"Packages",GetMapValue("AliPhysics")); OutputToJDL(*os,"Executable",Form("%s/AOD_merge.sh",RemoteDir().Data())); OutputToJDL(*os,"Price","1"); if ( final ) { OutputToJDL(*os,"Jobtag","comment: AliMuonAccEffSubmitter final merging"); } else { OutputToJDL(*os,"Jobtag","comment: AliMuonAccEffSubmitter merging stage $2"); } OutputToJDL(*os,"Workdirectorysize","5000MB"); OutputToJDL(*os,"Validationcommand",Form("%s/validation_merge.sh",RemoteDir().Data())); OutputToJDL(*os,"TTL","7200"); OutputToJDL(*os,"OutputArchive", //"log_archive.zip:stderr,stdout@disk=1", "root_archive.zip:AliAOD.root,AliAOD.Muons.root,Merged.QA.Data.root,AnalysisResults.root@disk=2" ); OutputToJDL(*os,"Arguments",(final ? "2":"1")); // for AOD_merge.sh, 1 means intermediate merging stage, 2 means final merging TObjArray files; files.SetOwner(kTRUE); TIter next(LocalFileList()); TObjString* file; while ( ( file = static_cast<TObjString*>(next())) ) { if ( file->TestBit(BIT(23)) ) { files.Add(new TObjString(Form("LF:%s/%s",RemoteDir().Data(),file->String().Data()))); } } if ( final ) { files.Add(new TObjString(Form("LF:%s/$1/wn.xml",MergedDir().Data()))); } OutputToJDL(*os,"InputFile",files); if ( !final ) { OutputToJDL(*os,"OutputDir",Form("%s/$1/Stage_$2/#alien_counter_03i#",MergedDir().Data())); OutputToJDL(*os,"InputDataCollection",Form("LF:%s/$1/Stage_$2.xml,nodownload",MergedDir().Data())); OutputToJDL(*os,"split","se"); OutputToJDL(*os,"SplitMaxInputFileNumber",Form("%d",GetSplitMaxInputFileNumber())); OutputToJDL(*os,"InputDataListFormat","xml-single"); OutputToJDL(*os,"InputDataList","wn.xml"); } else { OutputToJDL(*os,"OutputDir",Form("%s/$1",MergedDir().Data())); } return kTRUE; } //______________________________________________________________________________ Bool_t AliMuonAccEffSubmitter::GenerateRunJDL(const char* name) const { /// Generate (locally) the JDL to perform the simulation+reco+aod filtering /// (to be then copied to the grid and finally submitted) AliDebug(1,""); std::ostream* os = CreateJDLFile(name); if (!os) { return kFALSE; } OutputToJDL(*os,"Packages",GetMapValue("Generator"),GetMapValue("AliPhysics")); OutputToJDL(*os,"Jobtag","comment: AliMuonAccEffSubmitter RUN $1"); OutputToJDL(*os,"split","production:$2-$3"); OutputToJDL(*os,"Price","1"); OutputToJDL(*os,"OutputDir",Form("%s/$1/#alien_counter_03i#",RemoteDir().Data())); OutputToJDL(*os,"Executable","/alice/bin/aliroot_new"); TObjArray files; files.SetOwner(kTRUE); TIter next(LocalFileList()); TObjString* file; while ( ( file = static_cast<TObjString*>(next())) ) { if ( !file->String().Contains("jdl",TString::kIgnoreCase) && !file->String().Contains("OCDB_") ) { files.Add(new TObjString(Form("LF:%s/%s",RemoteDir().Data(),file->String().Data()))); } } if ( UseOCDBSnapshots() ) { files.Add(new TObjString(Form("LF:%s/OCDB/$1/OCDB_sim.root",RemoteDir().Data()))); files.Add(new TObjString(Form("LF:%s/OCDB/$1/OCDB_rec.root",RemoteDir().Data()))); } OutputToJDL(*os,"InputFile",files); if ( fLogOutToKeep.IsNull() || fRootOutToKeep.IsNull() ) { AliError(Form("Output files not correctly set. Log: %s Root: %s",fLogOutToKeep.Data(),fRootOutToKeep.Data())); delete os; return kFALSE; } else { OutputToJDL(*os,"OutputArchive",fLogOutToKeep.Data(),fRootOutToKeep.Data()); } OutputToJDL(*os,"splitarguments","--run $1 --event #alien_counter# --eventsPerJob $4"); OutputToJDL(*os,"Workdirectorysize","5000MB"); OutputToJDL(*os,"JDLVariables","Packages","OutputDir"); OutputToJDL(*os,"Validationcommand","/alice/validation/validation.sh"); if ( GetVar("VAR_GENERATOR").Contains("pythia",TString::kIgnoreCase) ) { OutputToJDL(*os,"TTL","36000"); } else { OutputToJDL(*os,"TTL","14400"); } return kTRUE; } //______________________________________________________________________________ Bool_t AliMuonAccEffSubmitter::MakeOCDBSnapshots() { /// Run sim.C and rec.C in a special mode to generate OCDB snapshots /// Can only be done after the templates have been copied locally if (!IsValid()) return kFALSE; if (!UseOCDBSnapshots()) return kTRUE; if (!NofRuns()) return kFALSE; AliDebug(1,""); Bool_t ok(kTRUE); const std::vector<int>& runs = RunList(); // we must create some default (perfect) objects for some calibration // data so they'll be picked up by the snapshots // : Pedestals, Config, OccupancyMap, HV, LV AliMuonOCDBSnapshotGenerator ogen(runs[0],Form("local://%s/OCDB",gSystem->WorkingDirectory()),OCDBPath().Data()); ogen.CreateLocalOCDBWithDefaultObjects(kFALSE); for ( std::vector<int>::size_type i = 0; i < runs.size() && ok; ++i ) { Int_t runNumber = runs[i]; TString ocdbSim(Form("%s/OCDB/%d/OCDB_sim.root",LocalSnapshotDir().Data(),runNumber)); TString ocdbRec(Form("%s/OCDB/%d/OCDB_rec.root",LocalSnapshotDir().Data(),runNumber)); ok = kFALSE; if ( !gSystem->AccessPathName(ocdbSim.Data()) && !gSystem->AccessPathName(ocdbRec.Data()) ) { ok = kTRUE; AliWarning(Form("Local OCDB snapshots already there for run %d. Will not redo them. If you want to force them, delete them by hand !",runNumber)); } else { ok = ogen.CreateSnapshot(0,ocdbSim.Data(),GetVar("VAR_SIM_ALIGNDATA")) && ogen.CreateSnapshot(1,ocdbRec.Data(),GetVar("VAR_REC_ALIGNDATA")); } if (ok) { AddToLocalFileList(ocdbRec); AddToLocalFileList(ocdbSim); } } LocalFileList()->Print(); return ok; } //______________________________________________________________________________ Bool_t AliMuonAccEffSubmitter::Merge(Int_t stage, Bool_t dryRun) { /// Submit multiple merging jobs with the format "submit AOD_merge(_final).jdl run# (stage#)". /// Also produce the xml collection before sending jobs /// Initial AODs will be taken from RemoteDir/[RUNNUMBER] while the merged /// ones will be put into MergedDir/[RUNNUMBER] if (!RemoteDirectoryExists(MergedDir().Data())) { AliError(Form("directory %s does not exist", MergedDir().Data())); return kFALSE; } gGrid->Cd(MergedDir().Data()); TString jdl = MergeJDLName(stage==0); if (!RemoteFileExists(jdl.Data())) { AliError(Form("file %s does not exist in %s\n", jdl.Data(), RemoteDir().Data())); return kFALSE; } const std::vector<int>& runs = RunList(); if (runs.empty()) { AliError("No run to work with"); return 0; } TString currRun; TString reply = ""; gSystem->Exec("rm -f __failed__"); Bool_t failedRun = kFALSE; for ( std::vector<int>::size_type i = 0; i < runs.size(); ++i ) { Int_t run = runs[i]; AliInfo(Form("\n --- processing run %d ---\n", run)); TString runDir = Form("%s/%d", MergedDir().Data(), run); if (!RemoteDirectoryExists(runDir.Data())) { AliInfo(Form(" - creating output directory %s\n", runDir.Data())); gSystem->Exec(Form("alien_mkdir -p %s", runDir.Data())); } if (RemoteFileExists(Form("%s/root_archive.zip", runDir.Data()))) { AliWarning(" ! final merging already done"); continue; } Int_t lastStage = GetLastStage(runDir.Data()); if (stage > 0 && stage != lastStage+1) { AliError(Form(" ! lastest merging stage = %d. Next must be stage %d or final stage\n", lastStage, lastStage+1)); continue; } TString wn = (stage > 0) ? Form("Stage_%d.xml", stage) : "wn.xml"; TString find = (lastStage == 0) ? Form("alien_find -x %s %s/%d *root_archive.zip", wn.Data(), RemoteDir().Data(), run) : Form("alien_find -x %s %s/%d/Stage_%d *root_archive.zip", wn.Data(), MergedDir().Data(), run, lastStage); gSystem->Exec(Form("%s 1> %s 2>/dev/null", find.Data(), wn.Data())); gSystem->Exec(Form("grep -c /event %s > __nfiles__", wn.Data())); ifstream f2("__nfiles__"); TString nFiles; nFiles.ReadLine(f2,kTRUE); f2.close(); gSystem->Exec("rm -f __nfiles__"); printf(" - number of files to merge = %d\n", nFiles.Atoi()); if (nFiles.Atoi() == 0) { printf(" ! collection of files to merge is empty\n"); gSystem->Exec(Form("rm -f %s", wn.Data())); continue; } else if (stage > 0 && nFiles.Atoi() <= GetSplitMaxInputFileNumber() && !reply.BeginsWith("y")) { if (!reply.BeginsWith("n")) { printf(" ! number of files to merge <= split level (%d). Continue? [Y/n] ", GetSplitMaxInputFileNumber()); fflush(stdout); reply.Gets(stdin,kTRUE); reply.ToLower(); } if (reply.BeginsWith("n")) { gSystem->Exec(Form("rm -f %s", wn.Data())); continue; } else reply = "y"; } if (!dryRun) { TString dirwn = Form("%s/%s", runDir.Data(), wn.Data()); if (RemoteFileExists(dirwn.Data())) gGrid->Rm(dirwn.Data()); gSystem->Exec(Form("alien_cp file:%s alien://%s", wn.Data(), dirwn.Data())); gSystem->Exec(Form("rm -f %s", wn.Data())); } TString query; if (stage > 0) query = Form("submit %s %d %d", jdl.Data(), run, stage); else query = Form("submit %s %d", jdl.Data(), run); printf(" - %s ...", query.Data()); fflush(stdout); if (dryRun) { AliInfo(" dry run"); continue; } Bool_t done = kFALSE; TGridResult *res = gGrid->Command(query); if (res) { TString cjobId1 = res->GetKey(0,"jobId"); if (!cjobId1.IsDec()) { AliError(" FAILED"); gGrid->Stdout(); gGrid->Stderr(); } else { AliInfo(Form(" DONE\n --> the job Id is: %s \n", cjobId1.Data())); done = kTRUE; } delete res; } else { AliError(" FAILED"); } if (!done) { gSystem->Exec(Form("echo %d >> __failed__", run)); failedRun = kTRUE; } } if (failedRun) { AliInfo("\n--------------------\n"); AliInfo("list of failed runs:\n"); gSystem->Exec("cat __failed__"); gSystem->Exec("rm -f __failed__"); return kFALSE; } return kTRUE; } //______________________________________________________________________________ void AliMuonAccEffSubmitter::Print(Option_t* opt) const { /// Printout AliMuonGridSubmitter::Print(opt); if ( fRatio > 0 ) { std::cout << std::endl << Form("-- For each run, will generate %5.2f times the number of real events for trigger %s", fRatio,ReferenceTrigger().Data()) << std::endl; } else { std::cout << std::endl << Form("-- For each run, will generate %10d events",fFixedNofEvents) << std::endl; } std::cout << "-- MaxEventsPerChunk = " << fMaxEventsPerChunk << std::endl; std::cout << "-- Will" << (UseOCDBSnapshots() ? "" : " NOT") << " use OCDB snaphosts" << std::endl; } //______________________________________________________________________________ Bool_t AliMuonAccEffSubmitter::Run(const char* mode) { /// mode can be one of (case insensitive) /// /// LOCAL : copy the template files from the template directory to the local one /// UPLOAD : copy the local files to the grid (requires LOCAL) /// OCDB : make ocdb snapshots (requires LOCAL) /// SUBMIT : submit the jobs (requires LOCAL + UPLOAD) /// FULL : all of the above (requires all of the above) /// /// TEST : as SUBMIT, but in dry mode (does not actually submit the jobs) /// /// LOCALTEST : completely local test (including execution) if (!IsValid()) return kFALSE; TString smode(mode); smode.ToUpper(); if ( smode == "FULL") { return ( Run("OCDB") && Run("UPLOAD") && Run("SUBMIT") ); } if ( smode == "LOCAL") { return CopyTemplateFilesToLocal(); } if ( smode == "UPLOAD" ) { return (CopyLocalFilesToRemote()); } if ( smode == "OCDB" ) { Bool_t ok = Run("LOCAL"); if (ok) { ok = MakeOCDBSnapshots(); } return ok; } if ( smode == "TEST" ) { Bool_t ok = Run("OCDB") && Run("UPLOAD"); if ( ok ) { ok = (Submit(kTRUE)>0); } return ok; } if ( smode == "FULL" ) { Bool_t ok = Run("OCDB") && Run("UPLOAD"); if ( ok ) { ok = (Submit(kFALSE)>0); } return ok; } if( smode == "SUBMIT" ) { return (Submit(kFALSE)>0); } if ( smode == "LOCALTEST" ) { Bool_t ok = Run("OCDB"); if ( ok ) { ok = LocalTest(); } return ok; } return kFALSE; } /// Set the variable to select the generator macro in Config.C /// generator must contain the name of a macro (without the extension .C) containing /// a function of the same name that returns a pointer to an AliGenerator. /// (see the examples in the template directory). That macro must be compilable. //______________________________________________________________________________ Bool_t AliMuonAccEffSubmitter::SetGenerator(const char* generator) { Invalidate(); TString generatorFile(Form("%s/%s.C",TemplateDir().Data(),generator)); Int_t nofMissingVariables(0); // first check we indeed have such a macro if (!gSystem->AccessPathName(generatorFile.Data())) { TObjArray* variables = GetVariables(generatorFile.Data()); TIter next(variables); TObjString* var; while ( ( var = static_cast<TObjString*>(next())) ) { if ( !Vars()->GetValue(var->String()) ) { ++nofMissingVariables; AliError(Form("file %s expect the variable %s to be defined, but we've not defined it !",generatorFile.Data(),var->String().Data())); } } delete variables; if ( !nofMissingVariables ) { if (CheckCompilation(generatorFile.Data())) { Validate(); SetVar("VAR_GENERATOR",Form("%s",generator)); AddToTemplateFileList(Form("%s.C",generator)); return kTRUE; } } else { return kFALSE; } } else { AliError(Form("Can not work with the macro %s",generatorFile.Data())); } return kFALSE; } /// Sets the OCDB path to be used //______________________________________________________________________________ void AliMuonAccEffSubmitter::SetOCDBPath(const char* ocdbPath) { SetMapKeyValue("OCDBPath",ocdbPath); } /// Change the remote directory used for snapshot //______________________________________________________________________________ void AliMuonAccEffSubmitter::SetOCDBSnapshotDir(const char* dir) { if (gSystem->AccessPathName(Form("%s/OCDB",dir))) { AliError(Form("Snapshot top directory (%s) should contain an OCDB subdir with runnumbers in there",dir)); } else { SetMapKeyValue("OCDBSnapshot",dir); } } /// Specify that the number of simulated events to be produced should be proportional to /// the number of real events of the given trigger. /// \param trigger the reference trigger classname to be used /// \param ratio the proportionality factor to be used (must be positive, can be < 1) //______________________________________________________________________________ void AliMuonAccEffSubmitter::MakeNofEventsPropToTriggerCount(const char* trigger, Float_t ratio) { SetMapKeyValue("ReferenceTrigger",trigger); fRatio = ratio; } /// Make the number of simulated events to be produced a specific one //______________________________________________________________________________ void AliMuonAccEffSubmitter::MakeNofEventsFixed(Int_t nevents) { fFixedNofEvents = nevents; fRatio=0.0; SetMapKeyValue("ReferenceTrigger",""); } //______________________________________________________________________________ Int_t AliMuonAccEffSubmitter::LocalTest() { /// Generate a local macro (simrun.sh) to execute locally a full scale test /// Can only be used with a fixed number of events (and runnumber is fixed to zero) if ( fRatio > 0 ) { AliError("Can only work in local test with a fixed number of events"); return 0; } if ( fFixedNofEvents <= 0 ) { AliError("Please fix the number of input events using MakeNofEventsFixed()"); return 0; } const std::vector<int>& runs = RunList(); if ( runs.empty() ) { AliError("No run to work with"); return 0; } // std::cout << "Generating script to execute : ./simrun.sh" << std::endl; // // std::ofstream out("simrun.sh"); // // out << "#!/bin/bash" << std::endl; //// root.exe -b -q simrun.C --run <x> --chunk <y> --event <n> // out << "root.exe -b -q simrun.C --run "<< runs[0] <<" --event " << fFixedNofEvents << std::endl; // // out.close(); gSystem->Exec("chmod +x simrun.sh"); gSystem->Exec("alien_cp alien:///alice/bin/aliroot_new file:"); gSystem->Exec("chmod u+x aliroot_new"); std::cout << "Cleaning up left-over files from previous simulation/reconstructions" << std::endl; gSystem->Exec("rm -rf TrackRefs.root *.SDigits*.root Kinematics.root *.Hits.root geometry.root gphysi.dat Run*.tag.root HLT*.root *.ps *.Digits.root *.RecPoints.root galice.root *QA*.root Trigger.root *.log AliESD* AliAOD* *.d *.so *.stat pwgevents.lhe pwg*.dat pwg*.top pwhg_checklimits bornequiv FlavRegList"); if ( UseOCDBSnapshots() ) { gSystem->Exec(Form("ln -si %s/OCDB/%d/OCDB_sim.root .",LocalSnapshotDir().Data(),runs[0])); gSystem->Exec(Form("ln -si %s/OCDB/%d/OCDB_rec.root .",LocalSnapshotDir().Data(),runs[0])); } TString command = Form("./aliroot_new --run %i --event 1 --eventsPerJob %i", runs[0], fFixedNofEvents); std::cout << "Executing the script : " << command.Data() << std::endl; gSystem->Exec(command.Data()); return 1; } namespace { void OutputRunList(const char* filename, const std::vector<int>& runlist) { /// output a runlist to ASCII file std::ofstream out(filename); for ( std::vector<int>::size_type j = 0; j < runlist.size(); ++j ) { out << runlist[j] << std::endl; } } } //______________________________________________________________________________ void AliMuonAccEffSubmitter::SetCompactMode ( Int_t mode ) { /// Set the compact mode: /// 0 -> keep all root files + all logs /// 1 -> keep only AOD.Muons + all logs /// 2 -> keep only AODs and AOD.Muons + all logs /// 10 -> keep all root files + stout,stderr /// 11 -> keep only AOD.Muons + stout,stderr /// 12 -> keep only AODs and AOD.Muons + stout,stderr const char* allLogs = "stderr,stdout,*.log"; const char* minLogs = "stderr,stdout"; const char* allRoot = "galice*.root,Kinematics*.root,TrackRefs*.root,AliESDs.root,AliAOD.root,AliAOD.Muons.root,Merged.QA.Data.root,Run*.root"; const char* muonAodRoot = "AliAOD.Muons.root,Merged.QA.Data.root"; const char* aodRoot = "AliAOD.root,Merged.QA.Data.root"; fLogOutToKeep = ""; fRootOutToKeep = ""; switch (mode) { case 0: fLogOutToKeep = allLogs; fRootOutToKeep = allRoot; break; case 1: fLogOutToKeep = allLogs; fRootOutToKeep = muonAodRoot; break; case 2: fLogOutToKeep = allLogs; fRootOutToKeep = aodRoot; break; case 10: fLogOutToKeep = minLogs; fRootOutToKeep = allRoot; break; case 11: fLogOutToKeep = minLogs; fRootOutToKeep = muonAodRoot; break; case 12: fLogOutToKeep = minLogs; fRootOutToKeep = aodRoot; break; default: AliError(Form("Unknown CompactMode %i",mode)); break; } if ( ! fLogOutToKeep.IsNull() ) { fLogOutToKeep.Prepend("log_archive.zip:"); fLogOutToKeep.Append("@disk=1"); } if ( ! fRootOutToKeep.IsNull() ) { fRootOutToKeep.Prepend("root_archive.zip:"); fRootOutToKeep.Append("@disk=2"); } } /// Initialize the variables to some default (possibly sensible) values //____________________________________________________________________________ void AliMuonAccEffSubmitter::SetDefaultVariables() { SetVar("VAR_OCDB_PATH",Form("\"%s\"",OCDBPath().Data())); SetVar("VAR_AOD_MERGE_FILES","\"AliAOD.root,AliAOD.Muons.root\""); SetVar("VAR_EFFTASK_PTMIN","-1."); SetVar("VAR_EXTRATASKS_CONFIGMACRO","\"\""); SetVar("VAR_GENPARAM_INCLUDE","AliGenMUONlib.h"); SetVar("VAR_GENPARAM_NPART","1"); SetVar("VAR_GENPARAM_GENLIB_TYPE","AliGenMUONlib::kJpsi"); SetVar("VAR_GENPARAM_GENLIB_PARNAME","\"pPb 5.03\""); SetVar("VAR_GENCORRHF_QUARK","5"); SetVar("VAR_GENCORRHF_ENERGY","5"); // some default values for J/psi SetVar("VAR_GENPARAMCUSTOM_PDGPARTICLECODE","443"); // default values below are from J/psi p+Pb (from muon_calo pass) SetVar("VAR_GENPARAMCUSTOM_Y_P0","4.08E5"); SetVar("VAR_GENPARAMCUSTOM_Y_P1","7.1E4"); SetVar("VAR_GENPARAMCUSTOM_PT_P0","1.13E9"); SetVar("VAR_GENPARAMCUSTOM_PT_P1","18.05"); SetVar("VAR_GENPARAMCUSTOM_PT_P2","2.05"); SetVar("VAR_GENPARAMCUSTOM_PT_P3","3.34"); // some default values for single muons SetVar("VAR_GENPARAMCUSTOMSINGLE_PTMIN","0.3"); SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P0","135.137"); SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P1","0.555323"); SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P2","0.578374"); SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P3","10.1345"); SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P4","0.000232233"); SetVar("VAR_GENPARAMCUSTOMSINGLE_PT_P5","-0.924726"); SetVar("VAR_GENPARAMCUSTOMSINGLE_Y_P0","1.95551"); SetVar("VAR_GENPARAMCUSTOMSINGLE_Y_P1","-0."); SetVar("VAR_GENPARAMCUSTOMSINGLE_Y_P2","-0.104761"); SetVar("VAR_GENPARAMCUSTOMSINGLE_Y_P3","0."); SetVar("VAR_GENPARAMCUSTOMSINGLE_Y_P4","0.00311324"); // some default values for single muons ben SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PTMIN","0.35"); SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P0","135.137"); SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P1","0.555323"); SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P2","0.578374"); SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P3","10.1345"); SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P4","0.000232233"); SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_PT_P5","-0.924726"); SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_Y_P0","1.95551"); SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_Y_P1","-0.104761"); SetVar("VAR_GENPARAMCUSTOMSINGLEBEN_Y_P2","0.00311324"); // some default values for GenBox SetVar("VAR_GENMUBOX_PTMIN","0"); SetVar("VAR_GENMUBOX_PTMAX","20"); SetVar("VAR_GENMUBOX_YMIN","-4.1"); SetVar("VAR_GENMUBOX_YMAX","-2.4"); SetVar("VAR_PYTHIA8_CMS_ENERGY","8000"); SetVar("VAR_PYTHIA6_CMS_ENERGY","8000"); SetVar("VAR_POWHEG_INPUT","powheg_Z.input"); SetVar("VAR_POWHEG_EXEC","pwhg_main_Z"); SetVar("VAR_POWHEG_SCALE_EVENTS","1"); SetVar("VAR_PURELY_LOCAL","0"); SetVar("VAR_USE_RAW_ALIGN","1"); SetVar("VAR_SIM_ALIGNDATA","\"alien://folder=/alice/simulation/2008/v4-15-Release/Ideal\""); SetVar("VAR_REC_ALIGNDATA","\"alien://folder=/alice/simulation/2008/v4-15-Release/Residual\""); SetVar("VAR_USE_ITS_RECO","0"); SetVar("VAR_USE_MC_VERTEX","1"); SetVar("VAR_VERTEX_SIGMA_X","0.0025"); SetVar("VAR_VERTEX_SIGMA_Y","0.0029"); SetVar("VAR_TRIGGER_CONFIGURATION",""); SetVar("VAR_LHAPDF","liblhapdf"); SetVar("VAR_MUONMCMODE","1"); SetVar("VAR_PYTHIA8_SETENV",""); SetVar("VAR_PYTHIA6_SETENV",""); SetVar("VAR_NEEDS_PYTHIA6", "0"); SetVar("VAR_NEEDS_PYTHIA8", "0"); SetVar("VAR_MAKE_COMPACT_ESD","0"); } /// Enter a mode where we don't need the Grid at all /// Note that this is just for testing purposes as this is a bit /// opposite to the very intent of this class ;-) //____________________________________________________________________________ void AliMuonAccEffSubmitter::SetLocalOnly() { SetVar("VAR_OCDB_PATH","\"local://$ALICE_ROOT/OCDB\""); SetVar("VAR_PURELY_LOCAL","1"); MakeNofEventsFixed(10); } /// Common setup (aka constructor) to the different ways to construct this object //__________________________________________________________________________ void AliMuonAccEffSubmitter::SetupCommon(Bool_t localOnly) { UseOCDBSnapshots(kFALSE); SetCompactMode(1); AddIncludePath("-I$ALICE_ROOT/include"); SetOCDBPath("raw://"); SetDefaultVariables(); if (localOnly) { SetLocalOnly(); } SetLocalDirectory("Snapshot",LocalDir()); SetMaxEventsPerChunk(fMaxEventsPerChunk); if (!localOnly) { MakeNofEventsPropToTriggerCount(); } AddToTemplateFileList("CheckESD.C"); AddToTemplateFileList("CheckAOD.C"); AddToTemplateFileList("AODtrainsim.C", kTRUE); // AddToTemplateFileList("validation.sh"); AddToTemplateFileList("Config.C"); AddToTemplateFileList("rec.C"); AddToTemplateFileList("sim.C"); AddToTemplateFileList("simrun.sh"); AddToTemplateFileList(RunJDLName().Data()); UseExternalConfig(fExternalConfig); } //______________________________________________________________________________ Bool_t AliMuonAccEffSubmitter::SetupCollision ( Double_t cmsEnergy, Int_t lhapdf, const char *nucleons, const char *collSystem, Int_t npdf, Int_t npdfErr ) { /// Setup of the collision system TString nucl(nucleons); TString system(collSystem); Bool_t checkConsistency = kTRUE; if ( system.Contains("p") ) { if ( ! nucl.Contains("p") ) checkConsistency = kFALSE; if ( system == "pp" && nucl != "pp" ) checkConsistency = kFALSE; } if ( ! checkConsistency ) { AliError(Form("Cannot have a %s nucleon collision in %s",nucleons,collSystem)); return kFALSE; } if ( system == "Pbp" && nucl == "pn" ) nucl = "np"; Int_t ih[2] = {1, 1}; for ( Int_t ipart=0; ipart<2; ipart++ ) { if ( nucl[ipart] == 'n' ) ih[1-ipart] = 2; } Int_t zNumber[2] = {1,1}; Int_t aNumber[2] = {1,1}; if ( system == "pPb" || system == "PbPb" ) { aNumber[0] = 208; zNumber[0] = 82; } if ( system == "Pbp" || system == "PbPb") { aNumber[1] = 208; zNumber[1] = 82; } SetVar("VAR_PROJECTILE_NAME",Form("\"%s\"",(ih[0] == 2)?"n":"p")); SetVar("VAR_PROJECTILE_A",Form("%i",aNumber[0])); SetVar("VAR_PROJECTILE_Z",Form("%i",zNumber[0])); SetVar("VAR_TARGET_NAME",Form("\"%s\"",(ih[1] == 2)?"n":"p")); SetVar("VAR_TARGET_A",Form("%i",aNumber[1])); SetVar("VAR_TARGET_Z",Form("%i",zNumber[1])); SetVar("VAR_POWHEG_PROJECTILE",Form("%i",ih[0])); SetVar("VAR_POWHEG_TARGET",Form("%i",ih[1])); SetVar("VAR_PROJECTILE_ENERGY", Form("%gd0",cmsEnergy/2.)); SetVar("VAR_TARGET_ENERGY", Form("%gd0",cmsEnergy/2.)); // FIXME: this is ugly, but necessary to avoid a direct dependence on LHAPDF const Int_t kNsets = 12; Int_t lhaPdfSets[kNsets] = {19170,19150,19070,19050,80060,10040,10100,10050,10041,10042,10800,11000}; TString lhaPdfSetsPythia[kNsets] = {"kCTEQ4L","kCTEQ4M","kCTEQ5L","kCTEQ5M","kGRVLO98","kCTEQ6","kCTEQ61","kCTEQ6m","kCTEQ6l","kCTEQ6ll","kCT10","kCT10nlo"}; const Int_t kNnpdfSets = 4; // EKS98 EPS08 EPS09LO EPS09NLO Int_t npdfSetsPythia[kNnpdfSets] = {0, 8, 9, 19}; Int_t chosenSet = lhapdf; if ( lhapdf >= kNsets ) { for ( Int_t iset=0; iset<kNsets; iset++ ) { if ( lhaPdfSets[iset] == lhapdf ) { chosenSet = iset; break; } } } if ( chosenSet >= kNsets ) { AliError(Form("Cannot find PDF set %i",lhapdf)); return kFALSE; } Int_t chosenNpdfSet = npdf; if ( npdf >= kNnpdfSets ) { for ( Int_t iset=0; iset<kNnpdfSets; iset++ ) { if ( npdfSetsPythia[iset] == npdf ) { chosenNpdfSet = iset; break; } } } if ( chosenNpdfSet >= kNnpdfSets ) { AliError(Form("Cannot find PDF set %i",npdf)); return kFALSE; } SetVar("VAR_LHAPDF_STRUCFUNC_SET",lhaPdfSetsPythia[chosenSet].Data()); SetVar("VAR_NPDF_SET",Form("%i",npdfSetsPythia[chosenNpdfSet])); SetVar("VAR_LHAPDF_SET",Form("%i",lhaPdfSets[chosenSet])); SetVar("VAR_POWHEG_NPDF_SET",Form("%i",chosenNpdfSet)); SetVar("VAR_POWHEG_NPDF_ERR",Form("%i",npdfErr)); return kTRUE; } //______________________________________________________________________________ Bool_t AliMuonAccEffSubmitter::SetupPowheg ( const char *particle, const char* version ) { /// Setup powheg TString part(particle); part.ToUpper(); TString pythiaProc = ""; TString baseName = ""; TString muonPtMin = "0."; if ( part == "CHARM" ) { pythiaProc = "kPyCharmPWHG"; SetVar("VAR_POWHEG_HVQ_MASS","1.5"); SetVar("VAR_POWHEG_HVQ_NCALL1","50000"); SetVar("VAR_POWHEG_HVQ_FOLDCSI","5"); baseName = "hvq"; } else if ( part == "BEAUTY" ) { pythiaProc = "kPyBeautyPWHG"; SetVar("VAR_POWHEG_HVQ_MASS","4.75"); SetVar("VAR_POWHEG_HVQ_NCALL1","10000"); SetVar("VAR_POWHEG_HVQ_FOLDCSI","2"); baseName = "hvq"; } else if ( part == "WPLUS" || part == "WMINUS" ) { pythiaProc = "kPyWPWHG"; SetVar("VAR_POWHEG_IDVECBOS",Form("%i",part.Contains("PLUS")?24:-24)); baseName = "W"; } else if ( part == "Z" ) { pythiaProc = "kPyWPWHG"; SetVar("VAR_POWHEG_ZMASS_LOW", "16"); muonPtMin = "8."; baseName = "Z"; } else { AliError(Form("Unrecognized particle %s",particle)); return kFALSE; } TString powhegInput = Form("powheg_%s.input",baseName.Data()); SetVar("VAR_POWHEG_INPUT",powhegInput.Data()); SetVar("VAR_POWHEG_EXEC",Form("pwhg_main_%s",baseName.Data())); SetVar("VAR_PYTHIA_POWHEG_PROCESS",pythiaProc.Data()); SetVar("VAR_CHILD_PT_MIN", muonPtMin.Data()); for ( Int_t ilist=0; ilist<2; ilist++ ) { TObjArray* fileList = ( ilist == 0 ) ? TemplateFileList() : LocalFileList(); TIter next(fileList); TObjString *str = 0x0; while ( (str = static_cast<TObjString*>(next())) ) { if ( str->String().Contains(".input") ) { fileList->Remove(str); break; } fileList->Compress(); } } AddToTemplateFileList(powhegInput.Data()); SetGeneratorPackage(Form("VO_ALICE@POWHEG::%s",version)); return kTRUE; } //______________________________________________________________________________ void AliMuonAccEffSubmitter::SetupPythia6 ( const char *version ) { /// Setup pythia 6 SetVar("VAR_NEEDS_PYTHIA6", "1"); TString p6env = Form("gSystem->Load(\"libpythia6_%s\");",version); SetVar("VAR_PYTHIA6_SETENV",p6env.Data()); gROOT->ProcessLine(p6env); } ///______________________________________________________________________________ void AliMuonAccEffSubmitter::SetupPythia8 ( const char *version, const char* configStrings ) { /// Setup pythia 6 SetVar("VAR_NEEDS_PYTHIA8", "1"); TString p8env = Form(" gSystem->Setenv(\"PYTHIA8DATA\", gSystem->ExpandPathName(\"$ALICE_ROOT/PYTHIA8/pythia%s/xmldoc\"));\n",version); SetVar("VAR_PYTHIA8_SETENV",p8env.Data()); SetVar("VAR_PYTHIA8_SETUP_STRINGS",Form("\"%s\"",configStrings)); } //______________________________________________________________________________ Int_t AliMuonAccEffSubmitter::SplitRunList(const char* inputList, int maxJobs) { /// In order to be able to submit, split a given runlist into chunks that will /// fit within maxJobs (1500 for a typical user) std::vector<int> runs; AliAnalysisTriggerScalers tmp(inputList); runs = tmp.GetRunList(); AliAnalysisTriggerScalers* ts(0x0); std::vector<int> currentRunList; int nJobs(0); int nTotalJobs(0); int nEvts(0); int nFiles(0); for (std::vector<int>::size_type i=0; i < runs.size(); ++i) { Int_t runNumber = runs[i]; Int_t nEvtRun(fFixedNofEvents); if ( fRatio > 0 ) { if (!ts) { AliInfo(Form("Creating AliAnalysisTriggerScalers from OCDB=%s",OCDBPath().Data())); ts = new AliAnalysisTriggerScalers(runs,OCDBPath().Data()); } AliAnalysisTriggerScalerItem* trigger = ts->GetTriggerScaler(runNumber, "L2A", ReferenceTrigger().Data()); if (!trigger) { AliError(Form("Could not get trigger %s for run %09d",ReferenceTrigger().Data(),runNumber)); continue; } nEvtRun = TMath::Nint(fRatio * trigger->Value()); } Int_t nChunk = 1; while (nEvtRun/nChunk+0.5 > MaxEventsPerChunk()) { ++nChunk; } Int_t nEvtChunk = TMath::Nint(nEvtRun/nChunk + 0.5); nJobs += nChunk; nTotalJobs += nChunk; nEvts += nChunk*nEvtChunk; if ( nJobs > maxJobs ) { ++nFiles; OutputRunList(Form("%s.%d",inputList,nFiles),currentRunList); nJobs = 0; currentRunList.clear(); } currentRunList.push_back(runNumber); } if ( !currentRunList.empty() ) { ++nFiles; OutputRunList(Form("%s.%d",inputList,nFiles),currentRunList); } delete ts; std::cout << Form("input run list was split into %d files. Total number of jobs %d. Total number of events %d", nFiles,nTotalJobs,nEvts) << std::endl; return nFiles; } //______________________________________________________________________________ Int_t AliMuonAccEffSubmitter::Submit(Bool_t dryRun) { /// Submit multiple production jobs with the format "submit jdl 000run#.xml 000run#". /// /// Return the number of submitted (master) jobs /// /// Example: /// - outputDir = "/alice/cern.ch/user/p/ppillot/Sim/LHC10h/JPsiPbPb276/AlignRawVtxRaw/ESDs" /// - runList must contains the list of run number /// - trigger is the (fully qualified) trigger name used to compute the base number of events /// - mult is the factor to apply to the number of trigger to get the number of events to be generated /// (# generated events = # triggers x mult if (!IsValid()) return 0; AliDebug(1,""); gGrid->Cd(RemoteDir()); if (!RemoteFileExists(RunJDLName())) { AliError(Form("file %s does not exist in %s", RunJDLName().Data(), RemoteDir().Data())); return 0; } if ( !NofRuns() ) { AliError("No run list set. Use SetRunList"); return 0; } const std::vector<int>& runs = RunList(); if (runs.empty()) { AliError("No run to work with"); return 0; } // cout << "total number of selected MB events = " << totEvt << endl; // cout << "required number of generated events = " << nGenEvents << endl; // cout << "number of generated events per MB event = " << ratio << endl; // cout << endl; std::cout << "run\tfirstChunk\tlastChunk\teventsPerJob" << std::endl; std::cout << "----------------------" << std::endl; Int_t nJobs(0); Int_t nEvts(0); Bool_t failedRun(kFALSE); AliAnalysisTriggerScalers* ts(0x0); for (std::vector<int>::size_type i=0; i < runs.size(); ++i) { Int_t runNumber = runs[i]; Int_t nEvtRun(fFixedNofEvents); if ( fRatio > 0 ) { if (!ts) { AliInfo(Form("Creating AliAnalysisTriggerScalers from OCDB=%s",OCDBPath().Data())); ts = new AliAnalysisTriggerScalers(runs,OCDBPath().Data()); } AliAnalysisTriggerScalerItem* trigger = ts->GetTriggerScaler(runNumber, "L2A", ReferenceTrigger().Data()); if (!trigger) { AliError(Form("Could not get trigger %s for run %09d",ReferenceTrigger().Data(),runNumber)); continue; } nEvtRun = TMath::Nint(fRatio * trigger->Value()); } Int_t nChunk = nEvtRun/MaxEventsPerChunk(); if ( nChunk == 0 ) nChunk++; Int_t nEvtChunk = 0, delta = MaxEventsPerChunk(); for ( Int_t tmpnChunk=nChunk; tmpnChunk<=nChunk+1; tmpnChunk++ ) { Int_t tmpnEventChunk = TMath::Min(nEvtRun/tmpnChunk,MaxEventsPerChunk()); Int_t tmpDelta = TMath::Abs(tmpnChunk*tmpnEventChunk-nEvtRun); if ( tmpDelta < delta ) { nChunk = tmpnChunk; nEvtChunk = tmpnEventChunk; delta = tmpDelta; } } nJobs += nChunk; nEvts += nChunk*nEvtChunk; std::cout << runNumber << "\t1\t" << nChunk << "\t" << nEvtChunk << std::endl; TString query(Form("submit %s %d 1 %d %d", RunJDLName().Data(), runNumber, nChunk, nEvtChunk)); std::cout << query.Data() << " ..." << std::flush; TGridResult* res = 0x0; if (!dryRun) { res = gGrid->Command(query); } Bool_t done = kFALSE; if (res) { TString cjobId1 = res->GetKey(0,"jobId"); if (!cjobId1.Length()) { std::cout << " FAILED" << std::endl << std::endl; gGrid->Stdout(); gGrid->Stderr(); } else { std::cout << "DONE" << std::endl; std::cout << Form(" --> the job Id is: %s",cjobId1.Data()) << std::endl << std::endl; done = kTRUE; } } else { std::cout << " FAILED" << std::endl << std::endl; } if (!dryRun && !done) { gSystem->Exec(Form("echo %d >> __failed__", runNumber)); failedRun = kTRUE; } delete res; } std::cout << std::endl << "total number of jobs = " << nJobs << std::endl << "total number of generated events = " << nEvts << std::endl << std::endl; if (failedRun) { AliInfo("\n--------------------\n"); AliInfo("list of failed runs:\n"); gSystem->Exec("cat __failed__"); gSystem->Exec("rm -f __failed__"); } delete ts; return nJobs; } //______________________________________________________________________________ void AliMuonAccEffSubmitter::UpdateLocalFileList(Bool_t clearSnapshots) { /// Update the list of local files AliMuonGridSubmitter::UpdateLocalFileList(); if (!NofRuns()) return; if ( clearSnapshots ) { TIter next(LocalFileList()); TObjString* file; while ( ( file = static_cast<TObjString*>(next())) ) { if ( file->String().Contains("OCDB_") ) { LocalFileList()->Remove(file); } } LocalFileList()->Compress(); } const char* type[] = { "sim","rec" }; const std::vector<int>& runs = RunList(); for ( std::vector<int>::size_type i = 0; i < runs.size(); ++i ) { Int_t runNumber = runs[i]; for ( Int_t t = 0; t < 2; ++t ) { TString snapshot(Form("%s/OCDB/%d/OCDB_%s.root",LocalSnapshotDir().Data(),runNumber,type[t])); if ( !gSystem->AccessPathName(snapshot.Data()) ) { AddToLocalFileList(snapshot); } } } } /// Whether or not we should use OCDB snapshots //______________________________________________________________________________ Bool_t AliMuonAccEffSubmitter::UseOCDBSnapshots() const { return GetVar("VAR_OCDB_SNAPSHOT")=="kTRUE"; } //______________________________________________________________________________ void AliMuonAccEffSubmitter::UseOCDBSnapshots(Bool_t flag) { /// Whether or not to use OCDB snapshots /// Using OCDB snapshots will speed-up both the sim and reco initialization /// phases on each worker node, but takes time to produce... /// So using them is not always a win-win... if ( flag ) { SetVar("VAR_OCDB_SNAPSHOT","kTRUE"); } else { SetVar("VAR_OCDB_SNAPSHOT","kFALSE"); } UpdateLocalFileList(); } //______________________________________________________________________________ void AliMuonAccEffSubmitter::UseAODMerging(Bool_t flag) { /// whether or not we should generate JDL for merging AODs fUseAODMerging = flag; AddToTemplateFileList(MergeJDLName(kFALSE).Data()); AddToTemplateFileList(MergeJDLName(kTRUE).Data()); AddToTemplateFileList("AOD_merge.sh"); AddToTemplateFileList("validation_merge.sh"); } /// Use an external config (or the default Config.C if externalConfigFullFilePath="") //______________________________________________________________________________ void AliMuonAccEffSubmitter::UseExternalConfig(const char* externalConfigFullFilePath) { fExternalConfig = externalConfigFullFilePath; if ( fExternalConfig.Length() > 0 ) { AddToTemplateFileList(fExternalConfig); } else { AddToTemplateFileList("Config.C"); } }
29.843632
314
0.655223
maroozm
76e571f497eee37ee1d1c998d036ab36c27fb434
407
cpp
C++
atcoder.jp/abc176/abc176_c/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
atcoder.jp/abc176/abc176_c/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
atcoder.jp/abc176/abc176_c/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { long long n; cin >> n; vector<long long> a(n); for (long long i = 0; i < n; i++) { cin >> a[i]; } long long sum = 0; for (long long i = 1; i < n; i++) { if (a[i - 1] - a[i] > 0) { sum += a[i - 1] - a[i]; a[i] = a[i - 1]; } } cout << sum << endl; }
17.695652
37
0.36855
shikij1
76e80425e6f570ee6e75f0f24157922dde924e0f
14,289
cc
C++
tile/lang/gen_special.cc
redoclag/plaidml
46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314
[ "Apache-2.0" ]
4,535
2017-10-20T05:03:57.000Z
2022-03-30T15:42:33.000Z
tile/lang/gen_special.cc
HOZHENWAI/plaidml
46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314
[ "Apache-2.0" ]
984
2017-10-20T17:16:09.000Z
2022-03-30T05:43:18.000Z
tile/lang/gen_special.cc
HOZHENWAI/plaidml
46d9e8b3f1e1093aab2a0dfa40b2e15e3cc7d314
[ "Apache-2.0" ]
492
2017-10-20T18:22:32.000Z
2022-03-30T09:00:05.000Z
#include "tile/lang/gen_special.h" #include <exception> #include <map> #include <memory> #include <utility> #include "base/util/logging.h" #include "tile/lang/gid.h" #include "tile/lang/ops.h" #include "tile/lang/sembuilder.h" #include "tile/lang/semprinter.h" namespace vertexai { namespace tile { namespace lang { static void GenGather(KernelList& r, const Op& op, const Bindings& bindings, // NOLINT(runtime/references) const std::string& kname, const HardwareSettings& settings) { using namespace vertexai::tile::sem::builder; // NOLINT IVLOG(3, "Making a gather"); // Extract shapes to locals const TensorShape out_shape = bindings.at(op.output).shape; const TensorShape data_shape = bindings.at(op.inputs[0]).shape; const TensorShape idx_shape = bindings.at(op.inputs[1]).shape; // Make an empty function body auto body = _Block({}); // Generate expressions for the GIDs. std::vector<size_t> lidx_sizes; for (const auto& d : idx_shape.dims) { lidx_sizes.push_back(d.size); } for (const auto& d : data_shape.dims) { lidx_sizes.push_back(d.size); } auto gids = gid::MakeMap(settings.goal_dimension_sizes, lidx_sizes); std::vector<sem::ExprPtr> gid_vars; gid_vars.reserve(gids.gid_sizes.size()); for (std::size_t idx = 0; idx < gids.gid_sizes.size(); ++idx) { std::string var = "gidx" + std::to_string(idx); body->append(_Declare({sem::Type::INDEX}, var, _Index(sem::IndexExpr::GLOBAL, idx))); gid_vars.push_back(_(var)); } // Generate expressions for the logical dimension indicies. std::vector<sem::ExprPtr> lid_vars; lid_vars.reserve(gids.dims.size()); for (std::size_t idx = 0; idx < gids.dims.size(); ++idx) { std::string var = "lidx" + std::to_string(idx); auto index = gid::LogicalIndex(gid_vars, gids.dims[idx]); body->append(_Declare({sem::Type::INDEX}, var, index)); lid_vars.push_back(_(var)); } // Generate the output offset sem::ExprPtr out_offset = _Const(0); for (size_t i = 0; i < out_shape.dims.size(); i++) { if (i < idx_shape.dims.size()) { out_offset = out_offset + lid_vars[i] * out_shape.dims[i].stride; } else { out_offset = out_offset + lid_vars[i + 1] * out_shape.dims[i].stride; } } // Generate the index offset sem::ExprPtr idx_offset = _Const(0); for (size_t i = 0; i < idx_shape.dims.size(); i++) { idx_offset = idx_offset + lid_vars[i] * idx_shape.dims[i].stride; } // Generate the data offset sem::ExprPtr data_offset = _Clamp(_("idx")[idx_offset], _Const(0), _Const(data_shape.dims[0].size - 1)); data_offset = data_offset * data_shape.dims[0].stride; for (size_t i = 1; i < data_shape.dims.size(); i++) { data_offset = data_offset + lid_vars[idx_shape.dims.size() + i] * data_shape.dims[i].stride; } // Copy the data across body->append(_("out")[out_offset] = _("data")[data_offset]); // Build function params sem::Function::params_t params; params.push_back(std::make_pair(sem::Type(sem::Type::POINTER_MUT, out_shape.type, 1, 0, sem::Type::GLOBAL), "out")); params.push_back( std::make_pair(sem::Type(sem::Type::POINTER_CONST, data_shape.type, 1, 0, sem::Type::GLOBAL), "data")); params.push_back(std::make_pair(sem::Type(sem::Type::POINTER_CONST, idx_shape.type, 1, 0, sem::Type::GLOBAL), "idx")); // Set kernel info KernelInfo ki; ki.kname = kname; ki.outputs.push_back(op.output); ki.inputs.push_back(r.var_rewrites.Lookup(op.inputs[0])); ki.inputs.push_back(r.var_rewrites.Lookup(op.inputs[1])); ki.kfunc = std::make_shared<sem::Function>(kname, sem::Type(sem::Type::TVOID), params, body); auto grids = gid::ComputeGrids(gids, settings.threads); uint64_t out_size = out_shape.elem_size(); ki.gwork = grids.first; ki.lwork = grids.second; ki.tot_bytes = out_size * ((bit_width(out_shape.type) + 7) / 8); ki.tot_flops = out_size; auto pb = ki.info.mutable_special(); pb->set_fn(op.f.fn); ki.info.set_flops(ki.tot_flops); ki.info.set_bytes(ki.tot_bytes); // Dump the code sem::Print dump(*ki.kfunc); IVLOG(4, "CODE:\n" << dump.str()); IVLOG(4, "gwork: " << ki.gwork << ", lwork: " << ki.lwork); // Add to kernel list r.kernels.push_back(ki); } static void GenScatter(KernelList& r, const Op& op, const Bindings& bindings, // NOLINT(runtime/references) const std::string& kname, const HardwareSettings& settings) { using namespace vertexai::tile::sem::builder; // NOLINT IVLOG(3, "Making a scatter"); // Extract shapes to locals const TensorShape out_shape = bindings.at(op.output).shape; const TensorShape expn_shape = bindings.at(op.inputs[0]).shape; const TensorShape idx_shape = bindings.at(op.inputs[1]).shape; const TensorShape val_shape = bindings.at(op.inputs[2]).shape; // Make an empty function body auto body = _Block({}); // Generate expressions for the GIDs. std::vector<size_t> lidx_sizes; for (size_t i = idx_shape.dims.size(); i < expn_shape.dims.size(); ++i) { lidx_sizes.push_back(expn_shape.dims[i].size); } auto gids = gid::MakeMap(settings.goal_dimension_sizes, lidx_sizes); std::vector<sem::ExprPtr> gid_vars; gid_vars.reserve(gids.gid_sizes.size()); for (std::size_t idx = 0; idx < gids.gid_sizes.size(); ++idx) { std::string var = "gidx" + std::to_string(idx); body->append(_Declare({sem::Type::INDEX}, var, _Index(sem::IndexExpr::GLOBAL, idx))); gid_vars.push_back(_(var)); } // Generate expressions for the logical dimension indicies. std::vector<sem::ExprPtr> lid_vars; lid_vars.reserve(gids.dims.size()); for (std::size_t idx = 0; idx < gids.dims.size(); ++idx) { std::string var = "lidx" + std::to_string(idx); auto index = gid::LogicalIndex(gid_vars, gids.dims[idx]); body->append(_Declare({sem::Type::INDEX}, var, index)); lid_vars.push_back(_(var)); } // inner is what will be inside the for loops over the index dimensions auto inner = _Block({}); // Generate the expansion offset sem::ExprPtr expn_offset = _Const(0); for (size_t i = 0; i < expn_shape.dims.size(); i++) { if (i < idx_shape.dims.size()) { expn_offset = expn_offset + _("i_" + std::to_string(i)) * expn_shape.dims[i].stride; } else { expn_offset = expn_offset + lid_vars[i - idx_shape.dims.size()] * expn_shape.dims[i].stride; } } inner->append(_Declare({sem::Type::INDEX}, "expn_offset", expn_offset)); // Generate the index offset sem::ExprPtr idx_offset = _Const(0); for (size_t i = 0; i < idx_shape.dims.size(); i++) { idx_offset = idx_offset + _("i_" + std::to_string(i)) * idx_shape.dims[i].stride; } inner->append(_Declare({sem::Type::INDEX}, "idx_offset", idx_offset)); // Generate the output offset sem::ExprPtr out_offset = _Clamp(_("idx")[_("idx_offset")], _Const(0), _Const(out_shape.dims[0].size - 1)); out_offset = out_offset * out_shape.dims[0].stride; for (size_t i = 1; i < out_shape.dims.size(); i++) { out_offset = out_offset + lid_vars[i - 1] * out_shape.dims[i].stride; } inner->append(_Declare({sem::Type::INDEX}, "out_offset", out_offset)); // Add in this entry inner->append(_("out")[_("out_offset")] = _("out")[_("out_offset")] + _("expn")[_("expn_offset")]); // Loop over the index dimensions for (size_t i = 0; i < idx_shape.dims.size(); ++i) { auto next = _Block({}); next->append(_For("i_" + std::to_string(i), idx_shape.dims[i].size, 1, inner)); inner = next; } body->append(inner); // Build function params sem::Function::params_t params; params.push_back(std::make_pair(sem::Type(sem::Type::POINTER_MUT, out_shape.type, 1, 0, sem::Type::GLOBAL), "out")); params.push_back( std::make_pair(sem::Type(sem::Type::POINTER_CONST, expn_shape.type, 1, 0, sem::Type::GLOBAL), "expn")); params.push_back(std::make_pair(sem::Type(sem::Type::POINTER_CONST, idx_shape.type, 1, 0, sem::Type::GLOBAL), "idx")); // Set kernel info KernelInfo ki; ki.kname = kname; ki.outputs.push_back(op.output); ki.inputs.push_back(r.var_rewrites.Lookup(op.inputs[0])); ki.inputs.push_back(r.var_rewrites.Lookup(op.inputs[1])); ki.kfunc = std::make_shared<sem::Function>(kname, sem::Type(sem::Type::TVOID), params, body); auto grids = gid::ComputeGrids(gids, settings.threads); uint64_t out_size = out_shape.elem_size(); ki.gwork = grids.first; ki.lwork = grids.second; ki.tot_bytes = out_size * ((bit_width(out_shape.type) + 7) / 8); ki.tot_flops = out_size; auto pb = ki.info.mutable_special(); pb->set_fn(op.f.fn); ki.info.set_flops(ki.tot_flops); ki.info.set_bytes(ki.tot_bytes); // Dump the code sem::Print dump(*ki.kfunc); IVLOG(4, "CODE:\n" << dump.str()); IVLOG(4, "gwork: " << ki.gwork << ", lwork: " << ki.lwork); // Add to kernel list r.kernels.push_back(ki); } static void GenShape(KernelList& r, const Op& op, const Bindings& bindings, // NOLINT(runtime/references) const std::string& kname, const HardwareSettings& setting) { using namespace vertexai::tile::sem::builder; // NOLINT IVLOG(3, "Making a shape"); // Extract shapes to locals const TensorShape out_shape = bindings.at(op.output).shape; const TensorShape data_shape = bindings.at(op.inputs[0]).shape; // Make an empty function body auto body = _Block({}); for (int i = 0; i < data_shape.dims.size(); i++) { sem::ExprPtr out_offset = _Const(i); body->append(_("out")[out_offset] = data_shape.dims[i].size); } sem::Function::params_t params; params.push_back(std::make_pair(sem::Type(sem::Type::POINTER_MUT, out_shape.type, 1, 0, sem::Type::GLOBAL), "out")); KernelInfo ki; ki.kname = kname; ki.outputs.push_back(op.output); ki.kfunc = std::make_shared<sem::Function>(kname, sem::Type(sem::Type::TVOID), params, body); uint64_t out_size = out_shape.elem_size(); IVLOG(4, "OUT_SIZE:\n" << out_size); ki.gwork = {{1, 1, 1}}; ki.lwork = {{1, 1, 1}}; ki.tot_bytes = out_size * ((bit_width(out_shape.type) + 7) / 8); ki.tot_flops = out_size; auto pb = ki.info.mutable_special(); pb->set_fn(op.f.fn); ki.info.set_flops(ki.tot_flops); ki.info.set_bytes(ki.tot_bytes); // Dump the code sem::Print dump(*ki.kfunc); IVLOG(4, "CODE:\n" << dump.str()); // Add to kernel list r.kernels.push_back(ki); } static void GenPRNG(KernelList& r, const Op& op, const Bindings& bindings, // NOLINT(runtime/references) const std::string& kname, const HardwareSettings& setting) { using namespace vertexai::tile::sem::builder; // NOLINT IVLOG(3, "Making PRNG"); if (op.inputs.size() < 1) { throw std::runtime_error("prng must have at least one parameter"); } if (op.f.params.size() != 2) { throw std::runtime_error("prng not properly part of triple"); } std::string sout = op.f.params[0]; std::string vout = op.f.params[1]; // Extract shapes to locals const TensorShape out_shape = bindings.at(vout).shape; // Predeclare types for nice syntax auto idx_type = sem::Type(sem::Type::INDEX); auto uint32_type = sem::Type(sem::Type::VALUE, DataType::UINT32); auto float_type = sem::Type(sem::Type::VALUE, DataType::FLOAT32); // Make function body auto body = _Block({}); body->append(_Declare(idx_type, "i", _Index(sem::IndexExpr::GLOBAL, 0))); body->append(_Declare(uint32_type, "s1", _("state_in")[_("i") + 0 * k_rng_size])); body->append(_Declare(uint32_type, "s2", _("state_in")[_("i") + 1 * k_rng_size])); body->append(_Declare(uint32_type, "s3", _("state_in")[_("i") + 2 * k_rng_size])); auto loop = _Block({}); loop->append(_("s1") = (((_("s1") & 4294967294) << 12) ^ (((sem::ExprPtr(_("s1")) << 13) ^ _("s1")) >> 19))); loop->append(_("s2") = (((_("s2") & 4294967288) << 4) ^ (((sem::ExprPtr(_("s2")) << 2) ^ _("s2")) >> 25))); loop->append(_("s3") = (((_("s3") & 4294967280) << 17) ^ (((sem::ExprPtr(_("s3")) << 3) ^ _("s3")) >> 11))); loop->append(_("out")[_("i")] = _Cast(float_type, _("s1") ^ _("s2") ^ _("s3")) / _Const(4294967296.0)); loop->append(_("i") = _("i") + k_rng_size); body->append(_While(_("i") < out_shape.elem_size(), loop)); body->append(_("i") = _Index(sem::IndexExpr::GLOBAL, 0)); body->append(_("state_out")[_("i") + 0 * k_rng_size] = _("s1")); body->append(_("state_out")[_("i") + 1 * k_rng_size] = _("s2")); body->append(_("state_out")[_("i") + 2 * k_rng_size] = _("s3")); sem::Function::params_t params; params.push_back( std::make_pair(sem::Type(sem::Type::POINTER_MUT, DataType::FLOAT32, 1, 0, sem::Type::GLOBAL), "out")); params.push_back( std::make_pair(sem::Type(sem::Type::POINTER_MUT, DataType::UINT32, 1, 0, sem::Type::GLOBAL), "state_out")); params.push_back( std::make_pair(sem::Type(sem::Type::POINTER_CONST, DataType::UINT32, 1, 0, sem::Type::GLOBAL), "state_in")); KernelInfo ki; ki.kname = kname; ki.outputs.push_back(vout); ki.outputs.push_back(sout); ki.inputs.push_back(r.var_rewrites.Lookup(op.inputs[0])); ki.kfunc = std::make_shared<sem::Function>(kname, sem::Type(sem::Type::TVOID), params, body); uint64_t out_size = out_shape.elem_size(); ki.gwork = {{k_rng_size, 1, 1}}; ki.lwork = {{size_t(setting.threads), 1, 1}}; ki.tot_bytes = out_size * ((bit_width(out_shape.type) + 7) / 8); ki.tot_flops = out_size; auto pb = ki.info.mutable_special(); pb->set_fn(op.f.fn); ki.info.set_flops(ki.tot_flops); ki.info.set_bytes(ki.tot_bytes); // Dump the code sem::Print dump(*ki.kfunc); IVLOG(3, "CODE:\n" << dump.str()); // Add to kernel list r.kernels.push_back(ki); } void GenSpecial(KernelList& r, const Op& op, const Bindings& bindings, // NOLINT(runtime/references) const std::string& kname, const HardwareSettings& settings) { IVLOG(3, "Making special kernel " << op.f.fn); if (op.f.fn == "gather") { GenGather(r, op, bindings, kname, settings); } else if (op.f.fn == "scatter") { GenScatter(r, op, bindings, kname, settings); } else if (op.f.fn == "shape") { GenShape(r, op, bindings, kname, settings); } else if (op.f.fn == "prng_step") { GenPRNG(r, op, bindings, kname, settings); } else { throw std::runtime_error("Unknown special function"); } } } // namespace lang } // namespace tile } // namespace vertexai
39.472376
120
0.654629
redoclag
76ec34d5e9013b663a976d1ec8b0e86c06081e50
650
cpp
C++
Sources/CryGame C++/Solution1/STLPORT/test/regression/lexcmp1.cpp
fromasmtodisasm/CryENGINE_MOD_SDK
0b242ffcf615cdc0177f6c96b03b4d60a4338321
[ "FSFAP" ]
14
2016-05-09T01:14:03.000Z
2021-10-12T21:41:02.000Z
src/STLport/test/regression/lexcmp1.cpp
aestesis/elektronika
870f72ca7f64942f8316b3cd8f733f43c7d2d117
[ "Apache-2.0" ]
null
null
null
src/STLport/test/regression/lexcmp1.cpp
aestesis/elektronika
870f72ca7f64942f8316b3cd8f733f43c7d2d117
[ "Apache-2.0" ]
6
2015-08-19T01:28:54.000Z
2020-10-25T05:17:08.000Z
// STLport regression testsuite component. // To compile as a separate example, please #define MAIN. #include <iostream> #include <algorithm> #ifdef MAIN #define lexcmp1_test main #endif #if !defined (STLPORT) || defined(__STL_USE_NAMESPACES) using namespace std; #endif int lexcmp1_test(int, char**) { cout<<"Results of lexcmp1_test:"<<endl; const unsigned size = 6; char n1[size] = "shoe"; char n2[size] = "shine"; bool before = lexicographical_compare(n1, n1 + size, n2, n2 + size); if(before) cout << n1 << " is before " << n2 << endl; else cout << n2 << " is before " << n1 << endl; return 0; }
23.214286
71
0.64
fromasmtodisasm
76f414310d4339aaf3d0b460446f0cf8c02a9f17
1,078
cpp
C++
Photon/photon/util/Transform.cpp
tatjam/Photon
a0c1584d10e1422cc2e468a6f94351a8310b7599
[ "MIT" ]
1
2017-05-28T12:10:30.000Z
2017-05-28T12:10:30.000Z
Photon/photon/util/Transform.cpp
tatjam/Photon
a0c1584d10e1422cc2e468a6f94351a8310b7599
[ "MIT" ]
null
null
null
Photon/photon/util/Transform.cpp
tatjam/Photon
a0c1584d10e1422cc2e468a6f94351a8310b7599
[ "MIT" ]
null
null
null
#include "Transform.h" namespace ph { glm::mat4 Transform::buildMatrix() { mat = glm::mat4(); mat = glm::translate(mat, pos); glm::mat4 rotm = glm::mat4_cast(rot); mat *= rotm; mat = glm::scale(mat, scale); return mat; } void Transform::rotEuler(glm::vec3 eu) { glm::quat qP = glm::angleAxis(glm::radians(eu.x), glm::vec3(1, 0, 0)); glm::quat qY = glm::angleAxis(glm::radians(eu.y), glm::vec3(0, 1, 0)); glm::quat qR = glm::angleAxis(glm::radians(eu.z), glm::vec3(0, 0, 1)); rot = qP * qY * qR; } glm::vec3 Transform::getEuler() { return glm::eulerAngles(rot); } void Transform::move(glm::vec3 o) { pos += o; buildMatrix(); } void Transform::rotate(glm::vec3 eu) { glm::vec3 curr = getEuler(); curr += eu; glm::quat qP = glm::angleAxis(glm::radians(curr.x), glm::vec3(1, 0, 0)); glm::quat qY = glm::angleAxis(glm::radians(curr.y), glm::vec3(0, 1, 0)); glm::quat qR = glm::angleAxis(glm::radians(curr.z), glm::vec3(0, 0, 1)); rot = qP * qY * qR; } Transform::Transform() { } Transform::~Transform() { } }
17.966667
74
0.59462
tatjam
76f529c822bc107727ad263e023f4c0149759b69
1,576
hpp
C++
redist/inc/imqdst.hpp
gmarcon83/mq-mqi-nodejs
27d44772254d0d76438022c6305277f603ff6acb
[ "Apache-2.0" ]
null
null
null
redist/inc/imqdst.hpp
gmarcon83/mq-mqi-nodejs
27d44772254d0d76438022c6305277f603ff6acb
[ "Apache-2.0" ]
null
null
null
redist/inc/imqdst.hpp
gmarcon83/mq-mqi-nodejs
27d44772254d0d76438022c6305277f603ff6acb
[ "Apache-2.0" ]
null
null
null
/* @(#) MQMBID sn=p924-L211104 su=_OdbBaj17EeygWfM06SbNXw pn=include/imqdst.pre_hpp */ #ifndef _IMQDST_HPP_ #define _IMQDST_HPP_ // Library: IBM MQ // Component: IMQI (IBM MQ C++ MQI) // Part: IMQDST.HPP // // Description: "ImqDistributionList" class declaration // <copyright // notice="lm-source-program" // pids="" // years="1994,2016" // crc="257479060" > // Licensed Materials - Property of IBM // // // // (C) Copyright IBM Corp. 1994, 2016 All Rights Reserved. // // US Government Users Restricted Rights - Use, duplication or // disclosure restricted by GSA ADP Schedule Contract with // IBM Corp. // </copyright> #include <imqque.hpp> // ImqQueue #define ImqDistributionList ImqDst class IMQ_EXPORTCLASS ImqDistributionList : public ImqQueue { ImqQueue * opfirstDistributedQueue; protected : friend class ImqQueue ; // Overloaded "ImqObject" methods: virtual void openInformationDisperse ( ); virtual ImqBoolean openInformationPrepare ( ); // Overloaded "ImqQueue" methods: virtual void putInformationDisperse ( ImqPmo & ); virtual ImqBoolean putInformationPrepare ( const ImqMsg &, ImqPmo & ); // New methods: void setFirstDistributedQueue ( ImqQueue * pqueue = 0 ) { opfirstDistributedQueue = pqueue ; } public : // New methods: ImqDistributionList ( ); ImqDistributionList ( const ImqDistributionList & ); virtual ~ ImqDistributionList ( ); void operator = ( const ImqDistributionList & ); ImqQueue * firstDistributedQueue ( ) const { return opfirstDistributedQueue ; } } ; #endif
28.142857
86
0.706853
gmarcon83
76f885c2f0a786d1eecf066cc26c0cf3da44d3a2
230
cpp
C++
src/plane_traits.cpp
richard-vock/triplet_match
a0375e75e08357c71b8b3945cb508ffb519121f8
[ "CC0-1.0" ]
3
2019-02-14T16:55:33.000Z
2022-02-07T13:08:47.000Z
src/plane_traits.cpp
richard-vock/triplet_match
a0375e75e08357c71b8b3945cb508ffb519121f8
[ "CC0-1.0" ]
1
2019-02-14T17:10:37.000Z
2019-02-14T17:10:37.000Z
src/plane_traits.cpp
richard-vock/triplet_match
a0375e75e08357c71b8b3945cb508ffb519121f8
[ "CC0-1.0" ]
null
null
null
#include <plane_traits> #include <impl/plane_traits.hpp> namespace triplet_match { #define INSTANTIATE_PCL_POINT_TYPE(type) \ template struct plane_traits<type>; #include "pcl_point_types.def" } // namespace triplet_match
20.909091
42
0.782609
richard-vock
76fa0b5358e9073caaf294c15fc60955f02be592
3,010
cpp
C++
src/stms/curl.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2021-10-02T19:31:14.000Z
2021-10-02T19:31:14.000Z
src/stms/curl.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2020-06-17T01:15:45.000Z
2020-06-17T01:16:08.000Z
src/stms/curl.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2020-10-17T23:57:27.000Z
2020-10-17T23:57:27.000Z
// // Created by grant on 6/2/20. // #include "stms/curl.hpp" #include <mutex> #include "stms/logging.hpp" namespace stms { void initCurl() { curl_global_init(CURL_GLOBAL_SSL | CURL_GLOBAL_WIN32); auto version = curl_version_info(CURLVERSION_NOW); STMS_INFO("LibCURL {}: On host '{}' with libZ {} & SSL {}", version->version, version->host, version->libz_version, version->ssl_version); } void quitCurl() { curl_global_cleanup(); } static size_t curlWriteCb(void *buf, size_t size, size_t nmemb, void *userDat) { auto dat = reinterpret_cast<CURLHandle *>(userDat); std::lock_guard<std::mutex> lg(dat->resultMtx); dat->result.append(reinterpret_cast<char *>(buf), size * nmemb); return size * nmemb; } static int curlProgressCb(void *userDat, double dTotal, double dNow, double uTotal, double uNow) { auto dat = reinterpret_cast<CURLHandle *>(userDat); dat->downloadTotal = dTotal; dat->downloadSoFar = dNow; dat->uploadSoFar = uNow; dat->uploadTotal = uTotal; return 0; } CURLHandle::CURLHandle(PoolLike *inPool) : pool(inPool), handle(curl_easy_init()) { curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, curlWriteCb); curl_easy_setopt(handle, CURLOPT_WRITEDATA, this); curl_easy_setopt(handle, CURLOPT_NOPROGRESS, 0); curl_easy_setopt(handle, CURLOPT_PROGRESSFUNCTION, curlProgressCb); curl_easy_setopt(handle, CURLOPT_PROGRESSDATA, this); } CURLHandle::~CURLHandle() { curl_easy_cleanup(handle); handle = nullptr; } std::future<CURLcode> CURLHandle::perform() { result.clear(); // Should we require the client to explicitly request this? std::shared_ptr<std::promise<CURLcode>> prom = std::make_shared<std::promise<CURLcode>>(); pool.load()->submitTask([=]() { auto err = curl_easy_perform(handle); // This is typically an expensive call so we async it if (err != CURLE_OK) { STMS_ERROR("Failed to perform curl operation on url {}", url); // We can't throw an exception so :[ } prom->set_value(err); }); return prom->get_future(); } CURLHandle &CURLHandle::operator=(CURLHandle &&rhs) noexcept { if (&rhs == this || rhs.handle.load() == handle.load()) { return *this; } std::lock_guard<std::mutex> rlg(rhs.resultMtx); std::lock_guard<std::mutex> tlg(resultMtx); result = std::move(rhs.result); downloadSoFar = rhs.downloadTotal; downloadTotal = rhs.downloadTotal; uploadSoFar = rhs.uploadSoFar; uploadTotal = rhs.uploadTotal; pool = rhs.pool.load(); handle = rhs.handle.load(); url = std::move(rhs.url); return *this; } CURLHandle::CURLHandle(CURLHandle &&rhs) noexcept : handle(nullptr) { *this = std::move(rhs); } }
31.354167
146
0.619934
RotartsiORG
76fbe39e413419e717be088742184ad004bd0256
1,937
cpp
C++
Engine/src/renderer/material/TexturePNG.cpp
Owlinated/SkyHockey
787a7fa6c4cd1773c5a5c7e15e014f675947a21e
[ "MIT" ]
null
null
null
Engine/src/renderer/material/TexturePNG.cpp
Owlinated/SkyHockey
787a7fa6c4cd1773c5a5c7e15e014f675947a21e
[ "MIT" ]
null
null
null
Engine/src/renderer/material/TexturePNG.cpp
Owlinated/SkyHockey
787a7fa6c4cd1773c5a5c7e15e014f675947a21e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <png.h> #include <src/support/Logger.h> #include "TexturePNG.h" /** * Load texture from .png file * @param image_path File of .png file. * @param mipmap Whether to load/generate mipmaps. */ TexturePNG::TexturePNG(const std::string& image_path, bool mipmap) { const auto fp = fopen(("res/" + image_path).c_str(), "rb"); const auto png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); const auto info = png_create_info_struct(png); png_init_io(png, fp); png_read_info(png, info); // Add alpha channel if png is RGB if (png_get_color_type(png, info) == PNG_COLOR_TYPE_RGB) { png_set_add_alpha(png, 0xff, PNG_FILLER_AFTER); png_read_update_info(png, info); } const auto width = png_get_image_width(png, info); const auto height = png_get_image_height(png, info); std::vector<unsigned char> data; data.resize(png_get_rowbytes(png, info) * height); const auto row_pointers = new png_bytep[height]; for (auto y = 0; y < height; y++) { row_pointers[height - 1 - y] = data.data() + y * png_get_rowbytes(png, info); } png_read_image(png, row_pointers); delete[] row_pointers; glGenTextures(1, &handle); glBindTexture(GL_TEXTURE_2D, handle); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data.data()); if(mipmap) { glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); this->width = static_cast<int>(width); this->height = static_cast<int>(height); }
33.396552
102
0.710893
Owlinated
76fcf2736b58a99b802d5f28f72253782ebdd52f
2,947
cpp
C++
RobWork/src/rw/trajectory/TimedUtil.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rw/trajectory/TimedUtil.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rw/trajectory/TimedUtil.cpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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 "TimedUtil.hpp" #include "TimeMetricUtil.hpp" #include <rw/models/Device.hpp> using namespace rw::trajectory; using namespace rw::math; using namespace rw::models; using namespace rw::kinematics; typedef Timed< State > TimedState; typedef Timed< Q > TimedQ; TimedQPath TimedUtil::makeTimedQPath (const Q& speed, const QPath& path, double offset) { TimedQPath result; if (path.empty ()) return result; typedef QPath::const_iterator I; I next = path.begin (); I cur = next; double time = offset; result.push_back (TimedQ (time, *next)); for (++next; next != path.end (); ++cur, ++next) { time += TimeMetricUtil::timeDistance (*cur, *next, speed); result.push_back (TimedQ (time, *next)); } return result; } TimedQPath TimedUtil::makeTimedQPath (const Device& device, const QPath& path, double offset) { return makeTimedQPath (device.getVelocityLimits (), path, offset); } TimedStatePath TimedUtil::makeTimedStatePath (const WorkCell& speed, const StatePath& path, double offset) { TimedStatePath result; if (path.empty ()) return result; typedef StatePath::const_iterator I; I next = path.begin (); I cur = next; double time = offset; result.push_back (TimedState (0, *next)); for (++next; next != path.end (); ++cur, ++next) { time += TimeMetricUtil::timeDistance (*cur, *next, speed); result.push_back (TimedState (time, *next)); } return result; } TimedStatePath TimedUtil::makeTimedStatePath (const Device& device, const QPath& path, const State& common_state, double offset) { State state = common_state; const TimedQPath qts = makeTimedQPath (device.getVelocityLimits (), path, offset); TimedStatePath result; typedef Timed< Q > TimedQ; for (const TimedQ& qt : qts) { device.setQ (qt.getValue (), state); result.push_back (makeTimed (qt.getTime (), state)); } return result; }
30.697917
93
0.624364
ZLW07
76fe86d469a3f2265d05dc3009f9981988a6a44a
647
cpp
C++
src/kc/core/Clock.cpp
nekoffski/libkc
f72cc40d2780747a707eaf6b822ba98848d92237
[ "MIT" ]
null
null
null
src/kc/core/Clock.cpp
nekoffski/libkc
f72cc40d2780747a707eaf6b822ba98848d92237
[ "MIT" ]
null
null
null
src/kc/core/Clock.cpp
nekoffski/libkc
f72cc40d2780747a707eaf6b822ba98848d92237
[ "MIT" ]
null
null
null
#include "Clock.h" #include <ctime> #include <iomanip> namespace kc::core { float toSeconds(const Clock::TimePoint& timePoint) { using namespace std::chrono; return duration_cast<microseconds>(timePoint.time_since_epoch()).count() / Clock::microsecondsInSecond; } std::string Clock::getTimeString(const std::string& format) const { auto t = std::time(nullptr); auto tm = *std::localtime(&t); std::ostringstream oss; oss << std::put_time(&tm, format.c_str()); return oss.str(); } Clock::TimePoint Clock::now() const { return m_clock.now(); } float Clock::nowAsFloat() const { return toSeconds(now()); } }
21.566667
107
0.678516
nekoffski
0a00f41bfb75f9575dd010edec32c552fcb78c42
4,845
cc
C++
packages/solid/Cylinder_3D.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
2
2020-04-13T20:06:41.000Z
2021-02-12T17:55:54.000Z
packages/solid/Cylinder_3D.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
1
2018-10-22T21:03:35.000Z
2018-10-22T21:03:35.000Z
packages/solid/Cylinder_3D.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
3
2019-04-03T02:15:37.000Z
2022-01-04T05:50:23.000Z
#include "Cylinder_3D.hh" #include "Vector_Functions_3D.hh" #include <cmath> using namespace std; namespace vf3 = Vector_Functions_3D; Cylinder_3D:: Cylinder_3D(int index, Surface_Type surface_type, double radius, vector<double> const &origin, vector<double> const &direction): Cylinder(index, 3, // dimension surface_type), radius_(radius), origin_(origin), direction_(direction) { } Cylinder_3D::Relation Cylinder_3D:: relation(vector<double> const &particle_position, bool check_equality) const { // Cross product approach // vector<double> const k0 = vf3::cross(direction_, // vf3::subtract(particle_position, // origin_)); // double const r = vf3::magnitude(k0); // Dot product approach vector<double> const k0 = vf3::subtract(particle_position, origin_); vector<double> const n = vf3::subtract(k0, vf3::multiply(direction_, vf3::dot(direction_, k0))); double const r = vf3::magnitude(n); double const dr = r - radius_; if (check_equality) { if (std::abs(dr) <= relation_tolerance_) { return Relation::EQUAL; } } if (dr > 0) { return Relation::OUTSIDE; } else // if (dr > 0) { return Relation::INSIDE; } } Cylinder_3D::Intersection Cylinder_3D:: intersection(vector<double> const &particle_position, vector<double> const &particle_direction) const { Intersection intersection; vector<double> const j0 = vf3::subtract(particle_position, origin_); vector<double> const k0 = vf3::subtract(j0, vf3::multiply(direction_, vf3::dot(direction_, j0))); vector<double> const k1 = vf3::subtract(particle_direction, vf3::multiply(direction_, vf3::dot(direction_, particle_direction))); double const l0 = vf3::magnitude_squared(k0) - radius_ * radius_; double const l1 = vf3::dot(k0, k1); double const l2 = vf3::magnitude_squared(k1); double const l3 = l1 * l1 - l0 * l2; if (l3 < 0) { intersection.type = Intersection::Type::NONE; return intersection; } else if (l2 <= intersection_tolerance_) { intersection.type = Intersection::Type::PARALLEL; return intersection; } double const l4 = sqrt(l3); double const s1 = (-l1 + l4) / l2; double const s2 = (-l1 - l4) / l2; if (s2 > 0) { intersection.distance = s2; } else if (s1 > 0) { intersection.distance = s1; } else { intersection.type = Intersection::Type::NEGATIVE; return intersection; } intersection.position = vf3::add(particle_position, vf3::multiply(particle_direction, intersection.distance)); if (l3 <= intersection_tolerance_) { intersection.type = Intersection::Type::TANGEANT; return intersection; } else { intersection.type = Intersection::Type::INTERSECTS; return intersection; } } Cylinder_3D::Normal Cylinder_3D:: normal_direction(vector<double> const &position, bool check_normal) const { Normal normal; vector<double> const k0 = vf3::subtract(position, origin_); vector<double> const n = vf3::subtract(k0, vf3::multiply(direction_, vf3::dot(direction_, k0))); if (check_normal) { if (std::abs(vf3::magnitude_squared(n) - radius_ * radius_) > normal_tolerance_ * radius_ * radius_) { normal.exists = false; return normal; } } normal.exists = true; normal.direction = vf3::normalize(n); return normal; } void Cylinder_3D:: check_class_invariants() const { Assert(origin_.size() == dimension_); Assert(direction_.size() == dimension_); }
29.011976
108
0.490815
brbass
0a028dcc0da795f0e336636cc08e39356c210a3f
7,281
cpp
C++
src/core/Hub.cpp
gabrielklein/SensorNode
e92dbd56aa0a7d75ab95b9c484f27ba6d0be64df
[ "MIT" ]
2
2018-01-21T11:43:36.000Z
2019-07-15T20:08:31.000Z
src/core/Hub.cpp
gabrielklein/SensorNode
e92dbd56aa0a7d75ab95b9c484f27ba6d0be64df
[ "MIT" ]
null
null
null
src/core/Hub.cpp
gabrielklein/SensorNode
e92dbd56aa0a7d75ab95b9c484f27ba6d0be64df
[ "MIT" ]
null
null
null
#include "Hub.h" #include "../Settings.h" Hub::Hub() { }; Hub::~Hub() { delete(this->webServerSN); delete(this->apStaClient); delete(this->led); delete(this->temp); delete(this->relay); delete(this->switc); delete(this->geiger); delete(this->mqtt); delete(this->otaUpdate); }; /** * Called at setup time. Use this call to initialize some data. */ void Hub::setup() { // Use serial Serial.begin ( 115200 ); Serial.println ("\nStarting Hub"); this->fileServ.setup(); #ifdef WEB_SERVER_SN_ENABLE this->webServerSN = new WebServerSN(&this->fileServ); this->webServerSN->addServ(this->webServerSN); this->webServerSN->setup(); #endif #ifdef WS281X_STRIP_ENABLE this->led = new Led(&this->fileServ); this->led->setup(); this->led->rgb(0, 0, 0, 50); if (this->webServerSN != NULL) this->webServerSN->addServ(this->led); #endif #ifdef AP_SERVER_CLIENT_ENABLE this->apStaClient = new APStaClient(&this->fileServ, this->led); isClientMode = this->apStaClient->setup(); if (this->webServerSN != NULL) { this->webServerSN->addServ(this->apStaClient); if (!isClientMode) { this->webServerSN->apModeOnly(); } } #endif #ifdef OTA_ENABLE this->otaUpdate = new OTAUpdate(); this->otaUpdate->setup(); #endif if (isClientMode) { #ifdef TIME_ENABLE this->iTime = new ITime(&this->fileServ); this->iTime->setup(); if (this->webServerSN != NULL) this->webServerSN->addServ(this->iTime); #endif #ifdef MQTT_ENABLE this->mqtt = new MQTT(&this->fileServ); this->mqtt->setup(); if (this->webServerSN != NULL) this->webServerSN->addServ(this->mqtt); #endif #ifdef TEMP_ENABLE this->temp = new Temp(); this->temp->setup(); if (this->webServerSN != NULL) this->webServerSN->addServ(this->temp); if (this->mqtt != NULL) this->mqtt->addServ(this->temp); #endif #ifdef RELAY_ENABLE this->relay = new Relay(); this->relay->setup(); if (this->webServerSN != NULL) this->webServerSN->addServ(this->relay); if (this->mqtt != NULL) this->mqtt->addServ(this->relay); #endif #ifdef SWITCH_ENABLE this->switc = new Switch(); this->switc->setup(); if (this->webServerSN != NULL) this->webServerSN->addServ(this->switc); if (this->mqtt != NULL) this->mqtt->addServ(this->switc); #endif #ifdef GEIGER_ENABLE this->geiger = new Geiger(&this->fileServ); this->geiger->setup(); if (this->webServerSN != NULL) this->webServerSN->addServ(this->geiger); if (this->mqtt != NULL) this->mqtt->addServ(this->geiger); #endif } }; /** * Loop */ void Hub::loop() { if (this->webServerSN!=NULL) { unsigned long now = millis(); this->webServerSN->loop(); unsigned long duration = millis() - now; if (duration > 100) { Serial.print("Loop for WebServerSN is a bit long: "); Serial.println(duration); } } if (this->otaUpdate!=NULL) { unsigned long now = millis(); this->otaUpdate->loop(); unsigned long duration = millis() - now; if (duration > 100) { Serial.print("Loop for otaUpdate is a bit long: "); Serial.println(duration); } } if (!isClientMode) { return; } if (this->iTime!=NULL) { unsigned long now = millis(); this->iTime->loop(); unsigned long duration = millis() - now; if (duration > 100) { Serial.print("Loop for iTime is a bit long: "); Serial.println(duration); } } if (this->led!=NULL) { unsigned long now = millis(); this->led->loop(); unsigned long duration = millis() - now; if (duration > 100) { Serial.print("Loop for led is a bit long: "); Serial.println(duration); } } if (this->temp!=NULL) { unsigned long now = millis(); this->temp->loop(); unsigned long duration = millis() - now; if (duration > 100) { Serial.print("Loop for temp is a bit long: "); Serial.println(duration); } } if (this->apStaClient!=NULL) { unsigned long now = millis(); this->apStaClient->loop(); unsigned long duration = millis() - now; if (duration > 100) { Serial.print("Loop for apStaClient is a bit long: "); Serial.println(duration); } } if (this->relay!=NULL) { unsigned long now = millis(); this->relay->loop(); unsigned long duration = millis() - now; if (duration > 100) { Serial.print("Loop for relay is a bit long: "); Serial.println(duration); } } if (this->switc!=NULL) { unsigned long now = millis(); this->switc->loop(); unsigned long duration = millis() - now; if (duration > 100) { Serial.print("Loop for switc is a bit long: "); Serial.println(duration); } } if (this->geiger!=NULL) { unsigned long now = millis(); this->geiger->loop(); unsigned long duration = millis() - now; if (duration > 100) { Serial.print("Loop for geiger is a bit long: "); Serial.println(duration); } } if (this->mqtt!=NULL) { unsigned long now = millis(); this->mqtt->loop(); unsigned long duration = millis() - now; if (duration > 100) { Serial.print("Loop for mqtt is a bit long: "); Serial.println(duration); } } }
30.721519
77
0.439363
gabrielklein
0a096f8d0bea078fd113c110e2ccfa182e51f0ee
156
hpp
C++
example/src/Utils/Config.hpp
matusnovak/doxydown
187dc2991dabe65f808263845e608e2ba2a41082
[ "MIT" ]
131
2019-12-12T09:08:03.000Z
2022-03-27T01:48:11.000Z
example/src/Utils/Config.hpp
matusnovak/doxydown
187dc2991dabe65f808263845e608e2ba2a41082
[ "MIT" ]
69
2020-02-21T05:50:27.000Z
2022-03-11T21:16:17.000Z
example/src/Utils/Config.hpp
matusnovak/doxydown
187dc2991dabe65f808263845e608e2ba2a41082
[ "MIT" ]
27
2020-02-20T04:50:23.000Z
2022-03-17T00:55:00.000Z
#pragma once /*! * @brief Autogenerated version string by CMake * @ingroup Utils */ #define ENGINE_VERSION "v1.0.1" #define ENGINE_ARCH "amd64"
17.333333
48
0.679487
matusnovak
0a0cf82fe63806cf84c2abc335fc5cb6eda5b4c6
563
cpp
C++
Section10/LetterPyramid/main.cpp
Yash-Singh1/cpp-programming
696c1dcff18af8e798fae6126a3b13f6259af4b7
[ "MIT" ]
null
null
null
Section10/LetterPyramid/main.cpp
Yash-Singh1/cpp-programming
696c1dcff18af8e798fae6126a3b13f6259af4b7
[ "MIT" ]
null
null
null
Section10/LetterPyramid/main.cpp
Yash-Singh1/cpp-programming
696c1dcff18af8e798fae6126a3b13f6259af4b7
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main() { cout << "Welcome to the Letter Pyramid Generator!" << endl; string input; cout << "Enter the input text: "; getline(cin, input); size_t padding{input.length() - 1}; for (size_t i{1}; i <= input.length(); ++i) { cout << string(padding, ' ') << input.substr(0, i); if (i != 1) { for (size_t ri{i - 2}; ri > 0; --ri) { cout << input[ri]; } cout << input[0]; } cout << endl; --padding; } cout << endl; return 0; }
17.060606
61
0.520426
Yash-Singh1
0a0f0a5347be9d4d7b08b04467c4ed9c6c63ce96
14,129
cpp
C++
include/h3api/H3Dialogs/H3BaseDialog.cpp
Patrulek/H3API
91f10de37c6b86f3160706c1fdf4792f927e9952
[ "MIT" ]
14
2020-09-07T21:49:26.000Z
2021-11-29T18:09:41.000Z
include/h3api/H3Dialogs/H3BaseDialog.cpp
Day-of-Reckoning/H3API
a82d3069ec7d5127b13528608d5350d2b80d57be
[ "MIT" ]
2
2021-02-12T15:52:31.000Z
2021-02-12T16:21:24.000Z
include/h3api/H3Dialogs/H3BaseDialog.cpp
Day-of-Reckoning/H3API
a82d3069ec7d5127b13528608d5350d2b80d57be
[ "MIT" ]
8
2021-02-12T15:52:41.000Z
2022-01-31T15:28:10.000Z
////////////////////////////////////////////////////////////////////// // // // Created by RoseKavalier: // // rosekavalierhc@gmail.com // // Created or last updated on: 2021-01-25 // // ***You may use or distribute these files freely // // so long as this notice remains present.*** // // // ////////////////////////////////////////////////////////////////////// #include "h3api/H3Dialogs/H3BaseDialog.hpp" #include "h3api/H3DialogControls.hpp" #include "h3api/H3Dialogs/H3Message.hpp" #include "h3api/H3Assets/H3Resource.hpp" #include "h3api/H3Managers/H3WindowManager.hpp" #include "h3api/H3Assets/H3LoadedDef.hpp" #include "h3api/H3Assets/H3LoadedPcx.hpp" namespace h3 { _H3API_ H3BaseDlg::H3BaseDlg(INT x, INT y, INT w, INT h) : zOrder(-1), nextDialog(), lastDialog(), flags(0x12), state(), xDlg(x), yDlg(y), widthDlg(w), heightDlg(h), lastItem(), firstItem(), focusedItemId(-1), pcx16(), deactivatesCount() { } _H3API_ VOID H3BaseDlg::Redraw(INT32 x, INT32 y, INT32 dx, INT32 dy) { H3WindowManager::Get()->H3Redraw(xDlg + x, yDlg + y, dx, dy); } _H3API_ VOID H3BaseDlg::Redraw() { vRedraw(TRUE, -65535, 65535); } _H3API_ INT32 H3BaseDlg::DefaultProc(H3Msg* msg) { return DefaultProc(*msg); } _H3API_ INT32 H3BaseDlg::DefaultProc(H3Msg& msg) { return THISCALL_2(INT32, 0x41B120, this, &msg); } _H3API_ H3DlgItem* H3BaseDlg::getDlgItem(UINT16 id, h3func vtable) const { H3DlgItem* it = firstItem; if (it == nullptr) return it; do { if ((it->GetID() == id) && (*reinterpret_cast<h3func*>(it) == vtable)) break; } while (it = it->GetNextItem()); return it; } _H3API_ INT32 H3BaseDlg::GetWidth() const { return widthDlg; } _H3API_ INT32 H3BaseDlg::GetHeight() const { return heightDlg; } _H3API_ INT32 H3BaseDlg::GetX() const { return xDlg; } _H3API_ INT32 H3BaseDlg::GetY() const { return yDlg; } _H3API_ BOOL H3BaseDlg::IsTopDialog() const { return nextDialog == nullptr; } _H3API_ VOID H3BaseDlg::AddControlState(INT32 id, eControlState state) { THISCALL_3(VOID, 0x5FF490, this, id, state); } _H3API_ VOID H3BaseDlg::RemoveControlState(INT32 id, eControlState state) { THISCALL_3(VOID, 0x5FF520, this, id, state); } _H3API_ H3DlgItem* H3BaseDlg::AddItem(H3DlgItem* item, BOOL initiate /*= TRUE*/) { dlgItems += item; if (initiate) return THISCALL_3(H3DlgItem*, 0x5FF270, this, item, -1); // LoadItem else return item; } _H3API_ H3DlgDef* H3BaseDlg::GetDef(UINT16 id) const { return get<H3DlgDef>(id); } _H3API_ H3DlgPcx* H3BaseDlg::GetPcx(UINT16 id) const { return get<H3DlgPcx>(id); } _H3API_ H3DlgEdit* H3BaseDlg::GetEdit(UINT16 id) const { return get<H3DlgEdit>(id); } _H3API_ H3DlgText* H3BaseDlg::GetText(UINT16 id) const { return get<H3DlgText>(id); } _H3API_ H3DlgFrame* H3BaseDlg::GetFrame(UINT16 id) const { return get<H3DlgFrame>(id); } _H3API_ H3DlgPcx16* H3BaseDlg::GetPcx16(UINT16 id) const { return get<H3DlgPcx16>(id); } _H3API_ H3DlgTextPcx* H3BaseDlg::GetTextPcx(UINT16 id) const { return get<H3DlgTextPcx>(id); } _H3API_ H3DlgDefButton* H3BaseDlg::GetDefButton(UINT16 id) const { return get<H3DlgDefButton>(id); } _H3API_ H3DlgScrollbar* H3BaseDlg::GetScrollbar(UINT16 id) const { return get<H3DlgScrollbar>(id); } _H3API_ H3DlgTransparentItem* H3BaseDlg::GetTransparent(UINT16 id) const { return get<H3DlgTransparentItem>(id); } _H3API_ H3DlgCustomButton* H3BaseDlg::GetCustomButton(UINT16 id) const { return get<H3DlgCustomButton>(id); } _H3API_ H3DlgCaptionButton* H3BaseDlg::GetCaptionButton(UINT16 id) const { return get<H3DlgCaptionButton>(id); } _H3API_ H3DlgScrollableText* H3BaseDlg::GetScrollableText(UINT16 id) const { return get<H3DlgScrollableText>(id); } _H3API_ H3DlgTransparentItem* H3BaseDlg::CreateHidden(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id) { H3DlgTransparentItem* it = H3DlgTransparentItem::Create(x, y, width, height, id); if (it) AddItem(it); return it; } _H3API_ H3LoadedPcx16* H3BaseDlg::GetCurrentPcx() { return pcx16; } _H3API_ H3DlgItem* H3BaseDlg::ItemAtPosition(H3Msg* msg) { return ItemAtPosition(*msg); } _H3API_ H3DlgItem* H3BaseDlg::ItemAtPosition(H3Msg& msg) { return THISCALL_3(H3DlgItem*, 0x5FF9A0, this, msg.GetX(), msg.GetY()); } _H3API_ H3Vector<H3DlgItem*>& H3BaseDlg::GetList() { return dlgItems; } _H3API_ H3DlgItem* H3BaseDlg::GetH3DlgItem(UINT16 id) { return THISCALL_2(H3DlgItem*, 0x5FF5B0, this, id); } _H3API_ VOID H3BaseDlg::RedrawItem(UINT16 itemID) { if (H3DlgItem* it = GetH3DlgItem(itemID)) it->Refresh(); } _H3API_ VOID H3BaseDlg::EnableItem(UINT16 id, BOOL enable) { H3DlgItem* it = GetH3DlgItem(id); if (it) it->EnableItem(enable); } _H3API_ VOID H3BaseDlg::SendCommandToItem(INT32 command, UINT16 itemID, UINT32 parameter) { THISCALL_5(VOID, 0x5FF400, this, 0x200, command, itemID, parameter); } _H3API_ VOID H3BaseDlg::SendCommandToAllItems(INT32 command, INT32 itemID, INT32 parameter) { H3Msg msg; msg.SetCommand(eMsgCommand::ITEM_COMMAND, eMsgSubtype(command), itemID, eMsgFlag::NONE, 0, 0, parameter, 0); THISCALL_2(VOID, 0x5FF3A0, this, &msg); } _H3API_ VOID H3BaseDlg::AdjustToPlayerColor(INT8 player, UINT16 itemId) { if (H3DlgItem* it = GetH3DlgItem(itemId)) it->ColorToPlayer(player); } _H3API_ H3DlgFrame* H3BaseDlg::CreateFrame(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, RGB565 color) { H3DlgFrame* frame = H3DlgFrame::Create(x, y, width, height, id, color); if (frame) AddItem(frame); return frame; } _H3API_ H3DlgFrame* H3BaseDlg::CreateFrame(INT32 x, INT32 y, INT32 width, INT32 height, RGB565 color) { H3DlgFrame* frame = H3DlgFrame::Create(x, y, width, height, 0, color); if (frame) AddItem(frame); return frame; } _H3API_ H3DlgFrame* H3BaseDlg::CreateFrame(H3DlgItem* target, RGB565 color, INT id, BOOL around_edge) { H3DlgFrame* frame = H3DlgFrame::Create(target, color, id, around_edge); if (frame) AddItem(frame); return frame; } _H3API_ H3DlgDef* H3BaseDlg::CreateDef(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR defName, INT32 frame, INT32 group, INT32 mirror, BOOL closeDialog) { H3DlgDef* def = H3DlgDef::Create(x, y, width, height, id, defName, frame, group, mirror, closeDialog); if (def) AddItem(def); return def; } _H3API_ H3DlgDef* H3BaseDlg::CreateDef(INT32 x, INT32 y, INT32 id, LPCSTR defName, INT32 frame, INT32 group, INT32 mirror, BOOL closeDialog) { H3DlgDef* def = H3DlgDef::Create(x, y, id, defName, frame, group, mirror, closeDialog); if (def) AddItem(def); return def; } _H3API_ H3DlgDefButton* H3BaseDlg::CreateButton(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR defName, INT32 frame, INT32 clickFrame, BOOL closeDialog, INT32 hotkey) { H3DlgDefButton* but = H3DlgDefButton::Create(x, y, width, height, id, defName, frame, clickFrame, closeDialog, hotkey); if (but) AddItem(but); return but; } _H3API_ H3DlgDefButton* H3BaseDlg::CreateButton(INT32 x, INT32 y, INT32 id, LPCSTR defName, INT32 frame, INT32 clickFrame, BOOL closeDialog, INT32 hotkey) { H3DlgDefButton* but = CreateButton(x, y, 0, 0, id, defName, frame, clickFrame, closeDialog, hotkey); if (but) { H3LoadedDef* def = but->GetDef(); if (def) { but->SetWidth(def->widthDEF); but->SetHeight(def->heightDEF); } } return but; } _H3API_ H3DlgDefButton* H3BaseDlg::CreateOKButton(INT32 x, INT32 y) { H3DlgDefButton* button = H3DlgDefButton::Create(x, y, int(eControlId::OK), NH3Dlg::Assets::OKAY_DEF, 0, 1, TRUE, NH3VKey::H3VK_ENTER); if (button) { AddItem(H3DlgPcx::Create(x - 1, y - 1, NH3Dlg::Assets::BOX_64_30_PCX)); AddItem(button); } return button; } _H3API_ H3DlgDefButton* H3BaseDlg::CreateSaveButton(INT32 x, INT32 y, LPCSTR button_name) { H3DlgDefButton* button = H3DlgDefButton::Create(x, y, int(eControlId::SAVE), button_name, 0, 1, FALSE, NH3VKey::H3VK_S); if (button) { AddItem(H3DlgFrame::Create(button, H3RGB565::Highlight(), 0, TRUE)); //AddItem(H3DlgPcx::Create(x - 1, y - 1, NH3Dlg::Assets::BOX_64_32_PCX)); AddItem(button); } return button; } _H3API_ H3DlgDefButton* H3BaseDlg::CreateOnOffCheckbox(INT32 x, INT32 y, INT32 id, INT32 frame, INT32 clickFrame) { if (clickFrame == -1) clickFrame = 1 - frame; H3DlgDefButton* button = H3DlgDefButton::Create(x, y, id, NH3Dlg::Assets::ON_OFF_CHECKBOX, frame, clickFrame, 0, 0); if (button) AddItem(button); return button; } _H3API_ H3DlgDefButton* H3BaseDlg::CreateOKButton() { H3DlgDefButton* button = H3DlgDefButton::Create(25, heightDlg - 50, int(eControlId::OK), NH3Dlg::Assets::OKAY_DEF, 0, 1, TRUE, NH3VKey::H3VK_ENTER); if (button) { AddItem(H3DlgPcx::Create(25 - 1, heightDlg - 50 - 1, NH3Dlg::Assets::BOX_64_30_PCX)); AddItem(button); } return button; } _H3API_ H3DlgDefButton* H3BaseDlg::CreateOK32Button(INT32 x, INT32 y) { H3DlgDefButton* button = H3DlgDefButton::Create(x, y, int(eControlId::OK), NH3Dlg::Assets::OKAY32_DEF, 0, 1, TRUE, NH3VKey::H3VK_ENTER); if (button) { AddItem(H3DlgPcx::Create(x - 1, y - 1, NH3Dlg::Assets::BOX_66_32_PCX)); AddItem(button); } return button; } _H3API_ H3DlgDefButton* H3BaseDlg::CreateCancelButton() { return CreateCancelButton(widthDlg - 25 - 64, heightDlg - 50); } _H3API_ H3DlgDefButton* H3BaseDlg::CreateCancelButton(INT32 x, INT32 y) { H3DlgDefButton* button = H3DlgDefButton::Create(x, y, eControlId::CANCEL, NH3Dlg::Assets::CANCEL_DEF, 0, 1, TRUE, NH3VKey::H3VK_ESCAPE); if (button) { AddItem(H3DlgPcx::Create(x - 1, y - 1, NH3Dlg::Assets::BOX_64_30_PCX)); AddItem(button); } return button; } _H3API_ H3DlgCaptionButton* H3BaseDlg::CreateCaptionButton(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR defName, LPCSTR text, LPCSTR font, INT32 frame, INT32 group, BOOL closeDialog, INT32 hotkey, INT32 color) { H3DlgCaptionButton* but = H3DlgCaptionButton::Create(x, y, width, height, id, defName, text, font, frame, group, closeDialog, hotkey, color); if (but) AddItem(but); return but; } _H3API_ H3DlgCustomButton* H3BaseDlg::CreateCustomButton(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR defName, H3DlgButton_proc customProc, INT32 frame, INT32 clickFrame) { H3DlgCustomButton* but = H3DlgCustomButton::Create(x, y, width, height, id, defName, customProc, frame, clickFrame); if (but) AddItem(but); return but; } _H3API_ H3DlgCustomButton* H3BaseDlg::CreateCustomButton(INT32 x, INT32 y, INT32 id, LPCSTR defName, H3DlgButton_proc customProc, INT32 frame, INT32 clickFrame) { H3DlgCustomButton* but = H3DlgCustomButton::Create(x, y, id, defName, customProc, frame, clickFrame); if (but) AddItem(but); return but; } _H3API_ H3DlgCustomButton* H3BaseDlg::CreateCustomButton(INT32 x, INT32 y, LPCSTR defName, H3DlgButton_proc customProc, INT32 frame, INT32 clickFrame) { return CreateCustomButton(x, y, 0, defName, customProc, frame, clickFrame); } _H3API_ H3DlgPcx* H3BaseDlg::CreatePcx(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR pcxName) { H3DlgPcx* pcx = H3DlgPcx::Create(x, y, width, height, id, pcxName); if (pcx) AddItem(pcx); return pcx; } _H3API_ H3DlgPcx* H3BaseDlg::CreatePcx(INT32 x, INT32 y, INT32 id, LPCSTR pcxName) { H3DlgPcx* pcx = CreatePcx(x, y, 0, 0, id, pcxName); if (pcx && pcx->GetPcx()) { H3LoadedPcx* p = pcx->GetPcx(); pcx->SetWidth(p->width); pcx->SetHeight(p->height); } return pcx; } _H3API_ H3DlgPcx* H3BaseDlg::CreateLineSeparator(INT32 x, INT32 y, INT32 width) { return CreatePcx(x, y, width, 2, 0, NH3Dlg::HDassets::LINE_SEPARATOR); } _H3API_ H3DlgPcx16* H3BaseDlg::CreatePcx16(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR pcxName) { H3DlgPcx16* pcx = H3DlgPcx16::Create(x, y, width, height, id, pcxName); if (pcx) AddItem(pcx); return pcx; } _H3API_ H3DlgEdit* H3BaseDlg::CreateEdit(INT32 x, INT32 y, INT32 width, INT32 height, INT32 maxLength, LPCSTR text, LPCSTR fontName, INT32 color, INT32 align, LPCSTR pcxName, INT32 id, INT32 hasBorder, INT32 borderX, INT32 borderY) { H3DlgEdit* ed = H3DlgEdit::Create(x, y, width, height, maxLength, text, fontName, color, align, pcxName, id, hasBorder, borderX, borderY); if (ed) AddItem(ed); return ed; } _H3API_ H3DlgText* H3BaseDlg::CreateText(INT32 x, INT32 y, INT32 width, INT32 height, LPCSTR text, LPCSTR fontName, INT32 color, INT32 id, eTextAlignment align, INT32 bkColor) { H3DlgText* tx = H3DlgText::Create(x, y, width, height, text, fontName, color, id, align, bkColor); if (tx) AddItem(tx); return tx; } _H3API_ H3DlgTextPcx* H3BaseDlg::CreateTextPcx(INT32 x, INT32 y, INT32 width, INT32 height, LPCSTR text, LPCSTR fontName, LPCSTR pcxName, INT32 color, INT32 id, INT32 align) { H3DlgTextPcx* tx = H3DlgTextPcx::Create(x, y, width, height, text, fontName, pcxName, color, id, align); if (tx) AddItem(tx); return tx; } _H3API_ H3DlgScrollableText* H3BaseDlg::CreateScrollableText(LPCSTR text, INT32 x, INT32 y, INT32 width, INT32 height, LPCSTR font, INT32 color, INT32 isBlue) { H3DlgScrollableText* sc = H3DlgScrollableText::Create(text, x, y, width, height, font, color, isBlue); if (sc) AddItem(sc); return sc; } _H3API_ H3DlgScrollbar* H3BaseDlg::CreateScrollbar(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, INT32 ticksCount, H3DlgScrollbar_proc scrollbarProc, BOOL isBlue, INT32 stepSize, BOOL arrowsEnabled) { H3DlgScrollbar* sc = H3DlgScrollbar::Create(x, y, width, height, id, ticksCount, scrollbarProc, isBlue, stepSize, arrowsEnabled); if (sc) AddItem(sc); return sc; } _H3API_ H3ExtendedDlg::H3ExtendedDlg(INT x, INT y, INT w, INT h) : H3BaseDlg(x, y, w, h) { } } /* namespace h3 */
34.293689
232
0.69375
Patrulek
0a0f1f29e718edf02fe77504a3c521cca069adde
5,283
cpp
C++
mgmtd/source/net/message/nodes/storagepools/ModifyStoragePoolMsgEx.cpp
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
mgmtd/source/net/message/nodes/storagepools/ModifyStoragePoolMsgEx.cpp
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
mgmtd/source/net/message/nodes/storagepools/ModifyStoragePoolMsgEx.cpp
TomatoYoung/beegfs
edf287940175ecded493183209719d2d90d45374
[ "BSD-3-Clause" ]
null
null
null
#include "ModifyStoragePoolMsgEx.h" #include <common/app/log/LogContext.h> #include <common/net/message/nodes/storagepools/ModifyStoragePoolRespMsg.h> #include <common/net/message/control/GenericResponseMsg.h> #include <nodes/StoragePoolStoreEx.h> #include <program/Program.h> bool ModifyStoragePoolMsgEx::processIncoming(ResponseContext& ctx) { if (Program::getApp()->isShuttingDown()) { ctx.sendResponse(GenericResponseMsg(GenericRespMsgCode_TRYAGAIN, "Mgmtd shutting down.")); return true; } StoragePoolStoreEx* storagePoolStore = Program::getApp()->getStoragePoolStore(); if (Program::getApp()->isShuttingDown()) { ctx.sendResponse(GenericResponseMsg(GenericRespMsgCode_TRYAGAIN, "Mgmtd shutting down.")); return true; } FhgfsOpsErr result = FhgfsOpsErr_SUCCESS; bool changesMade = false; // check if pool exists bool poolExists = storagePoolStore->poolExists(poolId); if (!poolExists) { LOG(STORAGEPOOLS, WARNING, "Storage pool ID doesn't exist", poolId); result = FhgfsOpsErr_INVAL; goto send_response; } bool setDescriptionResp; if (newDescription && !newDescription->empty()) // changeName { setDescriptionResp = storagePoolStore->setPoolDescription(poolId, *newDescription); if (setDescriptionResp == FhgfsOpsErr_SUCCESS) { changesMade = true; } else { LOG(STORAGEPOOLS, WARNING, "Could not set new description for storage pool"); result = FhgfsOpsErr_INTERNAL; } } else { setDescriptionResp = false; // needed later for notifications to metadata nodes } if (addTargets) // add targets to the pool { // -> this can only happen if targets are in the default pool for (auto it = addTargets->begin(); it != addTargets->end(); it++) { FhgfsOpsErr moveTargetsResp = storagePoolStore->moveTarget(StoragePoolStore::DEFAULT_POOL_ID, poolId, *it); if (moveTargetsResp == FhgfsOpsErr_SUCCESS) { changesMade = true; } else { LOG(STORAGEPOOLS, WARNING, "Could not add target to storage pool. " "Probably the target doesn't exist or is not a member of the default storage pool.", poolId, ("targetId",*it)); result = FhgfsOpsErr_INTERNAL; // however, we still try to move the remaining targets } } } if (rmTargets) // remove targets from the pool (i.e. move them to the default pool) { for (auto it = rmTargets->begin(); it != rmTargets->end(); it++) { FhgfsOpsErr moveTargetsResp = storagePoolStore->moveTarget(poolId, StoragePoolStore::DEFAULT_POOL_ID, *it); if (moveTargetsResp == FhgfsOpsErr_SUCCESS) { changesMade = true; } else { LOG(STORAGEPOOLS, WARNING, "Could not remove target from storage pool. " "Probably the target doesn't exist or is not a member of the storage pool.", poolId, ("targetId",*it)); result = FhgfsOpsErr_INTERNAL; // however, we still try to move the remaining targets } } } if (addBuddyGroups) // add targets to the pool { // -> this can only happen if targets are in the default pool for (auto it = addBuddyGroups->begin(); it != addBuddyGroups->end(); it++) { FhgfsOpsErr moveBuddyGroupsResp = storagePoolStore->moveBuddyGroup(StoragePoolStore::DEFAULT_POOL_ID, poolId, *it); if (moveBuddyGroupsResp == FhgfsOpsErr_SUCCESS) { changesMade = true; } else { LOG(STORAGEPOOLS, WARNING, "Could not add buddy group to storage pool. " "Probably the buddy group doesn't exist " "or is not a member of the default storage pool.", poolId, ("buddyGroupId",*it)); result = FhgfsOpsErr_INTERNAL; // however, we still try to move the remaining buddy groups } } } if (rmBuddyGroups) // remove targets from the pool (i.e. move them to the default pool) { for (auto it = rmBuddyGroups->begin(); it != rmBuddyGroups->end(); it++) { FhgfsOpsErr moveBuddyGroupsResp = storagePoolStore->moveBuddyGroup(poolId, StoragePoolStore::DEFAULT_POOL_ID, *it); if (moveBuddyGroupsResp == FhgfsOpsErr_SUCCESS) { changesMade = true; } else { LOG(STORAGEPOOLS, WARNING, "Could not remove buddy group from storage pool. " "Probably the buddy group doesn't exist or is not a member of the storage pool.", poolId, ("buddy group",*it)); result = FhgfsOpsErr_INTERNAL; // however, we still try to move the remaining buddy groups } } } if (changesMade) { // changes were made Program::getApp()->getHeartbeatMgr()->notifyAsyncRefreshStoragePools(); } send_response: ctx.sendResponse(ModifyStoragePoolRespMsg(result)); return true; }
29.847458
99
0.607609
TomatoYoung
0a1013d51b3e1a8ab70f40d2abc05e2d462045d7
5,677
cpp
C++
mainwindow.cpp
diegofps/picker
a8e09c74e2d34a17a61ba6e1be08df135cbce60b
[ "Apache-2.0" ]
null
null
null
mainwindow.cpp
diegofps/picker
a8e09c74e2d34a17a61ba6e1be08df135cbce60b
[ "Apache-2.0" ]
null
null
null
mainwindow.cpp
diegofps/picker
a8e09c74e2d34a17a61ba6e1be08df135cbce60b
[ "Apache-2.0" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QToolButton> #include <QShortcut> #include <QBitmap> #include <QStyle> #include <QFile> #include <QFileInfo> #include <QDir> #include <QSet> #include <QProcess> using namespace wup; MainWindow::MainWindow(Params & params, QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { iconSize = params.getInt("iconSize", 64); ui->setupUi(this); configureWindow(params); configureCloseOnEscape(); configureActions(params); // auto iconFilepath = "/usr/share/virt-manager/icons/hicolor/48x48/actions/vm_import_wizard.png"; // addButton("Button 1", iconFilepath, "q", 0, 0); // addButton("Button 2", iconFilepath, "w", 0, 1); // addButton("Button 3", iconFilepath, "e", 0, 2); // addButton("Button 4", iconFilepath, "r", 1, 0); // addButton("Button 5", iconFilepath, "t", 1, 1); // addButton("Button 6", iconFilepath, "y", 1, 2); } MainWindow::~MainWindow() { delete ui; } void MainWindow::configureWindow(Params &params) { if (params.has("fullscreen")) { setWindowFlags(Qt::Widget | Qt::FramelessWindowHint); setParent(nullptr); setAttribute(Qt::WA_NoSystemBackground, true); setAttribute(Qt::WA_TranslucentBackground, true); // setAttribute(Qt::WA_PaintOnScreen); QMainWindow::showFullScreen(); if (params.len("fullscreen")) { auto color = params.getString("fullscreen"); this->setStyleSheet(QString("background-color: #") + color); } } else { setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::FramelessWindowHint); setParent(nullptr); setAttribute(Qt::WA_NoSystemBackground, true); setAttribute(Qt::WA_TranslucentBackground, true); } } void MainWindow::configureCloseOnEscape() { auto s = new QShortcut(QKeySequence("Escape"), this); connect(s, &QShortcut::activated, [this]() { close(); }); } void MainWindow::changeEvent(QEvent * event) { QWidget::changeEvent(event); if (event->type() == QEvent::ActivationChange && !this->isActiveWindow()) close(); } void MainWindow::configureActions(Params &params) { QList<Action*> actions; const QString actionsFilepath = params.getString("actions"); const int numCols = params.getInt("cols", 5); loadActions(actionsFilepath, actions); int i = 0; int j = 0; for (auto & a : actions) { addButton(a, i, j); ++j; if (j == numCols) { ++i; j = 0; } } } void MainWindow::loadActions(const QString actionsFilepath, QList<MainWindow::Action *> &actions) { QString homeDir = QDir::homePath(); QFileInfo info(actionsFilepath); QFile file(actionsFilepath); QSet<QString> shortcuts; QDir::setCurrent(info.path()); if (!file.open(QIODevice::ReadOnly)) error("Could not open actions file"); int i = 0; while (!file.atEnd()) { QByteArray line = file.readLine(); auto cells = line.split(';'); if (cells.size() != 4) error("Wrong number of cells in actions file at line", i); auto a = new Action(); a->name = cells[0]; a->iconFilepath = QString(cells[1]).replace("~", homeDir); a->shortcut = cells[2]; a->cmd = QString(cells[3]).replace("~", homeDir); if (shortcuts.contains(a->shortcut)) error("Shortcut mapped twice:", a->shortcut); actions.push_back(a); ++i; } } void MainWindow::addButton(const Action * a, const int row, const int col) { // Get the icon QIcon * icon; if (a->iconFilepath.endsWith("svg")) { icon = new QIcon(a->iconFilepath); } else { QPixmap pixmap(a->iconFilepath); if (pixmap.width() != iconSize) { QPixmap scaled = pixmap.scaled( QSize(iconSize, iconSize), Qt::KeepAspectRatio, Qt::SmoothTransformation ); icon = new QIcon(scaled); } else { icon = new QIcon(pixmap); } } // Configure the button auto b = new QToolButton(); b->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); b->setIconSize(QSize(iconSize,iconSize)); b->setIcon(*icon); b->setText(a->name + "\n(" + a->shortcut + ")"); b->setStyleSheet( "QToolButton {" "border: 0px;" "border-radius: 6px;" "background-color: #ff222222;" "color: #fff;" "padding-top: 7px;" "padding-bottom: 6px;" "padding-right: 20px;" "padding-left: 20px;" "}" "QToolButton:hover {" "background-color: #ff333333;" "}"); // Callback to execute this action auto callback = [a, this]() { // QProcess::execute(a->cmd); QDir::setCurrent(QDir::homePath()); QProcess::startDetached(a->cmd); close(); }; // Configure button click connect(b, &QToolButton::clicked, callback); // Configure shortcut auto s = new QShortcut(QKeySequence(a->shortcut), this); connect(s, &QShortcut::activated, callback); // Add button to screen ui->gridLayout->addWidget(b, row, col); } void MainWindow::on_actiona_triggered() { print("a"); } void MainWindow::on_actionb_triggered() { print("b"); } void MainWindow::on_shortcut() { print("action"); }
24.469828
119
0.574599
diegofps
0a116c910ba20a7b92c886dcea15f9b4b3040368
24,529
cpp
C++
source/renderer/scene/adaptiveGrid/AdaptiveGrid.cpp
DaSutt/VolumetricParticles
6ec9bac4bec4a8757343bb770b23110ef2364dfd
[ "Apache-2.0" ]
6
2017-06-26T11:42:26.000Z
2018-09-10T17:53:53.000Z
source/renderer/scene/adaptiveGrid/AdaptiveGrid.cpp
DaSutt/VolumetricParticles
6ec9bac4bec4a8757343bb770b23110ef2364dfd
[ "Apache-2.0" ]
8
2017-06-24T20:25:42.000Z
2017-08-09T10:50:40.000Z
source/renderer/scene/adaptiveGrid/AdaptiveGrid.cpp
DaSutt/VolumetricParticles
6ec9bac4bec4a8757343bb770b23110ef2364dfd
[ "Apache-2.0" ]
null
null
null
/* MIT License Copyright(c) 2017 Daniel Suttor 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 "AdaptiveGrid.h" #include "..\..\passResources\ShaderBindingManager.h" #include "..\..\passes\Passes.h" #include "..\..\ShadowMap.h" #include "..\..\resources\BufferManager.h" #include "..\..\resources\ImageManager.h" #include "..\..\passes\GuiPass.h" #include "..\..\wrapper\Surface.h" #include "..\..\wrapper\Barrier.h" #include "..\..\wrapper\QueryPool.h" #include "..\..\..\scene\Scene.h" #include "..\..\..\utility\Status.h" #include "AdaptiveGridConstants.h" #include "debug\DebugData.h" #include <glm\gtc\matrix_transform.hpp> #define GLM_ENABLE_EXPERIMENTAL #include <glm\gtx\component_wise.hpp> #include <random> #include <functional> namespace Renderer { constexpr int debugScreenDivision_ = 1; AdaptiveGrid::AdaptiveGrid(float worldCellSize) : worldCellSize_{ worldCellSize }, imageAtlas_{GridConstants::imageResolution} { //min count for grid level data gridLevelData_.resize(3); } void AdaptiveGrid::SetWorldExtent(const glm::vec3& min, const glm::vec3& max) { glm::vec3 scale; const auto worldScale = max - min; //grid resolution of root node is 1 std::vector<int> resolutions = { 1, GridConstants::nodeResolution, GridConstants::nodeResolution }; glm::vec3 maxScale = CalcMaxScale(resolutions, GridConstants::nodeResolution); //add additional levels until the whole world is covered /*while (glm::compMax(worldScale) > glm::compMax(maxScale)) { resolutions.push_back(gridResolution_); maxScale = CalcMaxScale(resolutions, imageResolution_); }*/ scale = maxScale; printf("Scene size %f %f %f\n", scale.x, scale.y, scale.z); //Calculate world extent const auto center = glm::vec3(0,0,0); const auto halfScale = scale * 0.5f; worldBoundingBox_.min = center - halfScale; worldBoundingBox_.max = center + halfScale; raymarchingData_.gridMinPosition = worldBoundingBox_.min; radius_ = glm::distance(worldBoundingBox_.max, glm::vec3(0.0f)); int globalResolution = resolutions[0]; //Initialize all grid levels for (size_t i = 0; i < resolutions.size(); ++i) { if (i > 0) { globalResolution *= resolutions[i]; } gridLevels_.push_back({ resolutions[i] }); gridLevels_.back().SetWorldExtend(worldBoundingBox_.min, scale, static_cast<float>(globalResolution)); } for (size_t i = 1; i < gridLevels_.size(); ++i) { gridLevels_[i].SetParentLevel(&gridLevels_[i - 1]); } gridLevels_.back().SetLeafLevel(); mostDetailedParentLevel_ = static_cast<int>(gridLevels_.size() - 2); raymarchingData_.maxLevel = static_cast<int>(resolutions.size() - 1); gridLevelData_.resize(resolutions.size()); for (size_t i = 0; i < resolutions.size(); ++i) { gridLevelData_[i].gridCellSize = gridLevels_[i].GetGridCellSize(); gridLevelData_[i].gridResolution = GridConstants::nodeResolution; gridLevelData_[i].childCellSize = gridLevels_[i].GetGridCellSize() / GridConstants::nodeResolution; } groundFog_.SetSizes(gridLevels_[1].GetGridCellSize(), scale.x); particleSystems_.SetGridOffset(worldBoundingBox_.min); Status::UpdateGrid(scale, worldBoundingBox_.min); Status::SetParticleSystems(&particleSystems_); } void AdaptiveGrid::ResizeConstantBuffers(BufferManager* bufferManager) { const auto levelBufferSize = sizeof(LevelData) * gridLevelData_.size(); bufferManager->Ref_RequestBufferResize(cbIndices_[CB_RAYMARCHING_LEVELS], levelBufferSize); } void AdaptiveGrid::RequestResources(ImageManager* imageManager, BufferManager* bufferManager, int frameCount) { BufferManager::BufferInfo bufferInfo; bufferInfo.typeBits = BufferManager::BUFFER_CONSTANT_BIT | BufferManager::BUFFER_SCENE_BIT; bufferInfo.pool = BufferManager::MEMORY_CONSTANT; bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT; bufferInfo.bufferingCount = frameCount; frameCount_ = frameCount; auto cbIndex = CB_RAYMARCHING; { bufferInfo.data = &raymarchingData_; bufferInfo.size = sizeof(RaymarchingData); cbIndices_[cbIndex] = bufferManager->Ref_RequestBuffer(bufferInfo); } cbIndex = CB_RAYMARCHING_LEVELS; { bufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; bufferInfo.data = gridLevelData_.data(); cbIndices_[cbIndex] = bufferManager->Ref_RequestBuffer(bufferInfo); } { BufferManager::BufferInfo gridBufferInfo; gridBufferInfo.pool = BufferManager::MEMORY_GRID; gridBufferInfo.size = sizeof(uint32_t); gridBufferInfo.typeBits = BufferManager::BUFFER_GRID_BIT; gridBufferInfo.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; gridBufferInfo.bufferingCount = frameCount; for (size_t i = GPU_BUFFER_NODE_INFOS; i < GPU_MAX; ++i) { gpuResources_[i] = { bufferManager->Ref_RequestBuffer(gridBufferInfo), 1 }; } } imageAtlas_.RequestResources(imageManager, bufferManager, ImageManager::MEMORY_POOL_GRID, frameCount); const int atlasImageIndex = imageAtlas_.GetImageIndex(); const int atlasBufferIndex = imageAtlas_.GetBufferIndex(); debugFilling_.SetGpuResources(atlasImageIndex, atlasBufferIndex); globalVolume_.RequestResources(bufferManager, frameCount, atlasImageIndex); groundFog_.RequestResources(imageManager, bufferManager, frameCount, atlasImageIndex); particleSystems_.RequestResources(bufferManager, frameCount, atlasImageIndex); mipMapping_.RequestResources(imageManager, bufferManager, frameCount, atlasImageIndex); neighborCells_.RequestResources(bufferManager, frameCount, atlasImageIndex); for (size_t i = 0; i < gpuResources_.size(); ++i) { gpuResources_[i].maxSize = sizeof(int); } } void AdaptiveGrid::SetImageIndices(int raymarching, int depth, int shadowMap, int noise) { raymarchingImageIndex_ = raymarching; //TODO to test the image atlas //raymarchingImageIndex_ = mipMapping_.GetImageAtlasIndex(); depthImageIndex_ = depth; shadowMapIndex_ = shadowMap; noiseImageIndex_ = noise; debugTraversal_.SetImageIndices( imageAtlas_.GetImageIndex(), depthImageIndex_, shadowMap, noise ); } void AdaptiveGrid::OnLoadScene(const Scene* scene) { particleSystems_.OnLoadScene(scene); } void AdaptiveGrid::UpdateParticles(float dt) { particleSystems_.Update(dt); } int AdaptiveGrid::GetShaderBinding(ShaderBindingManager* bindingManager, Pass pass) { ShaderBindingManager::BindingInfo bindingInfo = {}; switch (pass) { case GRID_PASS_GLOBAL: return globalVolume_.GetShaderBinding(bindingManager, frameCount_); case GRID_PASS_GROUND_FOG: return groundFog_.GetShaderBinding(bindingManager, frameCount_); case GRID_PASS_PARTICLES: return particleSystems_.GetShaderBinding(bindingManager, frameCount_); case GRID_PASS_DEBUG_FILLING: return debugFilling_.GetShaderBinding(bindingManager, frameCount_); case GRID_PASS_MIPMAPPING: return mipMapping_.GetShaderBinding(bindingManager, frameCount_, pass - GRID_PASS_MIPMAPPING); case GRID_PASS_MIPMAPPING_MERGING: return mipMapping_.GetShaderBinding(bindingManager, frameCount_, pass - GRID_PASS_MIPMAPPING); case GRID_PASS_NEIGHBOR_UPDATE: return neighborCells_.GetShaderBinding(bindingManager, frameCount_); case GRID_PASS_RAYMARCHING: { bindingInfo.pass = SUBPASS_VOLUME_ADAPTIVE_RAYMARCHING; bindingInfo.resourceIndex = { raymarchingImageIndex_, depthImageIndex_, imageAtlas_.GetImageIndex(), //mipMapping_.GetImageAtlasIndex(), shadowMapIndex_, noiseImageIndex_, gpuResources_[GPU_BUFFER_NODE_INFOS].index, gpuResources_[GPU_BUFFER_ACTIVE_BITS].index, gpuResources_[GPU_BUFFER_BIT_COUNTS].index, gpuResources_[GPU_BUFFER_CHILDS].index, cbIndices_[CB_RAYMARCHING], cbIndices_[CB_RAYMARCHING_LEVELS] }; bindingInfo.stages = { VK_SHADER_STAGE_COMPUTE_BIT, VK_SHADER_STAGE_COMPUTE_BIT, VK_SHADER_STAGE_COMPUTE_BIT, VK_SHADER_STAGE_COMPUTE_BIT, VK_SHADER_STAGE_COMPUTE_BIT, VK_SHADER_STAGE_COMPUTE_BIT, VK_SHADER_STAGE_COMPUTE_BIT, VK_SHADER_STAGE_COMPUTE_BIT, VK_SHADER_STAGE_COMPUTE_BIT, VK_SHADER_STAGE_COMPUTE_BIT, VK_SHADER_STAGE_COMPUTE_BIT }; bindingInfo.types = { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER }; bindingInfo.refactoring_ = { false, false, true, true, true, true, true, true, true, true, true }; bindingInfo.setCount = frameCount_; }break; default: printf("Get shader bindings from adaptive grid for invalid type\n"); break; } return bindingManager->RequestShaderBinding(bindingInfo); } void AdaptiveGrid::Update(BufferManager* bufferManager, ImageManager* imageManager, Scene* scene, Surface* surface, ShadowMap* shadowMap, int frameIndex) { UpdateCBData(scene, surface, shadowMap); UpdateGrid(scene); ResizeGpuResources(bufferManager, imageManager); UpdateGpuResources(bufferManager, frameIndex); if (GuiPass::GetDebugVisState().nodeRendering) { UpdateBoundingBoxes(); } } void AdaptiveGrid::Dispatch(QueueManager* queueManager, ImageManager* imageManager, BufferManager* bufferManager, VkCommandBuffer commandBuffer, Pass pass, int frameIndex, int level) { switch (pass) { case GRID_PASS_GLOBAL: { globalVolume_.Dispatch(imageManager, commandBuffer, frameIndex); } break; case GRID_PASS_GROUND_FOG: { groundFog_.Dispatch(queueManager, imageManager, bufferManager, commandBuffer, frameIndex); } break; case GRID_PASS_PARTICLES: particleSystems_.Dispatch(imageManager, commandBuffer, frameIndex); break; case GRID_PASS_DEBUG_FILLING: debugFilling_.Dispatch(imageManager, commandBuffer); break; case GRID_PASS_MIPMAPPING: mipMappingStarted_ = true; case GRID_PASS_MIPMAPPING_MERGING: mipMapping_.Dispatch(imageManager, bufferManager, commandBuffer, frameIndex, level, pass - GRID_PASS_MIPMAPPING); break; case GRID_PASS_NEIGHBOR_UPDATE: { neighborCells_.Dispatch(commandBuffer, imageManager, level, mipMappingStarted_, frameIndex); } break; case GRID_PASS_RAYMARCHING: mipMappingStarted_ = false; break; default: break; } } namespace { uint32_t CalcDispatchSize(uint32_t number, uint32_t multiple) { if (number % multiple == 0) { return number / multiple; } else { return number / multiple + 1; } } } void AdaptiveGrid::Raymarch(ImageManager* imageManager, VkCommandBuffer commandBuffer, uint32_t width, uint32_t height, int frameIndex) { if (initialized_) { const uint32_t dispatchX = CalcDispatchSize(width / debugScreenDivision_, 16); const uint32_t dispatchY = CalcDispatchSize(height / debugScreenDivision_, 16); auto& queryPool = Wrapper::QueryPool::GetInstance(); queryPool.TimestampStart(commandBuffer, Wrapper::TIMESTAMP_GRID_RAYMARCHING, frameIndex); vkCmdDispatch(commandBuffer, dispatchX, dispatchY, 1); queryPool.TimestampEnd(commandBuffer, Wrapper::TIMESTAMP_GRID_RAYMARCHING, frameIndex); ImageManager::BarrierInfo imageAtlasBarrier{}; imageAtlasBarrier.imageIndex = imageAtlas_.GetImageIndex(); imageAtlasBarrier.type = ImageManager::BARRIER_READ_WRITE; ImageManager::BarrierInfo shadowMapBarrier{}; shadowMapBarrier.imageIndex = shadowMapIndex_; shadowMapBarrier.type = ImageManager::BARRIER_READ_WRITE; auto barriers = imageManager->Barrier({ imageAtlasBarrier, shadowMapBarrier }); Wrapper::PipelineBarrierInfo pipelineBarrierInfo{}; pipelineBarrierInfo.src = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; pipelineBarrierInfo.dst = VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; pipelineBarrierInfo.AddImageBarriers(barriers); Wrapper::AddPipelineBarrier(commandBuffer, pipelineBarrierInfo); } } void AdaptiveGrid::UpdateDebugTraversal(QueueManager* queueManager, BufferManager* bufferManager, ImageManager* imageManager) { const auto& volumeState = GuiPass::GetVolumeState(); if (volumeState.debugTraversal && !previousFrameTraversal_) { previousFrameTraversal_ = true; const glm::ivec2 position = static_cast<glm::ivec2>(volumeState.cursorPosition); debugTraversal_.Traversal(queueManager, bufferManager, imageManager, position.x, position.y); } else { previousFrameTraversal_ = false; } } void AdaptiveGrid::UpdateCBData(Scene* scene, Surface* surface, ShadowMap* shadowMap) { { const auto& camera = scene->GetCamera(); raymarchingData_.viewPortToWorld = glm::inverse(camera.GetViewProj()); raymarchingData_.nearPlane = camera.nearZ_; raymarchingData_.farPlane = camera.farZ_; raymarchingData_.shadowCascades = shadowMap->GetShadowMatrices(); const auto& screenSize = surface->GetSurfaceSize(); raymarchingData_.screenSize = { screenSize.width, screenSize.height}; static bool printedScreenSize = false; if (!printedScreenSize) { printf("Raymarching resolution %f %f\n", raymarchingData_.screenSize.x, raymarchingData_.screenSize.y); printedScreenSize = true; } } { const auto& lightingState = GuiPass::GetLightingState(); const auto& lv = lightingState.lightVector; const auto& li = lightingState.irradiance; raymarchingData_.irradiance = glm::vec3(li[0], li[1], li[2]); const auto lightDir = glm::vec4(lv.x, lv.y, lv.z, 0.0f); raymarchingData_.lightDirection = lightDir; const glm::vec4 shadowRayNormalPos = glm::vec4(0, 0, 0, 1) + radius_ * lightDir; raymarchingData_.shadowRayPlaneNormal = lightDir; raymarchingData_.shadowRayPlaneDistance = glm::dot(-lightDir, shadowRayNormalPos); } { const auto& volumeState = GuiPass::GetVolumeState(); globalMediumData_.scattering = volumeState.globalValue.scattering; globalMediumData_.extinction = volumeState.globalValue.absorption + volumeState.globalValue.scattering; globalMediumData_.phaseG = volumeState.globalValue.phaseG; raymarchingData_.lodScale_Reciprocal = 1.0f / volumeState.lodScale; raymarchingData_.globalScattering = { globalMediumData_.scattering, globalMediumData_.extinction, globalMediumData_.phaseG, 0.0f }; raymarchingData_.maxDepth = volumeState.maxDepth; raymarchingData_.jitteringScale = volumeState.jitteringScale; raymarchingData_.maxSteps = volumeState.stepCount; raymarchingData_.exponentialScale = log(volumeState.maxDepth); //TODO check why these values are double volumeMediaData_.scattering = volumeState.groundFogValue.scattering; volumeMediaData_.extinction = volumeState.groundFogValue.absorption + volumeState.groundFogValue.scattering; volumeMediaData_.phaseG = volumeState.groundFogValue.phaseG; if (volumeState.debugTraversal) { DebugData::raymarchData_ = raymarchingData_; DebugData::levelData_.data = gridLevelData_; } groundFog_.UpdateCBData(volumeState.groundFogHeight, volumeState.groundFogValue.scattering, volumeState.groundFogValue.absorption, volumeState.groundFogValue.phaseG, volumeState.groundFogNoiseScale); globalVolume_.UpdateCB(&groundFog_); for (auto& levelData : gridLevelData_) { //levelData.minStepSize = levelData.gridCellSize / volumeState.lodScale; levelData.shadowRayStepSize = levelData.gridCellSize / static_cast<float>(volumeState.shadowRayPerLevel); levelData.texelScale = GridConstants::nodeResolution / ((GridConstants::nodeResolution + 2) * imageAtlas_.GetSideLength() * levelData.gridCellSize); } } { static std::default_random_engine generator; static std::uniform_real_distribution<float> distribution(0.0f, 1.0f); static auto RandPos = std::bind(distribution, generator); raymarchingData_.randomness = { RandPos(), RandPos(), RandPos() }; } { const float nodeResolutionWithBorder = static_cast<float>(GridConstants::nodeResolution + 2); raymarchingData_.atlasSideLength_Reciprocal = 1.0f / raymarchingData_.atlasSideLength; raymarchingData_.textureOffset = 1.0f / nodeResolutionWithBorder / raymarchingData_.atlasSideLength; raymarchingData_.atlasTexelToNodeTexCoord = 1.0f / GridConstants::imageResolution / static_cast<float>(raymarchingData_.atlasSideLength); const float relTexelSize = 1.0f / GridConstants::imageResolution / static_cast<float>(raymarchingData_.atlasSideLength); raymarchingData_.texelHalfSize = relTexelSize * 0.5f; raymarchingData_.nodeTexelSize = raymarchingData_.atlasSideLength_Reciprocal - relTexelSize; } particleSystems_.UpdateCBData(&gridLevels_[2]); } void AdaptiveGrid::UpdateGrid(Scene* scene) { for (auto& gridLevel : gridLevels_) { gridLevel.Reset(); } gridLevels_[0].AddNode({ 0,0,0 }); //gridLevels_[1].AddNode({ 256, 256, 256 }); //gridLevels_[2].AddNode({ 256, 258,256 }); //gridLevels_[2].AddNode({ 258, 256, 256 }); //gridLevels_[2].AddNode({ 256, 256, 258 }); //gridLevels_[2].AddNode({ 254, 256,256 }); groundFog_.UpdateGridCells(&gridLevels_[1]); particleSystems_.GridInsertParticleNodes(raymarchingData_.gridMinPosition, &gridLevels_[2]); int parentChildOffset = 0; for (auto& level : gridLevels_) { parentChildOffset = level.Update(parentChildOffset); } imageAtlas_.UpdateSize(gridLevels_.back().GetImageOffset()); const int atlasSideLength = imageAtlas_.GetSideLength(); mipMapping_.UpdateAtlasProperties(atlasSideLength, imageAtlas_.GetResolution()); for (auto& level : gridLevels_) { level.UpdateImageIndices(atlasSideLength); } particleSystems_.UpdateGpuData(&gridLevels_[1], &gridLevels_[2], atlasSideLength); const int maxParentLevel = static_cast<int>(gridLevels_.size() - 1); for (size_t i = 0; i < maxParentLevel; ++i) { mipMapping_.UpdateMipMapNodes(&gridLevels_[i], &gridLevels_[i + 1]); } //neighborCells_.CalculateNeighbors(gridLevels_); debugFilling_.SetImageCount(&gridLevels_[2]); debugFilling_.AddDebugNodes(gridLevels_); volumeMediaData_.atlasSideLength = atlasSideLength; volumeMediaData_.imageResolutionOffset = GridConstants::imageResolution; raymarchingData_.atlasSideLength = atlasSideLength; //neighborCells_.UpdateAtlasProperties(atlasSideLength); } std::array<VkDeviceSize, AdaptiveGrid::GPU_MAX> AdaptiveGrid::GetGpuResourceSize() { std::array<VkDeviceSize, GPU_MAX> totalSizes{}; for (const auto& level : gridLevels_) { totalSizes[GPU_BUFFER_NODE_INFOS] += level.GetNodeInfoSize(); totalSizes[GPU_BUFFER_ACTIVE_BITS] += level.GetActiveBitSize(); totalSizes[GPU_BUFFER_BIT_COUNTS] += level.GetBitCountsSize(); totalSizes[GPU_BUFFER_CHILDS] += level.GetChildSize(); } return totalSizes; } void AdaptiveGrid::ResizeGpuResources(BufferManager* bufferManager, ImageManager* imageManager) { bool resize = false; std::vector<ResourceResize>resourceResizes; const auto totalSizes = GetGpuResourceSize(); imageAtlas_.ResizeImage(imageManager); for (int i = 0; i < GPU_MAX; ++i) { const auto totalSize = totalSizes[i]; auto& maxSize = gpuResources_[i].maxSize; if (maxSize < totalSize) { resize = true; maxSize = totalSize; } resourceResizes.push_back({ maxSize, gpuResources_[i].index }); } resize = groundFog_.ResizeGPUResources(resourceResizes) ? true : resize; resize = particleSystems_.ResizeGpuResources(resourceResizes) ? true : resize; resize = mipMapping_.ResizeGpuResources(imageManager, resourceResizes) ? true : resize; resize = neighborCells_.ResizeGpuResources(resourceResizes) ? true : resize; if (!initialized_) { resize = true; initialized_ = true; } if (resize) { bufferManager->Ref_ResizeBuffers(resourceResizes, BufferManager::MEMORY_GRID); } resizing_ = resize; } namespace { struct ResourceInfo { void* dataPtr; int offset; }; } void* AdaptiveGrid::GetDebugBufferCopyDst(GridLevel::BufferType type, int size) { switch (type) { case GridLevel::BUFFER_NODE_INFOS: DebugData::nodeInfos_.data.resize(size / sizeof(NodeInfo)); return DebugData::nodeInfos_.data.data(); case GridLevel::BUFFER_ACTIVE_BITS: DebugData::activeBits_.data.resize(size / sizeof(uint32_t)); return DebugData::activeBits_.data.data(); case GridLevel::BUFFER_BIT_COUNTS: DebugData::bitCounts_.data.resize(size / sizeof(int)); return DebugData::bitCounts_.data.data(); case GridLevel::BUFFER_CHILDS: DebugData::childIndices_.indices.resize(size / sizeof(int)); return DebugData::childIndices_.indices.data(); default: printf("Invalid buffer type to get copy dst\n"); break; } return nullptr; } void AdaptiveGrid::UpdateGpuResources(BufferManager* bufferManager, int frameIndex) { const auto& volumeState = GuiPass::GetVolumeState(); std::array<ResourceInfo, GPU_MAX> offsets{}; for (int i = 0; i < GPU_MAX; ++i) { offsets[i].dataPtr = bufferManager->Ref_Map(gpuResources_[i].index, frameIndex, BufferManager::BUFFER_GRID_BIT); } for (size_t i = 0; i < gridLevels_.size(); ++i) { //TODO check if neccessary gridLevelData_[i].nodeArrayOffset = offsets[GridLevel::BUFFER_NODE_INFOS].offset; gridLevelData_[i].childArrayOffset = offsets[GridLevel::BUFFER_CHILDS].offset; gridLevelData_[i].nodeOffset = gridLevelData_[i].nodeArrayOffset / sizeof(NodeInfo); gridLevelData_[i].childOffset = gridLevelData_[i].childArrayOffset / sizeof(int); for (int resourceIndex = 0; resourceIndex < GridLevel::BUFFER_MAX; ++resourceIndex) { const auto bufferType = static_cast<GridLevel::BufferType>(resourceIndex); const int offset = offsets[resourceIndex].offset; offsets[resourceIndex].offset = gridLevels_[i].CopyBufferData(offsets[resourceIndex].dataPtr, static_cast<GridLevel::BufferType>(resourceIndex), offsets[resourceIndex].offset); if (volumeState.debugTraversal) { gridLevels_[i].CopyBufferData(GetDebugBufferCopyDst(bufferType, offsets[resourceIndex].offset), bufferType, offset); } } } for (int i = GPU_BUFFER_NODE_INFOS; i < GPU_MAX; ++i) { bufferManager->Ref_Unmap(gpuResources_[i].index, frameIndex, BufferManager::BUFFER_GRID_BIT); } groundFog_.UpdatePerNodeBuffer(bufferManager, &gridLevels_[1], frameIndex, imageAtlas_.GetSideLength()); particleSystems_.UpdateGpuResources(bufferManager, frameIndex); mipMapping_.UpdateGpuResources(bufferManager, frameIndex); neighborCells_.UpdateGpuResources(bufferManager, frameIndex); } void AdaptiveGrid::UpdateBoundingBoxes() { debugBoundingBoxes_.clear(); for (auto& level : gridLevels_) { level.UpdateBoundingBoxes(); const auto& nodeData = level.GetNodeData(); glm::vec4 color = glm::vec4(0, 1, 0, 1); for (size_t i = 0; i < level.nodeBoundingBoxes_.size(); ++i) { debugBoundingBoxes_.push_back({ WorldMatrix(level.nodeBoundingBoxes_[i]), color }); } } debugBoundingBoxes_.push_back({ WorldMatrix(worldBoundingBox_), glm::vec4(0,1,0,0) }); } glm::vec3 AdaptiveGrid::CalcMaxScale(std::vector<int> levelResolutions, int textureResolution) { glm::vec3 scale = glm::vec3(worldCellSize_) * static_cast<float>(textureResolution); for (const auto res : levelResolutions) { scale *= static_cast<float>(res); } return scale; } }
34.941595
154
0.755229
DaSutt
0a11745da99a17acd76d39f6448e62662e77c7cd
826
hpp
C++
iOS/G3MiOSSDK/Commons/Mesh/DirectMesh.hpp
RMMJR/g3m
990467dc8e2bf584f8b512bdf06ecf4def625185
[ "BSD-2-Clause" ]
1
2016-08-23T10:29:44.000Z
2016-08-23T10:29:44.000Z
iOS/G3MiOSSDK/Commons/Mesh/DirectMesh.hpp
RMMJR/g3m
990467dc8e2bf584f8b512bdf06ecf4def625185
[ "BSD-2-Clause" ]
null
null
null
iOS/G3MiOSSDK/Commons/Mesh/DirectMesh.hpp
RMMJR/g3m
990467dc8e2bf584f8b512bdf06ecf4def625185
[ "BSD-2-Clause" ]
null
null
null
// // DirectMesh.hpp // G3MiOSSDK // // Created by Diego Gomez Deck on 12/1/12. // // #ifndef __G3MiOSSDK__DirectMesh__ #define __G3MiOSSDK__DirectMesh__ #include "AbstractMesh.hpp" class DirectMesh : public AbstractMesh { protected: void rawRender(const G3MRenderContext* rc) const; Mesh* createNormalsMesh() const; public: DirectMesh(const int primitive, bool owner, const Vector3D& center, IFloatBuffer* vertices, float lineWidth, float pointSize, const Color* flatColor = NULL, IFloatBuffer* colors = NULL, const float colorsIntensity = 0.0f, bool depthTest = true, IFloatBuffer* normals = NULL); ~DirectMesh() { #ifdef JAVA_CODE super.dispose(); #endif } }; #endif
19.209302
51
0.621065
RMMJR
0a11a41c4f6816516a80e4c0094caf5df7e4b4c3
137
inl
C++
TAO/orbsvcs/orbsvcs/Event/EC_Null_Scheduling.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/orbsvcs/orbsvcs/Event/EC_Null_Scheduling.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/orbsvcs/orbsvcs/Event/EC_Null_Scheduling.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: EC_Null_Scheduling.inl 73791 2006-07-27 20:54:56Z wotte $ ACE_INLINE TAO_EC_Null_Scheduling::TAO_EC_Null_Scheduling (void) { }
17.125
65
0.773723
cflowe
0a12180042ae162df850e0e4289edbb1cfb7fd52
369
hpp
C++
include/texugo/message/MessageParser.hpp
leozz37/Texugo
61d1d2e65fb383b1402bb5d61871d72563060494
[ "MIT" ]
20
2020-07-17T04:07:37.000Z
2022-01-07T19:02:07.000Z
include/texugo/message/MessageParser.hpp
leozz37/Texugo
61d1d2e65fb383b1402bb5d61871d72563060494
[ "MIT" ]
15
2020-08-29T03:30:34.000Z
2022-02-27T10:12:27.000Z
include/texugo/message/MessageParser.hpp
leozz37/Texugo
61d1d2e65fb383b1402bb5d61871d72563060494
[ "MIT" ]
5
2020-07-11T10:38:37.000Z
2020-09-26T20:56:45.000Z
#pragma once #include <nlohmann/json.hpp> #include <string> #include <vector> class MessageParser { public: explicit MessageParser(const std::string&); const std::vector<std::string>& getDestination() const; const std::string& getMessage() const; private: std::vector<std::string> m_destination; std::string m_message; };
23.0625
59
0.661247
leozz37
0a14825b689f0c39af63ff61ae29ce1652980afa
1,250
cpp
C++
src/game/piece/pawn.cpp
Aviraj55/Chess
51dfdd4a33f18f6cbb9666b6b16ecd4d859ac3e1
[ "MIT" ]
null
null
null
src/game/piece/pawn.cpp
Aviraj55/Chess
51dfdd4a33f18f6cbb9666b6b16ecd4d859ac3e1
[ "MIT" ]
null
null
null
src/game/piece/pawn.cpp
Aviraj55/Chess
51dfdd4a33f18f6cbb9666b6b16ecd4d859ac3e1
[ "MIT" ]
1
2020-10-03T20:59:17.000Z
2020-10-03T20:59:17.000Z
#include "pawn.h" #include "../board.h" std::vector<Coordinate> Pawn::get_candidate_moves() const { std::vector<Coordinate> candidate_moves; int dir = color_ == Color::WHITE ? 1 : -1; // Pawns may always move one square forward std::vector<int> forward_moves(1, 1); if (move_history_.empty()) { // If this is the first move that this pawn has made, then it may optionally // move two squares forward forward_moves.push_back(2); } for (int rank_offset : forward_moves) { Coordinate dest(coordinate_.get_rank() + rank_offset * dir, coordinate_.get_file()); // When moving forward, pawns may be blocked by pieces of either color (and // may not capture) if (board_->piece_at(dest) == nullptr) { candidate_moves.push_back(dest); } } // Pawns may move diagonally one square to capture an enemy piece for (int file_offset : {-1, 1}) { Coordinate dest(coordinate_.get_rank() + dir, coordinate_.get_file() + file_offset); Piece *dest_piece = board_->piece_at(dest); if (dest_piece != nullptr && dest_piece->get_color() != color_) { candidate_moves.push_back(dest); } } // TODO: Implement en passant return candidate_moves; }
30.487805
80
0.656
Aviraj55
0a16121a40d0ec98bee0874a48b135d8e44a5164
3,651
cpp
C++
src/robot_state_publisher-kinetic-devel/test/test_subclass.cpp
mowtian/Projektarbeit
43d575f6cf06690e869da4f995ed271fe4088f69
[ "MIT" ]
37
2017-12-13T16:14:32.000Z
2022-02-19T03:12:52.000Z
src/robot_state_publisher-kinetic-devel/test/test_subclass.cpp
mowtian/Projektarbeit
43d575f6cf06690e869da4f995ed271fe4088f69
[ "MIT" ]
71
2018-01-17T20:17:03.000Z
2022-03-23T19:48:45.000Z
src/robot_state_publisher-kinetic-devel/test/test_subclass.cpp
mowtian/Projektarbeit
43d575f6cf06690e869da4f995ed271fe4088f69
[ "MIT" ]
32
2018-01-08T03:21:18.000Z
2022-02-19T03:12:47.000Z
/* * Software License Agreement (BSD License) * * Copyright (c) 2016, Open Source Robotics Foundation, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <gtest/gtest.h> #include <urdf/model.h> #include <kdl_parser/kdl_parser.hpp> #include "robot_state_publisher/joint_state_listener.h" #include "robot_state_publisher/robot_state_publisher.h" namespace robot_state_publisher_test { class AccessibleJointStateListener : public robot_state_publisher::JointStateListener { public: AccessibleJointStateListener( const KDL::Tree& tree, const MimicMap& m, const urdf::Model& model) : robot_state_publisher::JointStateListener(tree, m, model) { } bool usingTfStatic() const { return use_tf_static_; } }; class AccessibleRobotStatePublisher : public robot_state_publisher::RobotStatePublisher { public: AccessibleRobotStatePublisher(const KDL::Tree& tree, const urdf::Model& model) : robot_state_publisher::RobotStatePublisher(tree, model) { } const urdf::Model & getModel() const { return model_; } }; } // robot_state_publisher_test TEST(TestRobotStatePubSubclass, robot_state_pub_subclass) { urdf::Model model; model.initParam("robot_description"); KDL::Tree tree; if (!kdl_parser::treeFromUrdfModel(model, tree)){ ROS_ERROR("Failed to extract kdl tree from xml robot description"); FAIL(); } MimicMap mimic; for(std::map< std::string, urdf::JointSharedPtr >::iterator i = model.joints_.begin(); i != model.joints_.end(); i++){ if(i->second->mimic){ mimic.insert(make_pair(i->first, i->second->mimic)); } } robot_state_publisher_test::AccessibleRobotStatePublisher state_pub(tree, model); EXPECT_EQ(model.name_, state_pub.getModel().name_); EXPECT_EQ(model.root_link_, state_pub.getModel().root_link_); robot_state_publisher_test::AccessibleJointStateListener state_listener(tree, mimic, model); EXPECT_TRUE(state_listener.usingTfStatic()); } int main(int argc, char** argv) { ros::init(argc, argv, "test_subclass"); testing::InitGoogleTest(&argc, argv); int res = RUN_ALL_TESTS(); return res; }
32.891892
120
0.743632
mowtian
0a1afd47397ae3f5abf49c9eb0d6a9d1945edb4e
3,666
cpp
C++
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/platformsupport/input/shared/qtouchoutputmapping.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/platformsupport/input/shared/qtouchoutputmapping.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/src/platformsupport/input/shared/qtouchoutputmapping.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the plugins module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qtouchoutputmapping_p.h" #include <QFile> #include <QVariantMap> #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> QT_BEGIN_NAMESPACE bool QTouchOutputMapping::load() { static QByteArray configFile = qgetenv("QT_QPA_EGLFS_KMS_CONFIG"); if (configFile.isEmpty()) return false; QFile file(QString::fromUtf8(configFile)); if (!file.open(QFile::ReadOnly)) { qWarning("touch input support: Failed to open %s", configFile.constData()); return false; } const QJsonDocument doc = QJsonDocument::fromJson(file.readAll()); if (!doc.isObject()) { qWarning("touch input support: Failed to parse %s", configFile.constData()); return false; } // What we are interested is the virtualIndex and touchDevice properties for // each element in the outputs array. const QJsonArray outputs = doc.object().value(QLatin1String("outputs")).toArray(); for (int i = 0; i < outputs.size(); ++i) { const QVariantMap output = outputs.at(i).toObject().toVariantMap(); if (!output.contains(QStringLiteral("touchDevice"))) continue; if (!output.contains(QStringLiteral("name"))) { qWarning("evdevtouch: Output %d specifies touchDevice but not name, this is wrong", i); continue; } const QString &deviceNode = output.value(QStringLiteral("touchDevice")).toString(); const QString &screenName = output.value(QStringLiteral("name")).toString(); m_screenTable.insert(deviceNode, screenName); } return true; } QString QTouchOutputMapping::screenNameForDeviceNode(const QString &deviceNode) { return m_screenTable.value(deviceNode); } QT_END_NAMESPACE
39.847826
99
0.68958
GrinCash
0a20b224df22148e34f8f09e929d28394b7c6c9a
18,357
hpp
C++
accessor/scaled_reduced_row_major.hpp
JakubTrzcskni/ginkgo
8a9988b9c3f8c4ff59fae30050575311f230065e
[ "BSD-3-Clause" ]
null
null
null
accessor/scaled_reduced_row_major.hpp
JakubTrzcskni/ginkgo
8a9988b9c3f8c4ff59fae30050575311f230065e
[ "BSD-3-Clause" ]
null
null
null
accessor/scaled_reduced_row_major.hpp
JakubTrzcskni/ginkgo
8a9988b9c3f8c4ff59fae30050575311f230065e
[ "BSD-3-Clause" ]
null
null
null
/*******************************<GINKGO LICENSE>****************************** Copyright (c) 2017-2022, the Ginkgo authors 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. ******************************<GINKGO LICENSE>*******************************/ #ifndef GKO_ACCESSOR_SCALED_REDUCED_ROW_MAJOR_HPP_ #define GKO_ACCESSOR_SCALED_REDUCED_ROW_MAJOR_HPP_ #include <array> #include <cinttypes> #include <type_traits> #include <utility> #include "accessor_helper.hpp" #include "index_span.hpp" #include "range.hpp" #include "scaled_reduced_row_major_reference.hpp" #include "utils.hpp" namespace gko { /** * @brief The accessor namespace. * * @ingroup accessor */ namespace acc { namespace detail { // In case of a const type, do not provide a write function template <int Dimensionality, typename Accessor, typename ScalarType, bool = std::is_const<ScalarType>::value> struct enable_write_scalar { using scalar_type = ScalarType; }; // In case of a non-const type, enable the write function template <int Dimensionality, typename Accessor, typename ScalarType> struct enable_write_scalar<Dimensionality, Accessor, ScalarType, false> { static_assert(Dimensionality >= 1, "Dimensionality must be a positive number!"); using scalar_type = ScalarType; /** * Writes the scalar value at the given indices. * The number of indices must be equal to the number of dimensions, even * if some of the indices are ignored (depending on the scalar mask). * * @param value value to write * @param indices indices where to write the value * * @returns the written value. */ template <typename... Indices> constexpr GKO_ACC_ATTRIBUTES scalar_type write_scalar_masked(scalar_type value, Indices&&... indices) const { static_assert(sizeof...(Indices) == Dimensionality, "Number of indices must match dimensionality!"); scalar_type* GKO_ACC_RESTRICT rest_scalar = self()->scalar_; return rest_scalar[self()->compute_mask_scalar_index( std::forward<Indices>(indices)...)] = value; } /** * Writes the scalar value at the given indices. * Only the actually used indices must be provided, meaning the number of * specified indices must be equal to the number of set bits in the * scalar mask. * * @param value value to write * @param indices indices where to write the value * * @returns the written value. */ template <typename... Indices> constexpr GKO_ACC_ATTRIBUTES scalar_type write_scalar_direct(scalar_type value, Indices&&... indices) const { scalar_type* GKO_ACC_RESTRICT rest_scalar = self()->scalar_; return rest_scalar[self()->compute_direct_scalar_index( std::forward<Indices>(indices)...)] = value; } private: constexpr GKO_ACC_ATTRIBUTES const Accessor* self() const { return static_cast<const Accessor*>(this); } }; } // namespace detail /** * The scaled_reduced_row_major class allows a storage format that is different * from the arithmetic format (which is returned from the brace operator). * Additionally, a scalar is used when reading and writing data to allow for * a shift in range. * As storage, the StorageType is used. * * This accessor uses row-major access. For example, for three dimensions, * neighboring z coordinates are next to each other in memory, followed by y * coordinates and then x coordinates. * * @tparam Dimensionality The number of dimensions managed by this accessor * * @tparam ArithmeticType Value type used for arithmetic operations and * for in- and output * * @tparam StorageType Value type used for storing the actual value to memory * * @tparam ScalarMask Binary mask that marks which indices matter for the * scalar selection (set bit means the corresponding index * needs to be considered, 0 means it is not). The least * significand bit corresponds to the last index dimension, * the second least to the second last index dimension, and * so on. * For example, the mask = 0b011101 means that for the 5d * indices (x1, x2, x3, x4, x5), (x1, x2, x3, x5) are * considered for the scalar, making the scalar itself 4d. * * @note This class only manages the accesses and not the memory itself. */ template <std::size_t Dimensionality, typename ArithmeticType, typename StorageType, std::uint64_t ScalarMask> class scaled_reduced_row_major : public detail::enable_write_scalar< Dimensionality, scaled_reduced_row_major<Dimensionality, ArithmeticType, StorageType, ScalarMask>, ArithmeticType, std::is_const<StorageType>::value> { public: using arithmetic_type = std::remove_cv_t<ArithmeticType>; using storage_type = StorageType; static constexpr auto dimensionality = Dimensionality; static constexpr auto scalar_mask = ScalarMask; static constexpr bool is_const{std::is_const<storage_type>::value}; using scalar_type = std::conditional_t<is_const, const arithmetic_type, arithmetic_type>; using const_accessor = scaled_reduced_row_major<dimensionality, arithmetic_type, const storage_type, ScalarMask>; static_assert(!is_complex<ArithmeticType>::value && !is_complex<StorageType>::value, "Both arithmetic and storage type must not be complex!"); static_assert(Dimensionality >= 1, "Dimensionality must be a positive number!"); static_assert(dimensionality <= 32, "Only Dimensionality <= 32 is currently supported"); // Allow access to both `scalar_` and `compute_mask_scalar_index()` friend class detail::enable_write_scalar< dimensionality, scaled_reduced_row_major, scalar_type>; friend class range<scaled_reduced_row_major>; protected: static constexpr std::size_t scalar_dim{ helper::count_mask_dimensionality<scalar_mask, dimensionality>()}; static constexpr std::size_t scalar_stride_dim{ scalar_dim == 0 ? 0 : (scalar_dim - 1)}; using dim_type = std::array<size_type, dimensionality>; using storage_stride_type = std::array<size_type, dimensionality - 1>; using scalar_stride_type = std::array<size_type, scalar_stride_dim>; using reference_type = reference_class::scaled_reduced_storage<arithmetic_type, StorageType>; private: using index_type = std::int64_t; protected: /** * Creates the accessor for an already allocated storage space with a * stride. The first stride is used for computing the index for the first * index, the second stride for the second index, and so on. * * @param size multidimensional size of the memory * @param storage pointer to the block of memory containing the storage * @param storage_stride stride array used for memory accesses to storage * @param scalar pointer to the block of memory containing the scalar * values. * @param scalar_stride stride array used for memory accesses to scalar */ constexpr GKO_ACC_ATTRIBUTES scaled_reduced_row_major( dim_type size, storage_type* storage, storage_stride_type storage_stride, scalar_type* scalar, scalar_stride_type scalar_stride) : size_(size), storage_{storage}, storage_stride_(storage_stride), scalar_{scalar}, scalar_stride_(scalar_stride) {} /** * Creates the accessor for an already allocated storage space with a * stride. The first stride is used for computing the index for the first * index, the second stride for the second index, and so on. * * @param size multidimensional size of the memory * @param storage pointer to the block of memory containing the storage * @param stride stride array used for memory accesses to storage * @param scalar pointer to the block of memory containing the scalar * values. */ constexpr GKO_ACC_ATTRIBUTES scaled_reduced_row_major( dim_type size, storage_type* storage, storage_stride_type stride, scalar_type* scalar) : scaled_reduced_row_major{ size, storage, stride, scalar, helper::compute_default_masked_row_major_stride_array< scalar_mask, scalar_stride_dim, dimensionality>(size)} {} /** * Creates the accessor for an already allocated storage space. * It is assumed that all accesses are without padding. * * @param size multidimensional size of the memory * @param storage pointer to the block of memory containing the storage * @param scalar pointer to the block of memory containing the scalar * values. */ constexpr GKO_ACC_ATTRIBUTES scaled_reduced_row_major(dim_type size, storage_type* storage, scalar_type* scalar) : scaled_reduced_row_major{ size, storage, helper::compute_default_row_major_stride_array(size), scalar} {} /** * Creates an empty accessor (pointing nowhere with an empty size) */ constexpr GKO_ACC_ATTRIBUTES scaled_reduced_row_major() : scaled_reduced_row_major{{0, 0, 0}, nullptr, nullptr} {} public: /** * Creates a scaled_reduced_row_major range which contains a read-only * version of the current accessor. * * @returns a scaled_reduced_row_major major range which is read-only. */ constexpr GKO_ACC_ATTRIBUTES range<const_accessor> to_const() const { return range<const_accessor>{size_, storage_, storage_stride_, scalar_, scalar_stride_}; } /** * Reads the scalar value at the given indices. Only indices where the * scalar mask bit is set are considered, the others are ignored. * * @param indices indices which data to access * * @returns the scalar value at the given indices. */ template <typename... Indices> constexpr GKO_ACC_ATTRIBUTES scalar_type read_scalar_masked(Indices&&... indices) const { const arithmetic_type* GKO_ACC_RESTRICT rest_scalar = scalar_; return rest_scalar[compute_mask_scalar_index( std::forward<Indices>(indices)...)]; } /** * Reads the scalar value at the given indices. Only the actually used * indices must be provided, meaning the number of specified indices must * be equal to the number of set bits in the scalar mask. * * @param indices indices which data to access * * @returns the scalar value at the given indices. */ template <typename... Indices> constexpr GKO_ACC_ATTRIBUTES scalar_type read_scalar_direct(Indices&&... indices) const { const arithmetic_type* GKO_ACC_RESTRICT rest_scalar = scalar_; return rest_scalar[compute_direct_scalar_index( std::forward<Indices>(indices)...)]; } /** * Returns the length in dimension `dimension`. * * @param dimension a dimension index * * @returns length in dimension `dimension` */ constexpr GKO_ACC_ATTRIBUTES size_type length(size_type dimension) const { return dimension < dimensionality ? size_[dimension] : 1; } /** * Returns the stored value for the given indices. If the storage is const, * a value is returned, otherwise, a reference is returned. * * @param indices indices which value is supposed to access * * @returns the stored value if the accessor is const (if the storage type * is const), or a reference if the accessor is non-const */ template <typename... Indices> constexpr GKO_ACC_ATTRIBUTES std::enable_if_t< are_all_integral<Indices...>::value, std::conditional_t<is_const, arithmetic_type, reference_type>> operator()(Indices... indices) const { return reference_type{storage_ + compute_index(indices...), read_scalar_masked(indices...)}; } /** * Returns a sub-range spinning the current range (x1_span, x2_span, ...) * * @param spans span for the indices * * @returns a sub-range for the given spans. */ template <typename... SpanTypes> constexpr GKO_ACC_ATTRIBUTES std::enable_if_t<helper::are_index_span_compatible<SpanTypes...>::value, range<scaled_reduced_row_major>> operator()(SpanTypes... spans) const { return helper::validate_index_spans(size_, spans...), range<scaled_reduced_row_major>{ dim_type{ (index_span{spans}.end - index_span{spans}.begin)...}, storage_ + compute_index((index_span{spans}.begin)...), storage_stride_, scalar_ + compute_mask_scalar_index(index_span{spans}.begin...), scalar_stride_}; } /** * Returns the size of the accessor * * @returns the size of the accessor */ constexpr GKO_ACC_ATTRIBUTES dim_type get_size() const { return size_; } /** * Returns a const reference to the storage stride array of size * dimensionality - 1 * * @returns a const reference to the storage stride array of size * dimensionality - 1 */ constexpr GKO_ACC_ATTRIBUTES const storage_stride_type& get_storage_stride() const { return storage_stride_; } /** * Returns a const reference to the scalar stride array * * @returns a const reference to the scalar stride array */ constexpr GKO_ACC_ATTRIBUTES const scalar_stride_type& get_scalar_stride() const { return scalar_stride_; } /** * Returns the pointer to the storage data * * @returns the pointer to the storage data */ constexpr GKO_ACC_ATTRIBUTES storage_type* get_stored_data() const { return storage_; } /** * Returns a const pointer to the storage data * * @returns a const pointer to the storage data */ constexpr GKO_ACC_ATTRIBUTES const storage_type* get_const_storage() const { return storage_; } /** * Returns the pointer to the scalar data * * @returns the pointer to the scalar data */ constexpr GKO_ACC_ATTRIBUTES scalar_type* get_scalar() const { return scalar_; } /** * Returns a const pointer to the scalar data * * @returns a const pointer to the scalar data */ constexpr GKO_ACC_ATTRIBUTES const scalar_type* get_const_scalar() const { return scalar_; } protected: template <typename... Indices> constexpr GKO_ACC_ATTRIBUTES size_type compute_index(Indices&&... indices) const { static_assert(sizeof...(Indices) == dimensionality, "Number of indices must match dimensionality!"); return helper::compute_row_major_index<index_type, dimensionality>( size_, storage_stride_, std::forward<Indices>(indices)...); } template <typename... Indices> constexpr GKO_ACC_ATTRIBUTES size_type compute_mask_scalar_index(Indices&&... indices) const { static_assert(sizeof...(Indices) == dimensionality, "Number of indices must match dimensionality!"); return helper::compute_masked_index<index_type, scalar_mask, scalar_stride_dim>( size_, scalar_stride_, std::forward<Indices>(indices)...); } template <typename... Indices> constexpr GKO_ACC_ATTRIBUTES size_type compute_direct_scalar_index(Indices&&... indices) const { static_assert( sizeof...(Indices) == scalar_dim, "Number of indices must match number of set bits in scalar mask!"); return helper::compute_masked_index_direct<index_type, scalar_mask, scalar_stride_dim>( size_, scalar_stride_, std::forward<Indices>(indices)...); } private: const dim_type size_; storage_type* const storage_; const storage_stride_type storage_stride_; scalar_type* const scalar_; const scalar_stride_type scalar_stride_; }; } // namespace acc } // namespace gko #endif // GKO_ACCESSOR_SCALED_REDUCED_ROW_MAJOR_HPP_
36.861446
80
0.661873
JakubTrzcskni
0a2345ce151ac883b882315f001ad2d8196644a1
3,195
cpp
C++
src/classical/xmg/xmg_path.cpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
src/classical/xmg/xmg_path.cpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
src/classical/xmg/xmg_path.cpp
eletesta/cirkit
6d0939798ea25cecf92306ce796be154139b94f5
[ "MIT" ]
null
null
null
/* CirKit: A circuit toolkit * Copyright (C) 2009-2015 University of Bremen * Copyright (C) 2015-2017 EPFL * * 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 "xmg_path.hpp" #include <vector> #include <boost/range/algorithm.hpp> namespace cirkit { /****************************************************************************** * Types * ******************************************************************************/ /****************************************************************************** * Private functions * ******************************************************************************/ /****************************************************************************** * Public functions * ******************************************************************************/ std::vector<std::vector<xmg_node>> xmg_find_critical_paths( xmg_graph& xmg ) { /* dynamic programming to compute each node delay */ std::vector<std::pair<xmg_node, unsigned>> delays( xmg.size(), std::make_pair( 0, 0 ) ); for ( auto node : xmg.topological_nodes() ) { if ( xmg.is_input( node ) ) { delays[node] = {node, 0u}; } else { for ( auto child : xmg.children( node ) ) { if ( delays[child.node].second + 1 >= delays[node].second ) { delays[node].first = child.node; delays[node].second = delays[child.node].second + 1; } } } } std::vector<std::vector<xmg_node>> critical_paths; for ( const auto& output : xmg.outputs() ) { std::vector<xmg_node> path; path.push_back( output.first.node ); while ( delays[path.back()].first != path.back() ) { path.push_back( delays[path.back()].first ); } boost::reverse( path ); critical_paths.push_back( path ); } return critical_paths; } } // Local Variables: // c-basic-offset: 2 // eval: (c-set-offset 'substatement-open 0) // eval: (c-set-offset 'innamespace 0) // End:
32.938144
90
0.533333
eletesta
0a24dde8f169bcf2ef83da543811e80997893197
347
cpp
C++
Dataset/Leetcode/train/94/88.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/94/88.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/94/88.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: void inorder(TreeNode*root,vector <int> & res) { if (root!=nullptr) return; inorder (root->left,res); res.push_back(root->val); inorder(root->right,res); } vector<int> XXX(TreeNode* root) { vector <int> vec; inorder(root,vec); return vec; } };
19.277778
51
0.541787
kkcookies99
0a25d69676aae709b47041e5d6b4f6c8a7db1610
924
cpp
C++
main.cpp
hnqiu/cpp-test
ec3eafd3126be8468ba4f2d6a26c5863659aa8e3
[ "MIT" ]
1
2019-03-21T04:06:13.000Z
2019-03-21T04:06:13.000Z
main.cpp
hnqiu/cpp-test
ec3eafd3126be8468ba4f2d6a26c5863659aa8e3
[ "MIT" ]
null
null
null
main.cpp
hnqiu/cpp-test
ec3eafd3126be8468ba4f2d6a26c5863659aa8e3
[ "MIT" ]
null
null
null
/* Copyright (C) 2019 hnqiu. All rights reserved. * Licensed under the MIT License. See LICENSE for details. */ #include <iostream> #include "string_test.h" #include "sizeof_test.h" #include "continue_test.h" #include "return_list_test.h" #include "return_pointer_to_array_test.h" #include "class_test.h" #include "cons_des.h" #include "inheritance_test.h" #include "template_test.h" #include "operator_test.h" #include "predicate_test.h" #include "bitset_test.h" #include "clock_test.h" int main(int argc, char *argv[]) { //string_test(); //sizeof_test(); //continue_test(); //return_list_test(); //return_pointer_to_array_test(); //class_test(); //smart_ptr_test(); //cons_des(); //inheritance_test(); //template_test(); //template_test_v2(); //operator_test(); // predicate_test(); bitset_test(); c_clock_test(); cpp_clock_test(); return 0; }
22.536585
59
0.675325
hnqiu
0a266fc73810200877750334d795b4558aaf7381
1,531
cpp
C++
src/vector_types.cpp
DoubleJump/waggle
06a2fb07d7e3678f990396d1469cf4f85e3863a1
[ "MIT" ]
1
2021-04-30T11:14:32.000Z
2021-04-30T11:14:32.000Z
src/vector_types.cpp
DoubleJump/waggle
06a2fb07d7e3678f990396d1469cf4f85e3863a1
[ "MIT" ]
null
null
null
src/vector_types.cpp
DoubleJump/waggle
06a2fb07d7e3678f990396d1469cf4f85e3863a1
[ "MIT" ]
null
null
null
struct Vec2 { f32 x, y; f32& operator[](int i){ return (&x)[i]; } }; struct Vec3 { f32 x, y, z; f32& operator[](int i){ return (&x)[i]; } }; static Vec3 vec3_up = {0,1,0}; static Vec3 vec3_down = {0,-1,0}; static Vec3 vec3_left = {-1,0,0}; static Vec3 vec3_right = {1,0,0}; static Vec3 vec3_forward = {0,0,1}; static Vec3 vec3_back = {0,0,-1}; static Vec3 vec3_zero = {0,0,0}; static Vec3 vec3_one = {1,1,1}; struct Vec4 { f32 x, y, z, w; f32& operator[](int i){ return (&x)[i]; } }; struct Mat3 { f32 m[9]; f32& operator[](int i){ return m[i]; } }; struct Mat4 { f32 m[16]; f32& operator[](int i){ return m[i]; }; }; struct Ray { Vec3 origin; Vec3 direction; f32 length; }; struct AABB { Vec3 min; Vec3 max; }; struct Bezier_Segment { Vec3 a,b,c,d; }; struct Triangle { Vec3 a,b,c; }; struct Plane { Vec3 position; Vec3 normal; }; struct Sphere { Vec3 position; f32 radius; }; struct Capsule { Vec3 position; f32 radius; f32 height; }; struct Hit_Info { b32 hit; Vec3 point; Vec3 normal; f32 t; }; enum struct Float_Primitive { F32 = 0, VEC2 = 1, VEC3 = 2, VEC4 = 3, QUATERNION = 4, }; static u32 get_stride(Float_Primitive p) { switch(p) { case Float_Primitive::F32: return 1; case Float_Primitive::VEC2: return 2; case Float_Primitive::VEC3: return 3; case Float_Primitive::VEC4: return 4; case Float_Primitive::QUATERNION: return 4; } }
13.918182
46
0.580666
DoubleJump
0a26a32a3eaa6c15d09010643fef518594583b5f
1,202
cpp
C++
src/example/greating_client.cpp
Nekrolm/grpc_callback
1f0db9f2dd60afe1fac400e6541698d8f1fc4c34
[ "WTFPL" ]
3
2019-07-27T16:01:01.000Z
2022-03-01T00:09:19.000Z
src/example/greating_client.cpp
Nekrolm/grpc_callback
1f0db9f2dd60afe1fac400e6541698d8f1fc4c34
[ "WTFPL" ]
null
null
null
src/example/greating_client.cpp
Nekrolm/grpc_callback
1f0db9f2dd60afe1fac400e6541698d8f1fc4c34
[ "WTFPL" ]
null
null
null
#include "greating_client.h" #include <grpcpp/channel.h> #include <functional> #include <thread> #include <memory> #include <grpc/simplified_async_callback_api.h> GreatingClient::GreatingClient(std::shared_ptr<grpc::Channel> ch) : stub_(test::Greeting::NewStub(ch)) {} GreatingClient::~GreatingClient() {} void GreatingClient::greeting(const std::string& name) { test::HelloRequest request; request.set_name(name); grpc::simple_responce_handler_t<test::HelloReply> callback = [](std::shared_ptr<test::HelloReply> reply, std::shared_ptr<grpc::Status> status) { if (status->ok()) std::cout << reply->message() << std::endl; else std::cout << "failed!" << std::endl; }; client_.request(stub_.get(), &test::Greeting::Stub::AsyncSayHello, request, callback); }
35.352941
116
0.46589
Nekrolm
0a2a3b88dd3554373e63dcb5ff92d9a0bd52f202
10,241
hxx
C++
src/Utils/Table.hxx
ebertolazzi/Malloc
4c1f8950cd631c185e141aaccfe0cd53daa91490
[ "BSD-2-Clause", "MIT" ]
null
null
null
src/Utils/Table.hxx
ebertolazzi/Malloc
4c1f8950cd631c185e141aaccfe0cd53daa91490
[ "BSD-2-Clause", "MIT" ]
null
null
null
src/Utils/Table.hxx
ebertolazzi/Malloc
4c1f8950cd631c185e141aaccfe0cd53daa91490
[ "BSD-2-Clause", "MIT" ]
null
null
null
/*--------------------------------------------------------------------------*\ | | | Copyright (C) 2021 | | | | , __ , __ | | /|/ \ /|/ \ | | | __/ _ ,_ | __/ _ ,_ | | | \|/ / | | | | \|/ / | | | | | |(__/|__/ |_/ \_/|/|(__/|__/ |_/ \_/|/ | | /| /| | | \| \| | | | | Enrico Bertolazzi | | Dipartimento di Ingegneria Industriale | | Universita` degli Studi di Trento | | email: enrico.bertolazzi@unitn.it | | | \*--------------------------------------------------------------------------*/ /// /// eof: Table.hxx /// /*\ Based on terminal-table: https://github.com/Bornageek/terminal-table Copyright 2015 Andreas Wilhelm 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. \*/ namespace Utils { namespace Table { using std::string; using std::vector; class Table; typedef int integer; enum Alignment { LEFT, RIGHT, CENTER }; class Style { private: char m_border_top = '-'; char m_border_top_mid = '+'; char m_border_top_left = '+'; char m_border_top_right = '+'; char m_border_bottom = '-'; char m_border_bottom_mid = '+'; char m_border_bottom_left = '+'; char m_border_bottom_right = '+'; char m_border_left = '|'; char m_border_left_mid = '+'; char m_border_mid = '-'; char m_border_mid_mid = '+'; char m_border_right = '|'; char m_border_right_mid = '+'; char m_border_middle = '|'; integer m_padding_left = 1; integer m_padding_right = 1; Alignment m_Align = Alignment::LEFT; integer m_Width = 0; public: Style() = default; char border_top() const { return m_border_top; } void border_top( char borderStyle ) { m_border_top = borderStyle; } char border_top_mid() const { return m_border_top_mid; } void border_top_mid( char borderStyle ) { m_border_top_mid = borderStyle; } char border_top_left() const { return m_border_top_left; } void border_top_left( char borderStyle ) { m_border_top_left = borderStyle; } char border_top_right() const { return m_border_top_right; } void border_top_right( char borderStyle ) { m_border_top_right = borderStyle; } char border_bottom() const { return m_border_bottom; } void border_bottom( char borderStyle ) { m_border_bottom = borderStyle; } char border_bottom_mid() const { return m_border_bottom_mid; } void border_bottom_mid( char borderStyle ) { m_border_bottom_mid = borderStyle; } char border_bottom_left() const { return m_border_bottom_left; } void border_bottom_left( char borderStyle ) { m_border_bottom_left = borderStyle; } char border_bottom_right() const { return m_border_bottom_right; } void border_bottom_right( char borderStyle) { m_border_bottom_right = borderStyle; } char border_left() const { return m_border_left; } void border_left( char borderStyle ) { m_border_left = borderStyle; } char border_left_mid() const { return m_border_left_mid; } void border_left_mid( char borderStyle ) { m_border_left_mid = borderStyle; } char border_mid() const { return m_border_mid; } void border_mid( char borderStyle ) { m_border_mid = borderStyle; } char border_mid_mid() const { return m_border_mid_mid; } void border_mid_mid( char borderStyle ) { m_border_mid_mid = borderStyle; } char border_right() const { return m_border_right; } void border_right( char borderStyle ) { m_border_right = borderStyle; } char border_right_mid() const { return m_border_right_mid; } void border_right_mid( char borderStyle ) { m_border_right_mid = borderStyle; } char border_middle() const { return m_border_middle; } void border_middle( char borderStyle ) { m_border_middle = borderStyle; } integer padding_left() const { return m_padding_left; } void padding_left( integer padding ) { m_padding_left = padding; } integer padding_right() const { return m_padding_right; } void padding_right( integer padding ) { m_padding_right = padding; } Alignment alignment() const { return m_Align; } void alignment( Alignment align ) { m_Align = align; } integer width() const { return m_Width; } void width( integer width ) { m_Width = width; } }; class Cell { private: Table * m_Table = nullptr; std::string m_Value = ""; Alignment m_Align = Alignment::LEFT; integer m_col_span = 1; integer m_Width = 0; public: Cell() = default; explicit Cell( Table* table, std::string const & val = "", integer col_span = 1 ); std::string const & value() const { return m_Value; } void value( std::string const & val ) { m_Value = val; } Alignment alignment() const { return m_Align; } void alignment( Alignment align ) { m_Align = align; } integer col_span() const { return m_col_span; } void col_span( integer col_span ) { m_col_span = col_span; } integer width( integer col ) const; integer height() const; integer maximum_line_width() const; std::string line( integer idx ) const; void trim_line( std::string & line ) const; std::string render( integer line, integer col ) const; }; class Row { protected: typedef std::vector<Cell> vecCell; typedef std::vector<std::string> vecstr; Table * m_Table = nullptr; vecCell m_Cells; public: Row() = default; explicit Row( Table * table, vecstr const & cells = vecstr() ); Table const * table() const { return m_Table; } //vecCell & cells() { return m_Cells; } void cells( vecstr const & cells ); integer num_cells() const { return integer(m_Cells.size()); } integer cell_width( integer idx ) const; void cell_col_span( integer idx, integer span ); void cell( std::string const & value ); //Cell& cell( integer idx ) { return m_Cells[idx]; } Cell const & operator [] ( integer idx ) const { return m_Cells[idx]; } Cell & operator [] ( integer idx ) { return m_Cells[idx]; } integer height() const; std::string render() const; }; class Table { public: typedef std::vector<Row> vecRow; typedef std::vector<Cell> vecCell; typedef std::vector<string> vecstr; typedef std::vector<vecstr> vecvecstr; typedef int integer; private: Style m_Style; std::string m_Title; Row m_Headings; vecRow m_Rows; public: Table() = default; explicit Table( Style const & style, vecvecstr const & rows = vecvecstr() ) : m_Style(style) { this->rows(rows); } void setup( Style const & style, vecvecstr const & rows = vecvecstr() ) { m_Style = style; this->rows(rows); } void align_column( integer n, Alignment align ); void add_row( vecstr const & row ); integer cell_spacing() const; integer cell_padding() const; vecCell column( integer n ) const; integer column_width( integer n ) const; integer num_columns() const; Style const & style() const { return m_Style; } void style( Style const & style ) { m_Style = style; } std::string const & title() const { return m_Title; } void title( std::string const & title ) { m_Title = title; } Row const & headings() const { return m_Headings; } void headings( vecstr const & headings ); Row & row( integer n ); Row const & row( integer n ) const; Row & operator [] ( integer n ) { return this->row(n); } Row const & operator [] ( integer n ) const { return this->row(n); } Cell & operator () ( integer i, integer j ) { return (*this)[i][j]; } Cell const & operator () ( integer i, integer j ) const { return (*this)[i][j]; } vecRow const & rows() const { return m_Rows; } void rows( vecvecstr const & rows ); std::string render_separator( char left, char mid, char right, char sep ) const; std::string render() const; }; } } inline Utils::ostream_type& operator << ( Utils::ostream_type& stream, Utils::Table::Row const & row ) { return stream << row.render(); } inline Utils::ostream_type& operator << ( Utils::ostream_type& stream, Utils::Table::Table const & table ) { return stream << table.render(); } /// /// eof: Table.hxx ///
31.318043
90
0.545357
ebertolazzi
0a2d06bc7e22d43976c5d56ab0c34f1f7e1b7e70
339
cpp
C++
Competitive Programing Problem Solutions/C++ Tutorial-Code - OOP/m4-d.cpp
BIJOY-SUST/ACM---ICPC
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
1
2022-02-27T12:07:59.000Z
2022-02-27T12:07:59.000Z
Competitive Programing Problem Solutions/C++ Tutorial-Code - OOP/m4-d.cpp
BIJOY-SUST/Competitive-Programming
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
null
null
null
Competitive Programing Problem Solutions/C++ Tutorial-Code - OOP/m4-d.cpp
BIJOY-SUST/Competitive-Programming
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int factorial(int n){ return (n == 1 || n == 0) ? 1 : factorial(n - 1)*n; } int main(){ int T,N,M; cin>>T; while(T--){ int ans; cin>>N>>M; ans = factorial(N+M-1)/(factorial(N)*factorial(M-1)); cout<<ans<<endl; } return 0; }
19.941176
62
0.471976
BIJOY-SUST
0a2d609e9dbd9540d570fb36b415739333d2abb0
387
cpp
C++
clang/test/SemaCXX/lookup-through-linkage.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
605
2019-10-18T01:15:54.000Z
2022-03-31T14:31:04.000Z
clang/test/SemaCXX/lookup-through-linkage.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
3,180
2019-10-18T01:21:21.000Z
2022-03-31T23:25:41.000Z
clang/test/SemaCXX/lookup-through-linkage.cpp
LaudateCorpus1/llvm-project
ff2e0f0c1112558b3f30d8afec7c9882c33c79e3
[ "Apache-2.0" ]
275
2019-10-18T05:27:22.000Z
2022-03-30T09:04:21.000Z
// RUN: %clang_cc1 %s -verify // expected-no-diagnostics extern "C++" { namespace A { namespace B { int bar; } } // namespace A namespace C { void foo() { using namespace A; (void)B::bar; } } // namespace C } extern "C" { extern "C++" { namespace D { namespace E { int bar; } } // namespace A namespace F { void foo() { using namespace D; (void)E::bar; } } // namespace C } }
11.382353
29
0.602067
LaudateCorpus1
0a2ed7375825eafbffc9a933d77cf1f6cfc96180
685
cpp
C++
src/QtYangVrRecord/src/video/yangrecordwin.cpp
yangxinghai/yangrecord
787eaca132df1e427f5fc5b4391db1436d481088
[ "MIT" ]
1
2021-11-11T02:06:55.000Z
2021-11-11T02:06:55.000Z
src/QtYangVrRecord/src/video/yangrecordwin.cpp
yangxinghai/yangrecord
787eaca132df1e427f5fc5b4391db1436d481088
[ "MIT" ]
null
null
null
src/QtYangVrRecord/src/video/yangrecordwin.cpp
yangxinghai/yangrecord
787eaca132df1e427f5fc5b4391db1436d481088
[ "MIT" ]
1
2022-01-24T07:59:48.000Z
2022-01-24T07:59:48.000Z
#include "yangrecordwin.h" #include "yangutil/yangtype.h" #include <QMenu> #include <QAction> #include <QDebug> //#include "../tooltip/RDesktopTip.h" #include "../yangwinutil/yangrecordcontext.h" YangRecordWin::YangRecordWin(QWidget *parent):QWidget(parent) { m_hb=new QHBoxLayout(); m_hb->setMargin(0); m_hb->setSpacing(1); setLayout(m_hb); this->setAutoFillBackground(true); //m_selectUser=nullptr; vwin=nullptr; //this->setWidget(m_centerWdiget); } YangRecordWin::~YangRecordWin() { // m_mh=nullptr; //m_selectUser=nullptr; // if(1) return; YANG_DELETE(vwin); YANG_DELETE(m_hb); } void YangRecordWin::init(){ }
15.222222
61
0.671533
yangxinghai
0a2f8e4a67a74949a182496fb002fdf38f79a3e7
5,912
cpp
C++
Sources/CEigenBridge/eigen_dbl.cpp
taketo1024/swm-eigen
952ecdb73a2739641e75909c8d9e724e32b2ed0f
[ "MIT" ]
6
2021-09-19T07:55:41.000Z
2021-11-10T00:43:47.000Z
Sources/CEigenBridge/eigen_dbl.cpp
taketo1024/swm-eigen
952ecdb73a2739641e75909c8d9e724e32b2ed0f
[ "MIT" ]
null
null
null
Sources/CEigenBridge/eigen_dbl.cpp
taketo1024/swm-eigen
952ecdb73a2739641e75909c8d9e724e32b2ed0f
[ "MIT" ]
null
null
null
// // File.cpp // // // Created by Taketo Sano on 2021/06/10. // #import "eigen_dbl.h" #import <iostream> #import <Eigen/Eigen> using namespace std; using namespace Eigen; using R = double; using Mat = Matrix<R, Dynamic, Dynamic>; void *eigen_dbl_init(int_t rows, int_t cols) { Mat *A = new Mat(rows, cols); A->setZero(); return static_cast<void *>(A); } void eigen_dbl_free(void *ptr) { Mat *A = static_cast<Mat *>(ptr); delete A; } void eigen_dbl_copy(void *from, void *to) { Mat *A = static_cast<Mat *>(from); Mat *B = static_cast<Mat *>(to); *B = *A; } double eigen_dbl_get_entry(void *a, int_t i, int_t j) { Mat *A = static_cast<Mat *>(a); return A->coeff(i, j); } void eigen_dbl_set_entry(void *a, int_t i, int_t j, double r) { Mat *A = static_cast<Mat *>(a); A->coeffRef(i, j) = r; } void eigen_dbl_copy_entries(void *a, double *vals) { Mat *A = static_cast<Mat *>(a); for(int_t i = 0; i < A->rows(); i++) { for(int_t j = 0; j < A->cols(); j++) { *(vals++) = A->coeff(i, j); } } } int_t eigen_dbl_rows(void *a) { Mat *A = static_cast<Mat *>(a); return A->rows(); } int_t eigen_dbl_cols(void *a) { Mat *A = static_cast<Mat *>(a); return A->cols(); } bool eigen_dbl_is_zero(void *a) { Mat *A = static_cast<Mat *>(a); return A->isZero(); } double eigen_dbl_det(void *a) { Mat *A = static_cast<Mat *>(a); return A->determinant(); } double eigen_dbl_trace(void *a) { Mat *A = static_cast<Mat *>(a); return A->trace(); } void eigen_dbl_inv(void *a, void *b) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); *B = A->inverse(); } void eigen_dbl_transpose(void *a, void *b) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); *B = A->transpose(); } void eigen_dbl_submatrix(void *a, int_t i, int_t j, int_t h, int_t w, void *b) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); *B = A->block(i, j, h, w); } void eigen_dbl_concat(void *a, void *b, void *c) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); Mat *C = static_cast<Mat *>(c); C->leftCols(A->cols()) = *A; C->rightCols(B->cols()) = *B; } void eigen_dbl_stack(void *a, void *b, void *c) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); Mat *C = static_cast<Mat *>(c); C->topRows(A->rows()) = *A; C->bottomRows(B->rows()) = *B; } void eigen_dbl_perm_rows(void *a, perm_t p, void *b) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); Eigen::VectorXi indices(p.length); for(int_t i = 0; i < p.length; ++i) { indices[i] = p.indices[i]; } PermutationMatrix<Eigen::Dynamic> P(indices); *B = P * (*A); } void eigen_dbl_perm_cols(void *a, perm_t p, void *b) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); Eigen::VectorXi indices(p.length); for(int_t i = 0; i < p.length; ++i) { indices[i] = p.indices[i]; } PermutationMatrix<Eigen::Dynamic> P(indices); *B = (*A) * P.transpose(); } bool eigen_dbl_eq(void *a, void *b) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); return (*A).isApprox(*B); } void eigen_dbl_add(void *a, void *b, void *c) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); Mat *C = static_cast<Mat *>(c); *C = *A + *B; } void eigen_dbl_neg(void *a, void *b) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); *B = -(*A); } void eigen_dbl_minus(void *a, void *b, void *c) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); Mat *C = static_cast<Mat *>(c); *C = *A - *B; } void eigen_dbl_mul(void *a, void *b, void *c) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); Mat *C = static_cast<Mat *>(c); *C = (*A) * (*B); } void eigen_dbl_scal_mul(double r, void *a, void *b) { Mat *A = static_cast<Mat *>(a); Mat *B = static_cast<Mat *>(b); *B = r * (*A); } void eigen_dbl_lu(void *a, perm_t p, perm_t q, void *l, void *u) { Mat *A = static_cast<Mat *>(a); Mat *L = static_cast<Mat *>(l); Mat *U = static_cast<Mat *>(u); int_t n = A->rows(); int_t m = A->cols(); if(n == 0 || m == 0) { L->resize(n, 0); U->resize(0, m); } else { using LU = FullPivLU<Mat>; LU lu(*A); int_t r = lu.rank(); // make P LU::PermutationPType::IndicesType P = lu.permutationP().indices(); for(int_t i = 0; i < n; ++i) { p.indices[i] = P[i]; } // make Q LU::PermutationQType::IndicesType Q = lu.permutationQ().indices(); for(int_t i = 0; i < m; ++i) { q.indices[i] = Q[i]; } // make L L->resize(n, r); L->setIdentity(); L->triangularView<StrictlyLower>() = lu.matrixLU().block(0, 0, n, r); // make U U->resize(r, m); U->triangularView<Upper>() = lu.matrixLU().block(0, 0, r, m); } } void eigen_dbl_solve_lt(void *l, void *b, void *x) { Mat *L = static_cast<Mat *>(l); Mat *B = static_cast<Mat *>(b); Mat *X = static_cast<Mat *>(x); using DMat = Matrix<R, Dynamic, Dynamic>; DMat b_ = *B; DMat x_ = L->triangularView<Lower>().solve(b_); *X = x_.sparseView(); } void eigen_dbl_solve_ut(void *u, void *b, void *x) { Mat *U = static_cast<Mat *>(u); Mat *B = static_cast<Mat *>(b); Mat *X = static_cast<Mat *>(x); using DMat = Matrix<R, Dynamic, Dynamic>; DMat b_ = *B; DMat x_ = U->triangularView<Upper>().solve(b_); *X = x_.sparseView(); } void eigen_dbl_dump(void *ptr) { Mat *m = static_cast<Mat *>(ptr); cout << *m << endl; }
24.03252
80
0.538058
taketo1024
0a30f745e13504ad1b5ed62319ce67bdfb9ab3f3
7,152
inl
C++
MathLib/Include/CoordinatePoints.inl
bgin/MissileSimulation
90adcbf1c049daafb939f3fe9f9dfe792f26d5df
[ "MIT" ]
23
2016-08-28T23:20:12.000Z
2021-12-15T14:43:58.000Z
MathLib/Include/CoordinatePoints.inl
bgin/MissileSimulation
90adcbf1c049daafb939f3fe9f9dfe792f26d5df
[ "MIT" ]
1
2018-06-02T21:29:51.000Z
2018-06-05T05:59:31.000Z
MathLib/Include/CoordinatePoints.inl
bgin/MissileSimulation
90adcbf1c049daafb939f3fe9f9dfe792f26d5df
[ "MIT" ]
1
2019-07-04T22:38:22.000Z
2019-07-04T22:38:22.000Z
mathlib::CoordPoints<__m128>::CoordPoints() { /*Initialize coordinates to zero*/ this->m_F32Coord3D = _mm_setzero_ps(); } mathlib::CoordPoints<__m128>::CoordPoints(_In_ const float x, _In_ const float y, _In_ const float z) : m_F32Coord3D(_mm_set_ps(NAN_FLT, z, y, x)) { } mathlib::CoordPoints<__m128>::CoordPoints(_In_ const float s) : m_F32Coord3D(_mm_set_ps(NAN_FLT, s, s, s)) { } mathlib::CoordPoints<__m128>::CoordPoints(_In_ const double x, _In_ const double y, _In_ const double z) : /* Warning: Precion is lost from ~16 digits to ~8*/ m_F32Coord3D(_mm256_cvtpd_ps(_mm256_set_pd(NAN_DBL, z, y, x))) { } mathlib::CoordPoints<__m128>::CoordPoints(_In_ float(&ar)[4]) : m_F32Coord3D(_mm_loadu_ps(&ar[0])) { } mathlib::CoordPoints<__m128>::CoordPoints(_In_ const std::initializer_list<float> &list) : m_F32Coord3D(_mm_loadu_ps(&list.begin()[0])){ } mathlib::CoordPoints<__m128>::CoordPoints(_In_ const __m128 &v) : m_F32Coord3D(v) { } mathlib::CoordPoints<__m128>::CoordPoints(_In_ const CoordPoints &rhs) : m_F32Coord3D(rhs.m_F32Coord3D){ } mathlib::CoordPoints<__m128>::CoordPoints(_In_ CoordPoints &&rhs) : m_F32Coord3D(std::move(rhs.m_F32Coord3D)) { } auto mathlib::CoordPoints<__m128>::operator=(_In_ const CoordPoints &rhs)->mathlib::CoordPoints<__m128> &{ if (this == &rhs) return (*this); this->m_F32Coord3D = rhs.m_F32Coord3D; return (*this); } auto mathlib::CoordPoints<__m128>::operator=(_In_ const CoordPoints &&rhs)->mathlib::CoordPoints<__m128> & { if (this == &rhs) return (*this); this->m_F32Coord3D = std::move(rhs.m_F32Coord3D); return (*this); } auto mathlib::CoordPoints<__m128>::operator+=(_In_ const CoordPoints &rhs)->mathlib::CoordPoints<__m128> & { this->m_F32Coord3D = _mm_add_ps(this->m_F32Coord3D, rhs.m_F32Coord3D); return (*this); } auto mathlib::CoordPoints<__m128>::operator+=(_In_ const float s)->mathlib::CoordPoints<__m128> & { this->m_F32Coord3D = _mm_add_ps(this->m_F32Coord3D,_mm_set_ps(NAN_FLT, s, s, s)); return (*this); } auto mathlib::CoordPoints<__m128>::operator-=(_In_ const CoordPoints &rhs)->mathlib::CoordPoints<__m128> & { this->m_F32Coord3D = _mm_sub_ps(this->m_F32Coord3D, rhs.m_F32Coord3D); return (*this); } auto mathlib::CoordPoints<__m128>::operator-=(_In_ const float s)->mathlib::CoordPoints<__m128> & { this->m_F32Coord3D = _mm_sub_ps(this->m_F32Coord3D, _mm_set_ps(NAN_FLT, s, s, s)); return (*this); } auto mathlib::CoordPoints<__m128>::operator*=(_In_ const CoordPoints &rhs)->mathlib::CoordPoints<__m128> & { this->m_F32Coord3D = _mm_mul_ps(this->m_F32Coord3D, rhs.m_F32Coord3D); return (*this); } auto mathlib::CoordPoints<__m128>::operator*=(_In_ const float s)->mathlib::CoordPoints<__m128> & { this->m_F32Coord3D = _mm_mul_ps(this->m_F32Coord3D, _mm_set_ps(NAN_FLT, s, s, s)); return (*this); } auto mathlib::CoordPoints<__m128>::operator/=(_In_ const CoordPoints &rhs)->mathlib::CoordPoints<__m128> & { if (!(_mm_testz_ps(rhs.m_F32Coord3D, _mm_set_ps(NAN_FLT, 0.f, 0.f, 0.f)))){ this->m_F32Coord3D = _mm_mul_ps(this->m_F32Coord3D, _mm_rcp_ps(rhs.m_F32Coord3D)); return (*this); } } auto mathlib::CoordPoints<__m128>::operator/=(_In_ const float s)->mathlib::CoordPoints<__m128> & { if (s != 0.f){ float inv_s{ 1.f / s }; this->m_F32Coord3D = _mm_mul_ps(this->m_F32Coord3D, _mm_set_ps(NAN_FLT, inv_s, inv_s, inv_s)); return (*this); } } auto mathlib::CoordPoints<__m128>::operator==(_In_ const CoordPoints &rhs)const-> __m128 { return (_mm_cmpeq_ps(this->m_F32Coord3D, rhs.m_F32Coord3D)); } auto mathlib::CoordPoints<__m128>::operator==(_In_ const float s)const-> __m128 { // 3rd scalar counting from 0 = Don't care return (_mm_cmpeq_ps(this->m_F32Coord3D, _mm_set_ps(NAN_FLT, s, s, s))); } auto mathlib::CoordPoints<__m128>::operator!=(_In_ const CoordPoints &rhs)const-> __m128 { return (_mm_cmpneq_ps(this->m_F32Coord3D, rhs.m_F32Coord3D)); } auto mathlib::CoordPoints<__m128>::operator!=(_In_ const float s)const-> __m128 { // 3rd scalar counting from 0 = Don't care return (_mm_cmpneq_ps(this->m_F32Coord3D, _mm_set_ps(NAN_FLT, s, s, s))); } mathlib::CoordPoints<__m128>::operator __m128 () { return this->m_F32Coord3D; } mathlib::CoordPoints<__m128>::operator __m128 const () const { return this->m_F32Coord3D; } auto mathlib::operator<<(_In_ std::ostream &os, _In_ const mathlib::CoordPoints<__m128> &rhs)->std::ostream & { os << "X: " << reinterpret_cast<const double*>(&rhs.m_F32Coord3D)[0] << std::endl; os << "Y: " << reinterpret_cast<const double*>(&rhs.m_F32Coord3D)[1] << std::endl; os << "Z: " << reinterpret_cast<const double*>(&rhs.m_F32Coord3D)[2] << std::endl; return os; } inline auto mathlib::CoordPoints<__m128>::getF32Coord3D()const-> __m128 { return this->m_F32Coord3D; } inline auto mathlib::CoordPoints<__m128>::X()const->float { return (reinterpret_cast<const double*>(&this->m_F32Coord3D)[0]); } inline auto mathlib::CoordPoints<__m128>::Y()const->float { return (reinterpret_cast<const double*>(&this->m_F32Coord3D)[1]); } inline auto mathlib::CoordPoints<__m128>::Z()const->float { return (reinterpret_cast<const double*>(&this->m_F32Coord3D)[2]); } inline auto mathlib::CoordPoints<__m128>::CArray()->double * { double* pF32Coord3D = nullptr; pF32Coord3D = reinterpret_cast<double*>(&this->m_F32Coord3D); return (pF32Coord3D); } inline auto mathlib::CoordPoints<__m128>::CArray()const->const double * { const double* pF32Coord3D = nullptr; pF32Coord3D = reinterpret_cast<const double*>(&this->m_F32Coord3D); return (pF32Coord3D); } inline auto mathlib::CoordPoints<__m128>::setX(_In_ const float s)->void { this->m_F32Coord3D.m128_f32[0] = s; } inline auto mathlib::CoordPoints<__m128>::setY(_In_ const float s)->void { this->m_F32Coord3D.m128_f32[1] = s; } inline auto mathlib::CoordPoints<__m128>::setZ(_In_ const float s)->void { this->m_F32Coord3D.m128_f32[2] = s; } inline auto mathlib::CoordPoints<__m128>::magnitude()const->float { auto temp(_mm_mul_ps(this->m_F32Coord3D, this->m_F32Coord3D)); return (reinterpret_cast<const double*>(&temp)[0] + reinterpret_cast<const double*>(&temp)[1] + reinterpret_cast<const double*>(&temp)[2]); } inline auto mathlib::CoordPoints<__m128>::perpendicular()const->float { auto temp(_mm_mul_ps(this->m_F32Coord3D, this->m_F32Coord3D)); return (reinterpret_cast<const double*>(&temp)[0] + reinterpret_cast<const double*>(&temp)[1]); } inline auto mathlib::CoordPoints<__m128>::rho()const->float { return (std::sqrt(this->perpendicular())); } inline auto mathlib::CoordPoints<__m128>::phi()const->float { return((this->X() == 0.f && this->Y() == 0.f) ? 0.f : std::atan2(this->X(), this->Y())); } inline auto mathlib::CoordPoints<__m128>::theta()const->float { return ((this->X() == 0.f && this->Y() == 0.f && this->Z()) ? 0.f : std::atan2(this->rho(), this->Z())); }
31.646018
115
0.685263
bgin
0a37e91c00ea720fe4fc3942d74ef52cc8dae67b
3,082
cpp
C++
old.c++/AGIResources/PlatformAbstractionLayer_POSIX.cpp
princess-rosella/sierra-agi-resources
2755e7b04a4f9782ced4530016e4374ca5b7985b
[ "MIT" ]
null
null
null
old.c++/AGIResources/PlatformAbstractionLayer_POSIX.cpp
princess-rosella/sierra-agi-resources
2755e7b04a4f9782ced4530016e4374ca5b7985b
[ "MIT" ]
null
null
null
old.c++/AGIResources/PlatformAbstractionLayer_POSIX.cpp
princess-rosella/sierra-agi-resources
2755e7b04a4f9782ced4530016e4374ca5b7985b
[ "MIT" ]
null
null
null
// // PlatformAbstractionLayer_POSIX.cpp // AGI // // Copyright (c) 2018 Princess Rosella. All rights reserved. // #include "AGIResources.hpp" #include "PlatformAbstractionLayer_POSIX.hpp" #include <dirent.h> #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <vector> using namespace AGI::Resources; PlatformAbstractionLayer_POSIX_FileDescriptor::PlatformAbstractionLayer_POSIX_FileDescriptor(int desc) : _desc(desc) { } PlatformAbstractionLayer_POSIX_FileDescriptor::~PlatformAbstractionLayer_POSIX_FileDescriptor() { if (_desc >= 0) close(_desc); } ssize_t PlatformAbstractionLayer_POSIX_FileDescriptor::readall(void* data, size_t length) { ssize_t readed = 0; while (length) { ssize_t thisRead = read(_desc, data, length); if (thisRead < 0) return thisRead; else if (thisRead == 0) break; data = ((uint8_t*)data) + thisRead; length -= thisRead; } if (length) memset(data, 0, length); return readed; } PlatformAbstractionLayer_POSIX::PlatformAbstractionLayer_POSIX(const std::string& folder) : _folder(folder) { if (_folder.length() == 0) { _folder = "./"; return; } if (_folder[_folder.length() - 1] == '/') return; _folder += '/'; } std::string PlatformAbstractionLayer_POSIX::fullPathName(const char* fileName) const { return _folder + fileName; } bool PlatformAbstractionLayer_POSIX::fileExists(const char* fileName) const { if (access(fullPathName(fileName).c_str(), R_OK)) return false; return true; } size_t PlatformAbstractionLayer_POSIX::fileSize(const char* fileName) const { struct stat st; if (stat(fullPathName(fileName).c_str(), &st)) return (size_t)-1u; return (size_t)st.st_size; } bool PlatformAbstractionLayer_POSIX::fileRead(const char* fileName, size_t offset, void* data, size_t length) const { std::unique_ptr<PlatformAbstractionLayer_POSIX_FileDescriptor> fd(new PlatformAbstractionLayer_POSIX_FileDescriptor(open(fullPathName(fileName).c_str(), O_RDONLY))); if (offset) { if (lseek(fd->desc(), offset, SEEK_SET) == -1) throw std::runtime_error(strerror(errno)); } if (fd->readall(data, length) < 0) throw std::runtime_error(strerror(errno)); return true; } std::vector<std::string> PlatformAbstractionLayer_POSIX::fileList() const { DIR *dir = opendir(_folder.c_str()); if (!dir) return std::vector<std::string>(); std::vector<std::string> files; while (struct dirent *entry = readdir(dir)) { std::string name(entry->d_name, entry->d_namlen); if (name == "." || name == ".." || name[0] == '.') continue; files.push_back(name); } closedir(dir); return files; } std::string AGI::Resources::format(const char* format, ...) { va_list va; char buffer[2048]; va_start(va, format); vsnprintf(buffer, sizeof(buffer), format, va); va_end(va); return buffer; }
24.854839
169
0.658014
princess-rosella
0a3c83602b58e93c47389718b0ec4248917f4c0e
3,644
cpp
C++
PitchedDelay/Source/dsp/simpledetune.cpp
elk-audio/lkjb-plugins
8cbff01864bdb76493361a46f56d7073d49698da
[ "MIT" ]
82
2016-12-02T20:02:30.000Z
2022-03-12T22:38:30.000Z
PitchedDelay/Source/dsp/simpledetune.cpp
elk-audio/lkjb-plugins
8cbff01864bdb76493361a46f56d7073d49698da
[ "MIT" ]
6
2018-01-19T21:44:46.000Z
2022-03-08T08:46:19.000Z
PitchedDelay/Source/dsp/simpledetune.cpp
elk-audio/lkjb-plugins
8cbff01864bdb76493361a46f56d7073d49698da
[ "MIT" ]
16
2016-04-13T08:31:36.000Z
2022-03-01T03:04:42.000Z
#include "simpledetune.h" DetunerBase::DetunerBase(int bufmax) : bufMax(bufmax), windowSize(0), sampleRate(44100), buf(bufMax), win(bufMax) { clear(); setWindowSize(bufMax); } void DetunerBase::clear() { pos0 = 0; pos1 = 0.f; pos2 = 0.f; for(int i=0;i<bufMax;i++) buf[i] = 0; } void DetunerBase::setWindowSize(int size, bool force) { //recalculate crossfade window if (windowSize != size || force) { windowSize = size; if (windowSize >= bufMax) windowSize = bufMax; //bufres = 1000.0f * (float)windowSize / sampleRate; double p=0.0; double dp = 6.28318530718 / windowSize; for(int i=0;i<windowSize;i++) { win[i] = (float)(0.5 - 0.5 * cos(p)); p+=dp; } } } void DetunerBase::setPitchSemitones(float newPitch) { dpos2 = (float)pow(1.0594631f, newPitch); dpos1 = 1.0f / dpos2; } void DetunerBase::setPitch(float newPitch) { dpos2 = newPitch; dpos1 = 1.0f / dpos2; } void DetunerBase::setSampleRate(float newSampleRate) { if (sampleRate != newSampleRate) { sampleRate = newSampleRate; setWindowSize(windowSize, true); } } void DetunerBase::processBlock(float* data, int numSamples) { float a, b, c, d; float x; float p1 = pos1; float p1f; float d1 = dpos1; float p2 = pos2; float d2 = dpos2; int p0 = pos0; int p1i; int p2i; int l = windowSize-1; int lh = windowSize>>1; float lf = (float) windowSize; for (int i=0; i<numSamples; ++i) { a = data[i]; b = a; c = 0; d = 0; --p0 &= l; *(buf + p0) = (a); //input p1 -= d1; if(p1<0.0f) p1 += lf; //output p1i = (int) p1; p1f = p1 - (float) p1i; a = *(buf + p1i); ++p1i &= l; a += p1f * (*(buf + p1i) - a); //linear interpolation p2i = (p1i + lh) & l; //180-degree ouptut b = *(buf + p2i); ++p2i &= l; b += p1f * (*(buf + p2i) - b); //linear interpolation p2i = (p1i - p0) & l; //crossfade x = *(win + p2i); //++p2i &= l; //x += p1f * (*(win + p2i) - x); //linear interpolation (doesn't do much) c += b + x * (a - b); p2 -= d2; //repeat for downwards shift - can't see a more efficient way? if(p2<0.0f) p2 += lf; //output p1i = (int) p2; p1f = p2 - (float) p1i; a = *(buf + p1i); ++p1i &= l; a += p1f * (*(buf + p1i) - a); //linear interpolation p2i = (p1i + lh) & l; //180-degree ouptut b = *(buf + p2i); ++p2i &= l; b += p1f * (*(buf + p2i) - b); //linear interpolation p2i = (p1i - p0) & l; //crossfade x = *(win + p2i); //++p2i &= l; //x += p1f * (*(win + p2i) - x); //linear interpolation (doesn't do much) d += b + x * (a - b); data[i] = d; } pos0=p0; pos1=p1; pos2=p2; } int DetunerBase::getWindowSize() { return windowSize; } // ============================================================================================================== Detune::Detune(const String& name_, int windowSize) : name(name_), tunerL(windowSize), tunerR(windowSize) { } void Detune::prepareToPlay(double sampleRate, int /*blockSize*/) { tunerL.setSampleRate((float) sampleRate); tunerR.setSampleRate((float) sampleRate); } void Detune::processBlock(float* chL, float* chR, int numSamples) { tunerL.processBlock(chL, numSamples); tunerR.processBlock(chR, numSamples); } void Detune::processBlock(float* ch, int numSamples) { tunerL.processBlock(ch, numSamples); } void Detune::setPitch(float newPitch) { tunerL.setPitch(newPitch); tunerR.setPitch(newPitch); } int Detune::getLatency() { return tunerL.getWindowSize(); } void Detune::clear() { tunerL.clear(); tunerR.clear(); } String Detune::getName() { return name; }
18.591837
113
0.572448
elk-audio
0a3e70e44718dea8c998736ac815ba9c233a23c2
1,261
cc
C++
src/flow/transform/EmptyBlockElimination.cc
christianparpart/libflow
29c8a4b4c1ba140c1a3998dcb84885386d312787
[ "Unlicense" ]
null
null
null
src/flow/transform/EmptyBlockElimination.cc
christianparpart/libflow
29c8a4b4c1ba140c1a3998dcb84885386d312787
[ "Unlicense" ]
null
null
null
src/flow/transform/EmptyBlockElimination.cc
christianparpart/libflow
29c8a4b4c1ba140c1a3998dcb84885386d312787
[ "Unlicense" ]
null
null
null
// This file is part of the "x0" project, http://github.com/christianparpart/libflow// // (c) 2009-2014 Christian Parpart <trapni@gmail.com> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <flow/transform/EmptyBlockElimination.h> #include <flow/ir/BasicBlock.h> #include <flow/ir/IRHandler.h> #include <flow/ir/Instructions.h> #include <list> namespace flow { bool EmptyBlockElimination::run(IRHandler* handler) { std::list<BasicBlock*> eliminated; for (BasicBlock* bb : handler->basicBlocks()) { if (bb->instructions().size() != 1) continue; if (BrInstr* br = dynamic_cast<BrInstr*>(bb->getTerminator())) { BasicBlock* newSuccessor = br->targetBlock(); eliminated.push_back(bb); if (bb == handler->getEntryBlock()) { handler->setEntryBlock(bb); break; } else { for (BasicBlock* pred : bb->predecessors()) { pred->getTerminator()->replaceOperand(bb, newSuccessor); } } } } for (BasicBlock* bb : eliminated) { bb->parent()->erase(bb); } return eliminated.size() > 0; } } // namespace flow
28.659091
86
0.656622
christianparpart
0a4602ec6f7a003112d67433dac9b55f964d6207
17,254
cpp
C++
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/common/exports.cpp
nsivov/wpf
d36941860f05dd7a09008e99d1bcd635b0a69fdb
[ "MIT" ]
2
2020-05-18T17:00:43.000Z
2021-12-01T10:00:29.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/common/exports.cpp
nsivov/wpf
d36941860f05dd7a09008e99d1bcd635b0a69fdb
[ "MIT" ]
5
2020-05-05T08:05:01.000Z
2021-12-11T21:35:37.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/core/common/exports.cpp
nsivov/wpf
d36941860f05dd7a09008e99d1bcd635b0a69fdb
[ "MIT" ]
4
2020-05-04T06:43:25.000Z
2022-02-20T12:02:50.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ // // //------------------------------------------------------------------------- #include "precomp.hpp" //+------------------------------------------------------------------------ // // Function: MIL3DCalcProjected2DBounds // // Synopsis: Computes the 2D screen bounds of the CMilPointAndSize3F after // projecting with the current 3D world, view, and projection // transforms and clipping to the camera's Near and Far // planes. // //------------------------------------------------------------------------- extern "C" HRESULT WINAPI MIL3DCalcProjected2DBounds( __in_ecount(1) const CMatrix<CoordinateSpace::Local3D,CoordinateSpace::PageInPixels> *pFullTransform3D, __in_ecount(1) const CMilPointAndSize3F *pboxBounds, __out_ecount(1) CRectF<CoordinateSpace::PageInPixels> *prcTargetRect ) { HRESULT hr = S_OK; CFloatFPU oGuard; if (pFullTransform3D == NULL || pboxBounds == NULL || prcTargetRect == NULL) { IFC(E_INVALIDARG); } CalcProjectedBounds(*pFullTransform3D, pboxBounds, prcTargetRect); Cleanup: RRETURN(hr); } //+----------------------------------------------------------------------------- // // Calculate a mask for the number of "bits to mask" at a "bit offset" from // the left (high-order bit) of a single byte. // // Consider this example: // // bitOffset=3 // bitsToMask=3 // // In memory, this is laid out as: // // ------------------------------------------------- // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | // ------------------------------------------------- // <--- bitOffset ---> // <-- bitsToMask --> // // The general algorithm is to start with 0xFF, shift to the right such that // only bitsToMask number of bits are left on, and then shift back to the // left to align with the requested bitOffset. // // The result will be: // // ------------------------------------------------- // | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | // ------------------------------------------------- // //------------------------------------------------------------------------------ BYTE GetOffsetMask( __in_range(0, 7) UINT bitOffset, __in_range(1, 8) UINT bitsToMask ) { Assert((bitOffset + bitsToMask) <= 8); BYTE mask = 0xFF; UINT maskShift = 8 - bitsToMask; mask = static_cast<BYTE>(mask >> maskShift); mask <<= (maskShift - bitOffset); return mask; } //+----------------------------------------------------------------------------- // // Return the next byte (or partial byte) from the input buffer starting at the // specified bit offset and containing no more than the specified remaining // bits to copy. In the case of a partial byte, the results are left-aligned. // // Consider this example: // // inputBufferOffsetInBits=5 // bitsRemainingToCopy=4 // // In memory, this is laid out as: // // --------------------------------------------------------------- // | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 | 7 | 6 ... // --------------------------------------------------------------- // <-- inputBufferOffsetInBits --> // <- bitsRemainingToCopy-> // // The result will be a single byte containing the 3 lower bits of the first // byte plus the 1 upper bit of the second byte. // //------------------------------------------------------------------------------ BYTE GetNextByteFromInputBuffer( __in_bcount(2) BYTE * pInputBuffer, // Some cases only require 1 byte... __in_range(0, 7) UINT inputBufferOffsetInBits, __in_range(1, UINT_MAX) UINT bitsRemainingToCopy ) { // bitsRemainingToCopy could be some huge number. We only care about the // next byte's worth. if (bitsRemainingToCopy > 8) bitsRemainingToCopy = 8; if (inputBufferOffsetInBits == 0) { BYTE mask = GetOffsetMask(0, bitsRemainingToCopy); return pInputBuffer[0] & mask; } BYTE nextByte = 0; UINT bitsFromFirstByte = 8 - inputBufferOffsetInBits; // Read from the first byte. The results are left-aligned. BYTE mask = GetOffsetMask(inputBufferOffsetInBits, bitsFromFirstByte); nextByte = pInputBuffer[0] & mask; nextByte <<= inputBufferOffsetInBits; bitsRemainingToCopy -= bitsFromFirstByte; // Read from the second byte, if needed if (bitsRemainingToCopy > 0) { // Note: bitsRemainingToCopy and bitsFromFirstByte are both small // numbers, so addition is safe from overflow. if (bitsRemainingToCopy + bitsFromFirstByte == 8) { // This is a common case where we are reading 8 bits of data // straddled across a byte boundary. We can simply invert the // mask from the first byte for the second byte. mask = ~mask; } else { mask = GetOffsetMask(0, bitsRemainingToCopy); } nextByte |= static_cast<BYTE>(pInputBuffer[1] & mask) >> bitsFromFirstByte; } return nextByte; } //+----------------------------------------------------------------------------- // // Copies bytes and partial bytes from the input buffer to the output buffer. // This function handles the case where the bit offsets are different for the // input and output buffers. // //------------------------------------------------------------------------------ VOID CopyUnalignedPixelBuffer( __out_bcount(outputBufferSize) BYTE * pOutputBuffer, __in_range(1, UINT_MAX) UINT outputBufferSize, __in_range(1, UINT_MAX) UINT outputBufferStride, __in_range(0, 7) UINT outputBufferOffsetInBits, __in_bcount(inputBufferSize) BYTE * pInputBuffer, __in_range(1, UINT_MAX) UINT inputBufferSize, __in_range(1, UINT_MAX) UINT inputBufferStride, __in_range(0, 7) UINT inputBufferOffsetInBits, __in_range(1, UINT_MAX) UINT height, __in_range(1, UINT_MAX) UINT copyWidthInBits ) { for (UINT row = 0; row < height; row++) { UINT bitsRemaining = copyWidthInBits; BYTE * pInputPosition = pInputBuffer; BYTE * pOutputPosition = pOutputBuffer; while (bitsRemaining > 0) { BYTE nextByte = GetNextByteFromInputBuffer( pInputPosition, inputBufferOffsetInBits, bitsRemaining); if (bitsRemaining >= 8) { if (outputBufferOffsetInBits == 0) { // The output buffer is at a byte boundary, so we can just // write the next byte. pOutputPosition[0] = nextByte; } else { // The output buffer has a bit-offset, so the next byte // will straddle two bytes. UINT bitsCopiedToFirstByte = 8 - outputBufferOffsetInBits; // Write to the first byte... BYTE mask = GetOffsetMask(outputBufferOffsetInBits, bitsCopiedToFirstByte); pOutputPosition[0] = (pOutputPosition[0] & ~mask) | (static_cast<BYTE>(nextByte >> outputBufferOffsetInBits) & mask); // Write to the second byte... pOutputPosition[1] = static_cast<BYTE>((pOutputPosition[1] & mask) | ((nextByte << bitsCopiedToFirstByte) & ~mask)); } bitsRemaining -= 8; } else { // Note: by the time we get to this condition, both bitsRemaining and // outputBufferOffsetInBits are both small numbers, making them safe // from overflow. UINT relativeOffsetOfLastBit = outputBufferOffsetInBits + bitsRemaining; if (relativeOffsetOfLastBit <= 8) { // The remaining bits fit inside a single byte. BYTE mask = GetOffsetMask(outputBufferOffsetInBits, bitsRemaining); pOutputPosition[0] = (pOutputPosition[0] & ~mask) | (static_cast<BYTE>(nextByte >> outputBufferOffsetInBits) & mask); } else { // The remaining bits will cross a byte boundary. UINT bitsCopiedToFirstByte = 8 - outputBufferOffsetInBits; // Write to the first byte... BYTE mask = GetOffsetMask(outputBufferOffsetInBits, bitsCopiedToFirstByte); pOutputPosition[0] = (pOutputPosition[0] & ~mask) | (static_cast<BYTE>(nextByte >> outputBufferOffsetInBits) & mask); // Write to the second byte... mask = GetOffsetMask(0, bitsRemaining - bitsCopiedToFirstByte); pOutputPosition[1] = static_cast<BYTE>((pOutputPosition[1] & ~mask) | ((nextByte << bitsCopiedToFirstByte) & mask)); } bitsRemaining = 0; } pOutputPosition++; pInputPosition++; } pOutputBuffer += outputBufferStride; pInputBuffer += inputBufferStride; } } //+----------------------------------------------------------------------------- // // MilUtility_CopyPixelBuffer // // This function copies memory from the input buffer to the output buffer, // with explicit support for sub-byte pixel formats. Generally speaking, this // functions treats memory as 2D (width*height). However, the width of the // buffer often differs from the natural width of the pixels (width * // bits-per-pixel, converted to bytes), due to memory alignment requirements. // The actual distance between adjacent rows is known as the stride, and this // is always specified in bytes. // // The buffers are therefore specified by a pointer, a size, and a stride. // As usual, the size and stride are specified in bytes. // // However, the requested area to copy is specified in bits. This includes // bit offsets into both the input and output buffers, as well as number of // bits to copy for each row. The number of rows to copy is specified as the // height. The bit offsets must only specify the offset within the first // byte (they must range from 0 to 7, inclusive). The buffer pointers should // be adjusted before calling this method if the bit offset is large. // //------------------------------------------------------------------------------ extern "C" HRESULT WINAPI MilUtility_CopyPixelBuffer( __out_bcount(outputBufferSize) BYTE* pOutputBuffer, UINT outputBufferSize, UINT outputBufferStride, UINT outputBufferOffsetInBits, __in_bcount(inputBufferSize) BYTE* pInputBuffer, UINT inputBufferSize, UINT inputBufferStride, UINT inputBufferOffsetInBits, UINT height, UINT copyWidthInBits ) { HRESULT hr = S_OK; if (height == 0 || copyWidthInBits == 0) { // Nothing to do. goto Cleanup; } if (outputBufferOffsetInBits > 7 || inputBufferOffsetInBits > 7) { // Bit offsets should be 0..7, inclusive. IFC(E_INVALIDARG); } UINT minimumOutputBufferStrideInBits; minimumOutputBufferStrideInBits = 0; IFC(UIntAdd(outputBufferOffsetInBits, copyWidthInBits, &minimumOutputBufferStrideInBits)); UINT minimumOutputBufferStride; minimumOutputBufferStride = BitsToBytes(minimumOutputBufferStrideInBits); if (outputBufferStride < minimumOutputBufferStride) { // The stride of the output buffer is too small. IFC(E_INVALIDARG); } UINT minimumOutputBufferSize; minimumOutputBufferSize = 0; IFC(UIntMult(outputBufferStride, (height-1), &minimumOutputBufferSize)); IFC(UIntAdd(minimumOutputBufferSize, minimumOutputBufferStride, &minimumOutputBufferSize)); if (outputBufferSize < minimumOutputBufferSize) { // The output buffer is too small. IFC(E_INVALIDARG); } UINT minimumInputBufferStrideInBits; minimumInputBufferStrideInBits = 0; IFC(UIntAdd(inputBufferOffsetInBits, copyWidthInBits, &minimumInputBufferStrideInBits)); UINT minimumInputBufferStride; minimumInputBufferStride = BitsToBytes(minimumInputBufferStrideInBits); if (inputBufferStride < minimumInputBufferStride) { // The stride of the input buffer is too small. IFC(E_INVALIDARG); } UINT minimumInputBufferSize; minimumInputBufferSize = 0; IFC(UIntMult(inputBufferStride, (height-1), &minimumInputBufferSize)); IFC(UIntAdd(minimumInputBufferSize, minimumInputBufferStride, &minimumInputBufferSize)); if (inputBufferSize < minimumInputBufferSize) { // The input buffer is too small. IFC(E_INVALIDARG); } if (outputBufferOffsetInBits != inputBufferOffsetInBits) { CopyUnalignedPixelBuffer( pOutputBuffer, outputBufferSize, outputBufferStride, outputBufferOffsetInBits, pInputBuffer, inputBufferSize, inputBufferStride, inputBufferOffsetInBits, height, copyWidthInBits); } else { // Since the input and output offsets are the same, we use more general // variable names here. UINT minimumBufferStrideInBits = minimumInputBufferStrideInBits; UINT minimumBufferStride = minimumInputBufferStride; UINT bufferOffsetInBits = inputBufferOffsetInBits; UINT finalByteOffset = minimumBufferStride - 1; if ((bufferOffsetInBits == 0) && (copyWidthInBits % 8 == 0)) { if (minimumBufferStride == inputBufferStride && inputBufferStride == outputBufferStride) { // Fast-Path // The input and output buffers are on byte boundaries, both // share the same stride, and we are copying the entire // stride of each row. These conditions allow us to do a // single large memory copy instead of multiple copies per row. memcpy(pOutputBuffer, pInputBuffer, inputBufferStride*height); } else { // We are copying whole bytes from the input buffer to the // output buffer, but we still need to copy row-by-row since // the width is not the same as the stride. for (UINT i = 0; i < height; i++) { memcpy(pOutputBuffer, pInputBuffer, minimumBufferStride); pOutputBuffer += outputBufferStride; pInputBuffer += inputBufferStride; } } } else if (finalByteOffset == 0) { // If the first byte is also the final byte, we need to double mask. BYTE mask = GetOffsetMask(bufferOffsetInBits, copyWidthInBits); for (UINT i = 0; i < height; i++) { pOutputBuffer[0] = (pOutputBuffer[0] & ~mask) | (pInputBuffer[0] & mask); pOutputBuffer += outputBufferStride; pInputBuffer += inputBufferStride; } } else { // In this final case: // - only part of either the first or last byte should be copied, // - the first byte is not the last byte, // - and there are between 0 and n whole bytes in between to copy. bool firstByteIsWhole = bufferOffsetInBits == 0; bool finalByteIsWhole = minimumBufferStrideInBits % 8 == 0; UINT wholeBytesPerRow = minimumBufferStride - (finalByteIsWhole ? 0 : 1) - (firstByteIsWhole ? 0 : 1); for (UINT i = 0; i < height; i++) { if (!firstByteIsWhole) { BYTE mask = GetOffsetMask(bufferOffsetInBits, 8 - bufferOffsetInBits); pOutputBuffer[0] = (pOutputBuffer[0] & ~mask) | (pInputBuffer[0] & mask); } if (wholeBytesPerRow > 0) { UINT firstByteOffset = (firstByteIsWhole ? 0 : 1); memcpy( pOutputBuffer + firstByteOffset, pInputBuffer + firstByteOffset, wholeBytesPerRow); } if (!finalByteIsWhole) { BYTE mask = GetOffsetMask(0, minimumBufferStrideInBits % 8); pOutputBuffer[finalByteOffset] = (pOutputBuffer[finalByteOffset] & ~mask) | (pInputBuffer[finalByteOffset] & mask); } pOutputBuffer += outputBufferStride; pInputBuffer += inputBufferStride; } } } Cleanup: RRETURN(hr); }
36.946467
137
0.561261
nsivov
0a46470e941be66cd0e253e942162108a6e2ef6a
932
cpp
C++
242_b.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
242_b.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
242_b.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
// Created by Tanuj Jain #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int,int> pii; template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("inputf.in","r",stdin); freopen("outputf.in","w",stdout); #endif int t; cin>>t; //set<pair<int,int>,int>st; int l=INT_MAX; int r=-1; vector<pair<int,int>>v; for(int i=0;i<t;i++) { int a,b; cin>>a>>b; l=min(l,a); r=max(r,b); v.pb({a,b}); //st.insert{a,b}; } for(int i=0;i<t;i++) { if(v[i].first==l && v[i].second==r) { cout<<i+1; return 0; } } cout<<-1; return 0; }
18.64
106
0.60515
onexmaster
0a48c1aaf97bfabf334b622ab83745318c6af1be
2,851
hpp
C++
src/Omega_h_vtk.hpp
matz-e/omega_h
a43850787b24f96d50807cee5688f09259e96b75
[ "BSD-2-Clause-FreeBSD" ]
44
2019-01-23T03:37:18.000Z
2021-08-24T02:20:29.000Z
src/Omega_h_vtk.hpp
matz-e/omega_h
a43850787b24f96d50807cee5688f09259e96b75
[ "BSD-2-Clause-FreeBSD" ]
67
2019-01-29T15:35:42.000Z
2021-08-17T20:42:40.000Z
src/Omega_h_vtk.hpp
matz-e/omega_h
a43850787b24f96d50807cee5688f09259e96b75
[ "BSD-2-Clause-FreeBSD" ]
29
2019-01-14T21:33:32.000Z
2021-08-10T11:35:24.000Z
#ifndef OMEGA_H_VTK_HPP #define OMEGA_H_VTK_HPP #include <iosfwd> #include <string> #include <vector> #include <Omega_h_comm.hpp> #include <Omega_h_defines.hpp> #include <Omega_h_file.hpp> namespace Omega_h { class Mesh; namespace vtk { filesystem::path get_pvtu_path(filesystem::path const& step_path); filesystem::path get_pvd_path(filesystem::path const& root_path); void write_pvtu(std::ostream& stream, Mesh* mesh, Int cell_dim, filesystem::path const& piecepath, TagSet const& tags); void write_pvtu(filesystem::path const& filename, Mesh* mesh, Int cell_dim, filesystem::path const& piecepath, TagSet const& tags); std::streampos write_initial_pvd( filesystem::path const& root_path, Real restart_time); void update_pvd(filesystem::path const& root_path, std::streampos* pos_inout, I64 step, Real time); void read_vtu(std::istream& stream, CommPtr comm, Mesh* mesh); void read_vtu_ents(std::istream& stream, Mesh* mesh); void read_pvtu(std::istream& stream, CommPtr comm, I32* npieces_out, std::string* vtupath_out, Int* nghost_layers_out); void read_pvtu(filesystem::path const& pvtupath, CommPtr comm, I32* npieces_out, filesystem::path* vtupath_out, Int* nghost_layers_out); void read_pvd(std::istream& stream, std::vector<Real>* times_out, std::vector<filesystem::path>* pvtupaths_out); void read_pvd(filesystem::path const& pvdpath, std::vector<Real>* times_out, std::vector<filesystem::path>* pvtupaths_out); template <bool is_signed, std::size_t size> struct IntTraits; template <std::size_t size> struct FloatTraits; void write_vtkfile_vtu_start_tag(std::ostream& stream, bool compress); void write_p_tag(std::ostream& stream, TagBase const* tag, Int space_dim); void write_tag( std::ostream& stream, TagBase const* tag, Int space_dim, bool compress); template <typename T> void write_p_data_array( std::ostream& stream, std::string const& name, Int ncomps); template <typename T_osh, typename T_vtk = T_osh> void write_array(std::ostream& stream, std::string const& name, Int ncomps, Read<T_osh> array, bool compress); #define OMEGA_H_EXPL_INST_DECL(T) \ extern template void write_p_data_array<T>( \ std::ostream & stream, std::string const& name, Int ncomps); \ extern template void write_array(std::ostream& stream, \ std::string const& name, Int ncomps, Read<T> array, bool compress); OMEGA_H_EXPL_INST_DECL(I8) OMEGA_H_EXPL_INST_DECL(I32) OMEGA_H_EXPL_INST_DECL(I64) OMEGA_H_EXPL_INST_DECL(Real) #undef OMEGA_H_EXPL_INST_DECL extern template void write_array<Real, std::uint8_t>(std::ostream& stream, std::string const& name, Int ncomps, Read<Real> array, bool compress); } // namespace vtk } // end namespace Omega_h #endif
32.397727
80
0.726061
matz-e
0a4c6282a0249bac1a4d6dbfb95bf3dd1d8c4009
23,969
cxx
C++
osprey/be/lno/sclrze.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/lno/sclrze.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/lno/sclrze.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2002, 2003, 2004, 2005, 2006 PathScale, Inc. All Rights Reserved. */ /* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ // Array Scalarization // ------------------- // // Description: // // In loops, convert things that look like // do i // a[i] = ... // ... = a[i] // // into // // do i // t = ... // a[i] = t // ... = t // // This is useful because // 1) It gets rid of loads // 2) If it gets rid of all the loads to a local array then // the array equivalencing algorithm will get rid of the array // // Because SWP will do 1 as well as we do, we'll only apply this // algorithm to local arrays (Although it's trivial to change this). // /* ==================================================================== * ==================================================================== * * Module: sclrze.cxx * $Revision: 1.7 $ * $Date: 05/04/07 19:50:39-07:00 $ * $Author: kannann@iridot.keyresearch $ * $Source: be/lno/SCCS/s.sclrze.cxx $ * * Revision history: * dd-mmm-94 - Original Version * * Description: Scalarize arrays * * ==================================================================== * ==================================================================== */ #ifdef USE_PCH #include "lno_pch.h" #endif // USE_PCH #pragma hdrstop const static char *source_file = __FILE__; const static char *rcs_id = "$Source: be/lno/SCCS/s.sclrze.cxx $ $Revision: 1.7 $"; #include <sys/types.h> #include "lnopt_main.h" #include "dep_graph.h" #include "lwn_util.h" #include "opt_du.h" #include "reduc.h" #include "sclrze.h" #include "lnoutils.h" static void Process_Store(WN *, VINDEX16 , ARRAY_DIRECTED_GRAPH16 *, BOOL, BOOL, REDUCTION_MANAGER *red_manager); static BOOL Intervening_Write(INT,VINDEX16, VINDEX16 ,ARRAY_DIRECTED_GRAPH16 *); static BOOL Is_Invariant(ACCESS_ARRAY *store, WN *store_wn); static BOOL MP_Problem(WN *wn1, WN *wn2); static HASH_TABLE<ST *, INT> * Array_Use_Hash; static int DSE_Count = 0; extern BOOL ST_Has_Dope_Vector(ST *); // Query whether 'st' represents a local variable. static BOOL Is_Local_Var(ST * st) { if ((ST_sclass(st) == SCLASS_AUTO) && (ST_base_idx(st) == ST_st_idx(st)) && !ST_has_nested_ref(st) && (ST_class(st) == CLASS_VAR)) return TRUE; return FALSE; } // Query whether use references to 'st' is tracked in "Mark_Array_Uses". // Limit to local allocate arrays. static BOOL Is_Tracked(ST * st) { return (Is_Local_Var(st) && ST_Has_Dope_Vector(st)); } // bit mask for symbol attributes. #define HAS_ESCAPE_USE 1 // has a use not reachable by a dominating def. #define ADDR_TAKEN 2 // is address-taken. #define HAS_USE 4 // has a use. #define IS_ALLOC 8 // is allocated/dealloacted. // Query whether 'store_wn' is dead, i.e., its address is not taken and it has no use. static BOOL Is_Dead_Store(WN * store_wn) { OPERATOR opr = WN_operator(store_wn); if (!OPERATOR_is_scalar_store(opr)) { WN * base = WN_array_base(WN_kid(store_wn,1)); if (WN_has_sym(base)) { ST * st = WN_st(base); if (st && Is_Tracked(st) && Array_Use_Hash && (Array_Use_Hash->Find(st) == IS_ALLOC)) return TRUE; } } return FALSE; } // Given an array reference 'load_wn", query where there exists a reaching def that dominates it. static BOOL Has_Dom_Reaching_Def(ARRAY_DIRECTED_GRAPH16 * dep_graph, WN * load_wn) { OPERATOR opr = WN_operator(load_wn); if (!OPERATOR_is_load(opr) || OPERATOR_is_scalar_load(opr)) return FALSE; VINDEX16 v = dep_graph->Get_Vertex(load_wn); if (!v) return FALSE; WN * kid = WN_kid0(load_wn); if (WN_operator(kid) != OPR_ARRAY) return FALSE; ACCESS_ARRAY * load = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid); if (!load) return FALSE; for (EINDEX16 e = dep_graph->Get_In_Edge(v); e; e = dep_graph->Get_Next_In_Edge(e)) { VINDEX16 source = dep_graph->Get_Source(e); WN * store_wn = dep_graph->Get_Wn(source); OPERATOR opr = WN_operator(store_wn); if (OPERATOR_is_store(opr) && !OPERATOR_is_scalar_store(opr)) { kid = WN_kid1(store_wn); if (WN_operator(kid) != OPR_ARRAY) continue; ACCESS_ARRAY * store = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid); if (Equivalent_Access_Arrays(store,load,store_wn,load_wn) && (DEPV_COMPUTE::Base_Test(store_wn,NULL,load_wn,NULL) == DEP_CONTINUE)) { if (Dominates(store_wn, load_wn) && !Intervening_Write(dep_graph->Depv_Array(e)->Max_Level(), source, v, dep_graph) && !MP_Problem(store_wn, load_wn)) return TRUE; } } } return FALSE; } // Given an array reference 'store_wn', query whether there exists a kill that post-dominates it. static BOOL Has_Post_Dom_Kill(ARRAY_DIRECTED_GRAPH16 * dep_graph, WN * store_wn) { OPERATOR opr = WN_operator(store_wn); if (!OPERATOR_is_store(opr) || OPERATOR_is_scalar_store(opr)) return FALSE; VINDEX16 v = dep_graph->Get_Vertex(store_wn); if (!v) return FALSE; WN * kid = WN_kid1(store_wn); if (WN_operator(kid) != OPR_ARRAY) return FALSE; WN * base = WN_array_base(kid); if (!WN_has_sym(base)) return FALSE; ST * st = WN_st(base); // limit it to local non-address-taken arrays. if (!Is_Local_Var(st) || !Array_Use_Hash || ((Array_Use_Hash->Find(st) & ADDR_TAKEN) != 0)) return FALSE; ACCESS_ARRAY * store = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid); if (!store) return FALSE; for (EINDEX16 e = dep_graph->Get_Out_Edge(v); e; e = dep_graph->Get_Next_Out_Edge(e)) { VINDEX16 sink = dep_graph->Get_Sink(e); WN * kill_wn = dep_graph->Get_Wn(sink); if (kill_wn == store_wn) continue; OPERATOR opr = WN_operator(kill_wn); if (OPERATOR_is_store(opr) && !OPERATOR_is_scalar_store(opr)) { kid = WN_kid1(kill_wn); if (WN_operator(kid) != OPR_ARRAY) continue; ACCESS_ARRAY * kill = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid); if (Equivalent_Access_Arrays(store, kill, store_wn, kill_wn) && (DEPV_COMPUTE::Base_Test(store_wn, NULL, kill_wn, NULL) == DEP_CONTINUE)) { if ((LWN_Get_Parent(store_wn) == LWN_Get_Parent(kill_wn)) && !MP_Problem(store_wn, kill_wn)) { WN * next = WN_next(store_wn); while (next) { if (next == kill_wn) return TRUE; next = WN_next(next); } } } } } return FALSE; } // Check usage of a local allocate array. static void Check_use(ST * st, WN * wn, ARRAY_DIRECTED_GRAPH16 * dep_graph, BOOL escape) { if (st && Is_Tracked(st)) { int val = Array_Use_Hash->Find(st); val |= HAS_USE; if (escape || !Has_Dom_Reaching_Def(dep_graph, wn)) { val |= HAS_ESCAPE_USE; } if (val) { Array_Use_Hash->Find_And_Set(st, val); } } } // Check use references to local allocate arrays and mark attributes. // Limit it to Fortran programs currently. static void Mark_Array_Uses(ARRAY_DIRECTED_GRAPH16 * dep_graph, WN * wn) { FmtAssert(Array_Use_Hash, ("Expect a hash table.")); WN * kid; ST * st; OPERATOR opr = WN_operator(wn); switch (opr) { case OPR_BLOCK: kid = WN_first(wn); while (kid) { Mark_Array_Uses(dep_graph, kid); kid = WN_next(kid); } break; case OPR_LDA: st = WN_st(wn); if (Is_Tracked(st)) { int val = Array_Use_Hash->Find(st); BOOL is_pure = FALSE; WN * wn_p = LWN_Get_Parent(wn); if (wn_p && ST_Has_Dope_Vector(st)) { OPERATOR p_opr = WN_operator(wn_p); if (p_opr == OPR_PARM) { wn_p = LWN_Get_Parent(wn_p); if (wn_p && (WN_operator(wn_p) == OPR_CALL)) { char * name = ST_name(WN_st_idx(wn_p)); if ((strcmp(name, "_DEALLOCATE") == 0) || (strcmp(name, "_DEALLOC") == 0) || (strcmp(name, "_F90_ALLOCATE_B") == 0)) { is_pure = TRUE; val |= IS_ALLOC; } } } else if ((p_opr == OPR_STID) && WN_has_sym(wn_p)) { ST * p_st = WN_st(wn_p); TY_IDX ty = ST_type(p_st); if (strncmp(TY_name(ty), ".alloctemp.", 11) == 0) is_pure = TRUE; } } if (!is_pure) val |= ADDR_TAKEN; if (val) { Array_Use_Hash->Find_And_Set(st, val); } } break; case OPR_LDID: if (WN_has_sym(wn)) { st = WN_st(wn); WN * store = Find_Containing_Store(wn); if (store && (WN_operator(store) == OPR_STID) && (WN_st(store) != st)) { if (WN_kid0(store) == wn) { // Be conservative for direct assignment to a different variable. // Consider it as an escape use. Check_use(st, wn, dep_graph, TRUE); } else Check_use(st, wn, dep_graph, FALSE); } // Flag ADDR_TAKEN bit for parameters passed by reference. WN * wn_p = LWN_Get_Parent(wn); if (wn_p && (WN_operator(wn_p) == OPR_PARM)) { INT flag = WN_flag(wn_p); if (flag & WN_PARM_BY_REFERENCE) { int val = Array_Use_Hash->Find(st); val |= ADDR_TAKEN; if (val) { Array_Use_Hash->Find_And_Set(st, val); } } } } break; case OPR_ILOAD: kid = WN_kid0(wn); if (WN_operator(kid) == OPR_ARRAY) { WN * base = WN_array_base(kid); if (WN_has_sym(base)) { st = WN_st(base); Check_use(st, wn, dep_graph, FALSE); } } break; default: ; } if (opr == OPR_FUNC_ENTRY) Mark_Array_Uses(dep_graph,WN_func_body(wn)); else { INT start = (opr == OPR_ARRAY) ? 1 : 0; for (INT kidno = start; kidno < WN_kid_count(wn); kidno++) { kid = WN_kid(wn, kidno); Mark_Array_Uses(dep_graph, kid); } } } void Scalarize_Arrays(ARRAY_DIRECTED_GRAPH16 *dep_graph, BOOL do_variants, BOOL do_invariants, REDUCTION_MANAGER *red_manager, WN * wn) { if (Get_Trace(TP_LNOPT,TT_LNO_SCLRZE)) { fprintf(TFile,"Scalarizing arrays \n"); } Array_Use_Hash = NULL; PU & pu = Get_Current_PU(); if (Do_Aggressive_Fuse && wn && ((PU_src_lang(Get_Current_PU()) & PU_F90_LANG) || (PU_src_lang(Get_Current_PU()) & PU_F77_LANG))) { ST * st; INT i; Array_Use_Hash = CXX_NEW((HASH_TABLE<ST *, INT>) (100, &LNO_default_pool), &LNO_default_pool); Mark_Array_Uses(Array_Dependence_Graph, wn); } // search for a store VINDEX16 v; VINDEX16 v_next; DSE_Count = 0; for (v = dep_graph->Get_Vertex(); v; v = v_next) { v_next = dep_graph->Get_Next_Vertex_In_Edit(v); if (!dep_graph->Vertex_Is_In_Graph(v)) continue; WN *wn = dep_graph->Get_Wn(v); OPCODE opcode = WN_opcode(wn); if (OPCODE_is_store(opcode) && (WN_kid_count(wn) == 2)) { WN *array = WN_kid1(wn); if (WN_operator(array) == OPR_ARRAY) { WN *base = WN_array_base(array); OPERATOR base_oper = WN_operator(base); if ((base_oper == OPR_LDID) || (base_oper == OPR_LDA)) { ST *st = WN_st(base); // is it local #ifdef _NEW_SYMTAB if (ST_level(st) == CURRENT_SYMTAB) { #else if (ST_symtab_id(st) == SYMTAB_id(Current_Symtab)) { #endif if (ST_sclass(st) == SCLASS_AUTO && ST_base_idx(st) == ST_st_idx(st)) { if (!ST_has_nested_ref(st)) Process_Store(wn,v,dep_graph,do_variants,do_invariants, red_manager); } } else if (Is_Global_As_Local(st)) { Process_Store(wn,v,dep_graph,do_variants,do_invariants, red_manager); } } } } } if (DSE_Count > 0) { if (Get_Trace(TP_LNOPT,TT_LNO_SCLRZE)) printf("####Func: %d scalar replacement delete %d stores.\n", Current_PU_Count(), DSE_Count); } if (Array_Use_Hash) CXX_DELETE(Array_Use_Hash, &LNO_default_pool); } // Given a store to an array element 'wn', query whether it is read outside its enclosing loop // assuming unequal acccess arrays refer to disjointed locations. static BOOL Live_On_Exit(WN * wn) { ARRAY_DIRECTED_GRAPH16 * adg = Array_Dependence_Graph; OPERATOR opr = WN_operator(wn); FmtAssert(OPERATOR_is_store(opr) && !OPERATOR_is_scalar_store(opr), ("Expect a store.")); VINDEX16 v = adg->Get_Vertex(wn); if (!v) return TRUE; WN * kid = WN_kid1(wn); if (WN_operator(kid) != OPR_ARRAY) return TRUE; ACCESS_ARRAY * store = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid); if (!store) return TRUE; WN * loop_st = Enclosing_Loop(wn); for (EINDEX16 e = adg->Get_Out_Edge(v); e; e = adg->Get_Next_Out_Edge(e)) { VINDEX16 sink = adg->Get_Sink(e); WN * load_wn = adg->Get_Wn(sink); OPERATOR opr = WN_operator(load_wn); if (OPERATOR_is_load(opr) && !OPERATOR_is_scalar_load(opr)) { kid = WN_kid0(load_wn); if (WN_operator(kid) != OPR_ARRAY) continue; if (Enclosing_Loop(load_wn) == loop_st) continue; ACCESS_ARRAY * load = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map, kid); if (Equivalent_Access_Arrays(store,load,wn,load_wn) && (DEPV_COMPUTE::Base_Test(wn,NULL,load_wn,NULL) == DEP_CONTINUE)) { return TRUE; } } } return FALSE; } // Query whether 'wn' is located in a loop nest that allows dead store removal // after scalarization. static BOOL Do_Sclrze_Dse(WN * wn) { WN * wn_p = LWN_Get_Parent(wn); while (wn_p) { if (WN_operator(wn_p) == OPR_DO_LOOP) { DO_LOOP_INFO * dli = Get_Do_Loop_Info(wn_p); if (dli && (dli->Sclrze_Dse == 1)) return TRUE; } wn_p = LWN_Get_Parent(wn_p); } return FALSE; } // Delete 'store_wn'. static void Delete_Store(WN * store_wn, ARRAY_DIRECTED_GRAPH16 * dep_graph) { UINT32 limit = LNO_Sclrze_Dse_Limit; if ((limit > 0) && (DSE_Count > limit)) return; LWN_Update_Dg_Delete_Tree(store_wn, dep_graph); LWN_Delete_Tree(store_wn); DSE_Count++; } // Process a store. static void Process_Store(WN *store_wn, VINDEX16 v, ARRAY_DIRECTED_GRAPH16 *dep_graph, BOOL do_variants, BOOL do_invariants, REDUCTION_MANAGER *red_manager) { #ifdef TARG_X8664 // Do not sclrze vector stores. if (MTYPE_is_vector(WN_desc(store_wn))) return; #endif #ifdef KEY // Bug 6162 - can not scalarize to MTYPE_M pregs. if (WN_desc(store_wn) == MTYPE_M) return; #endif if (Inside_Loop_With_Goto(store_wn)) return; INT debug = Get_Trace(TP_LNOPT,TT_LNO_SCLRZE); BOOL scalarized_this_store = FALSE; WN_OFFSET preg_num=0; ST *preg_st=0; WN *preg_store = NULL; ACCESS_ARRAY *store = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map,WN_kid1(store_wn)); if (debug) { fprintf(TFile,"Processing the store "); store->Print(TFile); fprintf(TFile,"\n"); } if (Do_Aggressive_Fuse) { if (Is_Dead_Store(store_wn)) { if (!red_manager || (red_manager->Which_Reduction(store_wn) == RED_NONE)) { Delete_Store(store_wn, dep_graph); return; } } } BOOL is_invariant = Is_Invariant(store,store_wn); if (!do_variants && !is_invariant) { return; } if (!do_invariants && is_invariant) { return; } // Don't scalarize reductions as that will break the reduction if (red_manager && (red_manager->Which_Reduction(store_wn) != RED_NONE)) { return; } char preg_name[20]; TYPE_ID store_type = WN_desc(store_wn); TYPE_ID type = Promote_Type(store_type); EINDEX16 e,next_e=0; BOOL all_loads_scalarized = TRUE; BOOL has_post_dom_kill = FALSE; if (Do_Aggressive_Fuse) has_post_dom_kill = Has_Post_Dom_Kill(dep_graph, store_wn); for (e = dep_graph->Get_Out_Edge(v); e; e=next_e) { next_e = dep_graph->Get_Next_Out_Edge(e); VINDEX16 sink = dep_graph->Get_Sink(e); WN *load_wn = dep_graph->Get_Wn(sink); OPCODE opcode = WN_opcode(load_wn); if (OPCODE_is_load(opcode)) { if (OPCODE_operator(opcode) != OPR_LDID && // Do not scalarize MTYPE_M loads as this may result in a parent MTYPE_M store // having a child that is not MTYPE_M and function 'Add_def' may not be able to // handle such stores during coderep creation. The check here catches 'uses' involving // MTYPE_M whereas the check at the beginning of 'Process_Store' catches 'defs'. (WN_rtype(load_wn) != MTYPE_M) && (WN_desc(load_wn) != MTYPE_M)) { ACCESS_ARRAY *load = (ACCESS_ARRAY *) WN_MAP_Get(LNO_Info_Map,WN_kid0(load_wn)); if (WN_operator(WN_kid0(load_wn)) == OPR_ARRAY && Equivalent_Access_Arrays(store,load,store_wn,load_wn) && (DEPV_COMPUTE::Base_Test(store_wn,NULL,load_wn,NULL) == DEP_CONTINUE) #ifdef KEY && //Bug 9134: scalarizing only if store to and load from the same field WN_field_id(store_wn)==WN_field_id(load_wn) #endif ) { BOOL scalarized_this_load = FALSE; if (Dominates(store_wn,load_wn)) { if (!red_manager || (red_manager->Which_Reduction(store_wn) == RED_NONE)) { if (!Intervening_Write(dep_graph->Depv_Array(e)->Max_Level(), v,sink,dep_graph)) { if (!MP_Problem(store_wn,load_wn)) { scalarized_this_load = TRUE; if (!scalarized_this_store) { if (debug) { fprintf(TFile,"Scalarizing the load "); load->Print(TFile); fprintf(TFile,"\n"); } // Create a new preg preg_st = MTYPE_To_PREG(type); char *array_name = ST_name(WN_st(WN_array_base(WN_kid1(store_wn)))); INT length = strlen(array_name); if (length < 18) { strcpy(preg_name,array_name); preg_name[length] = '_'; preg_name[length+1] = '1'; preg_name[length+2] = 0; #ifdef _NEW_SYMTAB preg_num = Create_Preg(type,preg_name); } else { preg_num = Create_Preg(type, NULL); } #else preg_num = Create_Preg(type,preg_name, NULL); } else { preg_num = Create_Preg(type, NULL, NULL); } #endif // replace A[i] = x with "preg = x; A[i] = preg" OPCODE preg_s_opcode = OPCODE_make_op(OPR_STID,MTYPE_V,type); // Insert CVTL if necessary (854441) WN *wn_value = WN_kid0(store_wn); if (MTYPE_byte_size(store_type) < MTYPE_byte_size(type)) wn_value = LWN_Int_Type_Conversion(wn_value, store_type); preg_store = LWN_CreateStid(preg_s_opcode,preg_num, preg_st, Be_Type_Tbl(type),wn_value); WN_Set_Linenum(preg_store,WN_Get_Linenum(store_wn)); LWN_Copy_Frequency_Tree(preg_store,store_wn); LWN_Insert_Block_Before(LWN_Get_Parent(store_wn), store_wn,preg_store); OPCODE preg_l_opcode = OPCODE_make_op(OPR_LDID, type,type); WN *preg_load = WN_CreateLdid(preg_l_opcode,preg_num, preg_st, Be_Type_Tbl(type)); LWN_Copy_Frequency(preg_load,store_wn); WN_kid0(store_wn) = preg_load; LWN_Set_Parent(preg_load,store_wn); Du_Mgr->Add_Def_Use(preg_store,preg_load); } scalarized_this_store = TRUE; // replace the load with the use of the preg WN *new_load = WN_CreateLdid(OPCODE_make_op(OPR_LDID, type,type),preg_num,preg_st,Be_Type_Tbl(type)); LWN_Copy_Frequency_Tree(new_load,load_wn); WN *parent = LWN_Get_Parent(load_wn); for (INT i = 0; i < WN_kid_count(parent); i++) { if (WN_kid(parent,i) == load_wn) { WN_kid(parent,i) = new_load; LWN_Set_Parent(new_load,parent); LWN_Update_Dg_Delete_Tree(load_wn, dep_graph); LWN_Delete_Tree(load_wn); break; } } // update def-use for scalar Du_Mgr->Add_Def_Use(preg_store,new_load); } } if (!scalarized_this_load) all_loads_scalarized = FALSE; } } } } } } if (Do_Aggressive_Fuse) { OPERATOR opr = WN_operator(store_wn); if (!OPERATOR_is_scalar_store(opr) && scalarized_this_store && all_loads_scalarized) { WN * base = WN_array_base(WN_kid(store_wn,1)); if (WN_has_sym(base)) { ST * st = WN_st(base); if (st) { int val = Array_Use_Hash ? Array_Use_Hash->Find(st) : 0; if (Is_Global_As_Local(st) && ST_Has_Dope_Vector(st)) { if (Do_Sclrze_Dse(store_wn) && !Live_On_Exit(store_wn) && (ST_export(st) == EXPORT_LOCAL)) { Delete_Store(store_wn, dep_graph); } } else if (val && ((val & ADDR_TAKEN) == 0) && ((val & IS_ALLOC) != 0)) { if (has_post_dom_kill || ((val & HAS_ESCAPE_USE) == 0)) { Delete_Store(store_wn, dep_graph); } } } } } } } // Given that there is a must dependence between store and load, // is there ary other store that might occur between the the store and the // load // If there exists a store2, whose maximum dependence level wrt the // load is greater than store's dependence level (INT level below), // then store2 is intervening. // // If there exists a store2 whose maximum dependence level is equal // to store's, and there a dependence from store to store2 with dependence // level >= the previous level, then store2 is intervening static BOOL Intervening_Write(INT level,VINDEX16 store_v, VINDEX16 load_v,ARRAY_DIRECTED_GRAPH16 *dep_graph) { EINDEX16 e; for (e=dep_graph->Get_In_Edge(load_v); e; e=dep_graph->Get_Next_In_Edge(e)) { INT level2 = dep_graph->Depv_Array(e)->Max_Level(); if (level2 > level) { return TRUE; } else if (level2 == level) { VINDEX16 store2_v = dep_graph->Get_Source(e); EINDEX16 store_store_edge = dep_graph->Get_Edge(store_v,store2_v); if (store_store_edge) { INT store_store_level = dep_graph->Depv_Array(store_store_edge)->Max_Level(); if (store_store_level >= level) { return TRUE; } } } } return FALSE; } // Is this reference invariant in its inner loop static BOOL Is_Invariant(ACCESS_ARRAY *store, WN *store_wn) { // find the do loop info of the store WN *wn = LWN_Get_Parent(store_wn); while (WN_opcode(wn) != OPC_DO_LOOP) { wn = LWN_Get_Parent(wn); } DO_LOOP_INFO *dli = Get_Do_Loop_Info(wn); INT depth = dli->Depth; if (store->Too_Messy || (store->Non_Const_Loops() > depth)) { return FALSE; } for (INT i=0; i<store->Num_Vec(); i++) { ACCESS_VECTOR *av = store->Dim(i); if (av->Too_Messy || av->Loop_Coeff(depth)) { return FALSE; } } return TRUE; } // Don't scalarize across parallel boundaries static BOOL MP_Problem(WN *wn1, WN *wn2) { if (Contains_MP) { WN *mp1 = LWN_Get_Parent(wn1); while (mp1 && (!Is_Mp_Region(mp1)) && ((WN_opcode(mp1) != OPC_DO_LOOP) || !Do_Loop_Is_Mp(mp1))) { mp1 = LWN_Get_Parent(mp1); } WN *mp2 = LWN_Get_Parent(wn2); while (mp2 && (!Is_Mp_Region(mp2)) && ((WN_opcode(mp2) != OPC_DO_LOOP) || !Do_Loop_Is_Mp(mp2))) { mp2 = LWN_Get_Parent(mp2); } if ((mp1 || mp2) && (mp1 != mp2)) return TRUE; } return FALSE; }
29.664604
99
0.640285
sharugupta
aea91cb28aa59ddadacb795cd728da5735946be3
5,910
cpp
C++
src/eds/http/headers.cpp
panyam/halley
1bc8e9fe890d585c8ca524d6070591af656e206b
[ "Apache-2.0" ]
null
null
null
src/eds/http/headers.cpp
panyam/halley
1bc8e9fe890d585c8ca524d6070591af656e206b
[ "Apache-2.0" ]
null
null
null
src/eds/http/headers.cpp
panyam/halley
1bc8e9fe890d585c8ca524d6070591af656e206b
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** /*! * 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. * ***************************************************************************** * * \file headers.cpp * * \brief * All things http headers. * * \version * - Sri Panyam 05/03/2009 * Created * *****************************************************************************/ #include "../utils.h" #include "headers.h" const SString TRUE_STRING = "true"; const SString FALSE_STRING = "false"; //! CLears the header table so we can start over again void SHeaderTable::Reset() { closeConnection = false; locked = false; headers.clear(); } //! Write the headers to the stream int SHeaderTable::WriteToStream(std::ostream &output) { // write all headers! HeaderMap::const_iterator iter = headers.begin(); for (;iter != headers.end();++iter) { output << iter->first << ": " << iter->second << URLUtils::CRLF; SLogger::Get()->Log("DEBUG: Header %s: %s\n", iter->first.c_str(), iter->second.c_str()); } // and an extra URLUtils::CRLF output << URLUtils::CRLF; output.flush(); return 0; } //! Writes the headers to a file descriptor int SHeaderTable::WriteToFD(int fd) { SStringStream buffer; WriteToStream(buffer); SString outStr(buffer.str()); return SEDSUtils::SendFully(fd, outStr.c_str(), outStr.size()); } // Reads a http header. // Headers are read till a line with only a CRLF is found. bool SHeaderTable::ReadNextHeader(std::istream &input, SString &name, SString &value) { SString line = URLUtils::ReadTillCrLf(input); return ParseHeaderLine(line, name, value); } bool SHeaderTable::ReadHeaders(std::istream &input) { SString headerName; SString headerValue; // read all header lines while (ReadNextHeader(input, headerName, headerValue)) { } return !input.bad() && !input.eof(); } //! Parses header line bool SHeaderTable::ParseHeaderLine(const SString &line, SString &name, SString &value) { const char *pStart = line.c_str(); while (isspace(*pStart)) pStart++; const char *pCurr = pStart; // empty line? if (*pCurr == 0) return false; while (!URLUtils::iscontrol(*pCurr) && !URLUtils::isseperator(*pCurr)) pCurr++; // found a colon? if (*pCurr != ':') return false; const char *pHeaderEnd = pCurr; // skip the colon pCurr++; while (isspace(*pCurr)) pCurr++; name = SString(pStart, pHeaderEnd - pStart); value = SString(pCurr); SLogger::Get()->Log("DEBUG: Header %s: %s\n", name.c_str(), value.c_str()); SetHeader(name, value); return true; } // Tells if a header exists bool SHeaderTable::HasHeader(const SString &name) const { HeaderMap::const_iterator iter = headers.find(name); return iter != headers.end(); } // Gets a header SString SHeaderTable::Header(const SString &name) const { HeaderMap::const_iterator iter = headers.find(name); if (iter == headers.end()) return ""; else return iter->second; } //! Returns a header if it exists bool SHeaderTable::HeaderIfExists(const SString &name, SString &value) { HeaderMap::const_iterator iter = headers.find(name); if (iter == headers.end()) return false; value = iter->second; return true; } // Sets a header value - if it already exists, this value is appended to it. void SHeaderTable::SetHeader(const SString &name, const SString &value, bool append) { if (locked) return ; HeaderMap::iterator iter = headers.find(name); if (iter != headers.end()) { if (append) { SStringStream newvalue; newvalue << iter->second << "," << value; headers.insert(HeaderPair(name, newvalue.str())); } else { headers[name] = value; } } else { headers.insert(HeaderPair(name, value)); } if ((strcasecmp(name.c_str(), "Connection") == 0) && (strcasecmp(value.c_str(), "close") == 0)) { closeConnection = true; } if (strcasecmp(name.c_str(), "content-length") == 0) { // contentLength = atoi(value.c_str()); } } //! Sets the value of an bool typed header void SHeaderTable::SetBoolHeader(const SString &name, bool value) { SetHeader(name, value ? TRUE_STRING : FALSE_STRING); } //! Sets the value of an int typed header void SHeaderTable::SetUIntHeader(const SString &name, unsigned value) { char valueStr[64]; sprintf(&valueStr[0], "%u", value); SetHeader(name, &valueStr[0]); } //! Sets the value of an int typed header void SHeaderTable::SetIntHeader(const SString &name, int value) { char valueStr[64]; sprintf(valueStr, "%d", value); SetHeader(name, &valueStr[0]); } //! Sets the value of an double typed header void SHeaderTable::SetDoubleHeader(const SString &name, double value) { char valueStr[64]; sprintf(valueStr, "%f", value); SetHeader(name, &valueStr[0]); } // Removes a header SString SHeaderTable::RemoveHeader(const SString &name) { if ( ! locked) { HeaderMap::iterator iter = headers.find(name); if (iter != headers.end()) { headers.erase(iter); return iter->second; } } return ""; }
25.921053
102
0.607614
panyam
aeab5fab1b6bc6bce7acf07a3e3bb4f1379c8f8a
675
hpp
C++
ablateLibrary/flow/fluxDifferencer/offFluxDifferencer.hpp
pakserep/ablate
8c8443de8a252b03b3535f7c48b7a50aac1e56e4
[ "BSD-3-Clause" ]
null
null
null
ablateLibrary/flow/fluxDifferencer/offFluxDifferencer.hpp
pakserep/ablate
8c8443de8a252b03b3535f7c48b7a50aac1e56e4
[ "BSD-3-Clause" ]
null
null
null
ablateLibrary/flow/fluxDifferencer/offFluxDifferencer.hpp
pakserep/ablate
8c8443de8a252b03b3535f7c48b7a50aac1e56e4
[ "BSD-3-Clause" ]
null
null
null
#ifndef ABLATELIBRARY_OFFFLUXDIFFERENCER_HPP #define ABLATELIBRARY_OFFFLUXDIFFERENCER_HPP #include "fluxDifferencer.hpp" namespace ablate::flow::fluxDifferencer { /** * Turns off all flow through the flux differencer. This is good for testing. */ class OffFluxDifferencer : public fluxDifferencer::FluxDifferencer { private: static void OffDifferencerFunction(PetscReal Mm, PetscReal* sPm, PetscReal* sMm, PetscReal Mp, PetscReal* sPp, PetscReal* sMp); public: FluxDifferencerFunction GetFluxDifferencerFunction() override { return OffDifferencerFunction; } }; } // namespace ablate::flow::fluxDifferencer #endif // ABLATELIBRARY_OFFFLUXDIFFERENCER_HPP
35.526316
131
0.795556
pakserep
aeb7b7e5ef4835f5aab62c5420c65d825046fad1
1,426
cpp
C++
main/Main.cpp
Cararasu/holodec
d716d95a787ab7872a49a5c4fb930dc37be95ac7
[ "MIT" ]
215
2017-06-22T16:23:52.000Z
2022-01-27T23:33:37.000Z
main/Main.cpp
Cararasu/holodec
d716d95a787ab7872a49a5c4fb930dc37be95ac7
[ "MIT" ]
4
2017-06-29T16:49:28.000Z
2019-02-07T19:58:57.000Z
main/Main.cpp
Cararasu/holodec
d716d95a787ab7872a49a5c4fb930dc37be95ac7
[ "MIT" ]
21
2017-10-14T02:10:41.000Z
2021-07-13T06:08:38.000Z
#include "Main.h" #include <fstream> using namespace holodec; Main* Main::g_main; bool Main::registerArchitecture (Architecture* arch) { for (Architecture * a : architectures) if (caseCmpHString (a->name, arch->name)) return false; architectures.push_back (arch); return true; } Architecture* Main::getArchitecture (HString arch) { for (Architecture * a : architectures) if (caseCmpHString (a->name, arch)) return a; return nullptr; } bool Main::registerFileFormat (FileFormat* fileformat) { for (FileFormat * ff : fileformats) if (caseCmpHString (ff->name, fileformat->name)) return false; fileformats.push_back (fileformat); return true; } FileFormat* Main::getFileFormat (HString fileformat) { for (FileFormat * ff : fileformats) if (caseCmpHString (ff->name, fileformat)) return ff; return nullptr; } File* Main::loadDataFromFile (HString file) { std::ifstream t (file.cstr(), std::ios_base::binary); size_t size; std::vector<uint8_t> data; if (t) { t.seekg (0, t.end); size = (size_t) t.tellg(); data.resize(size); t.seekg (0, t.beg); uint64_t offset = 0; while (offset < size) { t.read((char*)data.data() + offset, size); uint64_t read = t.gcount(); if (read == 0) break; offset += read; printf("Read %zu chars\n", t.gcount()); } return new File(file, data); } return nullptr; } void holodec::Main::initMain() { g_main = new Main(); }
21.283582
56
0.671809
Cararasu
aec031dfa142d090bef5a69895f524840deb7403
4,775
cc
C++
diplomacy_research/proto/diplomacy_tensorflow/core/protobuf/master_service.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
39
2019-09-06T13:42:24.000Z
2022-03-18T18:38:43.000Z
diplomacy_research/proto/diplomacy_tensorflow/core/protobuf/master_service.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
9
2019-09-19T22:35:32.000Z
2022-02-24T18:04:57.000Z
diplomacy_research/proto/diplomacy_tensorflow/core/protobuf/master_service.pb.cc
wwongkamjan/dipnet_press
787263c1b9484698904f525c8d78d0e333e1c0d9
[ "MIT" ]
8
2019-10-16T21:09:14.000Z
2022-02-23T05:20:37.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: diplomacy_tensorflow/core/protobuf/master_service.proto #include "diplomacy_tensorflow/core/protobuf/master_service.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace diplomacy { namespace tensorflow { namespace grpc { } // namespace grpc } // namespace tensorflow } // namespace diplomacy namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprotobuf_2fmaster_5fservice_2eproto { void InitDefaults() { } const ::google::protobuf::uint32 TableStruct::offsets[1] = {}; static const ::google::protobuf::internal::MigrationSchema* schemas = NULL; static const ::google::protobuf::Message* const* file_default_instances = NULL; void protobuf_AssignDescriptors() { AddDescriptors(); AssignDescriptors( "diplomacy_tensorflow/core/protobuf/master_service.proto", schemas, file_default_instances, TableStruct::offsets, NULL, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n7diplomacy_tensorflow/core/protobuf/mas" "ter_service.proto\022\031diplomacy.tensorflow." "grpc\032/diplomacy_tensorflow/core/protobuf" "/master.proto2\203\010\n\rMasterService\022h\n\rCreat" "eSession\022*.diplomacy.tensorflow.CreateSe" "ssionRequest\032+.diplomacy.tensorflow.Crea" "teSessionResponse\022h\n\rExtendSession\022*.dip" "lomacy.tensorflow.ExtendSessionRequest\032+" ".diplomacy.tensorflow.ExtendSessionRespo" "nse\022n\n\017PartialRunSetup\022,.diplomacy.tenso" "rflow.PartialRunSetupRequest\032-.diplomacy" ".tensorflow.PartialRunSetupResponse\022V\n\007R" "unStep\022$.diplomacy.tensorflow.RunStepReq" "uest\032%.diplomacy.tensorflow.RunStepRespo" "nse\022e\n\014CloseSession\022).diplomacy.tensorfl" "ow.CloseSessionRequest\032*.diplomacy.tenso" "rflow.CloseSessionResponse\022b\n\013ListDevice" "s\022(.diplomacy.tensorflow.ListDevicesRequ" "est\032).diplomacy.tensorflow.ListDevicesRe" "sponse\022P\n\005Reset\022\".diplomacy.tensorflow.R" "esetRequest\032#.diplomacy.tensorflow.Reset" "Response\022e\n\014MakeCallable\022).diplomacy.ten" "sorflow.MakeCallableRequest\032*.diplomacy." "tensorflow.MakeCallableResponse\022b\n\013RunCa" "llable\022(.diplomacy.tensorflow.RunCallabl" "eRequest\032).diplomacy.tensorflow.RunCalla" "bleResponse\022n\n\017ReleaseCallable\022,.diploma" "cy.tensorflow.ReleaseCallableRequest\032-.d" "iplomacy.tensorflow.ReleaseCallableRespo" "nseBq\n\032org.tensorflow.distruntimeB\023Maste" "rServiceProtosP\001Z<github.com/tensorflow/" "tensorflow/tensorflow/go/core/protobufb\006" "proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 1286); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "diplomacy_tensorflow/core/protobuf/master_service.proto", &protobuf_RegisterTypes); ::protobuf_diplomacy_5ftensorflow_2fcore_2fprotobuf_2fmaster_2eproto::AddDescriptors(); } void AddDescriptors() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprotobuf_2fmaster_5fservice_2eproto namespace diplomacy { namespace tensorflow { namespace grpc { // @@protoc_insertion_point(namespace_scope) } // namespace grpc } // namespace tensorflow } // namespace diplomacy namespace google { namespace protobuf { } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope)
39.139344
119
0.770681
wwongkamjan
aec0575a03cec24039c6073cf35b9875a7db2962
353
hpp
C++
SDLTest.hpp
gazpachian/ScrabookDL
70424e4d866d17d95539242ba86ad0841f030091
[ "MIT" ]
null
null
null
SDLTest.hpp
gazpachian/ScrabookDL
70424e4d866d17d95539242ba86ad0841f030091
[ "MIT" ]
null
null
null
SDLTest.hpp
gazpachian/ScrabookDL
70424e4d866d17d95539242ba86ad0841f030091
[ "MIT" ]
null
null
null
#include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <stdio.h> #include <string> #include <algorithm> #include <tr1/memory> #include "vector.hpp" #include "controller.hpp" #include "render.hpp" //Window constants const Vector2 DEF_SCREEN_DIMS(1200, 675); const Vector3 DEF_BG_COL(0xFD, 0xF6, 0xE3); const char * window_title = "Title of window";
23.533333
46
0.745042
gazpachian
aeca4b2a297c118a8eb65076e18adcd6c73e2e56
6,680
cpp
C++
Interaction/albaDevice.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
9
2018-11-19T10:15:29.000Z
2021-08-30T11:52:07.000Z
Interaction/albaDevice.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Interaction/albaDevice.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
3
2018-06-10T22:56:29.000Z
2019-12-12T06:22:56.000Z
/*========================================================================= Program: ALBA (Agile Library for Biomedical Applications) Module: albaDevice Authors: Marco Petrone Copyright (c) BIC All rights reserved. See Copyright.txt or This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // to be includes first: includes wxWindows too... #include "albaDefines.h" // base includes #include "albaDevice.h" #include "mmuIdFactory.h" // GUI #include "albaGUI.h" // serialization #include "albaStorageElement.h" //------------------------------------------------------------------------------ // Events //------------------------------------------------------------------------------ ALBA_ID_IMP(albaDevice::DEVICE_NAME_CHANGED) ALBA_ID_IMP(albaDevice::DEVICE_STARTED) ALBA_ID_IMP(albaDevice::DEVICE_STOPPED) albaCxxTypeMacro(albaDevice) //------------------------------------------------------------------------------ albaDevice::albaDevice() //------------------------------------------------------------------------------ { m_Gui = NULL; m_ID = 0; m_Start = false; m_AutoStart = false; // auto is enabled when device is started the first time m_Locked = false; m_PersistentFalg = false; } //------------------------------------------------------------------------------ albaDevice::~albaDevice() //------------------------------------------------------------------------------ { } //------------------------------------------------------------------------------ void albaDevice::SetName(const char *name) //------------------------------------------------------------------------------ { Superclass::SetName(name); InvokeEvent(this,DEVICE_NAME_CHANGED); // send event to device manager (up) } //------------------------------------------------------------------------------ int albaDevice::InternalInitialize() //------------------------------------------------------------------------------ { int ret=Superclass::InternalInitialize(); m_AutoStart = 1; // enable auto starting of device // update the GUI if present return ret; } //------------------------------------------------------------------------------ int albaDevice::Start() //------------------------------------------------------------------------------ { if (Initialize()) return ALBA_ERROR; // send an event to advise interactors this device has been started InvokeEvent(this,DEVICE_STARTED,MCH_INPUT); return ALBA_OK; } //------------------------------------------------------------------------------ void albaDevice::Stop() //------------------------------------------------------------------------------ { if (!m_Initialized) return; Shutdown(); // send an event to advise interactors this device has been stopped InvokeEvent(this,DEVICE_STOPPED,MCH_INPUT); } //---------------------------------------------------------------------------- albaGUI *albaDevice::GetGui() //---------------------------------------------------------------------------- { if (!m_Gui) CreateGui(); return m_Gui; } //---------------------------------------------------------------------------- void albaDevice::CreateGui() //---------------------------------------------------------------------------- { /* //SIL. 07-jun-2006 : assert(m_Gui == NULL); m_Gui = new albaGUI(this); m_Gui->String(ID_NAME,"name",&m_Name); m_Gui->Divider(); m_Gui->Button(ID_ACTIVATE,"activate device"); m_Gui->Button(ID_SHUTDOWN,"shutdown device"); m_Gui->Bool(ID_AUTO_START,"auto start",&m_AutoStart,0,"automatically start device on application startup"); m_Gui->Enable(ID_ACTIVATE,!IsInitialized()); m_Gui->Enable(ID_SHUTDOWN,IsInitialized()!=0); */ assert(m_Gui == NULL); m_Gui = new albaGUI(this); m_Gui->String(ID_NAME,"name",&m_Name); m_Gui->Divider(); m_Gui->Bool(ID_ACTIVATE,"start",&m_Start,0,"activate/deactivate this device"); m_Gui->Bool(ID_AUTO_START,"auto start",&m_AutoStart,0,"automatically activate device on application startup"); //m_Gui->Enable(ID_ACTIVATE,!IsInitialized()); //m_Gui->Enable(ID_SHUTDOWN,IsInitialized()!=0); m_Gui->Divider(); } //---------------------------------------------------------------------------- void albaDevice::UpdateGui() //---------------------------------------------------------------------------- { if (m_Gui) { //m_Gui->Enable(ID_ACTIVATE,!IsInitialized()); //m_Gui->Enable(ID_SHUTDOWN,IsInitialized()!=0); m_Start = IsInitialized(); m_Gui->Update(); } } //---------------------------------------------------------------------------- void albaDevice::OnEvent(albaEventBase *e) //---------------------------------------------------------------------------- { albaEvent *ev = albaEvent::SafeDownCast(e); if (ev&& ev->GetSender()==m_Gui) { switch(ev->GetId()) { case ID_NAME: SetName(m_Name); // force sending an event break; case ID_ACTIVATE: if(m_Start) // user request to Start { if (Initialize()) albaErrorMessage("Cannot Initialize Device","I/O Error"); } else // user request to Stop { Shutdown(); } UpdateGui(); break; /* //SIL. 07-jun-2006 : case ID_SHUTDOWN: Shutdown(); UpdateGui(); break; */ } return; } else { // pass event to superclass to be processed Superclass::OnEvent(e); } } //------------------------------------------------------------------------------ int albaDevice::InternalStore(albaStorageElement *node) //------------------------------------------------------------------------------ { if (node->StoreText("Name",m_Name)==ALBA_OK && \ node->StoreInteger("ID",(m_ID-MIN_DEVICE_ID))==ALBA_OK && \ node->StoreInteger("AutoStart",m_AutoStart)==ALBA_OK) return ALBA_OK; return ALBA_ERROR; } //------------------------------------------------------------------------------ int albaDevice::InternalRestore(albaStorageElement *node) //------------------------------------------------------------------------------ { // Device Name if (node->RestoreText("Name",m_Name)==ALBA_OK) { int dev_id; node->RestoreInteger("ID",dev_id); SetID(dev_id+MIN_DEVICE_ID); int flag; // AutoStart flag (optional) if (node->RestoreInteger("AutoStart",flag)==ALBA_OK) { SetAutoStart(flag!=0); } // the ID??? return ALBA_OK; } return ALBA_ERROR; }
29.688889
112
0.448054
IOR-BIC
aecd7dece280518c3882099caebe07274c7374ae
1,525
cpp
C++
src/easy/trick-or-treat/solutions/c++/solution.cpp
rdtsc/codeeval-solutions
d5c06baf89125e9e9f4b163ee57e5a8f7e73e717
[ "MIT" ]
null
null
null
src/easy/trick-or-treat/solutions/c++/solution.cpp
rdtsc/codeeval-solutions
d5c06baf89125e9e9f4b163ee57e5a8f7e73e717
[ "MIT" ]
null
null
null
src/easy/trick-or-treat/solutions/c++/solution.cpp
rdtsc/codeeval-solutions
d5c06baf89125e9e9f4b163ee57e5a8f7e73e717
[ "MIT" ]
null
null
null
#include <cassert> #include <fstream> #include <iostream> #include <limits> template<typename T> static bool extractFrom(std::istream& inputStream, const char delimiter, T& value) { static constexpr auto ignoreLimit = std::numeric_limits<std::streamsize>::max(); return inputStream.ignore(ignoreLimit, delimiter) >> value; } template<typename T, typename... Values> static bool extractFrom(std::istream& inputStream, const char delimiter, T& value, Values&... values) { return ::extractFrom(inputStream, delimiter, value) && ::extractFrom(inputStream, delimiter, values...); } int main(const int argc, const char* const argv[]) { // Getting away with no error checking throughout because CodeEval makes some // strong guarantees about our runtime environment. No need to pay when we're // being benchmarked. Don't forget to define NDEBUG prior to submitting! assert(argc >= 2 && "Expecting at least one command-line argument."); std::ifstream inputStream(argv[1]); assert(inputStream && "Failed to open input stream."); unsigned v = 0, z = 0, w = 0, h = 0; while(::extractFrom(inputStream, ':', v, z, w, h)) { const auto take = v * 3 + // Vampires. z * 4 + // Zombies. w * 5; // Witches. const auto loot = (take * h), shares = (v + z + w); std::cout << (loot / shares) << '\n'; } }
29.326923
79
0.594098
rdtsc
aed084fb525b5f25e7ee5eed598324734eff4068
1,580
cpp
C++
src/effect_cas.cpp
stephanlachnit/vkBasalt
dd6a067b7eada67f4f34e56054ef24264f6856d7
[ "Zlib" ]
748
2019-10-20T14:21:20.000Z
2022-03-22T05:53:42.000Z
src/effect_cas.cpp
stephanlachnit/vkBasalt
dd6a067b7eada67f4f34e56054ef24264f6856d7
[ "Zlib" ]
160
2019-10-20T16:35:47.000Z
2022-03-30T19:21:56.000Z
src/effect_cas.cpp
stephanlachnit/vkBasalt
dd6a067b7eada67f4f34e56054ef24264f6856d7
[ "Zlib" ]
58
2019-10-20T19:15:01.000Z
2022-01-02T01:16:08.000Z
#include "effect_cas.hpp" #include <cstring> #include "image_view.hpp" #include "descriptor_set.hpp" #include "buffer.hpp" #include "renderpass.hpp" #include "graphics_pipeline.hpp" #include "framebuffer.hpp" #include "shader.hpp" #include "sampler.hpp" #include "shader_sources.hpp" namespace vkBasalt { CasEffect::CasEffect(LogicalDevice* pLogicalDevice, VkFormat format, VkExtent2D imageExtent, std::vector<VkImage> inputImages, std::vector<VkImage> outputImages, Config* pConfig) { float sharpness = pConfig->getOption<float>("casSharpness", 0.4f); vertexCode = full_screen_triangle_vert; fragmentCode = cas_frag; VkSpecializationMapEntry sharpnessMapEntry; sharpnessMapEntry.constantID = 0; sharpnessMapEntry.offset = 0; sharpnessMapEntry.size = sizeof(float); VkSpecializationInfo fragmentSpecializationInfo; fragmentSpecializationInfo.mapEntryCount = 1; fragmentSpecializationInfo.pMapEntries = &sharpnessMapEntry; fragmentSpecializationInfo.dataSize = sizeof(float); fragmentSpecializationInfo.pData = &sharpness; pVertexSpecInfo = nullptr; pFragmentSpecInfo = &fragmentSpecializationInfo; init(pLogicalDevice, format, imageExtent, inputImages, outputImages, pConfig); } CasEffect::~CasEffect() { } } // namespace vkBasalt
30.980392
86
0.635443
stephanlachnit
aed3281640470573c0c4ef23e1888bd1b850ecee
403
cpp
C++
Rafflesia/main.cpp
TelepathicFart/Rafflesia
9376e06b5a7ab3f712677f31504021c1b62c3f09
[ "MIT" ]
5
2021-05-11T02:52:31.000Z
2021-09-03T05:10:53.000Z
Rafflesia/main.cpp
TelepathicFart/Rafflesia
9376e06b5a7ab3f712677f31504021c1b62c3f09
[ "MIT" ]
null
null
null
Rafflesia/main.cpp
TelepathicFart/Rafflesia
9376e06b5a7ab3f712677f31504021c1b62c3f09
[ "MIT" ]
1
2022-02-24T13:56:26.000Z
2022-02-24T13:56:26.000Z
#include <QtWidgets> #include "MainWindow.h" #include <istream> #include <fstream> int main(int argc, char *argv[]) { #if defined(Q_OS_WIN) QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); #endif QApplication app(argc, argv); MainWindow window; window.show(); window.setWindowTitle(QApplication::translate("toplevel", "Top-level widget")); return app.exec(); }
18.318182
83
0.704715
TelepathicFart
aed923244e3a075b6566c3fb94879181634bcba8
1,094
cpp
C++
projects/Test_SkeletalAnimation/src/main.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
11
2016-08-30T12:01:35.000Z
2021-12-29T15:34:03.000Z
projects/Test_SkeletalAnimation/src/main.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
9
2016-05-19T03:14:22.000Z
2021-01-17T05:45:52.000Z
projects/Test_SkeletalAnimation/src/main.cpp
codeonwort/pathosengine
ea568afeac9af3ebe3f2e53cc5abeecb40714466
[ "MIT" ]
null
null
null
#include "world2.h" #include "pathos/core_minimal.h" using namespace std; using namespace pathos; constexpr int32 WINDOW_WIDTH = 1920; constexpr int32 WINDOW_HEIGHT = 1080; constexpr char* WINDOW_TITLE = "Test: Skeletal Animation"; constexpr float FOVY = 60.0f; const vector3 CAMERA_POSITION = vector3(0.0f, 0.0f, 300.0f); constexpr float CAMERA_Z_NEAR = 1.0f; constexpr float CAMERA_Z_FAR = 10000.0f; int main(int argc, char** argv) { EngineConfig conf; conf.windowWidth = WINDOW_WIDTH; conf.windowHeight = WINDOW_HEIGHT; conf.title = WINDOW_TITLE; conf.rendererType = ERendererType::Deferred; Engine::init(argc, argv, conf); const float ar = static_cast<float>(conf.windowWidth) / static_cast<float>(conf.windowHeight); World* world2 = new World2; world2->getCamera().lookAt(CAMERA_POSITION, CAMERA_POSITION + vector3(0.0f, 0.0f, -1.0f), vector3(0.0f, 1.0f, 0.0f)); world2->getCamera().changeLens(PerspectiveLens(FOVY, ar, CAMERA_Z_NEAR, CAMERA_Z_FAR)); gEngine->setWorld(world2); gEngine->start(); return 0; }
33.151515
118
0.710238
codeonwort
aede19bebef2025d433365c92bd970cd74a809aa
57
hpp
C++
src/boost_fusion_sequence_comparison_equal_to.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_sequence_comparison_equal_to.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_sequence_comparison_equal_to.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/sequence/comparison/equal_to.hpp>
28.5
56
0.824561
miathedev
aede8903b4395c28d2a04d5f065094bba39c31da
3,738
cpp
C++
Engine/Core/Source/Molten/Renderer/Vulkan/Utility/VulkanDeviceQueues.cpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
2
2019-11-11T21:17:14.000Z
2019-11-11T22:07:26.000Z
Engine/Core/Source/Molten/Renderer/Vulkan/Utility/VulkanDeviceQueues.cpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
null
null
null
Engine/Core/Source/Molten/Renderer/Vulkan/Utility/VulkanDeviceQueues.cpp
jimmiebergmann/CurseEngine
74a0502e36327f893c8e4f3e7cbe5b9d38fbe194
[ "MIT" ]
1
2020-04-05T03:50:57.000Z
2020-04-05T03:50:57.000Z
/* * MIT License * * Copyright (c) 2021 Jimmie Bergmann * * 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. * */ #if defined(MOLTEN_ENABLE_VULKAN) #include "Molten/Renderer/Vulkan/Utility/VulkanDeviceQueues.hpp" MOLTEN_UNSCOPED_ENUM_BEGIN namespace Molten::Vulkan { // Device queue indices implemenetations. DeviceQueueIndices::DeviceQueueIndices() : graphicsQueue{}, presentQueue{} {} // Device queues implementations. DeviceQueues::DeviceQueues() : graphicsQueue(VK_NULL_HANDLE), presentQueue(VK_NULL_HANDLE), graphicsQueueIndex(0), presentQueueIndex(0) {} // Static implementations. void FetchQueueFamilyProperties( QueueFamilyProperties& queueFamilyProperties, VkPhysicalDevice physicalDevice) { queueFamilyProperties.clear(); uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, nullptr); if (!queueFamilyCount) { return; } queueFamilyProperties.resize(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyCount, queueFamilyProperties.data()); } bool FindRenderableDeviceQueueIndices( DeviceQueueIndices& queueIndices, VkPhysicalDevice physicalDevice, const VkSurfaceKHR surface, const QueueFamilyProperties& queueFamilies) { queueIndices.graphicsQueue.reset(); queueIndices.presentQueue.reset(); uint32_t finalGraphicsQueueIndex = 0; uint32_t finalPresentQueueIndex = 0; bool graphicsFamilySupport = false; bool presentFamilySupport = false; for (uint32_t i = 0; i < queueFamilies.size(); i++) { auto& queueFamily = queueFamilies[i]; if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) { graphicsFamilySupport = true; finalGraphicsQueueIndex = i; } VkBool32 presentSupport = false; vkGetPhysicalDeviceSurfaceSupportKHR(physicalDevice, i, surface, &presentSupport); if (presentSupport) { presentFamilySupport = true; finalPresentQueueIndex = i; } if (graphicsFamilySupport && presentFamilySupport) { break; } } if (!graphicsFamilySupport || !presentFamilySupport) { return false; } queueIndices.graphicsQueue = finalGraphicsQueueIndex; queueIndices.presentQueue = finalPresentQueueIndex; return true; } } MOLTEN_UNSCOPED_ENUM_END #endif
30.390244
114
0.67817
jimmiebergmann
aee11d7d4e9a3c4135f46a2909da6c8017d15bd2
4,614
cpp
C++
Development/Editor/Plugin/Warcraft3/yd_lua_engine/lua_engine/libs_runtime.cpp
shawwwn/YDWE
b83ffe041d9623409d9ffd951988e2b482d9cfc3
[ "Apache-2.0" ]
2
2016-05-30T11:42:33.000Z
2017-10-31T11:53:42.000Z
Development/Editor/Plugin/Warcraft3/yd_lua_engine/lua_engine/libs_runtime.cpp
shawwwn/YDWE
b83ffe041d9623409d9ffd951988e2b482d9cfc3
[ "Apache-2.0" ]
null
null
null
Development/Editor/Plugin/Warcraft3/yd_lua_engine/lua_engine/libs_runtime.cpp
shawwwn/YDWE
b83ffe041d9623409d9ffd951988e2b482d9cfc3
[ "Apache-2.0" ]
null
null
null
#include <base/lua/state.h> #include <base/util/console.h> #include <cstring> #include "libs_runtime.h" namespace base { namespace warcraft3 { namespace lua_engine { namespace runtime { int version = 2; int handle_level = 2; bool console = false; bool sleep = true; bool catch_crash = true; void initialize() { handle_level = 2; console = false; sleep = true; catch_crash = true; } int set_err_function(lua::state* ls, int index) { if (ls->isfunction(index) || ls->isnil(index)) { ls->pushvalue(index); ls->setfield(LUA_REGISTRYINDEX, "_JASS_ERROR_HANDLE"); } return 0; } int get_err_function(lua::state* ls) { ls->getfield(LUA_REGISTRYINDEX, "_JASS_ERROR_HANDLE"); return 1; } int get_global_table(lua::state* ls, const char* name, bool weak) { ls->getfield(LUA_REGISTRYINDEX, name); if (!ls->istable(-1)) { ls->pop(1); ls->newtable(); if (weak) { ls->newtable(); { ls->pushstring("__mode"); ls->pushstring("kv"); ls->rawset(-3); } ls->setmetatable(-2); } ls->pushvalue(-1); ls->setfield(LUA_REGISTRYINDEX, name); } return 1; } int thread_get_table(lua::state* ls) { return get_global_table(ls, "_JASS_THREAD_TABLE", true); } int thread_create(lua::state* ls, int index) { thread_get_table(ls); ls->pushvalue(index); ls->rawget(-2); if (ls->isnil(-1)) { ls->pop(1); ls->newthread(); } else { ls->pushvalue(index); ls->pushnil(); ls->rawset(-4); } ls->remove(-2); return 1; } int thread_save(lua::state* ls, int key, int value) { thread_get_table(ls); ls->pushvalue(key); ls->pushvalue(value); ls->rawset(-3); ls->pop(1); return 0; } int handle_ud_get_table(lua::state* ls) { return get_global_table(ls, "_JASS_HANDLE_UD_TABLE", true); } int callback_get_table(lua::state* ls) { return get_global_table(ls, "_JASS_CALLBACK_TABLE", false); } int callback_push(lua::state* ls, int idx) { callback_get_table(ls); // read t[v] ls->pushvalue(idx); ls->rawget(-2); if (ls->isnumber(-1)) { int ret = ls->tointeger(-1); ls->pop(2); return ret; } ls->pop(1); // free = t[0] + 1 ls->rawgeti(-1, 0); int free = 1 + ls->tointeger(-1); ls->pop(1); // t[0] = free ls->pushinteger(free); ls->rawseti(-2, 0); // t[free] = v ls->pushvalue(idx); ls->rawseti(-2, free); // t[v] = free ls->pushvalue(idx); ls->pushinteger(free); ls->rawset(-3); // pop t ls->pop(1); return free; } int callback_read(lua::state* ls, int ref) { callback_get_table(ls); ls->rawgeti(-1, ref); ls->remove(-2); return 1; } } int jass_runtime_set(lua_State* L) { lua::state* ls = (lua::state*)L; const char* name = ls->tostring(2); if (strcmp("error_handle", name) == 0) { runtime::set_err_function(ls, 3); } else if (strcmp("handle_level", name) == 0) { runtime::handle_level = ls->checkinteger(3); } else if (strcmp("console", name) == 0) { runtime::console = !!ls->toboolean(3); if (runtime::console) { console::enable(); console::disable_close_button(); } else { console::disable(); } } else if (strcmp("sleep", name) == 0) { runtime::sleep = !!ls->toboolean(3); } else if (strcmp("catch_crash", name) == 0) { runtime::catch_crash = !!ls->toboolean(3); } return 0; } int jass_runtime_get(lua_State* L) { lua::state* ls = (lua::state*)L; const char* name = ls->tostring(2); if (strcmp("version", name) == 0) { ls->pushinteger(runtime::version); return 1; } else if (strcmp("error_handle", name) == 0) { return runtime::get_err_function(ls); } else if (strcmp("handle_level", name) == 0) { ls->pushinteger(runtime::handle_level); return 1; } else if (strcmp("console", name) == 0) { ls->pushboolean(runtime::console); return 1; } else if (strcmp("sleep", name) == 0) { ls->pushboolean(runtime::sleep); return 1; } else if (strcmp("catch_crash", name) == 0) { ls->pushboolean(runtime::catch_crash); return 1; } return 0; } int jass_runtime(lua::state* ls) { ls->newtable(); { ls->newtable(); { ls->pushstring("__index"); ls->pushcclosure((lua::cfunction)jass_runtime_get, 0); ls->rawset(-3); ls->pushstring("__newindex"); ls->pushcclosure((lua::cfunction)jass_runtime_set, 0); ls->rawset(-3); } ls->setmetatable(-2); } return 1; } }}}
18.309524
67
0.584092
shawwwn
aee5dbfe6d334342322d1d2cccc32e28a8cdf42b
209
cpp
C++
basic/12_fungsi/fungsi.cpp
khairanabila/CPP
48b18b6bf835d8075fc96bbf183adf28a71ba819
[ "MIT" ]
23
2021-09-10T00:08:48.000Z
2022-03-24T16:09:30.000Z
basic/12_fungsi/fungsi.cpp
khairanabila/CPP
48b18b6bf835d8075fc96bbf183adf28a71ba819
[ "MIT" ]
20
2021-09-21T15:34:21.000Z
2021-11-28T18:52:10.000Z
basic/12_fungsi/fungsi.cpp
khairanabila/CPP
48b18b6bf835d8075fc96bbf183adf28a71ba819
[ "MIT" ]
27
2021-09-10T02:35:56.000Z
2022-01-24T10:46:06.000Z
#include <iostream> // membuat fungsi tanpa return nilai void panggil() { std::cout << "Fungsi tanpa return" << std::endl; } int main(){ // memanggil fungsi panggil() panggil(); return 0; }
14.928571
52
0.617225
khairanabila
aee7a2814780ca3c8a8e7c7aa5c504bcb70ef324
1,961
cc
C++
bin/scaling/traversal.cc
manopapad/flecsi
8bb06e4375f454a0680564c76df2c60ffe49c770
[ "Unlicense" ]
null
null
null
bin/scaling/traversal.cc
manopapad/flecsi
8bb06e4375f454a0680564c76df2c60ffe49c770
[ "Unlicense" ]
null
null
null
bin/scaling/traversal.cc
manopapad/flecsi
8bb06e4375f454a0680564c76df2c60ffe49c770
[ "Unlicense" ]
null
null
null
CINCH_CAPTURE() << "------------- forall cells, vertices" << endl; for(auto cell : mesh->entities<2, $DOMAIN>()) { CINCH_CAPTURE() << "------------- cell id: " << cell.id() << endl; for(auto vertex : mesh->entities<0, $DOMAIN>(cell)) { CINCH_CAPTURE() << "--- vertex id: " << vertex.id() << endl; for(auto cell2 : mesh->entities<2, $DOMAIN>(vertex)) { CINCH_CAPTURE() << "+ cell2 id: " << cell2.id() << endl; } } } CINCH_CAPTURE() << "------------- forall cells, edges" << endl; for(auto cell : mesh->entities<2, $DOMAIN>()) { CINCH_CAPTURE() << "------- cell id: " << cell.id() << endl; for(auto edge : mesh->entities<1, $DOMAIN>(cell)) { CINCH_CAPTURE() << "--- edge id: " << edge.id() << endl; } } CINCH_CAPTURE() << "------------- forall vertices, edges" << endl; for(auto vertex : mesh->entities<0, $DOMAIN>()) { CINCH_CAPTURE() << "------- vertex id: " << vertex.id() << endl; for(auto edge : mesh->entities<1, $DOMAIN>(vertex)) { CINCH_CAPTURE() << "--- edge id: " << edge.id() << endl; } } CINCH_CAPTURE() << "------------- forall vertices, cells" << endl; for(auto vertex : mesh->entities<0, $DOMAIN>()) { CINCH_CAPTURE() << "------- vertex id: " << vertex.id() << endl; for(auto cell : mesh->entities<2, $DOMAIN>(vertex)) { CINCH_CAPTURE() << "--- cell id: " << cell.id() << endl; } } CINCH_CAPTURE() << "------------- forall edges, cells" << endl; for(auto edge : mesh->entities<1, $DOMAIN>()) { CINCH_CAPTURE() << "------- edge id: " << edge.id() << endl; for(auto cell : mesh->entities<2, $DOMAIN>(edge)) { CINCH_CAPTURE() << "--- cell id: " << cell.id() << endl; } } CINCH_CAPTURE() << "------------- forall edges, vertices" << endl; for(auto edge : mesh->entities<1, $DOMAIN>()) { CINCH_CAPTURE() << "------- edge id: " << edge.id() << endl; for(auto vertex : mesh->entities<0, $DOMAIN>(edge)) { CINCH_CAPTURE() << "--- vertex id: " << vertex.id() << endl; } }
34.403509
68
0.529322
manopapad
aef16175f836f498e1d48ed7f35241eb600ad19a
1,860
cpp
C++
Paladin/BuildSystem/FileFactory.cpp
pahefu/Paladin
4fcb66c6cda7bb50b7597532bd0d7469fc33655b
[ "MIT" ]
45
2018-10-05T21:50:17.000Z
2022-01-31T11:52:59.000Z
Paladin/BuildSystem/FileFactory.cpp
pahefu/Paladin
4fcb66c6cda7bb50b7597532bd0d7469fc33655b
[ "MIT" ]
163
2018-10-01T23:52:12.000Z
2022-02-15T18:05:58.000Z
Paladin/BuildSystem/FileFactory.cpp
pahefu/Paladin
4fcb66c6cda7bb50b7597532bd0d7469fc33655b
[ "MIT" ]
9
2018-10-01T23:48:02.000Z
2022-01-23T21:28:52.000Z
#include "FileFactory.h" #include "DPath.h" #include "SourceType.h" #include "SourceTypeC.h" #include "SourceTypeLex.h" #include "SourceTypeLib.h" #include "SourceTypeResource.h" #include "SourceTypeRez.h" #include "SourceTypeShell.h" #include "SourceTypeText.h" #include "SourceTypeYacc.h" FileFactory gFileFactory; FileFactory::FileFactory(void) : fList(20,true) { LoadTypes(); } void FileFactory::LoadTypes(void) { // We have this method to update the types. If we had addons to support // different types, we would be loading those here, too. fList.AddItem(new SourceTypeC); fList.AddItem(new SourceTypeLex); fList.AddItem(new SourceTypeLib); fList.AddItem(new SourceTypeResource); fList.AddItem(new SourceTypeRez); fList.AddItem(new SourceTypeShell); fList.AddItem(new SourceTypeYacc); fList.AddItem(new SourceTypeText); } SourceFile * FileFactory::CreateSourceFileItem(const char *path) { if (!path) return NULL; DPath file(path); for (int32 i = 0; i < fList.CountItems(); i++) { SourceType *item = fList.ItemAt(i); if (item->HasExtension(file.GetExtension())) return item->CreateSourceFileItem(path); } // The default source file class doesn't do anything significant SourceFile *sourcefile = new SourceFile(path); sourcefile->SetBuildFlag(BUILD_NO); return sourcefile; } entry_ref FileFactory::CreateSourceFile(const char *folder, const char *name, uint32 options) { DPath filename(name); SourceType *type = FindTypeForExtension(filename.GetExtension()); if (!type) return entry_ref(); return type->CreateSourceFile(folder, name, options); } SourceType * FileFactory::FindTypeForExtension(const char *ext) { for (int32 i = 0; i < fList.CountItems(); i++) { SourceType *type = fList.ItemAt(i); if (!type) continue; if (type->HasExtension(ext)) return type; } return NULL; }
20.666667
83
0.73172
pahefu
aef5cba87650b7ddc70acc522f6603139805e75e
101
hpp
C++
exercises/4/seminar/8/Matrix/Matrix/utility.hpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
19
2020-02-21T16:46:50.000Z
2022-01-26T19:59:49.000Z
exercises/4/seminar/9/Matrix/Matrix/utility.hpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
1
2020-03-14T08:09:45.000Z
2020-03-14T08:09:45.000Z
exercises/4/seminar/8/Matrix - Complete/Matrix/utility.hpp
triffon/oop-2019-20
db199631d59ddefdcc0c8eb3d689de0095618f92
[ "MIT" ]
11
2020-02-23T12:29:58.000Z
2021-04-11T08:30:12.000Z
#ifndef UTILITY #define UTILITY namespace utility { int gcd(int a, int b); } #endif // !UTILITY
12.625
26
0.673267
triffon
aef61af9e9f86157b2a0dd6386cbb49269321f3f
2,670
cpp
C++
Interaction/albaAgentEventHandler.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
9
2018-11-19T10:15:29.000Z
2021-08-30T11:52:07.000Z
Interaction/albaAgentEventHandler.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Interaction/albaAgentEventHandler.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
3
2018-06-10T22:56:29.000Z
2019-12-12T06:22:56.000Z
/*========================================================================= Program: Multimod Fundation Library Module: $RCSfile: albaAgentEventHandler.cpp,v $ Language: C++ Date: $Date: 2006-06-14 14:46:33 $ Version: $Revision: 1.4 $ =========================================================================*/ #include "albaDefines.h" //SIL #include "albaDecl.h" #include "albaAgentEventHandler.h" //---------------------------------------------------------------------------- // Constants //---------------------------------------------------------------------------- enum DISPATCH_ENUM {ID_DISPATCH_EVENT = MINID}; enum WX_EVENT_ALBA { wxEVT_ALBA = 12000 /* SIL: wxEVT_USER_FIRST*/ + 1234 }; //---------------------------------------------------------------------------- class albaWXEventHandler:public wxEvtHandler //---------------------------------------------------------------------------- { protected: virtual bool ProcessEvent(wxEvent& event); public: albaAgentEventHandler *m_Dispatcher; }; //---------------------------------------------------------------------------- bool albaWXEventHandler::ProcessEvent(wxEvent& event) //---------------------------------------------------------------------------- { if (event.GetId()==ID_DISPATCH_EVENT) { if (m_Dispatcher) { m_Dispatcher->DispatchEvents(); } } return true; } //------------------------------------------------------------------------------ // Events //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ albaCxxTypeMacro(albaAgentEventHandler); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ albaAgentEventHandler::albaAgentEventHandler() //------------------------------------------------------------------------------ { m_EventHandler = new albaWXEventHandler; m_EventHandler->m_Dispatcher=this; } //------------------------------------------------------------------------------ albaAgentEventHandler::~albaAgentEventHandler() //------------------------------------------------------------------------------ { delete m_EventHandler; //albaWarningMacro("Destroying albaAgentEventHandler"); } //------------------------------------------------------------------------------ void albaAgentEventHandler::RequestForDispatching() //------------------------------------------------------------------------------ { wxIdleEvent wx_event; wx_event.SetId(ID_DISPATCH_EVENT); wxPostEvent(m_EventHandler,wx_event); }
33.375
80
0.345693
IOR-BIC
aef6d7bb7d3fb685be390278a8c563fcd24b89ed
223
cpp
C++
example/generate_word_example.cpp
arapelle/wgen
53471bd78e7fd64c780f04cd132047e20abf254f
[ "MIT" ]
1
2020-06-02T07:25:37.000Z
2020-06-02T07:25:37.000Z
example/generate_word_example.cpp
arapelle/wgen
53471bd78e7fd64c780f04cd132047e20abf254f
[ "MIT" ]
6
2020-08-28T10:52:25.000Z
2020-11-02T18:59:49.000Z
example/generate_word_example.cpp
arapelle/wgen
53471bd78e7fd64c780f04cd132047e20abf254f
[ "MIT" ]
1
2020-09-04T10:36:23.000Z
2020-09-04T10:36:23.000Z
#include <wgen/default_syllabary.hpp> #include <iostream> int main() { wgen::default_syllabary syllabary; std::string word = syllabary.random_word(7); std::cout << word << std::endl; return EXIT_SUCCESS; }
20.272727
48
0.686099
arapelle
aef7bda9a1cd6340cd0896868149deadd2a1165b
4,959
cxx
C++
Servers/Filters/vtkPVExtractSelection.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
1
2016-05-09T00:36:44.000Z
2016-05-09T00:36:44.000Z
Servers/Filters/vtkPVExtractSelection.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
null
null
null
Servers/Filters/vtkPVExtractSelection.cxx
certik/paraview
973d37b466552ce770ac0674f30040bb7e31d7fe
[ "BSD-3-Clause" ]
3
2015-05-14T21:18:53.000Z
2022-03-07T02:53:45.000Z
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkPVExtractSelection.cxx,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPVExtractSelection.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkSelection.h" #include "vtkDataObjectTypes.h" #include "vtkDataSet.h" #include "vtkIdTypeArray.h" #include "vtkCellData.h" #include "vtkPointData.h" vtkCxxRevisionMacro(vtkPVExtractSelection, "$Revision: 1.6 $"); vtkStandardNewMacro(vtkPVExtractSelection); //---------------------------------------------------------------------------- vtkPVExtractSelection::vtkPVExtractSelection() { this->SetNumberOfOutputPorts(2); } //---------------------------------------------------------------------------- vtkPVExtractSelection::~vtkPVExtractSelection() { } //---------------------------------------------------------------------------- int vtkPVExtractSelection::FillOutputPortInformation( int port, vtkInformation* info) { if (port==0) { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkDataSet"); } else { info->Set(vtkDataObject::DATA_TYPE_NAME(), "vtkSelection"); } return 1; } //---------------------------------------------------------------------------- int vtkPVExtractSelection::RequestDataObject( vtkInformation* request, vtkInformationVector** inputVector , vtkInformationVector* outputVector) { if (!this->Superclass::RequestDataObject(request, inputVector, outputVector)) { return 0; } vtkInformation* info = outputVector->GetInformationObject(1); vtkSelection *selOut = vtkSelection::SafeDownCast( info->Get(vtkDataObject::DATA_OBJECT())); if (!selOut || !selOut->IsA("vtkSelection")) { vtkDataObject* newOutput = vtkDataObjectTypes::NewDataObject("vtkSelection"); if (!newOutput) { vtkErrorMacro("Could not create vtkSelectionOutput"); return 0; } newOutput->SetPipelineInformation(info); this->GetOutputPortInformation(1)->Set( vtkDataObject::DATA_EXTENT_TYPE(), newOutput->GetExtentType()); newOutput->Delete(); } return 1; } //---------------------------------------------------------------------------- int vtkPVExtractSelection::RequestData( vtkInformation* request, vtkInformationVector** inputVector , vtkInformationVector* outputVector) { if (!this->Superclass::RequestData(request, inputVector, outputVector)) { return 0; } vtkSelection* sel = 0; if (inputVector[1]->GetInformationObject(0)) { sel = vtkSelection::SafeDownCast( inputVector[1]->GetInformationObject(0)->Get( vtkDataObject::DATA_OBJECT())); } vtkDataSet *geomOutput = vtkDataSet::SafeDownCast( outputVector->GetInformationObject(0)->Get(vtkDataObject::DATA_OBJECT())); //make an ids selection for the second output //we can do this because all of the extractSelectedX filters produce //arrays called "vtkOriginalXIds" that record what input cells produced //each output cell, at least as long as PRESERVE_TOPOLOGY is off //when we start allowing PreserveTopology, this will have to instead run //through the vtkInsidedNess arrays, and for every on entry, record the //entries index vtkSelection *output = vtkSelection::SafeDownCast( outputVector->GetInformationObject(1)->Get(vtkDataObject::DATA_OBJECT())); output->Clear(); output->SetContentType(vtkSelection::INDICES); int ft = vtkSelection::CELL; if (sel && sel->GetProperties()->Has(vtkSelection::FIELD_TYPE())) { ft = sel->GetProperties()->Get(vtkSelection::FIELD_TYPE()); } output->GetProperties()->Set(vtkSelection::FIELD_TYPE(), ft); int inv = 0; if (sel && sel->GetProperties()->Has(vtkSelection::INVERSE())) { inv = sel->GetProperties()->Get(vtkSelection::INVERSE()); } output->GetProperties()->Set(vtkSelection::INVERSE(), inv); vtkIdTypeArray *oids; if (ft == vtkSelection::CELL) { oids = vtkIdTypeArray::SafeDownCast( geomOutput->GetCellData()->GetArray("vtkOriginalCellIds")); } else { oids = vtkIdTypeArray::SafeDownCast( geomOutput->GetPointData()->GetArray("vtkOriginalPointIds")); } if (oids) { output->SetSelectionList(oids); } return 1; } //---------------------------------------------------------------------------- void vtkPVExtractSelection::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); }
30.801242
79
0.623916
certik
aefa1c5a9c4ac52d9bcad3863423a1e077dad6ea
1,281
hpp
C++
db/DBAppender.hpp
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
db/DBAppender.hpp
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
db/DBAppender.hpp
naivewong/timeunion
8070492d2c6a2d68175e7d026c27b858c2aec8e6
[ "Apache-2.0" ]
null
null
null
#ifndef DBAPPENDER_H #define DBAPPENDER_H #include "db/AppenderInterface.hpp" #include "db/DB.hpp" #include "leveldb/status.h" namespace tsdb { namespace db { // DBAppender wraps the DB's head appender and triggers compactions on commit // if necessary. class DBAppender : public AppenderInterface { private: std::unique_ptr<db::AppenderInterface> app; db::DB *db; public: DBAppender(std::unique_ptr<db::AppenderInterface> &&app, db::DB *db) : app(std::move(app)), db(db) {} std::pair<uint64_t, leveldb::Status> add(const label::Labels &lset, int64_t t, double v) { return app->add(lset, t, v); } leveldb::Status add_fast(uint64_t ref, int64_t t, double v) { return app->add_fast(ref, t, v); } leveldb::Status commit() { leveldb::Status err = app->commit(); // We could just run this check every few minutes practically. But for // benchmarks and high frequency use cases this is the safer way. if (db->head()->MaxTime() - db->head()->MinTime() > db->head()->chunk_range / 2 * 3) { db->compact_channel()->send(0); } return err; } leveldb::Status rollback() { return app->rollback(); } ~DBAppender() {} }; } // namespace db } // namespace tsdb #endif
25.62
80
0.637002
naivewong
aefc07f39c103d371a4369ef6ae901d4e0e2a91f
1,473
cpp
C++
engine/mysqlparser/listener/SqlErrorListener.cpp
zhukovaskychina/XSQL
f91db06bf86f7f6ad321722c3aea11f83d34dba1
[ "MIT" ]
1
2020-10-23T09:38:22.000Z
2020-10-23T09:38:22.000Z
engine/mysqlparser/listener/SqlErrorListener.cpp
zhukovaskychina/XSQL
f91db06bf86f7f6ad321722c3aea11f83d34dba1
[ "MIT" ]
null
null
null
engine/mysqlparser/listener/SqlErrorListener.cpp
zhukovaskychina/XSQL
f91db06bf86f7f6ad321722c3aea11f83d34dba1
[ "MIT" ]
null
null
null
// // Created by zhukovasky on 2020/9/30. // #include <common/Exceptions.h> #include "SqlErrorListener.h" SQLErrorListener::~SQLErrorListener() { } void SQLErrorListener::syntaxError(antlr4::Recognizer *recognizer, antlr4::Token *offendingSymbol, size_t line, size_t charPositionInLine, const std::string &msg, std::exception_ptr e) { std::cerr<<"语法解析异常:"<<msg<<std::endl; throw SyntaxParseException(msg); // throw MySQLErrorCode ::ER_PARSE_ERROR; } void SQLErrorListener::reportAmbiguity(antlr4::Parser *recognizer, const antlr4::dfa::DFA &dfa, size_t startIndex, size_t stopIndex, bool exact, const antlrcpp::BitSet &ambigAlts, antlr4::atn::ATNConfigSet *configs) { } void SQLErrorListener::reportAttemptingFullContext(antlr4::Parser *recognizer, const antlr4::dfa::DFA &dfa, size_t startIndex, size_t stopIndex, const antlrcpp::BitSet &conflictingAlts, antlr4::atn::ATNConfigSet *configs) { } void SQLErrorListener::reportContextSensitivity(antlr4::Parser *recognizer, const antlr4::dfa::DFA &dfa, size_t startIndex, size_t stopIndex, size_t prediction, antlr4::atn::ATNConfigSet *configs) { } SQLErrorListener::SQLErrorListener() { }
34.255814
118
0.604888
zhukovaskychina
aefc2e747d34818630c7f0d8f2d53317886ac392
3,739
cpp
C++
Testing/Gui/16_testRWI/testRWILogic.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
9
2018-11-19T10:15:29.000Z
2021-08-30T11:52:07.000Z
Testing/Gui/16_testRWI/testRWILogic.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
Testing/Gui/16_testRWI/testRWILogic.cpp
IOR-BIC/ALBA
b574968b05d9a3a2756dd2ac61d015a0d20232a4
[ "Apache-2.0", "BSD-3-Clause" ]
3
2018-06-10T22:56:29.000Z
2019-12-12T06:22:56.000Z
/*========================================================================= Program: ALBA (Agile Library for Biomedical Applications) Module: testRWILogic Authors: Silvano Imboden Copyright (c) BIC All rights reserved. See Copyright.txt or This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "albaDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include "testRWILogic.h" #include "albaDecl.h" #include "albaGUI.h" #include "testRWIBaseDlg.h" #include "testRWIDlg.h" //-------------------------------------------------------------------------------- //const: //-------------------------------------------------------------------------------- enum { ID_D1 = MINID, ID_D2, ID_D3, }; //-------------------------------------------------------------------------------- testRWILogic::testRWILogic() //-------------------------------------------------------------------------------- { /**todo: PAOLO please read here */ // RESULT OF RWI TEST : // RWIBASE produce a memory leak 5600 byte long, as follow -- by me (Silvano) this is not considered an error but a feature :-) // C:\Program Files\VisualStudio7\Vc7\include\crtdbg.h(689) : {2804} normal block at 0x099C00A8, 5600 bytes long. // Data: < Buil> 00 00 00 00 00 00 00 00 00 00 00 00 42 75 69 6C // Object dump complete. // the leaks is always 5600 bytes long, doesn't matter how many instances of RWI you have created, // so maybe it is related to something concerned with the initialization of the OpenGL context, // and the real problem could be in my NVidia OpenGL Driver m_win = new wxFrame(NULL,-1,"TestRWI",wxDefaultPosition,wxDefaultSize, wxMINIMIZE_BOX | wxMAXIMIZE_BOX | /*wxRESIZE_BORDER |*/ wxSYSTEM_MENU | wxCAPTION ); albaSetFrame(m_win); albaGUI *gui = new albaGUI(this); gui->Divider(); gui->Label("Examples of VTK RenderWindow"); gui->Button(ID_D1,"test RWIBase"); gui->Button(ID_D2,"test RWI"); gui->Label(""); gui->Label(""); gui->Button(ID_D3,"quit"); gui->Reparent(m_win); m_win->Fit(); // resize m_win to fit it's content } //-------------------------------------------------------------------------------- testRWILogic::~testRWILogic() //-------------------------------------------------------------------------------- { } //-------------------------------------------------------------------------------- void testRWILogic::OnEvent(albaEventBase *alba_event) //-------------------------------------------------------------------------------- { if (albaEvent *e = albaEvent::SafeDownCast(alba_event)) { switch(e->GetId()) { case ID_D1: { testRWIBaseDlg d("test RWIBase"); d.ShowModal(); } break; case ID_D2: { testRWIDlg d("test RWI"); d.ShowModal(); } break; case ID_D3: m_win->Destroy(); break; } } } //-------------------------------------------------------------------------------- void testRWILogic::Show() //-------------------------------------------------------------------------------- { m_win->Show(true); }
33.088496
129
0.472319
IOR-BIC
aefc38192acba82870d5413f54a656d15199680b
511
cpp
C++
problems/acmicpc_14935.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
problems/acmicpc_14935.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
problems/acmicpc_14935.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; void f(string &s,int x){ if(x<10){s.push_back(x+'0');return;} f(s,x/10); s.push_back(x%10+'0'); } int main(){ string s; cin>>s; vector<string> v; while(true){ for(auto str:v){ if(s==str)goto A; } v.push_back(s); int x=(s[0]-'0')*(s.length()); string t; f(t,x); if(s==t)goto B; s=t; } A: printf("N"); B: printf("FA"); }
18.925926
40
0.471624
qawbecrdtey
4e033a2418992d27b732cbcf8e73193025f3b40a
1,521
cpp
C++
src/gpio_test.cpp
gbr1/upboard_ros
a4fd1ce54fc78724bcdfde5b09185feeca71225d
[ "MIT" ]
24
2019-05-10T11:48:40.000Z
2022-03-29T08:52:08.000Z
src/gpio_test.cpp
gbr1/upboard_ros
a4fd1ce54fc78724bcdfde5b09185feeca71225d
[ "MIT" ]
1
2020-07-08T04:20:17.000Z
2020-07-08T09:33:36.000Z
src/gpio_test.cpp
gbr1/upboard_ros
a4fd1ce54fc78724bcdfde5b09185feeca71225d
[ "MIT" ]
1
2019-05-11T23:44:33.000Z
2019-05-11T23:44:33.000Z
#include <ros/ros.h> #include <upboard_ros/Gpio.h> #include <upboard_ros/ListGpio.h> #define BUTTON 24 #define LED 22 #define SLOW 1.0 #define FAST 0.2 upboard_ros::Gpio tmp_msg; upboard_ros::ListGpio list_msg; bool status=false; ros::Time tp; float blinkrate=SLOW; ros::Publisher gpiopub; void gpioCallback(const upboard_ros::ListGpio & msg){ int k=0; bool found=false; while((!found) && (k<msg.gpio.size())){ if (msg.gpio[k].pin==BUTTON){ found=true; if (msg.gpio[k].value==0){ blinkrate=FAST; } else{ blinkrate=SLOW; } } k++; } } void blink(){ ros::Duration d=ros::Time::now()-tp; if (d.toSec()>=blinkrate){ //create a message to turn on led on pin 22 tmp_msg.pin=22; status=!status; tmp_msg.value=status; //add to list list_msg.gpio.push_back(tmp_msg); list_msg.header.stamp=ros::Time::now(); gpiopub.publish(list_msg); list_msg.gpio.clear(); tp=ros::Time::now(); } } int main(int argc, char **argv){ ros::init(argc, argv, "gpio_test"); ros::NodeHandle nh; gpiopub = nh.advertise<upboard_ros::ListGpio>("/upboard/gpio/write",10); ros::Subscriber gpiosub = nh.subscribe("/upboard/gpio/read", 10, gpioCallback); tp=ros::Time::now(); ros::Rate rate(100); while (ros::ok){ blink(); ros::spinOnce(); rate.sleep(); } }
21.728571
83
0.565417
gbr1
4e04a96449d7fcfc5f8e2e4005cf183d6c657597
8,476
cpp
C++
Testing/VME/mafPipeVolumeSliceTest.cpp
FusionBox2/MAF2
b576955f4f6b954467021f12baedfebcaf79a382
[ "Apache-2.0" ]
1
2018-01-23T09:13:40.000Z
2018-01-23T09:13:40.000Z
Testing/VME/mafPipeVolumeSliceTest.cpp
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
null
null
null
Testing/VME/mafPipeVolumeSliceTest.cpp
gradicosmo/MAF2
86ddf1f52a2de4479c09fd3f43dc321ff412af42
[ "Apache-2.0" ]
3
2020-09-24T16:04:53.000Z
2020-09-24T16:50:30.000Z
/*========================================================================= Program: MAF2 Module: mafPipeVolumeSliceTest Authors: Matteo Giacomoni Copyright (c) B3C All rights reserved. See Copyright.txt or http://www.scsitaly.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "mafDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the MAF must include "mafDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include <cppunit/config/SourcePrefix.h> #include "mafPipeVolumeSliceTest.h" #include "mafPipeVolumeSlice.h" #include "mafSceneNode.h" #include "mafVMEVolumeGray.h" #include "mmaVolumeMaterial.h" #include "vtkMAFAssembly.h" #include "vtkMapper.h" #include "vtkJPEGWriter.h" #include "vtkJPEGReader.h" #include "vtkWindowToImageFilter.h" #include "vtkImageMathematics.h" #include "vtkImageData.h" #include "vtkPointData.h" #include "vtkStructuredPointsReader.h" #include "vtkCamera.h" // render window stuff #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include <iostream> #include <fstream> enum PIPE_BOX_ACTORS { PIPE_BOX_ACTOR, PIPE_BOX_ACTOR_WIRED, PIPE_BOX_ACTOR_OUTLINE_CORNER, PIPE_BOX_NUMBER_OF_ACTORS, }; //---------------------------------------------------------------------------- void mafPipeVolumeSliceTest::TestFixture() //---------------------------------------------------------------------------- { } //---------------------------------------------------------------------------- void mafPipeVolumeSliceTest::setUp() //---------------------------------------------------------------------------- { vtkNEW(m_Renderer); vtkNEW(m_RenderWindow); vtkNEW(m_RenderWindowInteractor); } //---------------------------------------------------------------------------- void mafPipeVolumeSliceTest::tearDown() //---------------------------------------------------------------------------- { vtkDEL(m_Renderer); vtkDEL(m_RenderWindow); vtkDEL(m_RenderWindowInteractor); } //---------------------------------------------------------------------------- void mafPipeVolumeSliceTest::TestPipeExecution() //---------------------------------------------------------------------------- { ///////////////// render stuff ///////////////////////// m_Renderer->SetBackground(0.1, 0.1, 0.1); m_RenderWindow->AddRenderer(m_Renderer); m_RenderWindow->SetSize(640, 480); m_RenderWindow->SetPosition(200,0); m_RenderWindowInteractor->SetRenderWindow(m_RenderWindow); ///////////// end render stuff ///////////////////////// ////// Create VME (import vtkData) //////////////////// vtkStructuredPointsReader *importer; vtkNEW(importer); mafString filename1=MAF_DATA_ROOT; filename1<<"/Test_PipeVolumeSlice/VolumeSP.vtk"; importer->SetFileName(filename1.GetCStr()); importer->Update(); mafVMEVolumeGray *volumeInput; mafNEW(volumeInput); volumeInput->SetData((vtkImageData*)importer->GetOutput(),0.0); volumeInput->GetOutput()->GetVTKData()->Update(); volumeInput->GetOutput()->Update(); volumeInput->Update(); mmaVolumeMaterial *material; mafNEW(material); mafVMEOutputVolume::SafeDownCast(volumeInput->GetOutput())->SetMaterial(material); //Assembly will be create when instancing mafSceneNode mafSceneNode *sceneNode; sceneNode = new mafSceneNode(NULL,NULL,volumeInput, NULL); double zValue[3][3]={{4.0,4.0,0.0},{4.0,4.0,1.0},{4.0,4.0,2.0}}; for (int direction = SLICE_X ; direction<=SLICE_Z;direction++) { /////////// Pipe Instance and Creation /////////// mafPipeVolumeSlice *pipeSlice = new mafPipeVolumeSlice; pipeSlice->InitializeSliceParameters(direction,zValue[0],true); pipeSlice->Create(sceneNode); ////////// ACTORS List /////////////// vtkPropCollection *actorList = vtkPropCollection::New(); pipeSlice->GetAssemblyFront()->GetActors(actorList); actorList->InitTraversal(); vtkProp *actor = actorList->GetNextProp(); while(actor) { m_Renderer->AddActor(actor); m_RenderWindow->Render(); actor = actorList->GetNextProp(); } double x,y,z,vx,vy,vz; switch(direction) { case SLICE_X: //x=-1 ;y=0; z=0; vx=0; vy=0; vz=1; x=1 ;y=0; z=0; vx=0; vy=0; vz=1; break; case SLICE_Y: x=0; y=-1; z=0; vx=0; vy=0; vz=1; break; case SLICE_Z: //x=0; y=0; z=-1; vx=0; vy=-1; vz=0; x=0; y=0; z=-1; vx=0; vy=-1; vz=0; break; } m_Renderer->GetActiveCamera()->ParallelProjectionOn(); m_Renderer->GetActiveCamera()->SetFocalPoint(0,0,0); m_Renderer->GetActiveCamera()->SetPosition(x*100,y*100,z*100); m_Renderer->GetActiveCamera()->SetViewUp(vx,vy,vz); m_Renderer->GetActiveCamera()->SetClippingRange(0.1,1000); for(int i=0;i<3;i++) { pipeSlice->SetSlice(zValue[i]); m_Renderer->ResetCamera(); char *strings="Slice"; m_RenderWindow->Render(); printf("\n Visualization: %s \n", strings); mafSleep(1000); CompareImages(3*direction+i); } m_Renderer->RemoveAllProps(); vtkDEL(actorList); delete pipeSlice; } delete sceneNode; mafDEL(material); mafDEL(volumeInput); vtkDEL(importer); delete wxLog::SetActiveTarget(NULL); } //---------------------------------------------------------------------------- void mafPipeVolumeSliceTest::CompareImages(int imageIndex) //---------------------------------------------------------------------------- { char *file = __FILE__; std::string name(file); int slashIndex = name.find_last_of('\\'); name = name.substr(slashIndex+1); int pointIndex = name.find_last_of('.'); name = name.substr(0, pointIndex); mafString controlOriginFile=MAF_DATA_ROOT; controlOriginFile<<"/Test_PipeVolumeSlice/"; controlOriginFile<<name.c_str(); controlOriginFile<<"_"; controlOriginFile<<"image"; controlOriginFile<<imageIndex; controlOriginFile<<".jpg"; fstream controlStream; controlStream.open(controlOriginFile.GetCStr()); // visualization control m_RenderWindow->OffScreenRenderingOn(); vtkWindowToImageFilter *w2i; vtkNEW(w2i); w2i->SetInput(m_RenderWindow); //w2i->SetMagnification(magnification); w2i->Update(); m_RenderWindow->OffScreenRenderingOff(); //write comparing image vtkJPEGWriter *w; vtkNEW(w); w->SetInput(w2i->GetOutput()); mafString imageFile=MAF_DATA_ROOT; if(!controlStream) { imageFile<<"/Test_PipeVolumeSlice/"; imageFile<<name.c_str(); imageFile<<"_"; imageFile<<"image"; } else { imageFile<<"/Test_PipeVolumeSlice/"; imageFile<<name.c_str(); imageFile<<"_"; imageFile<<"comp"; } imageFile<<imageIndex; imageFile<<".jpg"; w->SetFileName(imageFile.GetCStr()); w->Write(); if(!controlStream) { vtkDEL(w); vtkDEL(w2i); controlStream.close(); return; } controlStream.close(); //read original Image vtkJPEGReader *rO; vtkNEW(rO); mafString imageFileOrig=MAF_DATA_ROOT; imageFileOrig<<"/Test_PipeVolumeSlice/"; imageFileOrig<<name.c_str(); imageFileOrig<<"_"; imageFileOrig<<"image"; imageFileOrig<<imageIndex; imageFileOrig<<".jpg"; rO->SetFileName(imageFileOrig.GetCStr()); rO->Update(); vtkImageData *imDataOrig = rO->GetOutput(); //read compared image vtkJPEGReader *rC; vtkNEW(rC); rC->SetFileName(imageFile.GetCStr()); rC->Update(); vtkImageData *imDataComp = rC->GetOutput(); vtkImageMathematics *imageMath; vtkNEW(imageMath); imageMath->SetInput1(imDataOrig); imageMath->SetInput2(imDataComp); imageMath->SetOperationToSubtract(); imageMath->Update(); double srR[2] = {-1,1}; imageMath->GetOutput()->GetPointData()->GetScalars()->GetRange(srR); CPPUNIT_ASSERT(srR[0] == 0.0 && srR[1] == 0.0); // end visualization control vtkDEL(imageMath); vtkDEL(rC); vtkDEL(rO); vtkDEL(w); vtkDEL(w2i); }
27.254019
84
0.597452
FusionBox2
4e05c6ff8543a5859c72437968dd4af1e056ef18
253
cpp
C++
server/src/DatabaseProxy/PostgresqlProxy.cpp
yuryloshmanov/messenger
98c2129cf2b5ca7e00cc5c1ba90535acf8be0ba1
[ "MIT" ]
null
null
null
server/src/DatabaseProxy/PostgresqlProxy.cpp
yuryloshmanov/messenger
98c2129cf2b5ca7e00cc5c1ba90535acf8be0ba1
[ "MIT" ]
null
null
null
server/src/DatabaseProxy/PostgresqlProxy.cpp
yuryloshmanov/messenger
98c2129cf2b5ca7e00cc5c1ba90535acf8be0ba1
[ "MIT" ]
null
null
null
/** * @file PostgresqlProxy.cpp * @date 22 Feb 2022 * @author Yury Loshmanov */ #include "../../include/DatabaseProxy/PostgresqlProxy.hpp" PostgresqlProxy::PostgresqlProxy(const std::string &endPoint) : connection(endPoint), work(connection) { }
21.083333
104
0.72332
yuryloshmanov
4e0c4243efa6ca0642bb4260c4daefdd7c40cd75
5,578
cpp
C++
Oem/dbxml/xqilla/src/ast/XQAttributeConstructor.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Oem/dbxml/xqilla/src/ast/XQAttributeConstructor.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Oem/dbxml/xqilla/src/ast/XQAttributeConstructor.cpp
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
/* * Copyright (c) 2001-2008 * DecisionSoft Limited. All rights reserved. * Copyright (c) 2004-2008 * Oracle. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * $Id$ */ #include <xqilla/framework/XQillaExport.hpp> #include <xqilla/ast/XQAttributeConstructor.hpp> #include <xqilla/ast/StaticAnalysis.hpp> #include <xqilla/ast/XQLiteral.hpp> #include <xqilla/context/DynamicContext.hpp> #include <xqilla/context/ItemFactory.hpp> #include <xqilla/exceptions/ASTException.hpp> #include <xqilla/exceptions/NamespaceLookupException.hpp> #include <xqilla/exceptions/StaticErrorException.hpp> #include <xqilla/utils/XPath2Utils.hpp> #include <xqilla/utils/XPath2NSUtils.hpp> #include <xqilla/items/Node.hpp> #include <xqilla/ast/XQAtomize.hpp> #include <xqilla/events/EventHandler.hpp> #include <xqilla/exceptions/StaticErrorException.hpp> #include <xercesc/validators/schema/SchemaSymbols.hpp> #include <xercesc/framework/XMLBuffer.hpp> #include <xercesc/util/XMLChar.hpp> #if defined(XERCES_HAS_CPP_NAMESPACE) XERCES_CPP_NAMESPACE_USE #endif XQAttributeConstructor::XQAttributeConstructor(ASTNode* name, VectorOfASTNodes* children, XPath2MemoryManager* mm) : XQDOMConstructor(mm), namespaceExpr(0), m_name(name), m_children(children) { } EventGenerator::Ptr XQAttributeConstructor::generateEvents(EventHandler *events, DynamicContext *context, bool preserveNS, bool preserveType) const { AnyAtomicType::Ptr itemName = m_name->createResult(context)->next(context); const ATQNameOrDerived* pQName = (const ATQNameOrDerived*)itemName.get(); const XMLCh *prefix = pQName->getPrefix(); const XMLCh *uri = pQName->getURI(); const XMLCh *name = pQName->getName(); if((uri==NULL && XPath2Utils::equals(name, XMLUni::fgXMLNSString)) || XPath2Utils::equals(uri, XMLUni::fgXMLNSURIName)) XQThrow(ASTException,X("DOM Constructor"),X("A computed attribute constructor cannot create a namespace declaration [err:XQDY0044]")); XMLBuffer value; getStringValue(m_children, value, context); const XMLCh *typeURI = SchemaSymbols::fgURI_SCHEMAFORSCHEMA; const XMLCh *typeName = ATUntypedAtomic::fgDT_UNTYPEDATOMIC; // check if it's xml:id static const XMLCh id[] = { 'i', 'd', 0 }; if(XPath2Utils::equals(name, id) && XPath2Utils::equals(uri, XMLUni::fgXMLURIName)) { // If the attribute name is xml:id, the string value and typed value of the attribute are further normalized by // discarding any leading and trailing space (#x20) characters, and by replacing sequences of space (#x20) characters // by a single space (#x20) character. XMLString::collapseWS(value.getRawBuffer(), context->getMemoryManager()); typeURI = SchemaSymbols::fgURI_SCHEMAFORSCHEMA; typeName = XMLUni::fgIDString; } events->attributeEvent(emptyToNull(prefix), emptyToNull(uri), name, value.getRawBuffer(), typeURI, typeName); return 0; } ASTNode* XQAttributeConstructor::staticResolution(StaticContext *context) { XPath2MemoryManager *mm = context->getMemoryManager(); // and run static resolution m_name = new (mm) XQNameExpression(m_name, mm); m_name->setLocationInfo(this); m_name = m_name->staticResolution(context); unsigned int i; for(i = 0;i < m_children->size(); ++i) { // atomize content and run static resolution (*m_children)[i] = new (mm) XQAtomize((*m_children)[i], mm); (*m_children)[i]->setLocationInfo(this); (*m_children)[i] = (*m_children)[i]->staticResolution(context); } return this; } ASTNode *XQAttributeConstructor::staticTypingImpl(StaticContext *context) { _src.clear(); _src.add(m_name->getStaticAnalysis()); if(m_name->getStaticAnalysis().isUpdating()) { XQThrow(StaticErrorException,X("XQAttributeConstructor::staticTyping"), X("It is a static error for the name expression of an attribute constructor " "to be an updating expression [err:XUST0001]")); } unsigned int i; for(i = 0; i < m_children->size(); ++i) { _src.add((*m_children)[i]->getStaticAnalysis()); if((*m_children)[i]->getStaticAnalysis().isUpdating()) { XQThrow(StaticErrorException,X("XQAttributeConstructor::staticTyping"), X("It is a static error for the a value expression of an attribute constructor " "to be an updating expression [err:XUST0001]")); } } _src.getStaticType() = StaticType::ATTRIBUTE_TYPE; _src.creative(true); _src.setProperties(StaticAnalysis::DOCORDER | StaticAnalysis::GROUPED | StaticAnalysis::PEER | StaticAnalysis::SUBTREE | StaticAnalysis::SAMEDOC | StaticAnalysis::ONENODE); return this; } const XMLCh* XQAttributeConstructor::getNodeType() const { return Node::attribute_string; } ASTNode *XQAttributeConstructor::getName() const { return m_name; } const VectorOfASTNodes *XQAttributeConstructor::getChildren() const { return m_children; } void XQAttributeConstructor::setName(ASTNode *name) { m_name = name; }
34.8625
138
0.723378
achilex
4e0d154599f4a3108f64944bf741ed7bf06ac09b
138
cpp
C++
base/stublibs/delay/delayimp.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/stublibs/delay/delayimp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/stublibs/delay/delayimp.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "windows.h" #include "delayimp.h" PUnloadInfo __puiHead; extern "C" void __delayLoadHelper2 ( void ) { }
9.857143
23
0.608696
npocmaka
4e1137c75d74b2effc529da7fe9de37e37846eb5
11,633
cpp
C++
MT2D/SDL/Render/MT2D_SDL_Render.cpp
ibm5155/MT2D
b9f1386cf3fe7d0bd2bba7e4fb40852048d253c1
[ "MIT" ]
3
2017-07-31T04:38:31.000Z
2020-03-21T02:59:36.000Z
MT2D/SDL/Render/MT2D_SDL_Render.cpp
ibm5155/MT2D
b9f1386cf3fe7d0bd2bba7e4fb40852048d253c1
[ "MIT" ]
5
2020-10-13T14:34:47.000Z
2021-08-17T15:02:02.000Z
MT2D/SDL/Render/MT2D_SDL_Render.cpp
ibm5155/MT2D
b9f1386cf3fe7d0bd2bba7e4fb40852048d253c1
[ "MIT" ]
null
null
null
#include <MT2D/MT2D_Terminal_Define.h> #if defined(SDL_USE) #include "../../SDL/MT2D_SDL_Redefine.h" #include "../../SDL/MT2D_SDL_Event_Handler.h" #include "../../MT2D.h" #include <stdio.h> #include <stdlib.h> extern MT2D_SDL_Texture* mTexture; extern MT2D_SDL_Rect gSpriteClips[256]; extern int FRAMEBUFFER[MAX_VER][MAX_HOR]; //used to store what was draw under the screen, (it should avoid overdrawn) extern MT2D_SDL_Texture *CharSprite[256]; extern MT2D_SDL_Texture *CharSpriteRotated[256]; extern SDL_DisplayMode mode; extern MT2D_SDL_Texture *OffscrBuff[2]; extern MT2D_SDL_Texture *ScreenBuffer; extern MT2D_SDL_Events MainEvents; extern MT2D_SDL_Window* gWindow; void SDL_Render_Sprites(); void CheckVideoEvent() { MT2D_SDL_Event_Handler(); if (MainEvents.Window_Started && MainEvents.Window_Resized) { if (MainEvents.Window_Resized = true){ MainEvents.Window_Resized = false; mode.w = MainEvents.Window.data1; mode.h = MainEvents.Window.data2; MT2D_SDL_SetRenderTarget(MainEvents.Render, NULL); SDL_DestroyTexture(ScreenBuffer); // MainEvents.Render = MT2D_SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED); // SDL_RenderClear(MainEvents.Render); ScreenBuffer = SDL_CreateTexture(MainEvents.Render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, mode.w, mode.h); // MT2D_SDL_SetRenderTarget(MainEvents.Render, ScreenBuffer); // SDL_SetRenderDrawColor(MainEvents.Render, 0, 0, 0, 255); // ScreenBuffer_Size.w = mode.w; // ScreenBuffer_Size.h = mode.h; for (int i = 0; i < MAX_HOR; i++) { for (int j = 0; j < MAX_VER; j++) { FRAMEBUFFER[j][i] = -1; } } // MT2D_SDL_SetRenderTarget(gRenderer, ScreenBuffer); // SDL_RenderClear(MainEvents.Render); // SDL_SetRenderDrawColor(MainEvents.Render, 0, 0, 0, 255); // MT2D_SDL_SetRenderTarget(gRenderer, NULL); } } } void CheckASCIIbelowSprites() { int Xstart, Xend, Ystart, Yend; int X; for (int i = 0; i < MainEvents.SpriteBuffer_Count; i++) { Xstart = (MAX_HOR * (MainEvents.SpriteBufferX[i]-1)) / 320; Xend = (MAX_HOR * (MainEvents.SpriteBufferX[i] + MainEvents.SpriteBuffer[i].ScaleX +1)) / 320; Ystart = (MAX_VER * (MainEvents.SpriteBufferY[i]-1)) / 240; Yend = (MAX_VER * (MainEvents.SpriteBufferY[i] + MainEvents.SpriteBuffer[i].ScaleY + 1)) / 240; //now we clear the BUFFER behind the sprites for (; Ystart <= Yend && Ystart < MAX_VER; Ystart++) { for (X = Xstart; X <= Xend && X < MAX_HOR; X++) { FRAMEBUFFER[Ystart][X] = -2; } } } } void Clean_Render() { SDL_RenderClear(MainEvents.Render); /* MT2D_SDL_Rect renderQuad; renderQuad.x = 0; renderQuad.y = 0; renderQuad.w = mode.w; renderQuad.h = mode.h; MT2D_SDL_RenderCopy(MainEvents.Render, mTexture, &gSpriteClips[32], &renderQuad); */ } void Render_New2(unsigned char BUFFER[][MAX_HOR]); void Render_NewOld(unsigned char BUFFER[][MAX_HOR]) { // Render_New2(BUFFER); // return; int posx = 0; int posy = 0; int angle = 0; int NextA = 0; int NextB = 0; MT2D_SDL_Rect renderQuad; MT2D_SDL_Rect Original; void *mPixels; int mPitch; int CHAR_ResizedX = 0; int CHAR_ResizedY = 0; int Heigth; int Width; int OffsetX, OffsetY; char collide = 0; bool inverte = false; CheckVideoEvent(); CheckASCIIbelowSprites(); if (mode.h >= mode.w) { //smartphone angle = 0; inverte = true; Heigth = mode.w; Width = mode.h; CHAR_ResizedX = Heigth / (MAX_VER);//afetando horizontal CHAR_ResizedY = Width / (MAX_HOR);//afetando a vertical } else { //desktop Heigth = mode.h; Width = mode.w; CHAR_ResizedX = Width / (MAX_HOR); CHAR_ResizedY = Heigth / (MAX_VER); } //Clean_Render(); // MT2D_SDL_RenderCopyEx(gRenderer, ScreenBuffer, &ScreenBuffer_Size, &ScreenBuffer_Size, NULL, NULL, SDL_FLIP_NONE); // MT2D_SDL_SetRenderTarget(gRenderer, ScreenBuffer); // SDL_RenderClear(gRenderer); // SDL_SetRenderDrawColor(gRenderer, rand() % 255, rand() % 255, rand()%255, 255); for (posx = 0; posx < MAX_HOR; posx++) { NextA = 0; for (posy = 0; posy < MAX_VER; posy++) { collide = false; if (FRAMEBUFFER[posy][posx] == -2) { collide = true; } if (' ' != BUFFER[posy][posx]/*|| collide == true*/) {//avoids overdraw //if (collide == false) { FRAMEBUFFER[posy][posx] = BUFFER[posy][posx]; //} Original.h = FONT_SIZEX; Original.w = FONT_SIZEY; Original.x = 0; Original.y = 0; if (mode.h >= mode.w){ //90� renderQuad.x = mode.w - NextA - CHAR_ResizedX; renderQuad.y = NextB; renderQuad.w = CHAR_ResizedX; renderQuad.h = CHAR_ResizedY; NextA += CHAR_ResizedX; MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSpriteRotated[BUFFER[posy][posx]], &Original, &renderQuad, angle, NULL, SDL_FLIP_HORIZONTAL); } else { renderQuad.x = NextB; renderQuad.y = NextA; renderQuad.w = CHAR_ResizedX; renderQuad.h = CHAR_ResizedY; NextA += CHAR_ResizedY; MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSprite[BUFFER[posy][posx]], &Original, &renderQuad, angle, NULL, SDL_FLIP_NONE); } } else { NextA += (mode.h >= mode.w ? CHAR_ResizedX : CHAR_ResizedY); } } if (mode.h >= mode.w) { NextB += CHAR_ResizedY; } else { NextB += CHAR_ResizedX; } } // MT2D_SDL_SetRenderTarget(gRenderer, NULL); // MT2D_SDL_RenderCopy(gRenderer, ScreenBuffer, &ScreenBuffer_Size, &ScreenBuffer_Size); SDL_Render_Sprites(); } void Render_New(unsigned char BUFFER[][MAX_HOR]) { int posx = 0; int posy = 0; int angle = 0; int NextA = 0; int NextB = 0; MT2D_SDL_Rect renderQuad; MT2D_SDL_Rect Original; void *mPixels; int mPitch; int CHAR_ResizedX = 0; int CHAR_ResizedY = 0; int Heigth; int Width; int OffsetX, OffsetY; bool inverte = false; CheckVideoEvent(); if (mode.h >= mode.w) { //smartphone angle = 0; inverte = true; Heigth = mode.w; Width = mode.h; MT2D_SDL_SetRenderTarget(MainEvents.Render, OffscrBuff[1]); } else { //desktop Heigth = mode.h; Width = mode.w; MT2D_SDL_SetRenderTarget(MainEvents.Render, OffscrBuff[0]); } Original.h = FONT_SIZEY; Original.w = FONT_SIZEX; Original.x = 0; Original.y = 0; for (posx = 0; posx < MAX_HOR; posx++) { NextA = 0; for (posy = 0; posy < MAX_VER; posy++) { if (FRAMEBUFFER[posy][posx] != BUFFER[posy][posx]) {//avoids overdraw FRAMEBUFFER[posy][posx] = BUFFER[posy][posx]; if (mode.h >= mode.w) { //90� renderQuad.x = mode.w - NextA - FONT_SIZEX; renderQuad.y = NextB; renderQuad.w = FONT_SIZEX; renderQuad.h = FONT_SIZEY; NextA += CHAR_ResizedX; MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSpriteRotated[BUFFER[posy][posx]], &Original, &renderQuad, angle, NULL, SDL_FLIP_HORIZONTAL); /**/ renderQuad.y = posx * FONT_SIZEX; renderQuad.x = ((MAX_VER-1) * FONT_SIZEY) - posy * FONT_SIZEY; renderQuad.w = FONT_SIZEX; renderQuad.h = FONT_SIZEY; NextA += CHAR_ResizedX; MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSpriteRotated[BUFFER[posy][posx]], &Original, &renderQuad, angle, NULL, SDL_FLIP_HORIZONTAL); } else { renderQuad.x = posx * FONT_SIZEX; renderQuad.y = posy * FONT_SIZEY; renderQuad.w = FONT_SIZEX; renderQuad.h = FONT_SIZEY; NextA += CHAR_ResizedY; MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSprite[BUFFER[posy][posx]], &Original, &renderQuad, angle, NULL, SDL_FLIP_NONE); } } } } MT2D_SDL_SetRenderTarget(MainEvents.Render, NULL); if (!inverte) { Original.h = FONT_SIZEY*MAX_VER; Original.w = FONT_SIZEX*MAX_HOR; Original.x = 0; Original.y = 0; renderQuad.x = 0; renderQuad.y = 0; renderQuad.w = mode.w; renderQuad.h = mode.h; MT2D_SDL_RenderCopy(MainEvents.Render, OffscrBuff[0], &Original, &renderQuad); } else { Original.w = FONT_SIZEY*MAX_VER; Original.h = FONT_SIZEX*MAX_HOR; Original.x = 0; Original.y = 0; renderQuad.x = 0; renderQuad.y = 0; renderQuad.w = mode.w; renderQuad.h = mode.h; MT2D_SDL_RenderCopy(MainEvents.Render, OffscrBuff[1], &Original, &renderQuad); } SDL_Render_Sprites(); } void SDL_Render() { MT2D_SDL_RenderPresent(MainEvents.Render); } void SDL_Add_ImagetoBuffer(Sprite *IMG,int X, int Y) { if (MainEvents.SpriteBuffer_Count == 0) { MainEvents.SpriteBuffer = (Sprite*)malloc(sizeof(Sprite)); MainEvents.SpriteBufferX = (int*)malloc(sizeof(int)); MainEvents.SpriteBufferY = (int*)malloc(sizeof(int)); MainEvents.SpriteBuffer[MainEvents.SpriteBuffer_Count] = *IMG; MainEvents.SpriteBufferX[MainEvents.SpriteBuffer_Count] = X; MainEvents.SpriteBufferY[MainEvents.SpriteBuffer_Count] = Y; } else { MainEvents.SpriteBuffer = (Sprite*)realloc(MainEvents.SpriteBuffer,(MainEvents.SpriteBuffer_Count+1)*sizeof(Sprite)); MainEvents.SpriteBufferY = (int*)realloc(MainEvents.SpriteBufferY, (MainEvents.SpriteBuffer_Count + 1) * sizeof(int)); MainEvents.SpriteBufferX = (int*)realloc(MainEvents.SpriteBufferX, (MainEvents.SpriteBuffer_Count + 1) * sizeof(int)); MainEvents.SpriteBuffer[MainEvents.SpriteBuffer_Count] = *IMG; MainEvents.SpriteBuffer[MainEvents.SpriteBuffer_Count] = *IMG; MainEvents.SpriteBufferX[MainEvents.SpriteBuffer_Count] = X; MainEvents.SpriteBufferY[MainEvents.SpriteBuffer_Count] = Y; } MainEvents.SpriteBuffer_Count++; } void SDL_Render_Sprites() { MT2D_SDL_Rect renderQuad; MT2D_SDL_Rect Original; SDL_Point Center; void *mPixels; int i = 0; int angle = 0; while (i < MainEvents.SpriteBuffer_Count) { if (mode.h >= mode.w) { Original.h = MainEvents.SpriteBuffer[i].SizeX; Original.w = MainEvents.SpriteBuffer[i].SizeY; Original.x = 0; Original.y = 0; //90� renderQuad.x = (( 320*(240 - MainEvents.SpriteBuffer[i].ScaleY - MainEvents.SpriteBufferY[i])/240 ) * mode.w) / 320; renderQuad.y = ( (240*MainEvents.SpriteBufferX[i])/ 320 * mode.h) / 240; // renderQuad.y = MainEvents.SpriteBuffer[i].ScaleX /2 +((MainEvents.SpriteBufferX[i] + 0) * mode.h) / 240; renderQuad.h = (MainEvents.SpriteBuffer[i].ScaleX * mode.h ) / 320; renderQuad.w = (MainEvents.SpriteBuffer[i].ScaleY * mode.w ) / 240; MT2D_SDL_RenderCopyEx(MainEvents.Render, (MT2D_SDL_Texture*)MainEvents.SpriteBuffer[i].RotatedTexture, &Original, &renderQuad,0,0, SDL_FLIP_HORIZONTAL); } else { Original.h = MainEvents.SpriteBuffer[i].SizeY; Original.w = MainEvents.SpriteBuffer[i].SizeX; Original.x = 0; Original.y = 0; renderQuad.x = (MainEvents.SpriteBufferX[i] * mode.w) / 320; renderQuad.y = (MainEvents.SpriteBufferY[i] * mode.h) / 240; renderQuad.w = (MainEvents.SpriteBuffer[i].ScaleX * mode.w ) / 320; renderQuad.h = (MainEvents.SpriteBuffer[i].ScaleY * mode.h) / 240; MT2D_SDL_RenderCopyEx(MainEvents.Render, (MT2D_SDL_Texture*)MainEvents.SpriteBuffer[i].Data, &Original, &renderQuad, 0, NULL, SDL_FLIP_NONE); } i++; } } /** Clear the sprite buffer and also the backup from the ASCII window so we can redraw everything again. **/ void SDL_Clear_RenderBuffers() { if (MainEvents.SpriteBuffer) { free(MainEvents.SpriteBuffer); MainEvents.SpriteBuffer = 0; MainEvents.SpriteBuffer_Count = 0; free(MainEvents.SpriteBufferX); free(MainEvents.SpriteBufferY); MainEvents.SpriteBufferY = 0; MainEvents.SpriteBufferX = 0; } } void MT2D_SDL_Clear_Main_Window() { int i = 0, j = 0; while (i <= MAX_VER) { while (j<MAX_HOR) { WINDOW1[i][j] = ' '; j++; } i++; j = 0; } WINDOW1[MAX_VER][MAX_HOR] = '\0'; SDL_Clear_RenderBuffers(); } void MT2D_SDL_Draw_Window(int which) { int i = 0; int j = 0; if (which == DISPLAY_WINDOW1) { Render_New(WINDOW1); } else { Render_New(WINDOW2); } SDL_Render(); } #endif
30.137306
155
0.693028
ibm5155
4e12d366112ece89a1a1b32ad66dde54bed8d0a7
6,673
cc
C++
src/modular/tests/module_context_test.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
210
2019-02-05T12:45:09.000Z
2022-03-28T07:59:06.000Z
src/modular/tests/module_context_test.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/modular/tests/module_context_test.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
73
2019-03-06T18:55:23.000Z
2022-03-26T12:04:51.000Z
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <fuchsia/modular/testing/cpp/fidl.h> #include <gmock/gmock.h> #include "lib/syslog/cpp/macros.h" #include "src/lib/fsl/vmo/strings.h" #include "src/modular/lib/modular_test_harness/cpp/fake_module.h" #include "src/modular/lib/modular_test_harness/cpp/fake_session_shell.h" #include "src/modular/lib/modular_test_harness/cpp/test_harness_fixture.h" using testing::ElementsAre; namespace { class ModuleContextTest : public modular_testing::TestHarnessFixture { protected: ModuleContextTest() : session_shell_(modular_testing::FakeSessionShell::CreateWithDefaultOptions()) {} void StartSession(modular_testing::TestHarnessBuilder builder) { builder.InterceptSessionShell(session_shell_->BuildInterceptOptions()); builder.BuildAndRun(test_harness()); // Wait for our session shell to start. RunLoopUntil([this] { return session_shell_->is_running(); }); } void RestartStory(std::string story_name) { fuchsia::modular::StoryControllerPtr story_controller; session_shell_->story_provider()->GetController(story_name, story_controller.NewRequest()); bool restarted = false; story_controller->Stop([&] { story_controller->RequestStart(); restarted = true; }); RunLoopUntil([&] { return restarted; }); } std::unique_ptr<modular_testing::FakeSessionShell> session_shell_; }; // A version of FakeModule which captures handled intents in a std::vector<> // and exposes callbacks triggered on certain lifecycle events. class TestModule : public modular_testing::FakeModule { public: explicit TestModule(std::string module_name = "") : modular_testing::FakeModule( {.url = modular_testing::TestHarnessBuilder::GenerateFakeUrl(module_name), .sandbox_services = modular_testing::FakeModule::GetDefaultSandboxServices()}) {} fit::function<void()> on_destroy; fit::function<void()> on_create; private: // |modular_testing::FakeModule| void OnCreate(fuchsia::sys::StartupInfo startup_info) override { modular_testing::FakeModule::OnCreate(std::move(startup_info)); if (on_create) on_create(); } // |modular_testing::FakeModule| void OnDestroy() override { if (on_destroy) on_destroy(); } }; class TestStoryWatcher : fuchsia::modular::StoryWatcher { public: TestStoryWatcher(fit::function<void(fuchsia::modular::StoryState)> on_state_change) : binding_(this), on_state_change_(std::move(on_state_change)) {} ~TestStoryWatcher() override = default; // Registers itself as a watcher on the given story. Only one story at a time // can be watched. void Watch(fuchsia::modular::StoryController* const story_controller) { story_controller->Watch(binding_.NewBinding()); } private: // |fuchsia::modular::StoryWatcher| void OnStateChange(fuchsia::modular::StoryState state) override { on_state_change_(state); } void OnModuleAdded(fuchsia::modular::ModuleData /*module_data*/) override {} void OnModuleFocused(std::vector<std::string> /*module_path*/) override {} fidl::Binding<fuchsia::modular::StoryWatcher> binding_; fit::function<void(fuchsia::modular::StoryState)> on_state_change_; }; // Test that ModuleContext.RemoveSelfFromStory() on the only mod in a story has // the affect of shutting down the module and removing it permanently from the // story (if the story is restarted, it is not relaunched). TEST_F(ModuleContextTest, RemoveSelfFromStory) { TestModule module1("module1"); modular_testing::TestHarnessBuilder builder; builder.InterceptComponent(module1.BuildInterceptOptions()); StartSession(std::move(builder)); modular_testing::AddModToStory(test_harness(), "storyname", "modname1", {.action = "action", .handler = module1.url()}); RunLoopUntil([&] { return module1.is_running(); }); // Instruct module1 to remove itself from the story. Expect to see that // module1 is terminated. module1.module_context()->RemoveSelfFromStory(); RunLoopUntil([&] { return !module1.is_running(); }); // Additionally, restarting the story should not result in module1 being // restarted. fuchsia::modular::StoryControllerPtr story_controller; session_shell_->story_provider()->GetController("storyname", story_controller.NewRequest()); bool story_stopped = false; bool story_restarted = false; TestStoryWatcher story_watcher([&](fuchsia::modular::StoryState state) { if (state == fuchsia::modular::StoryState::STOPPED) { story_stopped = true; } else if (state == fuchsia::modular::StoryState::RUNNING) { story_restarted = true; } }); story_watcher.Watch(story_controller.get()); RestartStory("storyname"); RunLoopUntil([&] { return story_stopped && story_restarted; }); EXPECT_FALSE(module1.is_running()); } // Test that when ModuleContext.RemoveSelfFromStory() is called on one of two // modules in a story, it has the affect of shutting down the module and // removing it permanently from the story (if the story is restarted, it is not // relaunched). TEST_F(ModuleContextTest, RemoveSelfFromStory_2mods) { modular_testing::TestHarnessBuilder builder; TestModule module1("module1"); TestModule module2("module2"); builder.InterceptComponent(module1.BuildInterceptOptions()); builder.InterceptComponent(module2.BuildInterceptOptions()); StartSession(std::move(builder)); modular_testing::AddModToStory(test_harness(), "storyname", "modname1", {.action = "action", .handler = module1.url()}); modular_testing::AddModToStory(test_harness(), "storyname", "modname2", {.action = "action", .handler = module2.url()}); RunLoopUntil([&] { return module1.is_running() && module2.is_running(); }); // Instruct module1 to remove itself from the story. Expect to see that // module1 is terminated and module2 is not. module1.module_context()->RemoveSelfFromStory(); RunLoopUntil([&] { return !module1.is_running(); }); ASSERT_TRUE(module2.is_running()); // Additionally, restarting the story should not result in module1 being // restarted whereas it should for module2. bool module2_destroyed = false; bool module2_restarted = false; module2.on_destroy = [&] { module2_destroyed = true; }; module2.on_create = [&] { module2_restarted = true; }; RestartStory("storyname"); RunLoopUntil([&] { return module2_restarted; }); EXPECT_FALSE(module1.is_running()); EXPECT_TRUE(module2_destroyed); } } // namespace
39.023392
95
0.728008
allansrc
4e1306360ebcb70ea72f14a0dd65f5090fec2721
961
hpp
C++
include/codegen/include/System/IServiceProvider.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/IServiceProvider.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/IServiceProvider.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Completed forward declares // Begin il2cpp-utils forward declares struct Il2CppObject; // Completed il2cpp-utils forward declares // Type namespace: System namespace System { // Autogenerated type: System.IServiceProvider class IServiceProvider { public: // public System.Object GetService(System.Type serviceType) // Offset: 0xFFFFFFFF ::Il2CppObject* GetService(System::Type* serviceType); }; // System.IServiceProvider } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::IServiceProvider*, "System", "IServiceProvider"); #pragma pack(pop)
31
80
0.700312
Futuremappermydud
4e13dd68b9e7fa96e93e3acd2797d589a6269baf
2,019
cc
C++
core/src/psfcore/unused/psftest.cc
ma-laforge/LibPSFC.jl
73a5176ca78cade63cc9c5da4d15b36f9042645c
[ "MIT" ]
null
null
null
core/src/psfcore/unused/psftest.cc
ma-laforge/LibPSFC.jl
73a5176ca78cade63cc9c5da4d15b36f9042645c
[ "MIT" ]
null
null
null
core/src/psfcore/unused/psftest.cc
ma-laforge/LibPSFC.jl
73a5176ca78cade63cc9c5da4d15b36f9042645c
[ "MIT" ]
null
null
null
#include "psf.h" #include "psfdata.h" #include <string> void noisesummary() { std::string pnoisefile("/nfs/home/henrik/spectre/1/pnoise.raw/pnoise_pout3g.pnoise"); PSFDataSet psfnoise(pnoisefile); std::vector<std::string> names = psfnoise.get_signal_names(); double sum=0; for(std::vector<std::string>::iterator i=names.begin(); i != names.end(); i++) { if(*i != std::string("out")) { StructVector *valvec = dynamic_cast<StructVector *>(psfnoise.get_signal_vector(*i)); Struct& data = (*valvec)[3]; if(data.find(std::string("total")) != data.end()) sum += (double)*data[std::string("total")]; delete(valvec); } } std::cout << "Total: " << sum << std::endl; } int main() { std::string dcopfile("../examples/data/opBegin"); std::string pssfdfile("../examples/data/pss0.fd.pss"); std::string tranfile("../examples/data/timeSweep"); std::string srcsweepfile("../examples/data/srcSweep"); // PSFDataSet psftran(tranfile); // PSFDataSet pssfd(pssfdfile); // PSFDataSet pssop(dcopfile); PSFDataSet srcsweep(srcsweepfile); noisesummary(); //pssop.get_signal_properties("XIRXRFMIXTRIM0.XRDAC4.XR.R1"); std::cout << "Header properties:" << std::endl; PropertyMap headerprops(srcsweep.get_header_properties()); for(PropertyMap::iterator i=headerprops.begin(); i!=headerprops.end(); i++) std::cout << i->first << ":" << *i->second << std::endl; // { // Float64Vector *parvec = (Float64Vector *)psfnoise.get_param_values(); // } // Float64Vector *parvec = (Float64Vector *)psftran.get_param_values(); // for(Float64Vector::iterator i=parvec->begin(); i!=parvec->end(); i++) // std::cout << *i << " "; // std::cout << std::endl; // std::cout << "len=" << parvec->size() << std::endl; //PSFDataVector *valvec = psf.get_signal_vector("tx_lopath_hb_stop.tx_lopath_hb_top.tx_lopath_hb_driver.driver_hb_channel_q.Ismall.Idriver_n.nout_off.imod"); }
32.047619
161
0.634968
ma-laforge
4e15065ca2ce0f75964a8116c46a77e630f247fe
5,766
cpp
C++
src/qt/i2poptionswidget.cpp
eddef/anoncoin
7a018e15c814bba30e805cfe83f187388eadc0a8
[ "MIT" ]
90
2015-01-13T14:32:43.000Z
2020-10-15T23:07:11.000Z
src/qt/i2poptionswidget.cpp
nonlinear-chaos-order-etc-etal/anoncoin
5e441d8746240072f1379577e14ff7a17390b81f
[ "MIT" ]
91
2015-01-07T03:44:14.000Z
2020-12-24T13:56:27.000Z
src/qt/i2poptionswidget.cpp
nonlinear-chaos-order-etc-etal/anoncoin
5e441d8746240072f1379577e14ff7a17390b81f
[ "MIT" ]
42
2015-01-28T12:34:14.000Z
2021-05-06T16:16:48.000Z
// Copyright (c) 2013-2014 The Anoncoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Many builder specific things set in the config file, don't see a need for it here, still better to not forget to include it in your source files. #if defined(HAVE_CONFIG_H) #include "config/anoncoin-config.h" #endif #include "i2poptionswidget.h" #include "ui_i2poptionswidget.h" #include "optionsmodel.h" #include "monitoreddatamapper.h" #include "i2pshowaddresses.h" #include "util.h" #include "clientmodel.h" I2POptionsWidget::I2POptionsWidget(QWidget *parent) : QWidget(parent), ui(new Ui::I2POptionsWidget), clientModel(0) { ui->setupUi(this); QObject::connect(ui->pushButtonCurrentI2PAddress, SIGNAL(clicked()), this, SLOT(ShowCurrentI2PAddress())); QObject::connect(ui->pushButtonGenerateI2PAddress, SIGNAL(clicked()), this, SLOT(GenerateNewI2PAddress())); QObject::connect(ui->checkBoxAllowZeroHop , SIGNAL(stateChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->checkBoxInboundAllowZeroHop , SIGNAL(stateChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->checkBoxUseI2POnly , SIGNAL(stateChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->lineEditSAMHost , SIGNAL(textChanged(QString)), this, SIGNAL(settingsChanged())); QObject::connect(ui->lineEditTunnelName , SIGNAL(textChanged(QString)), this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxInboundBackupQuality , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxInboundIPRestriction , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxInboundLength , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxInboundLengthVariance , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxInboundQuantity , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxOutboundBackupQuantity, SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxOutboundIPRestriction , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxOutboundLength , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxOutboundLengthVariance, SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxOutboundPriority , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxOutboundQuantity , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); QObject::connect(ui->spinBoxSAMPort , SIGNAL(valueChanged(int)) , this, SIGNAL(settingsChanged())); } I2POptionsWidget::~I2POptionsWidget() { delete ui; } void I2POptionsWidget::setMapper(MonitoredDataMapper& mapper) { mapper.addMapping(ui->checkBoxUseI2POnly , OptionsModel::eI2PUseI2POnly); mapper.addMapping(ui->lineEditSAMHost , OptionsModel::eI2PSAMHost); mapper.addMapping(ui->spinBoxSAMPort , OptionsModel::eI2PSAMPort); mapper.addMapping(ui->lineEditTunnelName , OptionsModel::eI2PSessionName); mapper.addMapping(ui->spinBoxInboundQuantity , OptionsModel::I2PInboundQuantity); mapper.addMapping(ui->spinBoxInboundLength , OptionsModel::I2PInboundLength); mapper.addMapping(ui->spinBoxInboundLengthVariance , OptionsModel::I2PInboundLengthVariance); mapper.addMapping(ui->spinBoxInboundBackupQuality , OptionsModel::I2PInboundBackupQuantity); mapper.addMapping(ui->checkBoxInboundAllowZeroHop , OptionsModel::I2PInboundAllowZeroHop); mapper.addMapping(ui->spinBoxInboundIPRestriction , OptionsModel::I2PInboundIPRestriction); mapper.addMapping(ui->spinBoxOutboundQuantity , OptionsModel::I2POutboundQuantity); mapper.addMapping(ui->spinBoxOutboundLength , OptionsModel::I2POutboundLength); mapper.addMapping(ui->spinBoxOutboundLengthVariance, OptionsModel::I2POutboundLengthVariance); mapper.addMapping(ui->spinBoxOutboundBackupQuantity, OptionsModel::I2POutboundBackupQuantity); mapper.addMapping(ui->checkBoxAllowZeroHop , OptionsModel::I2POutboundAllowZeroHop); mapper.addMapping(ui->spinBoxOutboundIPRestriction , OptionsModel::I2POutboundIPRestriction); mapper.addMapping(ui->spinBoxOutboundPriority , OptionsModel::I2POutboundPriority); } void I2POptionsWidget::setModel(ClientModel* model) { clientModel = model; } void I2POptionsWidget::ShowCurrentI2PAddress() { if (clientModel) { const QString pub = clientModel->getPublicI2PKey(); const QString priv = clientModel->getPrivateI2PKey(); const QString b32 = clientModel->getB32Address(pub); const QString configFile = QString::fromStdString(GetConfigFile().string()); ShowI2PAddresses i2pCurrDialog("Your current I2P-address", pub, priv, b32, configFile, this); i2pCurrDialog.exec(); } } void I2POptionsWidget::GenerateNewI2PAddress() { if (clientModel) { QString pub, priv; clientModel->generateI2PDestination(pub, priv); const QString b32 = clientModel->getB32Address(pub); const QString configFile = QString::fromStdString(GetConfigFile().string()); ShowI2PAddresses i2pCurrDialog("Generated I2P address", pub, priv, b32, configFile, this); i2pCurrDialog.exec(); } }
52.899083
148
0.73153
eddef
4e17b9dc4559616a2786013d641833dbddf34747
2,588
cpp
C++
manager/spline/spline_manager.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
1
2017-08-11T19:12:24.000Z
2017-08-11T19:12:24.000Z
manager/spline/spline_manager.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
11
2018-07-07T20:09:44.000Z
2020-02-16T22:45:09.000Z
manager/spline/spline_manager.cpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
null
null
null
//------------------------------------------------------------ // snakeoil (c) Alexis Constantin Link // Distributed under the MIT license //------------------------------------------------------------ #include "spline_manager.h" using namespace so_manager ; //********************************************************************************************** spline_manager::spline_manager( void_t ) { } //********************************************************************************************** spline_manager::spline_manager( this_rref_t rhv ) { _linears_res_mgr = std::move( rhv._linears_res_mgr ) ; _counter = rhv._counter ; } //********************************************************************************************** spline_manager::~spline_manager( void_t ) { } //********************************************************************************************** spline_manager::this_ptr_t spline_manager::create( this_rref_t rhv, so_memory::purpose_cref_t p ) { return so_manager::memory::alloc( std::move(rhv), p ) ; } //********************************************************************************************** void_t spline_manager::destroy( this_ptr_t ptr ) { so_manager::memory::dealloc( ptr ) ; } //********************************************************************************************** bool_t spline_manager::acquire( so_manager::key_cref_t key_in, so_resource::purpose_cref_t p, linears_handle_out_t hnd_out ) { return _linears_res_mgr.acquire( key_in, p, hnd_out ) ; } //********************************************************************************************** bool_t spline_manager::release( linears_handle_rref_t hnd ) { return _linears_res_mgr.release( std::move(hnd) ) ; } //********************************************************************************************** so_manager::result spline_manager::insert( so_manager::key_cref_t key_in, linears_manage_params_cref_t mp ) { linear_spline_store_item si ; // fill si auto si_ptr = so_manager::memory::alloc( std::move(si), "[so_manager::spline_manager::insert] : linear spline store item for " + key_in ) ; auto const res = _linears_res_mgr.insert( key_in, si_ptr ) ; if( so_log::log::error( so_resource::no_success( res ), "[so_manager::spline_manager::insert] : insert" ) ) { so_manager::memory::dealloc( si_ptr ) ; return so_manager::key_already_in_use; } return so_manager::ok ; } //**********************************************************************************************
35.452055
97
0.435471
aconstlink
4e1d50433f0a8654ffa2386314841105761d6aa4
10,804
cc
C++
unit_tests/tests/base/ThreadGroup/ThreadGroup_test.cc
Wlgen/force-riscv
9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8
[ "Apache-2.0" ]
111
2020-06-12T22:31:30.000Z
2022-03-19T03:45:20.000Z
unit_tests/tests/base/ThreadGroup/ThreadGroup_test.cc
Wlgen/force-riscv
9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8
[ "Apache-2.0" ]
34
2020-06-12T20:23:40.000Z
2022-03-15T20:04:31.000Z
unit_tests/tests/base/ThreadGroup/ThreadGroup_test.cc
Wlgen/force-riscv
9f09b86c5a21ca00f8e5ade8e5186d65bc3e26f8
[ "Apache-2.0" ]
32
2020-06-12T19:15:26.000Z
2022-02-20T11:38:31.000Z
// // Copyright (C) [2020] Futurewei Technologies, Inc. // // FORCE-RISCV is 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 // // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR // FIT FOR A PARTICULAR PURPOSE. // See the License for the specific language governing permissions and // limitations under the License. // #include <lest/lest.hpp> #include <Log.h> #include <Random.h> //------------------------------------------------ // include necessary header files here //------------------------------------------------ #include <Enums.h> #include <ThreadGroup.h> #include <Constraint.h> #include <ThreadGroupPartitioner.h> #include <vector> using text = std::string; const lest::test specification[] = { CASE( "Test Thread Group Moderator APIs" ) { SETUP( "Set up class" ) { using namespace Force; ThreadGroupModerator tg_mod(2,2,4); // 2 chip, 2 core and 4 thread SECTION ("Test default behavior") { EXPECT(tg_mod.GetThreadGroupId(0) == -1u); std::vector<uint32> free_threads; tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 16u); for (uint32 i = 0u; i < 16u; i++) EXPECT(free_threads[i] == i); std::vector<ThreadGroup* > thread_groups; tg_mod.QueryThreadGroup(-1u, thread_groups); EXPECT(thread_groups.size() == 0u); } SECTION ("Test partition: same chip") { tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::SameChip); std::vector<ThreadGroup* > thread_groups; tg_mod.QueryThreadGroup(-1, thread_groups); EXPECT(thread_groups.size() == 2u); EXPECT(thread_groups[0]->GetThreads()->ToSimpleString() == "0x0-0x7"); EXPECT(thread_groups[1]->GetThreads()->ToSimpleString() == "0x8-0xf"); std::vector<uint32> free_threads; tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 0u); EXPECT(tg_mod.GetThreadGroupId(7u) == 0u); // thread id 7 belongs to group 0 EXPECT(tg_mod.GetThreadGroupId(8u) == 1u); // thread id 8 belongs to group 1 } SECTION ("Test partition: same core") { tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::SameCore); std::vector<ThreadGroup* > thread_groups; tg_mod.QueryThreadGroup(-1, thread_groups); EXPECT(thread_groups.size() == 4u); EXPECT(thread_groups[0]->GetThreads()->ToSimpleString() == "0x0-0x3"); EXPECT(thread_groups[1]->GetThreads()->ToSimpleString() == "0x4-0x7"); EXPECT(thread_groups[2]->GetThreads()->ToSimpleString() == "0x8-0xb"); EXPECT(thread_groups[3]->GetThreads()->ToSimpleString() == "0xc-0xf"); std::vector<uint32> free_threads; tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 0u); EXPECT(tg_mod.GetThreadGroupId(3u) == 0u); // thread id 0 belongs to group 0 EXPECT(tg_mod.GetThreadGroupId(7u) == 1u); // thread id 7 belongs to group 1 EXPECT(tg_mod.GetThreadGroupId(8u) == 2u); // thread id 8 belongs to group 2 EXPECT(tg_mod.GetThreadGroupId(15u) == 3u); // thread id 15 belongs to group 3 } SECTION ("Test partition: diff chip") { tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::DiffChip); std::vector<ThreadGroup* > thread_groups; tg_mod.QueryThreadGroup(-1, thread_groups); EXPECT(thread_groups.size() == 8u); for (unsigned i = 0; i < 8u ; i++) { auto thread_constr = thread_groups[i]->GetThreads(); LOG(notice) << "Diff chip thread constraint:" << thread_constr->ToSimpleString() << ", group id: " << thread_groups[i]->GetId() << std::endl; EXPECT(thread_constr->Size() == 2u); std::vector<uint64> threads; thread_constr->GetValues(threads); if (threads[0] < 8u) { EXPECT(threads[1] >=8u); EXPECT(threads[1] <= 15u); } else EXPECT(threads[1] < 8u); } std::vector<uint32> free_threads; tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 0u); } SECTION ("Test partition: diff core") { tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::DiffCore); std::vector<ThreadGroup* > thread_groups; tg_mod.QueryThreadGroup(-1, thread_groups); EXPECT(thread_groups.size() == 4u); for (unsigned i = 0; i < 4u ; i++) { auto thread_constr = thread_groups[i]->GetThreads(); LOG(notice) << "Diff core thread constraint:" << thread_constr->ToSimpleString() << ", group id: " << thread_groups[i]->GetId() << std::endl; EXPECT(thread_constr->Size() == 4u); std::vector<uint64> threads; thread_constr->GetValues(threads); EXPECT(threads[0] < 4u); EXPECT(threads[1] >=4u); EXPECT(threads[1] < 8u); EXPECT(threads[2] >= 8u); EXPECT(threads[2] < 12u); EXPECT(threads[3] >= 12u); EXPECT(threads[3] < 16u); } std::vector<uint32> free_threads; tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 0u); } SECTION("Test partition: random all") { PartitionArgument arg(1); // one group tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::Random, &arg); std::vector<ThreadGroup* > thread_groups; tg_mod.QueryThreadGroup(-1, thread_groups); EXPECT(thread_groups.size() == 1u); auto thread_constr = thread_groups[0]->GetThreads(); EXPECT(thread_constr->ToSimpleString() == "0x0-0xf"); std::vector<uint32> free_threads; tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 0u); } SECTION("Test partition: random gradual") { PartitionArgument arg0(2, 2); // 2 groups, 2 threads in a group tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::Random, &arg0); std::vector<uint32> free_threads; tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 12u); PartitionArgument arg1(4, 1); // 4 groups, 1 thread in a group tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::Random, &arg1); free_threads.clear(); tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 8u); PartitionArgument arg2(2); // 2 groups tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::Random, &arg2); free_threads.clear(); tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 0u); std::vector<ThreadGroup* > thread_groups; tg_mod.QueryThreadGroup(-1, thread_groups); EXPECT(thread_groups.size() == 8u); EXPECT(thread_groups[0]->GetThreads()->Size() == 2u); EXPECT(thread_groups[2]->GetThreads()->Size() == 1u); EXPECT(thread_groups[6]->GetThreads()->Size() == 4u); for (auto thread_group : thread_groups) { LOG(notice) << "Random gradual group id:" << std::dec << thread_group->GetId() << ", job: " << thread_group->GetJob() << ", threads: " << thread_group->GetThreads()->ToSimpleString() << std::endl; } } SECTION("Test Set thread group") { PartitionArgument arg0(1, 2); // 1 groups with 2 threads tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::Random, &arg0); std::vector<ThreadGroup*> thread_groups; tg_mod.QueryThreadGroup(-1, thread_groups); EXPECT(thread_groups.size() == 1u); auto g_id = thread_groups[0]->GetId(); tg_mod.SetThreadGroup(g_id, "Set0", ConstraintSet("2-5")); EXPECT(thread_groups[0]->GetThreads()->ToSimpleString() == "0x2-0x5"); std::vector<uint32> free_threads; tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 12u); EXPECT(tg_mod.GetThreadGroupId(0x2) == g_id); tg_mod.SetThreadGroup(g_id, "Set1", ConstraintSet("8-10")); EXPECT(thread_groups[0]->GetThreads()->ToSimpleString() == "0x8-0xa"); free_threads.clear(); tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 13u); EXPECT(tg_mod.GetThreadGroupId(0x8) == g_id); EXPECT(tg_mod.GetThreadGroupId(0xa) == g_id); EXPECT(tg_mod.GetThreadGroupId(0x2) == -1u); EXPECT(tg_mod.GetThreadGroupId(0x5) == -1u); } SECTION("Test set thread group with multiple groups") { tg_mod.PartitionThreadGroup(EPartitionThreadPolicy::SameChip); std::vector<ThreadGroup*> thread_groups; tg_mod.QueryThreadGroup(-1, thread_groups); ThreadGroup* thread_group_0 = thread_groups[0]; tg_mod.SetThreadGroup(thread_group_0->GetId(), "Set0_0", ConstraintSet("1,3,5")); const ConstraintSet* group_0_thread_constr = thread_group_0->GetThreads(); EXPECT(group_0_thread_constr->ToSimpleString() == "0x1,0x3,0x5"); std::vector<uint64> group_0_threads; group_0_thread_constr->GetValues(group_0_threads); for (uint64 thread : group_0_threads) { EXPECT(tg_mod.GetThreadGroupId(thread) == thread_group_0->GetId()); } ThreadGroup* thread_group_1 = thread_groups[1]; tg_mod.SetThreadGroup(thread_group_1->GetId(), "Set1", ConstraintSet("2,4,6-10")); const ConstraintSet* group_1_thread_constr = thread_group_1->GetThreads(); EXPECT(group_1_thread_constr->ToSimpleString() == "0x2,0x4,0x6-0xa"); std::vector<uint64> group_1_threads; group_1_thread_constr->GetValues(group_1_threads); for (uint64 thread : group_1_threads) { EXPECT(tg_mod.GetThreadGroupId(thread) == thread_group_1->GetId()); } tg_mod.SetThreadGroup(thread_group_0->GetId(), "Set0_1", ConstraintSet("3,11,13-14")); group_0_thread_constr = thread_group_0->GetThreads(); EXPECT(group_0_thread_constr->ToSimpleString() == "0x3,0xb,0xd-0xe"); group_0_threads.clear(); group_0_thread_constr->GetValues(group_0_threads); for (uint64 thread : group_0_threads) { EXPECT(tg_mod.GetThreadGroupId(thread) == thread_group_0->GetId()); } std::vector<uint32> free_threads; tg_mod.GetFreeThreads(free_threads); EXPECT(free_threads.size() == 5u); for (uint32 free_thread : free_threads) { EXPECT(tg_mod.GetThreadGroupId(free_thread) == -1u); } } } } }; int main( int argc, char * argv[] ) { Force::Logger::Initialize(); Force::Random::Initialize(); int ret = lest::run( specification, argc, argv ); Force::Random::Destroy(); Force::Logger::Destroy(); return ret; }
37.776224
149
0.643003
Wlgen
4e1e89ed0e516be46415c2b1cf93c56d4e219c02
156
cpp
C++
PredPrey_Attempt2/main.cpp
08jne01/Predator-Prey-Attempt2
cfb1d259a73d3d038ca122cdf63e231968e93fa9
[ "MIT" ]
null
null
null
PredPrey_Attempt2/main.cpp
08jne01/Predator-Prey-Attempt2
cfb1d259a73d3d038ca122cdf63e231968e93fa9
[ "MIT" ]
null
null
null
PredPrey_Attempt2/main.cpp
08jne01/Predator-Prey-Attempt2
cfb1d259a73d3d038ca122cdf63e231968e93fa9
[ "MIT" ]
null
null
null
#include "Header.h" #include "Program.h" int main() { sf::err().rdbuf(NULL); Program p(700, 700, 2000, 100, 10, 0.0005, 0.01); return p.mainLoop(); }
13
50
0.615385
08jne01
89ecdd94e91e2120da96013ca06296e6a66ffb1d
5,368
cpp
C++
qttools/src/assistant/qhelpconverter/qhpwriter.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
1
2020-04-30T15:47:35.000Z
2020-04-30T15:47:35.000Z
qttools/src/assistant/qhelpconverter/qhpwriter.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
qttools/src/assistant/qhelpconverter/qhpwriter.cpp
wgnet/wds_qt
8db722fd367d2d0744decf99ac7bafaba8b8a3d3
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the Qt Assistant of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/QFile> #include "qhpwriter.h" #include "adpreader.h" QT_BEGIN_NAMESPACE QhpWriter::QhpWriter(const QString &namespaceName, const QString &virtualFolder) { m_namespaceName = namespaceName; m_virtualFolder = virtualFolder; setAutoFormatting(true); } void QhpWriter::setAdpReader(AdpReader *reader) { m_adpReader = reader; } void QhpWriter::setFilterAttributes(const QStringList &attributes) { m_filterAttributes = attributes; } void QhpWriter::setCustomFilters(const QList<CustomFilter> filters) { m_customFilters = filters; } void QhpWriter::setFiles(const QStringList &files) { m_files = files; } void QhpWriter::generateIdentifiers(IdentifierPrefix prefix, const QString prefixString) { m_prefix = prefix; m_prefixString = prefixString; } bool QhpWriter::writeFile(const QString &fileName) { QFile out(fileName); if (!out.open(QIODevice::WriteOnly)) return false; setDevice(&out); writeStartDocument(); writeStartElement(QLatin1String("QtHelpProject")); writeAttribute(QLatin1String("version"), QLatin1String("1.0")); writeTextElement(QLatin1String("namespace"), m_namespaceName); writeTextElement(QLatin1String("virtualFolder"), m_virtualFolder); writeCustomFilters(); writeFilterSection(); writeEndDocument(); out.close(); return true; } void QhpWriter::writeCustomFilters() { if (!m_customFilters.count()) return; foreach (const CustomFilter &f, m_customFilters) { writeStartElement(QLatin1String("customFilter")); writeAttribute(QLatin1String("name"), f.name); foreach (const QString &a, f.filterAttributes) writeTextElement(QLatin1String("filterAttribute"), a); writeEndElement(); } } void QhpWriter::writeFilterSection() { writeStartElement(QLatin1String("filterSection")); foreach (const QString &a, m_filterAttributes) writeTextElement(QLatin1String("filterAttribute"), a); writeToc(); writeKeywords(); writeFiles(); writeEndElement(); } void QhpWriter::writeToc() { QList<ContentItem> lst = m_adpReader->contents(); if (lst.isEmpty()) return; int depth = -1; writeStartElement(QLatin1String("toc")); foreach (const ContentItem &i, lst) { while (depth-- >= i.depth) writeEndElement(); writeStartElement(QLatin1String("section")); writeAttribute(QLatin1String("title"), i.title); writeAttribute(QLatin1String("ref"), i.reference); depth = i.depth; } while (depth-- >= -1) writeEndElement(); } void QhpWriter::writeKeywords() { QList<KeywordItem> lst = m_adpReader->keywords(); if (lst.isEmpty()) return; writeStartElement(QLatin1String("keywords")); foreach (const KeywordItem &i, lst) { writeEmptyElement(QLatin1String("keyword")); writeAttribute(QLatin1String("name"), i.keyword); writeAttribute(QLatin1String("ref"), i.reference); if (m_prefix == FilePrefix) { QString str = i.reference.mid( i.reference.lastIndexOf(QLatin1Char('/'))+1); str = str.left(str.lastIndexOf(QLatin1Char('.'))); writeAttribute(QLatin1String("id"), str + QLatin1String("::") + i.keyword); } else if (m_prefix == GlobalPrefix) { writeAttribute(QLatin1String("id"), m_prefixString + i.keyword); } } writeEndElement(); } void QhpWriter::writeFiles() { if (m_files.isEmpty()) return; writeStartElement(QLatin1String("files")); foreach (const QString &f, m_files) writeTextElement(QLatin1String("file"), f); writeEndElement(); } QT_END_NAMESPACE
30.327684
87
0.668219
wgnet
89f4fd7de675c72a755421110bd985e1a7a44779
8,401
cpp
C++
stromx/runtime/Compare.cpp
uboot/stromx
5aff42008c576ca4aa9dbb1fdd238dac1d875ece
[ "Apache-2.0" ]
11
2015-08-16T09:59:07.000Z
2021-06-15T14:39:20.000Z
stromx/runtime/Compare.cpp
uboot/stromx
5aff42008c576ca4aa9dbb1fdd238dac1d875ece
[ "Apache-2.0" ]
null
null
null
stromx/runtime/Compare.cpp
uboot/stromx
5aff42008c576ca4aa9dbb1fdd238dac1d875ece
[ "Apache-2.0" ]
8
2015-05-10T02:25:37.000Z
2020-10-28T13:06:01.000Z
/* * Copyright 2015 Matthias Fuchs * * 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 "stromx/runtime/Compare.h" #include "stromx/runtime/DataProvider.h" #include "stromx/runtime/EnumParameter.h" #include "stromx/runtime/Id2DataComposite.h" #include "stromx/runtime/Id2DataPair.h" #include "stromx/runtime/Locale.h" #include "stromx/runtime/NumericParameter.h" #include "stromx/runtime/OperatorException.h" #include "stromx/runtime/ReadAccess.h" #include "stromx/runtime/Variant.h" #include "stromx/runtime/VariantComposite.h" #include <cmath> namespace stromx { namespace runtime { const std::string Compare::TYPE("Compare"); const std::string Compare::PACKAGE(STROMX_RUNTIME_PACKAGE_NAME); const Version Compare::VERSION(STROMX_RUNTIME_VERSION_MAJOR, STROMX_RUNTIME_VERSION_MINOR, STROMX_RUNTIME_VERSION_PATCH); Compare::Compare() : OperatorKernel(TYPE, PACKAGE, VERSION, setupInitParameters()) , m_compareToInput(false) , m_comparisonType(LESS) , m_value(0.0) , m_epsilon(1e-6) { } void Compare::setParameter(unsigned int id, const Data& value) { try { switch(id) { case COMPARE_TO_INPUT: m_compareToInput = data_cast<Bool>(value); break; case COMPARISON_TYPE: m_comparisonType = data_cast<Enum>(value); break; case PARAMETER_VALUE: m_value = data_cast<Float64>(value); break; case EPSILON: m_epsilon = data_cast<Float64>(value); break; default: throw WrongParameterId(id, *this); } } catch(runtime::BadCast&) { throw WrongParameterType(parameter(id), *this); } } const DataRef Compare::getParameter(const unsigned int id) const { switch(id) { case COMPARE_TO_INPUT: return m_compareToInput; case COMPARISON_TYPE: return m_comparisonType; case PARAMETER_VALUE: return m_value; case EPSILON: return m_epsilon; default: throw WrongParameterId(id, *this); } } void Compare::initialize() { OperatorKernel::initialize(setupInputs(), setupOutputs(), setupParameters()); } void Compare::execute(DataProvider& provider) { double value1 = 0.0; double value2 = 0.0; Id2DataPair number1Mapper(NUMBER_1); Id2DataPair number2Mapper(NUMBER_2); if (m_compareToInput) { provider.receiveInputData(number1Mapper && number2Mapper); ReadAccess access1(number1Mapper.data()); ReadAccess access2(number2Mapper.data()); value1 = toDouble(access1.get()); value2 = toDouble(access2.get()); } else { provider.receiveInputData(number1Mapper); ReadAccess access(number1Mapper.data()); value1 = toDouble(access.get()); value2 = m_value; } bool result = false; switch(m_comparisonType) { case LESS: result = value1 < value2; break; case GREATER: result = value1 > value2; break; case LESS_OR_EQUAL: result = value1 < value2 + m_epsilon; break; case GREATER_OR_EQUAL: result = value1 + m_epsilon > value2; break; case EQUAL: result = std::abs(value1 - value2) < m_epsilon; break; case NOT_EQUAL: result = std::abs(value1 - value2) >= m_epsilon; break; default: throw InternalError("Unsupported comparison type."); } DataContainer resultContainer(new Bool(result)); provider.sendOutputData(Id2DataPair(RESULT, resultContainer)); } const std::vector<const Input*> Compare::setupInputs() { std::vector<const Input*> inputs; if (m_compareToInput) { Input* number1 = new Input(NUMBER_1, Variant::INT || Variant::FLOAT); number1->setTitle(L_("Input 1")); inputs.push_back(number1); Input* number2 = new Input(NUMBER_2, Variant::INT || Variant::FLOAT); number2->setTitle(L_("Number 2")); inputs.push_back(number2); } else { Input* number = new Input(NUMBER_1, Variant::INT || Variant::FLOAT); number->setTitle(L_("Number")); inputs.push_back(number); } return inputs; } const std::vector<const Output*> Compare::setupOutputs() { std::vector<const Output*> outputs; Output* result = new Output(RESULT, Variant::BOOL); result->setTitle(L_("Result")); outputs.push_back(result); return outputs; } const std::vector<const Parameter*> Compare::setupInitParameters() { std::vector<const Parameter*> parameters; Parameter* compareToInput = new Parameter(COMPARE_TO_INPUT, Variant::BOOL); compareToInput->setAccessMode(Parameter::NONE_WRITE); compareToInput->setTitle(L_("Compare to second input")); parameters.push_back(compareToInput); return parameters; } const std::vector<const Parameter*> Compare::setupParameters() { std::vector<const Parameter*> parameters; EnumParameter* comparisonType = new EnumParameter(COMPARISON_TYPE); comparisonType->setAccessMode(Parameter::ACTIVATED_WRITE); comparisonType->setTitle(L_("Comparison type")); comparisonType->add(EnumDescription(runtime::Enum(LESS), L_("Less"))); comparisonType->add(EnumDescription(runtime::Enum(LESS_OR_EQUAL), L_("Less or equal"))); comparisonType->add(EnumDescription(runtime::Enum(GREATER), L_("Greater"))); comparisonType->add(EnumDescription(runtime::Enum(GREATER_OR_EQUAL), L_("Greater or equal"))); comparisonType->add(EnumDescription(runtime::Enum(EQUAL), L_("Equal"))); comparisonType->add(EnumDescription(runtime::Enum(NOT_EQUAL), L_("Not equal"))); parameters.push_back(comparisonType); if (! m_compareToInput) { NumericParameter<Float64>* parameterValue = new NumericParameter<Float64>(PARAMETER_VALUE); parameterValue->setAccessMode(Parameter::ACTIVATED_WRITE); parameterValue->setTitle(L_("Value")); parameters.push_back(parameterValue); } NumericParameter<Float64>* epsilon = new NumericParameter<Float64>(EPSILON); epsilon->setAccessMode(Parameter::ACTIVATED_WRITE); epsilon->setTitle(L_("Epsilon")); epsilon->setMin(Float64(0.0)); parameters.push_back(epsilon); return parameters; } } }
36.211207
129
0.548268
uboot
d602d70d3a27518ad0a3ce6df426b00285405dcb
1,771
cpp
C++
compiler/src/Ast/AstDef.cpp
jadedrip/SimpleLang
f39c490e5a41151d1d0d2f8c77c6ce524b7842f0
[ "BSD-3-Clause" ]
16
2015-03-30T02:46:49.000Z
2020-07-28T13:36:54.000Z
compiler/src/Ast/AstDef.cpp
jadedrip/SimpleLang
f39c490e5a41151d1d0d2f8c77c6ce524b7842f0
[ "BSD-3-Clause" ]
1
2020-09-01T09:38:30.000Z
2020-09-01T09:38:30.000Z
compiler/src/Ast/AstDef.cpp
jadedrip/SimpleLang
f39c490e5a41151d1d0d2f8c77c6ce524b7842f0
[ "BSD-3-Clause" ]
2
2020-02-07T02:09:48.000Z
2020-02-19T13:31:35.000Z
#include "stdafx.h" #include "AstDef.h" #include "AstContext.h" #include "AstGetClass.h" #include "utility.h" #include "../Type/AutoType.h" #include "../Type/ClassInstanceType.h" #include "../CodeGenerate/DefGen.h" #include "../CodeGenerate/GenList.h" #include "../CodeGenerate/CastGen.h" #include "../CodeGenerate/StringLiteGen.h" #include <exception> using namespace llvm; using namespace std; void AstDef::draw(std::ostream & os) { std::string n = "def "; for (auto &i : vars) { n += i.first + ","; } n.pop_back(); dotLable(os, n); } CodeGen * AstDef::makeGen(AstContext * parent) { AstType* p = AutoType::isAuto(type) ? nullptr : type; if (vars.size() == 1) { auto x=vars.at(0); auto gen= makeDefGen(parent, p, x.first, x.second); if (!gen) throw std::runtime_error("Can't def " + x.first); parent->setSymbolValue(x.first, gen ); return gen; } auto list = new GenList(); for (auto &i : vars) { auto gen = makeDefGen(parent, p, i.first, i.second); list->generates.push_back(gen); parent->setSymbolValue(i.first, gen); } return list; } static string emptyStr; CodeGen * AstDef::makeDefGen(AstContext * parent, AstType * type, const std::string& n, AstNode* var) { CodeGen* v = var ? var->makeGen(parent) : nullptr; if (v && !type && v->type->isStructTy()) return v; llvm::Type* t = nullptr; LLVMContext& c = parent->context(); auto *a = dynamic_cast<AstGetClass*>(type); if (a) { a->context = parent; // 创建新对象 auto *x = parent->findClass(a->name); if (x) { // TODO: 测试 x 类型和 v 一致 if (v) return v; vector<pair<string, CodeGen*>> args; return x->makeNew(parent, args); } } else if (type) { t = type->llvmType(parent->context()); } else if (v) t = v->type; return new DefGen(n, t, v); }
22.417722
101
0.640316
jadedrip
d6077ea40b8d56f29839f9970ac2762b305a2e24
8,750
cpp
C++
src/probability.cpp
Michael-Stevens-27/silverblaze
f0f001710589fe072545b00f0d3524fc993f4cbd
[ "MIT" ]
3
2018-03-29T15:54:56.000Z
2018-10-15T18:28:59.000Z
src/probability.cpp
Michael-Stevens-27/silverblaze
f0f001710589fe072545b00f0d3524fc993f4cbd
[ "MIT" ]
2
2020-02-11T20:44:25.000Z
2020-06-18T20:00:32.000Z
src/probability.cpp
Michael-Stevens-27/silverblaze
f0f001710589fe072545b00f0d3524fc993f4cbd
[ "MIT" ]
null
null
null
#include <Rcpp.h> #include <math.h> #include "probability.h" #include "misc.h" using namespace std; //------------------------------------------------ // draw a value from an exponential distribution with set rate parameter double exp1(double rate){ return R::rexp(rate); } //------------------------------------------------ // draw a value from a chi squared distribution with set degrees of freedom double rchisq1(double df){ return R::rchisq(df); } //------------------------------------------------ // draw from continuous uniform distribution on interval [0,1) double runif_0_1() { return R::runif(0,1); } //------------------------------------------------ // draw from continuous uniform distribution on interval [a,b) double runif1(double a, double b) { return R::runif(a,b); } //------------------------------------------------ // draw from Bernoulli(p) distribution bool rbernoulli1(double p) { return R::rbinom(1, p); } //------------------------------------------------ // draw from univariate normal distribution double rnorm1(double mean, double sd) { return R::rnorm(mean, sd); } //------------------------------------------------ // density of univariate normal distribution double dnorm1(double x, double mean, double sd, bool log_on) { return R::dnorm(x, mean, sd, log_on); } //------------------------------------------------ // density of log-normal distribution double dlnorm1(double x, double meanlog, double sdlog, bool log_on) { return R::dlnorm(x, meanlog, sdlog, log_on); } //------------------------------------------------ // draw from univariate normal distribution and reflect to interval (a,b) double rnorm1_interval(double mean, double sd, double a, double b) { // draw raw value relative to a double ret = rnorm1(mean, sd) - a; double interval_difference = b - a; // std::cout << "Value " << ret << std::endl; // reflect off boundries at 0 and (b-a) if (ret < 0 || ret > interval_difference) { // use multiple reflections to bring into range [-2(b-a), 2(b-a)] double modded = std::fmod(ret, 2*interval_difference); // use one more reflection to bring into range [0, (b-a)] if (modded < 0) { modded = -1*modded; } if (modded > interval_difference) { modded = 2*interval_difference - modded; } ret = modded; } // no longer relative to a ret += a; // don't let ret equal exactly a or b if (ret == a) { ret += UNDERFLO; } else if (ret == b) { ret -= UNDERFLO; } return ret; } //------------------------------------------------ // sample single value from given probability vector (that sums to pSum) int sample1(vector<double> &p, double pSum) { double rand = pSum*runif_0_1(); double z = 0; for (int i=0; i<int(p.size()); i++) { z += p[i]; if (rand<z) { return i+1; } } return 0; } //------------------------------------------------ // sample single value x that lies between a and b (inclusive) with equal // probability. Works on positive or negative values of a or b, and works // irrespective of which of a or b is larger. int sample2(int a, int b) { if (a<b) { return floor(runif1(a, b+1)); } else { return floor(runif1(b, a+1)); } } //------------------------------------------------ // sample a given number of values from a vector without replacement (templated // for different data types). Note, this function re-arranges the original // vector (passed in by reference), and the result is stored in the first n // elements. // sample3 // DEFINED IN HEADER //------------------------------------------------ // draw from gamma(shape,rate) distribution // note all gamma functions from RCPP use a scale parameter in place of a rate, // for more info see: https://teuder.github.io/rcpp4everyone_en/310_Rmath.html // this is why all rates are inversed double rgamma1(double shape, double rate) { double x = R::rgamma(shape, 1/rate); // check for zero or infinite values (catches bug present in Visual Studio 2010) if (x<UNDERFLO) { x = UNDERFLO; } if (x>OVERFLO) { x = OVERFLO; } return x; } //------------------------------------------------ // density of gamma(shape,rate) distribution double dgamma1(double x, double shape, double rate) { double y = R::dgamma(x, shape, 1/rate, FALSE); // check for zero or infinite values (catches bug present in Visual Studio 2010) if (y<UNDERFLO) { y = UNDERFLO; } if (y>OVERFLO) { y = OVERFLO; } return y; } //------------------------------------------------ // draw from beta(alpha,beta) distribution double rbeta1(double shape1, double shape2) { if (shape1==1 && shape2==1) { return runif_0_1(); } return R::rbeta(shape1, shape2); } //------------------------------------------------ // probability density of beta(shape1,shape2) distribution double dbeta1(double x, double shape1, double shape2, bool return_log) { return R::dbeta(x, shape1, shape2, return_log); } //------------------------------------------------ // draw from dirichlet distribution using vector of shape parameters. Return vector of values. vector<double> rdirichlet1(vector<double> &shapeVec) { // draw a series of gamma random variables int n = shapeVec.size(); vector<double> ret(n); double retSum = 0; for (int i=0; i<n; i++) { ret[i] = rgamma1(shapeVec[i], 1.0); retSum += ret[i]; } // divide all by the sum double retSumInv = 1.0/retSum; for (int i=0; i<n; i++) { ret[i] *= retSumInv; } return(ret); } //------------------------------------------------ // draw from dirichlet distribution using bespoke inputs. Outputs are stored in // x, passed by reference for speed. Shape parameters are equal to alpha+beta, // where alpha is an integer vector, and beta is a single double. void rdirichlet2(std::vector<double> &x, std::vector<double> &alpha, double scale_factor) { int n = x.size(); double xSum = 0; for (int i = 0; i < n; i++) { // print(alpha[i]); x[i] = rgamma1(scale_factor*alpha[i], 1.0); xSum += x[i]; } double xSumInv = 1.0/xSum; // print(scale_factor); for (int i = 0; i < n; i++) { x[i] *= xSumInv; // print(x[i]); if (x[i] <= UNDERFLO) { x[i] = UNDERFLO; } } } //------------------------------------------------ // density of a dirichlet distribution in log space double ddirichlet(std::vector<double> &x, std::vector<double> &alpha, double scale_factor) { int n = x.size(); double logSum = 0; for (int i = 0; i < n; i++) { logSum += (scale_factor*alpha[i] - 1)*log(x[i]) - lgamma(scale_factor*alpha[i]); } return logSum; } //------------------------------------------------ // draw from Poisson(rate) distribution int rpois1(double rate) { return R::rpois(rate); } //------------------------------------------------ // probability mass of Poisson(rate) distribution double dpois1(int n, double rate, bool returnLog) { return R::dpois(n,rate,returnLog); } //------------------------------------------------ // draw from negative binomial distribution with mean lambda and variance gamma*lambda (gamma must be >1) int rnbinom1(double lambda, double gamma) { return R::rnbinom(lambda/(gamma-1), 1/gamma); } //------------------------------------------------ // probability mass of negative binomial distribution with mean lambda and // variance gamma*lambda (gamma must be >1) double dnbinom1(int n, double lambda, double gamma, bool returnLog) { return R::dnbinom(n, lambda/(gamma-1), 1/gamma, returnLog); } //------------------------------------------------ // probability mass of negative binomial distribution with mean and variance double dnbinom_mu1(int n, double size, double mean, bool returnLog) { return R::dnbinom_mu(n, size, mean, returnLog); } //------------------------------------------------ // return closest value to a vector of target values double closest(std::vector<double> const& vec, double value) { auto const it = std::lower_bound(vec.begin(), vec.end(), value); if (it == vec.end()) { return -1; } return *it; } //------------------------------------------------ // draw from binomial(N,p) distribution int rbinom1(int N, double p) { if (p >= 1.0) { return N; } else if (p <= 0.0) { return 0; } return R::rbinom(N, p); } //------------------------------------------------ // draw from multinomial(N,p) distribution, where p sums to p_sum void rmultinom1(int N, const vector<double> &p, double p_sum, vector<int> &ret) { int k = int(p.size()); fill(ret.begin(), ret.end(), 0); for (int i = 0; i < (k-1); ++i) { ret[i] = rbinom1(N, p[i] / p_sum); N -= ret[i]; if (N == 0) { break; } p_sum -= p[i]; } ret[k-1] = N; }
29.069767
105
0.551886
Michael-Stevens-27