hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
a8b65727aab1d85755f8257aad436a6bbbb7b5eb
3,712
cpp
C++
BasicBMPDiff/diff-PNG.cpp
kolmoblocks/imageexpander
661cc9761465910dec2859c9195fac68765b2cb4
[ "Zlib" ]
2
2019-02-19T20:55:33.000Z
2019-04-03T21:01:24.000Z
BasicBMPDiff/diff-PNG.cpp
kolmoblocks/imageexpander
661cc9761465910dec2859c9195fac68765b2cb4
[ "Zlib" ]
null
null
null
BasicBMPDiff/diff-PNG.cpp
kolmoblocks/imageexpander
661cc9761465910dec2859c9195fac68765b2cb4
[ "Zlib" ]
null
null
null
#include "lodepng.h" #include <iostream> using namespace std; unsigned int gcd(unsigned int u, unsigned int v) { // simple cases (termination) if (u == v) return u; if (u == 0) return v; if (v == 0) return u; // look for factors of 2 if (~u & 1) // u is even { if (v & 1) // v is odd return gcd(u >> 1, v); else // both u and v are even return gcd(u >> 1, v >> 1) << 1; } if (~v & 1) // u is odd, v is even return gcd(u, v >> 1); // reduce larger argument if (u > v) return gcd((u - v) >> 1, v); return gcd((v - u) >> 1, u); } // generateDiff(string, string) // generates the diff, which is used by expand_image to expand the lower // resolution image. void generateDiff (const char *lowRes, const char *highRes){ std::vector<unsigned char> lowResImage; std::vector<unsigned char> highResImage; unsigned lowResWidth, lowResHeight, highResWidth, highResHeight; unsigned error = lodepng::decode(lowResImage, lowResWidth, lowResHeight, lowRes, LCT_RGB, 8); if (error) { std::cout << error; return; } error = lodepng::decode(highResImage, highResWidth, highResHeight, highRes, LCT_RGB, 8); if (error) { std::cout << error; return; } unsigned denom = gcd(lowResWidth, highResWidth); // finding numerator and denominator of ratio (lowFactor, highFactor respectively) int lowFactor = lowResWidth / denom; int highFactor = highResWidth / denom; // finding diffWidth from the difference between smaller vs newer chunk sizes int diffWidth = highFactor * highFactor - lowFactor * lowFactor; int highResArea = highResWidth * highResHeight; // finding diffHeight from the number of chunks in a whole highRes image by finding the number of whole chunks (rounded up) for along the height and the width. int diffHeight = (highResWidth % highFactor == 0 ? highResWidth / highFactor : highResWidth / highFactor + 1 ) * (highResHeight % highFactor == 0 ? highResHeight / highFactor : highResHeight / highFactor + 1 ); std::vector<unsigned char> diffVec; const unsigned int height = highResHeight; const unsigned int width = highResWidth; // iterating through blocks, x and y indicate the top left positions of each block. for (std::size_t y=0; y<height; y+= highFactor) { for (std::size_t x=0; x<width; x+= highFactor) { // iterating through inner block pixels, innerX and innerY indicate the current position of the block we are at. for (int innerX = x; innerX < x+highFactor; ++innerX) { for (int innerY = y; innerY < y+highFactor; ++innerY) { // only get and set pixel if the block is not included in the old block (for now it is the top left smaller square with sides of length "lowFactor") if (!(innerX < x+lowFactor) || !(innerY < y+lowFactor)) { // set pixel of the diff at diffX , diffY with the Color at the highResImage at innerX , innerY diffVec.push_back(highResImage.at((innerX+innerY*highResWidth)*3)); diffVec.push_back(highResImage.at((innerX+innerY*highResWidth)*3+1)); diffVec.push_back(highResImage.at((innerX+innerY*highResWidth)*3+2)); } } } } } error = lodepng::encode("diff.png", diffVec, diffWidth, diffHeight, LCT_RGB ,8); cout<<diffVec.size()<<' ' << diffWidth << ' ' << diffHeight <<endl; std::cout << lodepng_error_text(error) << std::endl; } int main(int argc, char *argv[]){ // argv[1]: smaller file generateDiff(argv[1], argv[2]); }
36.752475
163
0.625808
kolmoblocks
a8b88121050448fe8c94270714dd59868be40852
452
cpp
C++
Tests/Experiments/Sources/MemFunc.cpp
Anonymus-Player/HackSolutions
7d865de8ec06bb098a3a11bd6328faaaf96dc1df
[ "MIT" ]
33
2020-11-20T14:58:25.000Z
2022-03-04T10:04:08.000Z
Tests/Experiments/Sources/MemFunc.cpp
Anonymus-Player/HackSolutions
7d865de8ec06bb098a3a11bd6328faaaf96dc1df
[ "MIT" ]
8
2021-01-05T23:18:32.000Z
2022-02-22T18:25:37.000Z
Tests/Experiments/Sources/MemFunc.cpp
Anonymus-Player/HackSolutions
7d865de8ec06bb098a3a11bd6328faaaf96dc1df
[ "MIT" ]
6
2021-01-05T22:02:57.000Z
2022-02-22T18:34:22.000Z
#include <TypeTraits.hpp> template <typename T> struct TestStruct { T* data = nullptr; hsd::usize sz = 0; TestStruct(T* ptr, hsd::usize size) : data{ptr}, sz{size} {} T* begin() { return data; } T* end() { return data + sz; } }; template <typename T> concept IsContainer = requires { hsd::declval<T>().begin(); }; int main() { static_assert(IsContainer<TestStruct<int>>); }
13.69697
48
0.553097
Anonymus-Player
a8bdd701da715f8ddec5009a55759eeec5710eef
648
cpp
C++
lab11_9_1question/lab11_9_1/lab11_9_1.cpp
wjingzhe/CPP_lab
081ba3612c2d96ffd074061ca1800b7f31486c37
[ "MIT" ]
null
null
null
lab11_9_1question/lab11_9_1/lab11_9_1.cpp
wjingzhe/CPP_lab
081ba3612c2d96ffd074061ca1800b7f31486c37
[ "MIT" ]
null
null
null
lab11_9_1question/lab11_9_1/lab11_9_1.cpp
wjingzhe/CPP_lab
081ba3612c2d96ffd074061ca1800b7f31486c37
[ "MIT" ]
null
null
null
// lab11_9_1.cpp : Defines the entry point for the console application. // #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } #include<iostream> #include<fstream> using namespace std; void main() { ofstream file; file.open("input.txt"); file<<"aaaaaaaa\nbbbbbbbb\ncccccccc"; file.close(); ifstream filei("input.txt"); ofstream fileo; fileo.open("output.txt"); char c; filei>>noskipws; int i=1; fileo<<i<<"."; cout<<i<<"."; while(filei>>c) { if(c=='\n') { i++; fileo<<"\n"; cout<<"\n"; fileo<<i<<"."; cout<<i<<"."; } else { fileo<<c; cout<<c; } } filei.close(); fileo.close(); }
14.4
71
0.591049
wjingzhe
a8bdf0cb01d14fe0d613c5aadc67c00c0cbf7a4d
1,491
hpp
C++
System/include/Switch/System/IO/WatcherChangeTypes.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
4
2021-10-14T01:43:00.000Z
2022-03-13T02:16:08.000Z
System/include/Switch/System/IO/WatcherChangeTypes.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
null
null
null
System/include/Switch/System/IO/WatcherChangeTypes.hpp
kkptm/CppLikeCSharp
b2d8d9da9973c733205aa945c9ba734de0c734bc
[ "MIT" ]
2
2022-03-13T02:16:06.000Z
2022-03-14T14:32:57.000Z
/// @file /// @brief Contains Switch::System::IO::WatcherChangeTypes enum. #pragma once #include <Switch/As.hpp> #include <Switch/System/EventArgs.hpp> #include <Switch/System/Exception.hpp> /// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more. namespace Switch { /// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. namespace System { /// @brief The System::IO namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support. namespace IO { /// @brief Changes that might occur to a file or directory. /// This enumeration has a FlagsAttribute attribute that allows a bitwise combination of its member values. enum class WatcherChangeTypes { /// @brief The creation, deletion, change, or renaming of a file or folder. All = 15, /// @brief The creation of a file or folder. Created = 1, /// @brief The deletion of a file or folder. Deleted = 2, /// @brief The change of a file or folder. The types of changes include: changes to size, attributes, security settings, last write, and last access time. Changed = 4, /// @brief The renaming of a file or folder. Renamed = 8 }; } } }
46.59375
215
0.695506
kkptm
a8bfdb823c5e96782c15b039d0f919d295062e3a
1,493
cpp
C++
d04/ex04/BocalSteroid.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
5
2018-02-10T12:33:53.000Z
2021-03-28T09:27:05.000Z
d04/ex04/BocalSteroid.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
null
null
null
d04/ex04/BocalSteroid.cpp
ncoden/42_CPP_pool
9f2d9aa030b65e3ad967086bff97e80e23705a29
[ "Apache-2.0" ]
6
2017-11-25T17:34:43.000Z
2020-12-20T12:00:04.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* BocalSteroid.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ncoden <ncoden@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/06/22 16:42:09 by ncoden #+# #+# */ /* Updated: 2015/06/22 16:59:43 by ncoden ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> #include <string> #include "BocalSteroid.hpp" BocalSteroid::BocalSteroid(void) {} BocalSteroid::BocalSteroid(BocalSteroid const &src) { *this = src; } BocalSteroid::~BocalSteroid(void) {} BocalSteroid &BocalSteroid::operator=(BocalSteroid const &rhs) { (void)rhs; return (*this); } std::string BocalSteroid::beMined(DeepCoreMiner *laser) const { (void)laser; return ("Zazium"); } std::string BocalSteroid::beMined(StripMiner *laser) const { (void)laser; return ("Krpite"); } std::string const BocalSteroid::getName(void) const { return ("BocalSteroid"); }
29.27451
80
0.352981
ncoden
a8c077c12d6da2d3d73a0234c8dd362c44040fe6
4,126
hpp
C++
xr3core/h/xr/strings/stringutils.hpp
zyndor/xrhodes
15017c2ba6499b19e1dd327608ffb44dbaba7a4e
[ "BSD-2-Clause" ]
7
2018-11-13T09:44:56.000Z
2022-01-12T02:22:41.000Z
xr3core/h/xr/strings/stringutils.hpp
zyndor/xrhodes
15017c2ba6499b19e1dd327608ffb44dbaba7a4e
[ "BSD-2-Clause" ]
2
2018-10-30T08:19:02.000Z
2018-12-31T18:48:13.000Z
xr3core/h/xr/strings/stringutils.hpp
zyndor/xrhodes
15017c2ba6499b19e1dd327608ffb44dbaba7a4e
[ "BSD-2-Clause" ]
null
null
null
#ifndef XR_STRINGUTILS_HPP #define XR_STRINGUTILS_HPP //============================================================================== // // XRhodes // // copyright (c) Gyorgy Straub. All rights reserved. // // License: https://github.com/zyndor/xrhodes#License-bsd-2-clause // //============================================================================== #include <cstdint> #include <sstream> namespace xr { ///@return @a original, or if it's null, an empty string. char const* GetStringSafe(char const* original); ///@brief Attempts to convert @a from to @a to. ///@return Whether the operation was successful. template <typename T> bool StringTo(char const* from, T& to); ///@brief Finds all instances of @a find in @a original and replaces them with /// @replace, writing no more than @a bufferSize characters of the result to /// @a buffer and the actual length of the processed string to @a processedSize. /// Does not allocate memory. If, after writing the string there's space left in /// the buffer (i.e. processedSize < bufferSize), it will write a null terminator. ///@param original: original string. May contain \0 characters; is not required /// to be null-terminated. ///@param originalSize: size of original string. ///@param find: null-terminated string to find. ///@param replace: null-terminated string to replace instances of find. ///@param bufferSize: the size of the provided buffer. No more than this many /// characters will be written. ///@param buffer: buffer to write the result to. ///@param processedSize: output. The number of characters actually written. /// Guaranteed to be less then or equal to @a bufferSize. ///@return The start of the replaced string. char const* Replace(char const* original, size_t originalSize, char const* find, char const* replace, size_t bufferSize, char* buffer, size_t& processedSize); ///@brief This overload of Replace() operates on a null-terminated string, /// not requiring the size of @a original to be supplied. char const* Replace(char const* original, char const* find, char const* replace, size_t bufferSize, char* buffer, size_t& processedSize); ///@brief Converts the character @a c into its two-byte textual hex /// representation. ///@return One past the last character written to in @a buffer. ///@note Does not null terminate. char* Char2Hex(char c, char buffer[2]); ///@brief URL-encodes the first @a originalSize characters of @a original, /// writing up to @a bufferSize characters into the provided @a buffer and the /// actual length of the processed string to @a processedSize. /// Writes a null terminator if it can. ///@param original: original string. May contain \0 characters; is not required /// to be null-terminated. ///@param originalSize: size of original string. ///@param bufferSize: the size of the provided buffer. No more than this many /// characters will be written. ///@param buffer: buffer to write the result to. ///@param processedSize: output. The number of characters actually written. /// Guaranteed to be less then or equal to @a bufferSize. ///@return One past the last character written to in @a buffer, NOT including /// a null terminator it may have written. char const* UrlEncode(char const* original, size_t originalSize, size_t bufferSize, char* buffer, size_t& processedSize); ///@brief This overload of UrlEncode() operates on a null-terminated string, /// not requiring the size of @a original to be supplied. char const* UrlEncode(char const* original, size_t bufferSize, char* buffer, size_t& processedSize); //============================================================================== // inline //============================================================================== inline char const* GetStringSafe(char const* original) { return original != nullptr ? original : ""; } //============================================================================== template <typename T> inline bool StringTo(const char* from, T& to) { std::istringstream iss(from); return !(iss >> std::ws >> to).fail() && (iss >> std::ws).eof(); } } // xr #endif //XR_STRINGUTILS_HPP
40.851485
83
0.663354
zyndor
a8c1159b3471732e1290bc1af1d285b6d70f9610
63
cpp
C++
src/Graphics/stb_image/stb_image.cpp
jkbz64/Zadymka
16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7
[ "MIT" ]
2
2020-03-18T16:13:04.000Z
2021-07-30T12:18:52.000Z
src/Graphics/stb_image/stb_image.cpp
jkbz64/Zadymka
16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7
[ "MIT" ]
null
null
null
src/Graphics/stb_image/stb_image.cpp
jkbz64/Zadymka
16c2bf66ce6c3bbff8eeeb3fad291b2939e4a5b7
[ "MIT" ]
null
null
null
#define STB_IMAGE_IMPLEMENTATION #include "../stb/stb_image.h"
21
32
0.793651
jkbz64
a8c381722bb1c74255fd83b43e9432d36c56ee35
3,068
hh
C++
TrkBase/TrkModuleId.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkBase/TrkModuleId.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
TrkBase/TrkModuleId.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
//-------------------------------------------------------------------------- // File and Version Information: // $Id: TrkModuleId.hh,v 1.3 2007/02/05 22:16:38 brownd Exp $ // // Description: // Trivial class to identify modules used in tracking. // Environment: // Software developed for the BaBar Detector at the SLAC B-Factory. // // Copyright Information: // Copyright (C) 2004 Lawrence Berkeley Laboratory // // Author(s): David Brown, 11/22/04 // //------------------------------------------------------------------------ #ifndef TRKMODULEID_HH #define TRKMODULEID_HH class TrkHistory; class TrkRecoTrk; #include <map> #include <vector> #include <string> class TrkModuleId { public: // enums defining module mapping. existing values should NEVER BE CHANGED, // new numbers may be added as needed enum trkFinders {nofinder=0,dchl3trkconverter=1,dchtrackfinder=2, dchradtrkfinder=3,dcxtrackfinder=4,dcxsparsefinder=5, svttrackfinder=6,svtcircle2helix=7, nfinders}; enum trkModifiers {nomodifier=0,dcxhitadder=1,dchtrkfitupdater=2,trksettrackt0=3, trksettrackt1=4,dchkal1dfit=5,dchkalrx=6,svtkal1dfit=7, svtkalrx=8,dchkalfinalfit=9, svtkalfinalfit=10,trksvthitadder=11,trackmerge=12, trkdchhitadder=13,trkdchradhitadder=14,defaultkalrx=15, trkhitfix=16,trkloopfix=17,trksvthafix=18,trkfailedfix=19,trkmomfix=20, nmodifiers}; // single accessor static const TrkModuleId& instance(); // singleton class, so constructor is protected. Use 'instance' method ~TrkModuleId(); // translate enum values to strings const std::string& finder(int ifnd) const; const std::string& modifier(int imod) const; // translate string to enum value int finder(const std::string& fndmod) const; int modifier(const std::string& modmod) const; // same for TrkHistory. If the module specified isn't a finder (modifier) // the appropriate version of 0 will be returned int finder(const TrkHistory& hist) const; int modifier(const TrkHistory& hist) const; // access maps const std::map<std::string,int>& finders() const { return _finders;} const std::map<std::string,int>& modifiers() const { return _modifiers;} // allow extending the finder and modifier maps void addFinder(const TrkHistory& hist); void addModifier(const TrkHistory& hist); // fill and decode a bitmap of finders/modifiers from a track. unsigned finderMap(const TrkRecoTrk*) const; void setFinders(TrkRecoTrk* trk,unsigned findermap) const; unsigned modifierMap(const TrkRecoTrk*) const; void setModifiers(TrkRecoTrk* trk,unsigned findermap) const; private: // static instance static TrkModuleId* _instance; TrkModuleId(); // pre-empt TrkModuleId(const TrkModuleId&); TrkModuleId& operator =(const TrkModuleId&); // map of finder module names to numbers std::map<std::string,int> _finders; // map of modifier module names to numbers std::map<std::string,int> _modifiers; // reverse-mapping std::vector<std::string> _findernames; std::vector<std::string> _modifiernames; }; #endif
36.52381
92
0.70339
brownd1978
a8c8c88328a9de59b535c4606e69b5fdc6de8b99
399
cpp
C++
App/Source/ECS/System/Render/SpriteRendererSystem.cpp
Clymiaru/GDPARCM_InteractiveLoadingScreen
20b6de0719ab3bd0e50efbbc792470826de8e7f1
[ "MIT" ]
null
null
null
App/Source/ECS/System/Render/SpriteRendererSystem.cpp
Clymiaru/GDPARCM_InteractiveLoadingScreen
20b6de0719ab3bd0e50efbbc792470826de8e7f1
[ "MIT" ]
null
null
null
App/Source/ECS/System/Render/SpriteRendererSystem.cpp
Clymiaru/GDPARCM_InteractiveLoadingScreen
20b6de0719ab3bd0e50efbbc792470826de8e7f1
[ "MIT" ]
null
null
null
#include "pch.h" #include "SpriteRendererSystem.h" SpriteRendererSystem::SpriteRendererSystem() { } SpriteRendererSystem::~SpriteRendererSystem() { } void SpriteRendererSystem::Render(sf::RenderWindow& window) { for (auto* component : m_SpriteRendererComponentList) { auto transform = component->GetTransform(); auto sprite = component->GetSprite(); window.draw(sprite, transform); } }
19
59
0.754386
Clymiaru
a8d1dcb69247bb3c4f6d515cf8603296d5587cfd
1,995
cpp
C++
hiro/qt/action/menu-radio-item.cpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
hiro/qt/action/menu-radio-item.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
hiro/qt/action/menu-radio-item.cpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
#if defined(Hiro_MenuRadioItem) namespace hiro { auto pMenuRadioItem::construct() -> void { qtMenuRadioItem = new QtMenuRadioItem(*this); qtActionGroup = new QActionGroup(nullptr); qtMenuRadioItem->setCheckable(true); qtMenuRadioItem->setActionGroup(qtActionGroup); qtMenuRadioItem->setChecked(true); qtMenuRadioItem->connect(qtMenuRadioItem, SIGNAL(triggered()), SLOT(onActivate())); if(auto parent = _parentMenu()) { parent->qtMenu->addAction(qtMenuRadioItem); } if(auto parent = _parentPopupMenu()) { parent->qtPopupMenu->addAction(qtMenuRadioItem); } setGroup(state().group); _setState(); } auto pMenuRadioItem::destruct() -> void { delete qtMenuRadioItem; delete qtActionGroup; qtMenuRadioItem = nullptr; qtActionGroup = nullptr; } auto pMenuRadioItem::setChecked() -> void { _setState(); } auto pMenuRadioItem::setGroup(sGroup group) -> void { bool first = true; if(auto& group = state().group) { for(auto& weak : group->state.objects) { if(auto object = weak.acquire()) { if(auto menuRadioItem = dynamic_cast<mMenuRadioItem*>(object.data())) { if(auto self = menuRadioItem->self()) { self->qtMenuRadioItem->setChecked(menuRadioItem->state.checked = first); first = false; } } } } } } auto pMenuRadioItem::setText(const string& text) -> void { _setState(); } auto pMenuRadioItem::_setState() -> void { if(auto& group = state().group) { if(auto object = group->object(0)) { if(auto menuRadioItem = dynamic_cast<mMenuRadioItem*>(object.data())) { if(auto self = menuRadioItem->self()) { qtMenuRadioItem->setActionGroup(self->qtActionGroup); } } } } qtMenuRadioItem->setChecked(state().checked); qtMenuRadioItem->setText(QString::fromUtf8(state().text)); } auto QtMenuRadioItem::onActivate() -> void { if(p.state().checked) return; p.self().setChecked(); p.self().doActivate(); } } #endif
25.253165
85
0.66416
mp-lee
a8d3aed4aa014d868ef457e9b6be1f6f89f6772a
1,093
hpp
C++
headers/MyFunctions.hpp
DetlevCM/chemical-kinetics-solver
7010fd6c72c29a0d912ad0c353ff13a5b643cc04
[ "MIT" ]
3
2015-07-03T20:14:00.000Z
2021-02-02T13:45:31.000Z
headers/MyFunctions.hpp
DetlevCM/chemical-kinetics-solver
7010fd6c72c29a0d912ad0c353ff13a5b643cc04
[ "MIT" ]
null
null
null
headers/MyFunctions.hpp
DetlevCM/chemical-kinetics-solver
7010fd6c72c29a0d912ad0c353ff13a5b643cc04
[ "MIT" ]
4
2017-11-09T19:49:18.000Z
2020-08-04T18:29:28.000Z
#ifndef _MY_OTHER_FUNCTIONS_ #define _MY_OTHER_FUNCTIONS_ //*** Define some of my random hard to classify functions ***// void Process_User_Input( FileNames& filenames, vector<string> User_Inputs ); void Get_Mechanism( string filename , Reaction_Mechanism& reaction_mechanism ); vector< double > Get_Delta_N( const vector< SingleReactionData >& Reactions ); // Making Scheme Irreversible vector< SingleReactionData > Make_Irreversible( vector< SingleReactionData > Reactions, const vector< ThermodynamicData > Thermodynamics, double Initial_Temperature, /// use initial temperature from initial data double Range // specify +/- range around initial temperature ); void Synchronize_Gas_Liquid_Model( size_t number_synchronized_species, size_t liquid_species_count, size_t gas_species_count, // gas and liquid counts so I know where concentration entries belong to double *y, // concentrations (&temperature) from the ODE solver double Vliq_div_Vgas, vector< double > Henry_Constants // need to line up with species IDs ); #endif /* _MY_OTHER_FUNCTIONS_ */
27.325
129
0.778591
DetlevCM
a8d942a2fb1a8ef5b8f33043378af3d4b7bc2422
1,125
hpp
C++
src/lib/interface/ChoixReseau.hpp
uvsq21603504/in608-tcp_ip_simulation
95cedcbe7dab5991b84e182297b6ada3ae24679b
[ "MIT" ]
null
null
null
src/lib/interface/ChoixReseau.hpp
uvsq21603504/in608-tcp_ip_simulation
95cedcbe7dab5991b84e182297b6ada3ae24679b
[ "MIT" ]
null
null
null
src/lib/interface/ChoixReseau.hpp
uvsq21603504/in608-tcp_ip_simulation
95cedcbe7dab5991b84e182297b6ada3ae24679b
[ "MIT" ]
null
null
null
#ifndef CHOIXRESEAU_H #define CHOIXRESEAU_H #include <QApplication> #include <QWidget> #include <QPushButton> #include <QLabel> #include <QVBoxLayout> #include <QComboBox> #include <QSpinBox> #include <QMessageBox> class ChoixReseau : public QVBoxLayout { Q_OBJECT private : // Attributs QComboBox* m_Depart; QComboBox* m_Arrive; QSpinBox* m_Ssthresh; QSpinBox* m_PaquetNombre; QComboBox* m_PaquetType; QPushButton* m_Valider; QMessageBox* m_VerifConfig; QPushButton* m_ConfigSimple; QPushButton* m_ConfigMaison; QPushButton* m_ConfigPme; QPushButton* m_ConfigEntreprise; QMessageBox* m_VerifReseau; public : // Constructeur ChoixReseau(); // Destructeur ~ChoixReseau(); // Méthode void analyseConfig(); private slots : // Méthodes Slots void selectConfigSimple(); void selectConfigMaison(); void selectConfigPme(); void selectConfigEntreprise(); void verifConfigMessage(); }; #endif // CHOIXRESEAU_H
20.089286
40
0.639111
uvsq21603504
a8df4e4843a9caae2341d5511806be09178b1caa
2,702
hh
C++
asv_wave_sim_gazebo_plugins/include/asv_wave_sim_gazebo_plugins/Algorithm.hh
minzlee/asv_wave_sim
d9426e1b7b75d43f0c1bd3201e6ba62e54af968f
[ "Apache-2.0" ]
25
2019-05-29T04:55:19.000Z
2022-03-18T19:07:07.000Z
asv_wave_sim_gazebo_plugins/include/asv_wave_sim_gazebo_plugins/Algorithm.hh
minzlee/asv_wave_sim
d9426e1b7b75d43f0c1bd3201e6ba62e54af968f
[ "Apache-2.0" ]
12
2019-02-14T16:26:57.000Z
2022-03-30T19:44:33.000Z
asv_wave_sim_gazebo_plugins/include/asv_wave_sim_gazebo_plugins/Algorithm.hh
minzlee/asv_wave_sim
d9426e1b7b75d43f0c1bd3201e6ba62e54af968f
[ "Apache-2.0" ]
11
2019-05-29T04:55:22.000Z
2022-02-23T11:55:32.000Z
// Copyright (C) 2019 Rhys Mainwaring // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /// \file Algorithm.hh /// \brief Methods for sorting indexes into arrays and vectors. #ifndef _ASV_WAVE_SIM_GAZEBO_PLUGINS_ALGORITHM_HH_ #define _ASV_WAVE_SIM_GAZEBO_PLUGINS_ALGORITHM_HH_ #include <algorithm> #include <array> #include <numeric> #include <vector> namespace asv { /// \brief A small collection of static template methods for sorting arrays and vectors. namespace algorithm { /// \brief Sort and keep track of indexes (largest first) /// /// See: /// <https://stackoverflow.com/questions/1577475/c-sorting-and-keeping-track-of-indexes> /// /// Usage: /// \code /// for (auto i: sort_indexes(v)) { /// cout << v[i] << endl; /// } /// \endcode /// /// \param[in] _v The array to be indexed. /// \return A vector of indexes in to the input array. template <typename T> std::vector<size_t> sort_indexes(const std::vector<T>& _v) { // initialize original index locations std::vector<size_t> idx(_v.size()); std::iota(idx.begin(), idx.end(), 0); // sort indexes based on comparing values in _v std::sort(idx.begin(), idx.end(), [&_v](size_t i1, size_t i2) {return _v[i1] > _v[i2];}); return idx; } /// \brief Sort and keep track of indexes (largest first) /// /// This version is for sorting std::array<T, N> /// \param[in] _v The array to be indexed. /// \return An array of indexes in to the input array. template <typename T, std::size_t N> std::array<size_t, N> sort_indexes(const std::array<T, N>& _v) { // initialize original index locations std::array<size_t, N> idx; std::iota(idx.begin(), idx.end(), 0); // sort indexes based on comparing values in _v std::sort(idx.begin(), idx.end(), [&_v](size_t i1, size_t i2) {return _v[i1] > _v[i2];}); return idx; } } // namespace algorithm } // namespace asv #endif // _ASV_WAVE_SIM_GAZEBO_PLUGINS_ALGORITHM_HH_
32.554217
92
0.650259
minzlee
a8e05fb9e6cce6191951628ed578fd922dc23416
4,043
cpp
C++
systems/plants/shapes/Geometry.cpp
peteflorence/drake
42bc694cd2371c73f79967a6a653be769935b33f
[ "BSD-3-Clause" ]
null
null
null
systems/plants/shapes/Geometry.cpp
peteflorence/drake
42bc694cd2371c73f79967a6a653be769935b33f
[ "BSD-3-Clause" ]
null
null
null
systems/plants/shapes/Geometry.cpp
peteflorence/drake
42bc694cd2371c73f79967a6a653be769935b33f
[ "BSD-3-Clause" ]
1
2021-09-29T19:37:28.000Z
2021-09-29T19:37:28.000Z
#include <fstream> #include "Geometry.h" #include "spruce.hh" using namespace std; using namespace Eigen; namespace DrakeShapes { Geometry::Geometry() : shape(UNKNOWN) {} Geometry::Geometry(const Geometry& other) { shape = other.getShape(); } Geometry::Geometry(Shape shape) : shape(shape) {}; const Shape Geometry::getShape() const { return shape; } Geometry* Geometry::clone() const { return new Geometry(*this); } Sphere::Sphere(double radius) : Geometry(SPHERE), radius(radius) {} Sphere* Sphere::clone() const { return new Sphere(*this); } Box::Box(const Eigen::Vector3d& size) : Geometry(BOX), size(size) {} Box* Box::clone() const { return new Box(*this); } Cylinder::Cylinder(double radius, double length) : Geometry( CYLINDER), radius(radius), length(length) {} Cylinder* Cylinder::clone() const { return new Cylinder(*this); } Capsule::Capsule(double radius, double length) : Geometry(CAPSULE), radius(radius), length(length) {} Capsule* Capsule::clone() const { return new Capsule(*this); } Mesh::Mesh(const string& filename) : Geometry(MESH), filename(filename) {} Mesh::Mesh(const string& filename, const string& resolved_filename) : Geometry(MESH), filename(filename), resolved_filename(resolved_filename) {} bool Mesh::extractMeshVertices(Matrix3Xd& vertex_coordinates) const { //DEBUG //cout << "Mesh::extractMeshVertices: resolved_filename = " << resolved_filename << endl; //END_DEBUG if (resolved_filename.empty()) { return false; } spruce::path spath(resolved_filename); string ext = spath.extension(); std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); ifstream file; //DEBUG //cout << "Mesh::extractMeshVertices: do we have obj?" << endl; //END_DEBUG if (ext.compare(".obj")==0) { //cout << "Loading mesh from " << fname << " (scale = " << scale << ")" << endl; file.open(spath.getStr().c_str(),ifstream::in); } else { //DEBUG //cout << "Mesh::extractMeshVertices: check for obj file with same name" << endl; //END_DEBUG spath.setExtension(".obj"); if ( spath.exists() ) { // try changing the extension to obj and loading // cout << "Loading mesh from " << mypath.replace_extension(".obj").native() << endl; file.open(spath.getStr().c_str(),ifstream::in); } } if (!file.is_open()) { cerr << "Warning: Mesh " << spath.getStr() << " ignored because it does not have extension .obj (nor can I find a juxtaposed file with a .obj extension)" << endl; return false; } //DEBUG //cout << "Mesh::extractMeshVertices: Count num_vertices" << endl; //END_DEBUG string line; // Count the number of vertices and resize vertex_coordinates int num_vertices = 0; while (getline(file,line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { ++num_vertices; } } //DEBUG //cout << "Mesh::extractMeshVertices: num_vertices = " << num_vertices << endl; //END_DEBUG vertex_coordinates.resize(3, num_vertices); file.clear(); file.seekg(0, file.beg); //DEBUG //cout << "Mesh::extractMeshVertices: Read vertices" << endl; //END_DEBUG double d; int j = 0; while (getline(file,line)) { istringstream iss(line); string type; if (iss >> type && type == "v") { //DEBUG //cout << "Mesh::extractMeshVertices: Vertex" << j << endl; //END_DEBUG int i = 0; while (iss >> d) { vertex_coordinates(i++, j) = d; } ++j; } } return true; } Mesh* Mesh::clone() const { return new Mesh(*this); } MeshPoints::MeshPoints(const Eigen::Matrix3Xd& points) : Geometry(MESH_POINTS), points(points) {} MeshPoints* MeshPoints::clone() const { return new MeshPoints(*this); } }
24.355422
168
0.602276
peteflorence
a8e13198cf7b051b3c5e3db005b77c2552950850
14,284
ipp
C++
implement/oglplus/enums/ext/nv_path_metric_query_class.ipp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
459
2016-03-16T04:11:37.000Z
2022-03-31T08:05:21.000Z
implement/oglplus/enums/ext/nv_path_metric_query_class.ipp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
2
2016-08-08T18:26:27.000Z
2017-05-08T23:42:22.000Z
implement/oglplus/enums/ext/nv_path_metric_query_class.ipp
Extrunder/oglplus
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
[ "BSL-1.0" ]
47
2016-05-31T15:55:52.000Z
2022-03-28T14:49:40.000Z
// File implement/oglplus/enums/ext/nv_path_metric_query_class.ipp // // Automatically generated file, DO NOT modify manually. // Edit the source 'source/enums/oglplus/ext/nv_path_metric_query.txt' // or the 'source/enums/make_enum.py' script instead. // // Copyright 2010-2015 Matus Chochlik. // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // namespace enums { template <typename Base, template<PathNVMetricQuery> class Transform> class EnumToClass<Base, PathNVMetricQuery, Transform> : public Base { private: Base& _base(void) { return *this; } public: #if defined GL_GLYPH_WIDTH_BIT_NV # if defined GlyphWidth # pragma push_macro("GlyphWidth") # undef GlyphWidth Transform<PathNVMetricQuery::GlyphWidth> GlyphWidth; # pragma pop_macro("GlyphWidth") # else Transform<PathNVMetricQuery::GlyphWidth> GlyphWidth; # endif #endif #if defined GL_GLYPH_HEIGHT_BIT_NV # if defined GlyphHeight # pragma push_macro("GlyphHeight") # undef GlyphHeight Transform<PathNVMetricQuery::GlyphHeight> GlyphHeight; # pragma pop_macro("GlyphHeight") # else Transform<PathNVMetricQuery::GlyphHeight> GlyphHeight; # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV # if defined GlyphHorizontalBearingX # pragma push_macro("GlyphHorizontalBearingX") # undef GlyphHorizontalBearingX Transform<PathNVMetricQuery::GlyphHorizontalBearingX> GlyphHorizontalBearingX; # pragma pop_macro("GlyphHorizontalBearingX") # else Transform<PathNVMetricQuery::GlyphHorizontalBearingX> GlyphHorizontalBearingX; # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV # if defined GlyphHorizontalBearingY # pragma push_macro("GlyphHorizontalBearingY") # undef GlyphHorizontalBearingY Transform<PathNVMetricQuery::GlyphHorizontalBearingY> GlyphHorizontalBearingY; # pragma pop_macro("GlyphHorizontalBearingY") # else Transform<PathNVMetricQuery::GlyphHorizontalBearingY> GlyphHorizontalBearingY; # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV # if defined GlyphHorizontalBearingAdvance # pragma push_macro("GlyphHorizontalBearingAdvance") # undef GlyphHorizontalBearingAdvance Transform<PathNVMetricQuery::GlyphHorizontalBearingAdvance> GlyphHorizontalBearingAdvance; # pragma pop_macro("GlyphHorizontalBearingAdvance") # else Transform<PathNVMetricQuery::GlyphHorizontalBearingAdvance> GlyphHorizontalBearingAdvance; # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_X_BIT_NV # if defined GlyphVerticalBearingX # pragma push_macro("GlyphVerticalBearingX") # undef GlyphVerticalBearingX Transform<PathNVMetricQuery::GlyphVerticalBearingX> GlyphVerticalBearingX; # pragma pop_macro("GlyphVerticalBearingX") # else Transform<PathNVMetricQuery::GlyphVerticalBearingX> GlyphVerticalBearingX; # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV # if defined GlyphVerticalBearingY # pragma push_macro("GlyphVerticalBearingY") # undef GlyphVerticalBearingY Transform<PathNVMetricQuery::GlyphVerticalBearingY> GlyphVerticalBearingY; # pragma pop_macro("GlyphVerticalBearingY") # else Transform<PathNVMetricQuery::GlyphVerticalBearingY> GlyphVerticalBearingY; # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV # if defined GlyphVerticalBearingAdvance # pragma push_macro("GlyphVerticalBearingAdvance") # undef GlyphVerticalBearingAdvance Transform<PathNVMetricQuery::GlyphVerticalBearingAdvance> GlyphVerticalBearingAdvance; # pragma pop_macro("GlyphVerticalBearingAdvance") # else Transform<PathNVMetricQuery::GlyphVerticalBearingAdvance> GlyphVerticalBearingAdvance; # endif #endif #if defined GL_GLYPH_HAS_KERNING_BIT_NV # if defined GlyphHasKerning # pragma push_macro("GlyphHasKerning") # undef GlyphHasKerning Transform<PathNVMetricQuery::GlyphHasKerning> GlyphHasKerning; # pragma pop_macro("GlyphHasKerning") # else Transform<PathNVMetricQuery::GlyphHasKerning> GlyphHasKerning; # endif #endif #if defined GL_FONT_X_MIN_BOUNDS_BIT_NV # if defined FontXMinBounds # pragma push_macro("FontXMinBounds") # undef FontXMinBounds Transform<PathNVMetricQuery::FontXMinBounds> FontXMinBounds; # pragma pop_macro("FontXMinBounds") # else Transform<PathNVMetricQuery::FontXMinBounds> FontXMinBounds; # endif #endif #if defined GL_FONT_Y_MIN_BOUNDS_BIT_NV # if defined FontYMinBounds # pragma push_macro("FontYMinBounds") # undef FontYMinBounds Transform<PathNVMetricQuery::FontYMinBounds> FontYMinBounds; # pragma pop_macro("FontYMinBounds") # else Transform<PathNVMetricQuery::FontYMinBounds> FontYMinBounds; # endif #endif #if defined GL_FONT_X_MAX_BOUNDS_BIT_NV # if defined FontXMaxBounds # pragma push_macro("FontXMaxBounds") # undef FontXMaxBounds Transform<PathNVMetricQuery::FontXMaxBounds> FontXMaxBounds; # pragma pop_macro("FontXMaxBounds") # else Transform<PathNVMetricQuery::FontXMaxBounds> FontXMaxBounds; # endif #endif #if defined GL_FONT_Y_MAX_BOUNDS_BIT_NV # if defined FontYMaxBounds # pragma push_macro("FontYMaxBounds") # undef FontYMaxBounds Transform<PathNVMetricQuery::FontYMaxBounds> FontYMaxBounds; # pragma pop_macro("FontYMaxBounds") # else Transform<PathNVMetricQuery::FontYMaxBounds> FontYMaxBounds; # endif #endif #if defined GL_FONT_UNITS_PER_EM_BIT_NV # if defined FontUnitsPerEm # pragma push_macro("FontUnitsPerEm") # undef FontUnitsPerEm Transform<PathNVMetricQuery::FontUnitsPerEm> FontUnitsPerEm; # pragma pop_macro("FontUnitsPerEm") # else Transform<PathNVMetricQuery::FontUnitsPerEm> FontUnitsPerEm; # endif #endif #if defined GL_FONT_ASCENDER_BIT_NV # if defined FontAscender # pragma push_macro("FontAscender") # undef FontAscender Transform<PathNVMetricQuery::FontAscender> FontAscender; # pragma pop_macro("FontAscender") # else Transform<PathNVMetricQuery::FontAscender> FontAscender; # endif #endif #if defined GL_FONT_DESCENDER_BIT_NV # if defined FontDescender # pragma push_macro("FontDescender") # undef FontDescender Transform<PathNVMetricQuery::FontDescender> FontDescender; # pragma pop_macro("FontDescender") # else Transform<PathNVMetricQuery::FontDescender> FontDescender; # endif #endif #if defined GL_FONT_HEIGHT_BIT_NV # if defined FontHeight # pragma push_macro("FontHeight") # undef FontHeight Transform<PathNVMetricQuery::FontHeight> FontHeight; # pragma pop_macro("FontHeight") # else Transform<PathNVMetricQuery::FontHeight> FontHeight; # endif #endif #if defined GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV # if defined FontMaxAdvanceWidth # pragma push_macro("FontMaxAdvanceWidth") # undef FontMaxAdvanceWidth Transform<PathNVMetricQuery::FontMaxAdvanceWidth> FontMaxAdvanceWidth; # pragma pop_macro("FontMaxAdvanceWidth") # else Transform<PathNVMetricQuery::FontMaxAdvanceWidth> FontMaxAdvanceWidth; # endif #endif #if defined GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV # if defined FontMaxAdvanceHeight # pragma push_macro("FontMaxAdvanceHeight") # undef FontMaxAdvanceHeight Transform<PathNVMetricQuery::FontMaxAdvanceHeight> FontMaxAdvanceHeight; # pragma pop_macro("FontMaxAdvanceHeight") # else Transform<PathNVMetricQuery::FontMaxAdvanceHeight> FontMaxAdvanceHeight; # endif #endif #if defined GL_FONT_UNDERLINE_POSITION_BIT_NV # if defined FontUnderlinePosition # pragma push_macro("FontUnderlinePosition") # undef FontUnderlinePosition Transform<PathNVMetricQuery::FontUnderlinePosition> FontUnderlinePosition; # pragma pop_macro("FontUnderlinePosition") # else Transform<PathNVMetricQuery::FontUnderlinePosition> FontUnderlinePosition; # endif #endif #if defined GL_FONT_UNDERLINE_THICKNESS_BIT_NV # if defined FontUnderlineThickness # pragma push_macro("FontUnderlineThickness") # undef FontUnderlineThickness Transform<PathNVMetricQuery::FontUnderlineThickness> FontUnderlineThickness; # pragma pop_macro("FontUnderlineThickness") # else Transform<PathNVMetricQuery::FontUnderlineThickness> FontUnderlineThickness; # endif #endif #if defined GL_FONT_HAS_KERNING_BIT_NV # if defined FontHasKerning # pragma push_macro("FontHasKerning") # undef FontHasKerning Transform<PathNVMetricQuery::FontHasKerning> FontHasKerning; # pragma pop_macro("FontHasKerning") # else Transform<PathNVMetricQuery::FontHasKerning> FontHasKerning; # endif #endif EnumToClass(void) { } EnumToClass(Base&& base) : Base(std::move(base)) #if defined GL_GLYPH_WIDTH_BIT_NV # if defined GlyphWidth # pragma push_macro("GlyphWidth") # undef GlyphWidth , GlyphWidth(_base()) # pragma pop_macro("GlyphWidth") # else , GlyphWidth(_base()) # endif #endif #if defined GL_GLYPH_HEIGHT_BIT_NV # if defined GlyphHeight # pragma push_macro("GlyphHeight") # undef GlyphHeight , GlyphHeight(_base()) # pragma pop_macro("GlyphHeight") # else , GlyphHeight(_base()) # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV # if defined GlyphHorizontalBearingX # pragma push_macro("GlyphHorizontalBearingX") # undef GlyphHorizontalBearingX , GlyphHorizontalBearingX(_base()) # pragma pop_macro("GlyphHorizontalBearingX") # else , GlyphHorizontalBearingX(_base()) # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV # if defined GlyphHorizontalBearingY # pragma push_macro("GlyphHorizontalBearingY") # undef GlyphHorizontalBearingY , GlyphHorizontalBearingY(_base()) # pragma pop_macro("GlyphHorizontalBearingY") # else , GlyphHorizontalBearingY(_base()) # endif #endif #if defined GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV # if defined GlyphHorizontalBearingAdvance # pragma push_macro("GlyphHorizontalBearingAdvance") # undef GlyphHorizontalBearingAdvance , GlyphHorizontalBearingAdvance(_base()) # pragma pop_macro("GlyphHorizontalBearingAdvance") # else , GlyphHorizontalBearingAdvance(_base()) # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_X_BIT_NV # if defined GlyphVerticalBearingX # pragma push_macro("GlyphVerticalBearingX") # undef GlyphVerticalBearingX , GlyphVerticalBearingX(_base()) # pragma pop_macro("GlyphVerticalBearingX") # else , GlyphVerticalBearingX(_base()) # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV # if defined GlyphVerticalBearingY # pragma push_macro("GlyphVerticalBearingY") # undef GlyphVerticalBearingY , GlyphVerticalBearingY(_base()) # pragma pop_macro("GlyphVerticalBearingY") # else , GlyphVerticalBearingY(_base()) # endif #endif #if defined GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV # if defined GlyphVerticalBearingAdvance # pragma push_macro("GlyphVerticalBearingAdvance") # undef GlyphVerticalBearingAdvance , GlyphVerticalBearingAdvance(_base()) # pragma pop_macro("GlyphVerticalBearingAdvance") # else , GlyphVerticalBearingAdvance(_base()) # endif #endif #if defined GL_GLYPH_HAS_KERNING_BIT_NV # if defined GlyphHasKerning # pragma push_macro("GlyphHasKerning") # undef GlyphHasKerning , GlyphHasKerning(_base()) # pragma pop_macro("GlyphHasKerning") # else , GlyphHasKerning(_base()) # endif #endif #if defined GL_FONT_X_MIN_BOUNDS_BIT_NV # if defined FontXMinBounds # pragma push_macro("FontXMinBounds") # undef FontXMinBounds , FontXMinBounds(_base()) # pragma pop_macro("FontXMinBounds") # else , FontXMinBounds(_base()) # endif #endif #if defined GL_FONT_Y_MIN_BOUNDS_BIT_NV # if defined FontYMinBounds # pragma push_macro("FontYMinBounds") # undef FontYMinBounds , FontYMinBounds(_base()) # pragma pop_macro("FontYMinBounds") # else , FontYMinBounds(_base()) # endif #endif #if defined GL_FONT_X_MAX_BOUNDS_BIT_NV # if defined FontXMaxBounds # pragma push_macro("FontXMaxBounds") # undef FontXMaxBounds , FontXMaxBounds(_base()) # pragma pop_macro("FontXMaxBounds") # else , FontXMaxBounds(_base()) # endif #endif #if defined GL_FONT_Y_MAX_BOUNDS_BIT_NV # if defined FontYMaxBounds # pragma push_macro("FontYMaxBounds") # undef FontYMaxBounds , FontYMaxBounds(_base()) # pragma pop_macro("FontYMaxBounds") # else , FontYMaxBounds(_base()) # endif #endif #if defined GL_FONT_UNITS_PER_EM_BIT_NV # if defined FontUnitsPerEm # pragma push_macro("FontUnitsPerEm") # undef FontUnitsPerEm , FontUnitsPerEm(_base()) # pragma pop_macro("FontUnitsPerEm") # else , FontUnitsPerEm(_base()) # endif #endif #if defined GL_FONT_ASCENDER_BIT_NV # if defined FontAscender # pragma push_macro("FontAscender") # undef FontAscender , FontAscender(_base()) # pragma pop_macro("FontAscender") # else , FontAscender(_base()) # endif #endif #if defined GL_FONT_DESCENDER_BIT_NV # if defined FontDescender # pragma push_macro("FontDescender") # undef FontDescender , FontDescender(_base()) # pragma pop_macro("FontDescender") # else , FontDescender(_base()) # endif #endif #if defined GL_FONT_HEIGHT_BIT_NV # if defined FontHeight # pragma push_macro("FontHeight") # undef FontHeight , FontHeight(_base()) # pragma pop_macro("FontHeight") # else , FontHeight(_base()) # endif #endif #if defined GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV # if defined FontMaxAdvanceWidth # pragma push_macro("FontMaxAdvanceWidth") # undef FontMaxAdvanceWidth , FontMaxAdvanceWidth(_base()) # pragma pop_macro("FontMaxAdvanceWidth") # else , FontMaxAdvanceWidth(_base()) # endif #endif #if defined GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV # if defined FontMaxAdvanceHeight # pragma push_macro("FontMaxAdvanceHeight") # undef FontMaxAdvanceHeight , FontMaxAdvanceHeight(_base()) # pragma pop_macro("FontMaxAdvanceHeight") # else , FontMaxAdvanceHeight(_base()) # endif #endif #if defined GL_FONT_UNDERLINE_POSITION_BIT_NV # if defined FontUnderlinePosition # pragma push_macro("FontUnderlinePosition") # undef FontUnderlinePosition , FontUnderlinePosition(_base()) # pragma pop_macro("FontUnderlinePosition") # else , FontUnderlinePosition(_base()) # endif #endif #if defined GL_FONT_UNDERLINE_THICKNESS_BIT_NV # if defined FontUnderlineThickness # pragma push_macro("FontUnderlineThickness") # undef FontUnderlineThickness , FontUnderlineThickness(_base()) # pragma pop_macro("FontUnderlineThickness") # else , FontUnderlineThickness(_base()) # endif #endif #if defined GL_FONT_HAS_KERNING_BIT_NV # if defined FontHasKerning # pragma push_macro("FontHasKerning") # undef FontHasKerning , FontHasKerning(_base()) # pragma pop_macro("FontHasKerning") # else , FontHasKerning(_base()) # endif #endif { } }; } // namespace enums
30.391489
91
0.810067
Extrunder
a8e1b70c01acc3aea8a195d5fd755ddd493f8e7b
33,182
cpp
C++
benchmark/create_complex/fruit.cpp
dan-42/di
3253bfd841d03d75f7b70c05ac3789b605337deb
[ "BSL-1.0" ]
null
null
null
benchmark/create_complex/fruit.cpp
dan-42/di
3253bfd841d03d75f7b70c05ac3789b605337deb
[ "BSL-1.0" ]
null
null
null
benchmark/create_complex/fruit.cpp
dan-42/di
3253bfd841d03d75f7b70c05ac3789b605337deb
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2012-2019 Kris Jusiak (kris at jusiak dot net) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <memory> #include <fruit/fruit.h> // clang-format off struct X00 { INJECT(X00()) { } }; struct X01 { INJECT(X01(X00)) { } }; struct X02 { INJECT(X02(X00, X01)) { } }; struct X03 { INJECT(X03(X00, X01, X02)) { } }; struct X04 { INJECT(X04(X00, X01, X02, X03)) { } }; struct X05 { INJECT(X05(X00, X01, X02, X03, X04)) { } }; struct X06 { INJECT(X06(X00, X01, X02, X03, X04, X05)) { } }; struct X07 { INJECT(X07(X00, X01, X02, X03, X04, X05, X06)) { } }; struct X08 { INJECT(X08(X00, X01, X02, X03, X04, X05, X06, X07)) { } }; struct X09 { INJECT(X09(X00, X01, X02, X03, X04, X05, X06, X07, X08)) { } }; struct X10 { INJECT(X10(X00, X01, X02, X03, X04, X05, X06, X07, X08, X09)) { } }; struct X11 { INJECT(X11(X01, X02, X03, X04, X05, X06, X07, X08, X09, X10)) { } }; struct X12 { INJECT(X12(X02, X03, X04, X05, X06, X07, X08, X09, X10, X11)) { } }; struct X13 { INJECT(X13(X03, X04, X05, X06, X07, X08, X09, X10, X11, X12)) { } }; struct X14 { INJECT(X14(X04, X05, X06, X07, X08, X09, X10, X11, X12, X13)) { } }; struct X15 { INJECT(X15(X05, X06, X07, X08, X09, X10, X11, X12, X13, X14)) { } }; struct X16 { INJECT(X16(X06, X07, X08, X09, X10, X11, X12, X13, X14, X15)) { } }; struct X17 { INJECT(X17(X07, X08, X09, X10, X11, X12, X13, X14, X15, X16)) { } }; struct X18 { INJECT(X18(X08, X09, X10, X11, X12, X13, X14, X15, X16, X17)) { } }; struct X19 { INJECT(X19(X09, X10, X11, X12, X13, X14, X15, X16, X17, X18)) { } }; struct X20 { INJECT(X20(X10, X11, X12, X13, X14, X15, X16, X17, X18, X19)) { } }; struct X21 { INJECT(X21(X11, X12, X13, X14, X15, X16, X17, X18, X19, X20)) { } }; struct X22 { INJECT(X22(X12, X13, X14, X15, X16, X17, X18, X19, X20, X21)) { } }; struct X23 { INJECT(X23(X13, X14, X15, X16, X17, X18, X19, X20, X21, X22)) { } }; struct X24 { INJECT(X24(X14, X15, X16, X17, X18, X19, X20, X21, X22, X23)) { } }; struct X25 { INJECT(X25(X15, X16, X17, X18, X19, X20, X21, X22, X23, X24)) { } }; struct X26 { INJECT(X26(X16, X17, X18, X19, X20, X21, X22, X23, X24, X25)) { } }; struct X27 { INJECT(X27(X17, X18, X19, X20, X21, X22, X23, X24, X25, X26)) { } }; struct X28 { INJECT(X28(X18, X19, X20, X21, X22, X23, X24, X25, X26, X27)) { } }; struct X29 { INJECT(X29(X19, X20, X21, X22, X23, X24, X25, X26, X27, X28)) { } }; struct X30 { INJECT(X30(X20, X21, X22, X23, X24, X25, X26, X27, X28, X29)) { } }; struct X31 { INJECT(X31(X21, X22, X23, X24, X25, X26, X27, X28, X29, X30)) { } }; struct X32 { INJECT(X32(X22, X23, X24, X25, X26, X27, X28, X29, X30, X31)) { } }; struct X33 { INJECT(X33(X23, X24, X25, X26, X27, X28, X29, X30, X31, X32)) { } }; struct X34 { INJECT(X34(X24, X25, X26, X27, X28, X29, X30, X31, X32, X33)) { } }; struct X35 { INJECT(X35(X25, X26, X27, X28, X29, X30, X31, X32, X33, X34)) { } }; struct X36 { INJECT(X36(X26, X27, X28, X29, X30, X31, X32, X33, X34, X35)) { } }; struct X37 { INJECT(X37(X27, X28, X29, X30, X31, X32, X33, X34, X35, X36)) { } }; struct X38 { INJECT(X38(X28, X29, X30, X31, X32, X33, X34, X35, X36, X37)) { } }; struct X39 { INJECT(X39(X29, X30, X31, X32, X33, X34, X35, X36, X37, X38)) { } }; struct X40 { INJECT(X40(X30, X31, X32, X33, X34, X35, X36, X37, X38, X39)) { } }; struct X41 { INJECT(X41(X31, X32, X33, X34, X35, X36, X37, X38, X39, X40)) { } }; struct X42 { INJECT(X42(X32, X33, X34, X35, X36, X37, X38, X39, X40, X41)) { } }; struct X43 { INJECT(X43(X33, X34, X35, X36, X37, X38, X39, X40, X41, X42)) { } }; struct X44 { INJECT(X44(X34, X35, X36, X37, X38, X39, X40, X41, X42, X43)) { } }; struct X45 { INJECT(X45(X35, X36, X37, X38, X39, X40, X41, X42, X43, X44)) { } }; struct X46 { INJECT(X46(X36, X37, X38, X39, X40, X41, X42, X43, X44, X45)) { } }; struct X47 { INJECT(X47(X37, X38, X39, X40, X41, X42, X43, X44, X45, X46)) { } }; struct X48 { INJECT(X48(X38, X39, X40, X41, X42, X43, X44, X45, X46, X47)) { } }; struct X49 { INJECT(X49(X39, X40, X41, X42, X43, X44, X45, X46, X47, X48)) { } }; struct X50 { INJECT(X50(X40, X41, X42, X43, X44, X45, X46, X47, X48, X49)) { } }; struct X51 { INJECT(X51(X41, X42, X43, X44, X45, X46, X47, X48, X49, X50)) { } }; struct X52 { INJECT(X52(X42, X43, X44, X45, X46, X47, X48, X49, X50, X51)) { } }; struct X53 { INJECT(X53(X43, X44, X45, X46, X47, X48, X49, X50, X51, X52)) { } }; struct X54 { INJECT(X54(X44, X45, X46, X47, X48, X49, X50, X51, X52, X53)) { } }; struct X55 { INJECT(X55(X45, X46, X47, X48, X49, X50, X51, X52, X53, X54)) { } }; struct X56 { INJECT(X56(X46, X47, X48, X49, X50, X51, X52, X53, X54, X55)) { } }; struct X57 { INJECT(X57(X47, X48, X49, X50, X51, X52, X53, X54, X55, X56)) { } }; struct X58 { INJECT(X58(X48, X49, X50, X51, X52, X53, X54, X55, X56, X57)) { } }; struct X59 { INJECT(X59(X49, X50, X51, X52, X53, X54, X55, X56, X57, X58)) { } }; struct X60 { INJECT(X60(X50, X51, X52, X53, X54, X55, X56, X57, X58, X59)) { } }; struct X61 { INJECT(X61(X51, X52, X53, X54, X55, X56, X57, X58, X59, X60)) { } }; struct X62 { INJECT(X62(X52, X53, X54, X55, X56, X57, X58, X59, X60, X61)) { } }; struct X63 { INJECT(X63(X53, X54, X55, X56, X57, X58, X59, X60, X61, X62)) { } }; struct X64 { INJECT(X64(X54, X55, X56, X57, X58, X59, X60, X61, X62, X63)) { } }; struct X65 { INJECT(X65(X55, X56, X57, X58, X59, X60, X61, X62, X63, X64)) { } }; struct X66 { INJECT(X66(X56, X57, X58, X59, X60, X61, X62, X63, X64, X65)) { } }; struct X67 { INJECT(X67(X57, X58, X59, X60, X61, X62, X63, X64, X65, X66)) { } }; struct X68 { INJECT(X68(X58, X59, X60, X61, X62, X63, X64, X65, X66, X67)) { } }; struct X69 { INJECT(X69(X59, X60, X61, X62, X63, X64, X65, X66, X67, X68)) { } }; struct X70 { INJECT(X70(X60, X61, X62, X63, X64, X65, X66, X67, X68, X69)) { } }; struct X71 { INJECT(X71(X61, X62, X63, X64, X65, X66, X67, X68, X69, X70)) { } }; struct X72 { INJECT(X72(X62, X63, X64, X65, X66, X67, X68, X69, X70, X71)) { } }; struct X73 { INJECT(X73(X63, X64, X65, X66, X67, X68, X69, X70, X71, X72)) { } }; struct X74 { INJECT(X74(X64, X65, X66, X67, X68, X69, X70, X71, X72, X73)) { } }; struct X75 { INJECT(X75(X65, X66, X67, X68, X69, X70, X71, X72, X73, X74)) { } }; struct X76 { INJECT(X76(X66, X67, X68, X69, X70, X71, X72, X73, X74, X75)) { } }; struct X77 { INJECT(X77(X67, X68, X69, X70, X71, X72, X73, X74, X75, X76)) { } }; struct X78 { INJECT(X78(X68, X69, X70, X71, X72, X73, X74, X75, X76, X77)) { } }; struct X79 { INJECT(X79(X69, X70, X71, X72, X73, X74, X75, X76, X77, X78)) { } }; struct X80 { INJECT(X80(X70, X71, X72, X73, X74, X75, X76, X77, X78, X79)) { } }; struct X81 { INJECT(X81(X71, X72, X73, X74, X75, X76, X77, X78, X79, X80)) { } }; struct X82 { INJECT(X82(X72, X73, X74, X75, X76, X77, X78, X79, X80, X81)) { } }; struct X83 { INJECT(X83(X73, X74, X75, X76, X77, X78, X79, X80, X81, X82)) { } }; struct X84 { INJECT(X84(X74, X75, X76, X77, X78, X79, X80, X81, X82, X83)) { } }; struct X85 { INJECT(X85(X75, X76, X77, X78, X79, X80, X81, X82, X83, X84)) { } }; struct X86 { INJECT(X86(X76, X77, X78, X79, X80, X81, X82, X83, X84, X85)) { } }; struct X87 { INJECT(X87(X77, X78, X79, X80, X81, X82, X83, X84, X85, X86)) { } }; struct X88 { INJECT(X88(X78, X79, X80, X81, X82, X83, X84, X85, X86, X87)) { } }; struct X89 { INJECT(X89(X79, X80, X81, X82, X83, X84, X85, X86, X87, X88)) { } }; struct X90 { INJECT(X90(X80, X81, X82, X83, X84, X85, X86, X87, X88, X89)) { } }; struct X91 { INJECT(X91(X81, X82, X83, X84, X85, X86, X87, X88, X89, X90)) { } }; struct X92 { INJECT(X92(X82, X83, X84, X85, X86, X87, X88, X89, X90, X91)) { } }; struct X93 { INJECT(X93(X83, X84, X85, X86, X87, X88, X89, X90, X91, X92)) { } }; struct X94 { INJECT(X94(X84, X85, X86, X87, X88, X89, X90, X91, X92, X93)) { } }; struct X95 { INJECT(X95(X85, X86, X87, X88, X89, X90, X91, X92, X93, X94)) { } }; struct X96 { INJECT(X96(X86, X87, X88, X89, X90, X91, X92, X93, X94, X95)) { } }; struct X97 { INJECT(X97(X87, X88, X89, X90, X91, X92, X93, X94, X95, X96)) { } }; struct X98 { INJECT(X98(X88, X89, X90, X91, X92, X93, X94, X95, X96, X97)) { } }; struct X99 { INJECT(X99(X89, X90, X91, X92, X93, X94, X95, X96, X97, X98)) { } }; struct I00 { virtual ~I00() noexcept = default; virtual void dummy() = 0; }; struct Impl00 : I00 { INJECT(Impl00(X00, X01, X02, X03, X04, X05, X06, X07, X08, X09)) { } void dummy() override { } }; struct I01 { virtual ~I01() noexcept = default; virtual void dummy() = 0; }; struct Impl01 : I01 { INJECT(Impl01(X01, X02, X03, X04, X05, X06, X07, X08, X09, X10)) { } void dummy() override { } }; struct I02 { virtual ~I02() noexcept = default; virtual void dummy() = 0; }; struct Impl02 : I02 { INJECT(Impl02(X02, X03, X04, X05, X06, X07, X08, X09, X10, X11)) { } void dummy() override { } }; struct I03 { virtual ~I03() noexcept = default; virtual void dummy() = 0; }; struct Impl03 : I03 { INJECT(Impl03(X03, X04, X05, X06, X07, X08, X09, X10, X11, X12)) { } void dummy() override { } }; struct I04 { virtual ~I04() noexcept = default; virtual void dummy() = 0; }; struct Impl04 : I04 { INJECT(Impl04(X04, X05, X06, X07, X08, X09, X10, X11, X12, X13)) { } void dummy() override { } }; struct I05 { virtual ~I05() noexcept = default; virtual void dummy() = 0; }; struct Impl05 : I05 { INJECT(Impl05(X05, X06, X07, X08, X09, X10, X11, X12, X13, X14)) { } void dummy() override { } }; struct I06 { virtual ~I06() noexcept = default; virtual void dummy() = 0; }; struct Impl06 : I06 { INJECT(Impl06(X06, X07, X08, X09, X10, X11, X12, X13, X14, X15)) { } void dummy() override { } }; struct I07 { virtual ~I07() noexcept = default; virtual void dummy() = 0; }; struct Impl07 : I07 { INJECT(Impl07(X07, X08, X09, X10, X11, X12, X13, X14, X15, X16)) { } void dummy() override { } }; struct I08 { virtual ~I08() noexcept = default; virtual void dummy() = 0; }; struct Impl08 : I08 { INJECT(Impl08(X08, X09, X10, X11, X12, X13, X14, X15, X16, X17)) { } void dummy() override { } }; struct I09 { virtual ~I09() noexcept = default; virtual void dummy() = 0; }; struct Impl09 : I09 { INJECT(Impl09(X09, X10, X11, X12, X13, X14, X15, X16, X17, X18)) { } void dummy() override { } }; struct I10 { virtual ~I10() noexcept = default; virtual void dummy() = 0; }; struct Impl10 : I10 { INJECT(Impl10(X10, X11, X12, X13, X14, X15, X16, X17, X18, X19)) { } void dummy() override { } }; struct I11 { virtual ~I11() noexcept = default; virtual void dummy() = 0; }; struct Impl11 : I11 { INJECT(Impl11(X11, X12, X13, X14, X15, X16, X17, X18, X19, X20)) { } void dummy() override { } }; struct I12 { virtual ~I12() noexcept = default; virtual void dummy() = 0; }; struct Impl12 : I12 { INJECT(Impl12(X12, X13, X14, X15, X16, X17, X18, X19, X20, X21)) { } void dummy() override { } }; struct I13 { virtual ~I13() noexcept = default; virtual void dummy() = 0; }; struct Impl13 : I13 { INJECT(Impl13(X13, X14, X15, X16, X17, X18, X19, X20, X21, X22)) { } void dummy() override { } }; struct I14 { virtual ~I14() noexcept = default; virtual void dummy() = 0; }; struct Impl14 : I14 { INJECT(Impl14(X14, X15, X16, X17, X18, X19, X20, X21, X22, X23)) { } void dummy() override { } }; struct I15 { virtual ~I15() noexcept = default; virtual void dummy() = 0; }; struct Impl15 : I15 { INJECT(Impl15(X15, X16, X17, X18, X19, X20, X21, X22, X23, X24)) { } void dummy() override { } }; struct I16 { virtual ~I16() noexcept = default; virtual void dummy() = 0; }; struct Impl16 : I16 { INJECT(Impl16(X16, X17, X18, X19, X20, X21, X22, X23, X24, X25)) { } void dummy() override { } }; struct I17 { virtual ~I17() noexcept = default; virtual void dummy() = 0; }; struct Impl17 : I17 { INJECT(Impl17(X17, X18, X19, X20, X21, X22, X23, X24, X25, X26)) { } void dummy() override { } }; struct I18 { virtual ~I18() noexcept = default; virtual void dummy() = 0; }; struct Impl18 : I18 { INJECT(Impl18(X18, X19, X20, X21, X22, X23, X24, X25, X26, X27)) { } void dummy() override { } }; struct I19 { virtual ~I19() noexcept = default; virtual void dummy() = 0; }; struct Impl19 : I19 { INJECT(Impl19(X19, X20, X21, X22, X23, X24, X25, X26, X27, X28)) { } void dummy() override { } }; struct I20 { virtual ~I20() noexcept = default; virtual void dummy() = 0; }; struct Impl20 : I20 { INJECT(Impl20(X20, X21, X22, X23, X24, X25, X26, X27, X28, X29)) { } void dummy() override { } }; struct I21 { virtual ~I21() noexcept = default; virtual void dummy() = 0; }; struct Impl21 : I21 { INJECT(Impl21(X21, X22, X23, X24, X25, X26, X27, X28, X29, X30)) { } void dummy() override { } }; struct I22 { virtual ~I22() noexcept = default; virtual void dummy() = 0; }; struct Impl22 : I22 { INJECT(Impl22(X22, X23, X24, X25, X26, X27, X28, X29, X30, X31)) { } void dummy() override { } }; struct I23 { virtual ~I23() noexcept = default; virtual void dummy() = 0; }; struct Impl23 : I23 { INJECT(Impl23(X23, X24, X25, X26, X27, X28, X29, X30, X31, X32)) { } void dummy() override { } }; struct I24 { virtual ~I24() noexcept = default; virtual void dummy() = 0; }; struct Impl24 : I24 { INJECT(Impl24(X24, X25, X26, X27, X28, X29, X30, X31, X32, X33)) { } void dummy() override { } }; struct I25 { virtual ~I25() noexcept = default; virtual void dummy() = 0; }; struct Impl25 : I25 { INJECT(Impl25(X25, X26, X27, X28, X29, X30, X31, X32, X33, X34)) { } void dummy() override { } }; struct I26 { virtual ~I26() noexcept = default; virtual void dummy() = 0; }; struct Impl26 : I26 { INJECT(Impl26(X26, X27, X28, X29, X30, X31, X32, X33, X34, X35)) { } void dummy() override { } }; struct I27 { virtual ~I27() noexcept = default; virtual void dummy() = 0; }; struct Impl27 : I27 { INJECT(Impl27(X27, X28, X29, X30, X31, X32, X33, X34, X35, X36)) { } void dummy() override { } }; struct I28 { virtual ~I28() noexcept = default; virtual void dummy() = 0; }; struct Impl28 : I28 { INJECT(Impl28(X28, X29, X30, X31, X32, X33, X34, X35, X36, X37)) { } void dummy() override { } }; struct I29 { virtual ~I29() noexcept = default; virtual void dummy() = 0; }; struct Impl29 : I29 { INJECT(Impl29(X29, X30, X31, X32, X33, X34, X35, X36, X37, X38)) { } void dummy() override { } }; struct I30 { virtual ~I30() noexcept = default; virtual void dummy() = 0; }; struct Impl30 : I30 { INJECT(Impl30(X30, X31, X32, X33, X34, X35, X36, X37, X38, X39)) { } void dummy() override { } }; struct I31 { virtual ~I31() noexcept = default; virtual void dummy() = 0; }; struct Impl31 : I31 { INJECT(Impl31(X31, X32, X33, X34, X35, X36, X37, X38, X39, X40)) { } void dummy() override { } }; struct I32 { virtual ~I32() noexcept = default; virtual void dummy() = 0; }; struct Impl32 : I32 { INJECT(Impl32(X32, X33, X34, X35, X36, X37, X38, X39, X40, X41)) { } void dummy() override { } }; struct I33 { virtual ~I33() noexcept = default; virtual void dummy() = 0; }; struct Impl33 : I33 { INJECT(Impl33(X33, X34, X35, X36, X37, X38, X39, X40, X41, X42)) { } void dummy() override { } }; struct I34 { virtual ~I34() noexcept = default; virtual void dummy() = 0; }; struct Impl34 : I34 { INJECT(Impl34(X34, X35, X36, X37, X38, X39, X40, X41, X42, X43)) { } void dummy() override { } }; struct I35 { virtual ~I35() noexcept = default; virtual void dummy() = 0; }; struct Impl35 : I35 { INJECT(Impl35(X35, X36, X37, X38, X39, X40, X41, X42, X43, X44)) { } void dummy() override { } }; struct I36 { virtual ~I36() noexcept = default; virtual void dummy() = 0; }; struct Impl36 : I36 { INJECT(Impl36(X36, X37, X38, X39, X40, X41, X42, X43, X44, X45)) { } void dummy() override { } }; struct I37 { virtual ~I37() noexcept = default; virtual void dummy() = 0; }; struct Impl37 : I37 { INJECT(Impl37(X37, X38, X39, X40, X41, X42, X43, X44, X45, X46)) { } void dummy() override { } }; struct I38 { virtual ~I38() noexcept = default; virtual void dummy() = 0; }; struct Impl38 : I38 { INJECT(Impl38(X38, X39, X40, X41, X42, X43, X44, X45, X46, X47)) { } void dummy() override { } }; struct I39 { virtual ~I39() noexcept = default; virtual void dummy() = 0; }; struct Impl39 : I39 { INJECT(Impl39(X39, X40, X41, X42, X43, X44, X45, X46, X47, X48)) { } void dummy() override { } }; struct I40 { virtual ~I40() noexcept = default; virtual void dummy() = 0; }; struct Impl40 : I40 { INJECT(Impl40(X40, X41, X42, X43, X44, X45, X46, X47, X48, X49)) { } void dummy() override { } }; struct I41 { virtual ~I41() noexcept = default; virtual void dummy() = 0; }; struct Impl41 : I41 { INJECT(Impl41(X41, X42, X43, X44, X45, X46, X47, X48, X49, X50)) { } void dummy() override { } }; struct I42 { virtual ~I42() noexcept = default; virtual void dummy() = 0; }; struct Impl42 : I42 { INJECT(Impl42(X42, X43, X44, X45, X46, X47, X48, X49, X50, X51)) { } void dummy() override { } }; struct I43 { virtual ~I43() noexcept = default; virtual void dummy() = 0; }; struct Impl43 : I43 { INJECT(Impl43(X43, X44, X45, X46, X47, X48, X49, X50, X51, X52)) { } void dummy() override { } }; struct I44 { virtual ~I44() noexcept = default; virtual void dummy() = 0; }; struct Impl44 : I44 { INJECT(Impl44(X44, X45, X46, X47, X48, X49, X50, X51, X52, X53)) { } void dummy() override { } }; struct I45 { virtual ~I45() noexcept = default; virtual void dummy() = 0; }; struct Impl45 : I45 { INJECT(Impl45(X45, X46, X47, X48, X49, X50, X51, X52, X53, X54)) { } void dummy() override { } }; struct I46 { virtual ~I46() noexcept = default; virtual void dummy() = 0; }; struct Impl46 : I46 { INJECT(Impl46(X46, X47, X48, X49, X50, X51, X52, X53, X54, X55)) { } void dummy() override { } }; struct I47 { virtual ~I47() noexcept = default; virtual void dummy() = 0; }; struct Impl47 : I47 { INJECT(Impl47(X47, X48, X49, X50, X51, X52, X53, X54, X55, X56)) { } void dummy() override { } }; struct I48 { virtual ~I48() noexcept = default; virtual void dummy() = 0; }; struct Impl48 : I48 { INJECT(Impl48(X48, X49, X50, X51, X52, X53, X54, X55, X56, X57)) { } void dummy() override { } }; struct I49 { virtual ~I49() noexcept = default; virtual void dummy() = 0; }; struct Impl49 : I49 { INJECT(Impl49(X49, X50, X51, X52, X53, X54, X55, X56, X57, X58)) { } void dummy() override { } }; struct I50 { virtual ~I50() noexcept = default; virtual void dummy() = 0; }; struct Impl50 : I50 { INJECT(Impl50(X50, X51, X52, X53, X54, X55, X56, X57, X58, X59)) { } void dummy() override { } }; struct I51 { virtual ~I51() noexcept = default; virtual void dummy() = 0; }; struct Impl51 : I51 { INJECT(Impl51(X51, X52, X53, X54, X55, X56, X57, X58, X59, X60)) { } void dummy() override { } }; struct I52 { virtual ~I52() noexcept = default; virtual void dummy() = 0; }; struct Impl52 : I52 { INJECT(Impl52(X52, X53, X54, X55, X56, X57, X58, X59, X60, X61)) { } void dummy() override { } }; struct I53 { virtual ~I53() noexcept = default; virtual void dummy() = 0; }; struct Impl53 : I53 { INJECT(Impl53(X53, X54, X55, X56, X57, X58, X59, X60, X61, X62)) { } void dummy() override { } }; struct I54 { virtual ~I54() noexcept = default; virtual void dummy() = 0; }; struct Impl54 : I54 { INJECT(Impl54(X54, X55, X56, X57, X58, X59, X60, X61, X62, X63)) { } void dummy() override { } }; struct I55 { virtual ~I55() noexcept = default; virtual void dummy() = 0; }; struct Impl55 : I55 { INJECT(Impl55(X55, X56, X57, X58, X59, X60, X61, X62, X63, X64)) { } void dummy() override { } }; struct I56 { virtual ~I56() noexcept = default; virtual void dummy() = 0; }; struct Impl56 : I56 { INJECT(Impl56(X56, X57, X58, X59, X60, X61, X62, X63, X64, X65)) { } void dummy() override { } }; struct I57 { virtual ~I57() noexcept = default; virtual void dummy() = 0; }; struct Impl57 : I57 { INJECT(Impl57(X57, X58, X59, X60, X61, X62, X63, X64, X65, X66)) { } void dummy() override { } }; struct I58 { virtual ~I58() noexcept = default; virtual void dummy() = 0; }; struct Impl58 : I58 { INJECT(Impl58(X58, X59, X60, X61, X62, X63, X64, X65, X66, X67)) { } void dummy() override { } }; struct I59 { virtual ~I59() noexcept = default; virtual void dummy() = 0; }; struct Impl59 : I59 { INJECT(Impl59(X59, X60, X61, X62, X63, X64, X65, X66, X67, X68)) { } void dummy() override { } }; struct I60 { virtual ~I60() noexcept = default; virtual void dummy() = 0; }; struct Impl60 : I60 { INJECT(Impl60(X60, X61, X62, X63, X64, X65, X66, X67, X68, X69)) { } void dummy() override { } }; struct I61 { virtual ~I61() noexcept = default; virtual void dummy() = 0; }; struct Impl61 : I61 { INJECT(Impl61(X61, X62, X63, X64, X65, X66, X67, X68, X69, X70)) { } void dummy() override { } }; struct I62 { virtual ~I62() noexcept = default; virtual void dummy() = 0; }; struct Impl62 : I62 { INJECT(Impl62(X62, X63, X64, X65, X66, X67, X68, X69, X70, X71)) { } void dummy() override { } }; struct I63 { virtual ~I63() noexcept = default; virtual void dummy() = 0; }; struct Impl63 : I63 { INJECT(Impl63(X63, X64, X65, X66, X67, X68, X69, X70, X71, X72)) { } void dummy() override { } }; struct I64 { virtual ~I64() noexcept = default; virtual void dummy() = 0; }; struct Impl64 : I64 { INJECT(Impl64(X64, X65, X66, X67, X68, X69, X70, X71, X72, X73)) { } void dummy() override { } }; struct I65 { virtual ~I65() noexcept = default; virtual void dummy() = 0; }; struct Impl65 : I65 { INJECT(Impl65(X65, X66, X67, X68, X69, X70, X71, X72, X73, X74)) { } void dummy() override { } }; struct I66 { virtual ~I66() noexcept = default; virtual void dummy() = 0; }; struct Impl66 : I66 { INJECT(Impl66(X66, X67, X68, X69, X70, X71, X72, X73, X74, X75)) { } void dummy() override { } }; struct I67 { virtual ~I67() noexcept = default; virtual void dummy() = 0; }; struct Impl67 : I67 { INJECT(Impl67(X67, X68, X69, X70, X71, X72, X73, X74, X75, X76)) { } void dummy() override { } }; struct I68 { virtual ~I68() noexcept = default; virtual void dummy() = 0; }; struct Impl68 : I68 { INJECT(Impl68(X68, X69, X70, X71, X72, X73, X74, X75, X76, X77)) { } void dummy() override { } }; struct I69 { virtual ~I69() noexcept = default; virtual void dummy() = 0; }; struct Impl69 : I69 { INJECT(Impl69(X69, X70, X71, X72, X73, X74, X75, X76, X77, X78)) { } void dummy() override { } }; struct I70 { virtual ~I70() noexcept = default; virtual void dummy() = 0; }; struct Impl70 : I70 { INJECT(Impl70(X70, X71, X72, X73, X74, X75, X76, X77, X78, X79)) { } void dummy() override { } }; struct I71 { virtual ~I71() noexcept = default; virtual void dummy() = 0; }; struct Impl71 : I71 { INJECT(Impl71(X71, X72, X73, X74, X75, X76, X77, X78, X79, X80)) { } void dummy() override { } }; struct I72 { virtual ~I72() noexcept = default; virtual void dummy() = 0; }; struct Impl72 : I72 { INJECT(Impl72(X72, X73, X74, X75, X76, X77, X78, X79, X80, X81)) { } void dummy() override { } }; struct I73 { virtual ~I73() noexcept = default; virtual void dummy() = 0; }; struct Impl73 : I73 { INJECT(Impl73(X73, X74, X75, X76, X77, X78, X79, X80, X81, X82)) { } void dummy() override { } }; struct I74 { virtual ~I74() noexcept = default; virtual void dummy() = 0; }; struct Impl74 : I74 { INJECT(Impl74(X74, X75, X76, X77, X78, X79, X80, X81, X82, X83)) { } void dummy() override { } }; struct I75 { virtual ~I75() noexcept = default; virtual void dummy() = 0; }; struct Impl75 : I75 { INJECT(Impl75(X75, X76, X77, X78, X79, X80, X81, X82, X83, X84)) { } void dummy() override { } }; struct I76 { virtual ~I76() noexcept = default; virtual void dummy() = 0; }; struct Impl76 : I76 { INJECT(Impl76(X76, X77, X78, X79, X80, X81, X82, X83, X84, X85)) { } void dummy() override { } }; struct I77 { virtual ~I77() noexcept = default; virtual void dummy() = 0; }; struct Impl77 : I77 { INJECT(Impl77(X77, X78, X79, X80, X81, X82, X83, X84, X85, X86)) { } void dummy() override { } }; struct I78 { virtual ~I78() noexcept = default; virtual void dummy() = 0; }; struct Impl78 : I78 { INJECT(Impl78(X78, X79, X80, X81, X82, X83, X84, X85, X86, X87)) { } void dummy() override { } }; struct I79 { virtual ~I79() noexcept = default; virtual void dummy() = 0; }; struct Impl79 : I79 { INJECT(Impl79(X79, X80, X81, X82, X83, X84, X85, X86, X87, X88)) { } void dummy() override { } }; struct I80 { virtual ~I80() noexcept = default; virtual void dummy() = 0; }; struct Impl80 : I80 { INJECT(Impl80(X80, X81, X82, X83, X84, X85, X86, X87, X88, X89)) { } void dummy() override { } }; struct I81 { virtual ~I81() noexcept = default; virtual void dummy() = 0; }; struct Impl81 : I81 { INJECT(Impl81(X81, X82, X83, X84, X85, X86, X87, X88, X89, X90)) { } void dummy() override { } }; struct I82 { virtual ~I82() noexcept = default; virtual void dummy() = 0; }; struct Impl82 : I82 { INJECT(Impl82(X82, X83, X84, X85, X86, X87, X88, X89, X90, X91)) { } void dummy() override { } }; struct I83 { virtual ~I83() noexcept = default; virtual void dummy() = 0; }; struct Impl83 : I83 { INJECT(Impl83(X83, X84, X85, X86, X87, X88, X89, X90, X91, X92)) { } void dummy() override { } }; struct I84 { virtual ~I84() noexcept = default; virtual void dummy() = 0; }; struct Impl84 : I84 { INJECT(Impl84(X84, X85, X86, X87, X88, X89, X90, X91, X92, X93)) { } void dummy() override { } }; struct I85 { virtual ~I85() noexcept = default; virtual void dummy() = 0; }; struct Impl85 : I85 { INJECT(Impl85(X85, X86, X87, X88, X89, X90, X91, X92, X93, X94)) { } void dummy() override { } }; struct I86 { virtual ~I86() noexcept = default; virtual void dummy() = 0; }; struct Impl86 : I86 { INJECT(Impl86(X86, X87, X88, X89, X90, X91, X92, X93, X94, X95)) { } void dummy() override { } }; struct I87 { virtual ~I87() noexcept = default; virtual void dummy() = 0; }; struct Impl87 : I87 { INJECT(Impl87(X87, X88, X89, X90, X91, X92, X93, X94, X95, X96)) { } void dummy() override { } }; struct I88 { virtual ~I88() noexcept = default; virtual void dummy() = 0; }; struct Impl88 : I88 { INJECT(Impl88(X88, X89, X90, X91, X92, X93, X94, X95, X96, X97)) { } void dummy() override { } }; struct I89 { virtual ~I89() noexcept = default; virtual void dummy() = 0; }; struct Impl89 : I89 { INJECT(Impl89(X89, X90, X91, X92, X93, X94, X95, X96, X97, X98)) { } void dummy() override { } }; struct I90 { virtual ~I90() noexcept = default; virtual void dummy() = 0; }; struct Impl90 : I90 { INJECT(Impl90(X90, X91, X92, X93, X94, X95, X96, X97, X98, X99)) { } void dummy() override { } }; struct I91 { virtual ~I91() noexcept = default; virtual void dummy() = 0; }; struct Impl91 : I91 { INJECT(Impl91(X91, X92, X93, X94, X95, X96, X97, X98, X99, X00)) { } void dummy() override { } }; struct I92 { virtual ~I92() noexcept = default; virtual void dummy() = 0; }; struct Impl92 : I92 { INJECT(Impl92(X92, X93, X94, X95, X96, X97, X98, X99, X00, X01)) { } void dummy() override { } }; struct I93 { virtual ~I93() noexcept = default; virtual void dummy() = 0; }; struct Impl93 : I93 { INJECT(Impl93(X93, X94, X95, X96, X97, X98, X99, X00, X01, X02)) { } void dummy() override { } }; struct I94 { virtual ~I94() noexcept = default; virtual void dummy() = 0; }; struct Impl94 : I94 { INJECT(Impl94(X94, X95, X96, X97, X98, X99, X00, X01, X02, X03)) { } void dummy() override { } }; struct I95 { virtual ~I95() noexcept = default; virtual void dummy() = 0; }; struct Impl95 : I95 { INJECT(Impl95(X95, X96, X97, X98, X99, X00, X01, X02, X03, X04)) { } void dummy() override { } }; struct I96 { virtual ~I96() noexcept = default; virtual void dummy() = 0; }; struct Impl96 : I96 { INJECT(Impl96(X96, X97, X98, X99, X00, X01, X02, X03, X04, X05)) { } void dummy() override { } }; struct I97 { virtual ~I97() noexcept = default; virtual void dummy() = 0; }; struct Impl97 : I97 { INJECT(Impl97(X97, X98, X99, X00, X01, X02, X03, X04, X05, X06)) { } void dummy() override { } }; struct I98 { virtual ~I98() noexcept = default; virtual void dummy() = 0; }; struct Impl98 : I98 { INJECT(Impl98(X98, X99, X00, X01, X02, X03, X04, X05, X06, X07)) { } void dummy() override { } }; struct I99 { virtual ~I99() noexcept = default; virtual void dummy() = 0; }; struct Impl99 : I99 { INJECT(Impl99(X99, X00, X01, X02, X03, X04, X05, X06, X07, X08)) { } void dummy() override { } }; struct C0 { INJECT(C0(std::shared_ptr<I00>, std::shared_ptr<I01>, std::shared_ptr<I02>, std::shared_ptr<I03>, std::shared_ptr<I04>, std::shared_ptr<I05>, std::shared_ptr<I06>, std::shared_ptr<I07>, std::shared_ptr<I08>, std::shared_ptr<I09>)) { } }; struct C1 { INJECT(C1(std::shared_ptr<I10>, std::shared_ptr<I11>, std::shared_ptr<I12>, std::shared_ptr<I13>, std::shared_ptr<I14>, std::shared_ptr<I15>, std::shared_ptr<I16>, std::shared_ptr<I17>, std::shared_ptr<I18>, std::shared_ptr<I19>)) { } }; struct C2 { INJECT(C2(std::shared_ptr<I20>, std::shared_ptr<I21>, std::shared_ptr<I22>, std::shared_ptr<I23>, std::shared_ptr<I24>, std::shared_ptr<I25>, std::shared_ptr<I26>, std::shared_ptr<I27>, std::shared_ptr<I28>, std::shared_ptr<I29>)) { } }; struct C3 { INJECT(C3(std::shared_ptr<I30>, std::shared_ptr<I31>, std::shared_ptr<I32>, std::shared_ptr<I33>, std::shared_ptr<I34>, std::shared_ptr<I35>, std::shared_ptr<I36>, std::shared_ptr<I37>, std::shared_ptr<I38>, std::shared_ptr<I39>)) { } }; struct C4 { INJECT(C4(std::shared_ptr<I40>, std::shared_ptr<I41>, std::shared_ptr<I42>, std::shared_ptr<I43>, std::shared_ptr<I44>, std::shared_ptr<I45>, std::shared_ptr<I46>, std::shared_ptr<I47>, std::shared_ptr<I48>, std::shared_ptr<I49>)) { } }; struct C5 { INJECT(C5(std::shared_ptr<I50>, std::shared_ptr<I51>, std::shared_ptr<I52>, std::shared_ptr<I53>, std::shared_ptr<I54>, std::shared_ptr<I55>, std::shared_ptr<I56>, std::shared_ptr<I57>, std::shared_ptr<I58>, std::shared_ptr<I59>)) { } }; struct C6 { INJECT(C6(std::shared_ptr<I60>, std::shared_ptr<I61>, std::shared_ptr<I62>, std::shared_ptr<I63>, std::shared_ptr<I64>, std::shared_ptr<I65>, std::shared_ptr<I66>, std::shared_ptr<I67>, std::shared_ptr<I68>, std::shared_ptr<I69>)) { } }; struct C7 { INJECT(C7(std::shared_ptr<I70>, std::shared_ptr<I71>, std::shared_ptr<I72>, std::shared_ptr<I73>, std::shared_ptr<I74>, std::shared_ptr<I75>, std::shared_ptr<I76>, std::shared_ptr<I77>, std::shared_ptr<I78>, std::shared_ptr<I79>)) { } }; struct C8 { INJECT(C8(std::shared_ptr<I80>, std::shared_ptr<I81>, std::shared_ptr<I82>, std::shared_ptr<I83>, std::shared_ptr<I84>, std::shared_ptr<I85>, std::shared_ptr<I86>, std::shared_ptr<I87>, std::shared_ptr<I88>, std::shared_ptr<I89>)) { } }; struct C9 { INJECT(C9(std::shared_ptr<I90>, std::shared_ptr<I91>, std::shared_ptr<I92>, std::shared_ptr<I93>, std::shared_ptr<I94>, std::shared_ptr<I95>, std::shared_ptr<I96>, std::shared_ptr<I97>, std::shared_ptr<I98>, std::shared_ptr<I99>)) { } }; struct Complex { INJECT(Complex(C0, C1, C2, C3, C4, C5, C6, C7, C8, C9)) { } }; // clang-format off fruit::Component<Complex> module() { return fruit::createComponent() .bind<I00, Impl00>() .bind<I01, Impl01>() .bind<I02, Impl02>() .bind<I03, Impl03>() .bind<I04, Impl04>() .bind<I05, Impl05>() .bind<I06, Impl06>() .bind<I07, Impl07>() .bind<I08, Impl08>() .bind<I09, Impl09>() .bind<I10, Impl10>() .bind<I11, Impl11>() .bind<I12, Impl12>() .bind<I13, Impl13>() .bind<I14, Impl14>() .bind<I15, Impl15>() .bind<I16, Impl16>() .bind<I17, Impl17>() .bind<I18, Impl18>() .bind<I19, Impl19>() .bind<I20, Impl20>() .bind<I21, Impl21>() .bind<I22, Impl22>() .bind<I23, Impl23>() .bind<I24, Impl24>() .bind<I25, Impl25>() .bind<I26, Impl26>() .bind<I27, Impl27>() .bind<I28, Impl28>() .bind<I29, Impl29>() .bind<I30, Impl30>() .bind<I31, Impl31>() .bind<I32, Impl32>() .bind<I33, Impl33>() .bind<I34, Impl34>() .bind<I35, Impl35>() .bind<I36, Impl36>() .bind<I37, Impl37>() .bind<I38, Impl38>() .bind<I39, Impl39>() .bind<I40, Impl40>() .bind<I41, Impl41>() .bind<I42, Impl42>() .bind<I43, Impl43>() .bind<I44, Impl44>() .bind<I45, Impl45>() .bind<I46, Impl46>() .bind<I47, Impl47>() .bind<I48, Impl48>() .bind<I49, Impl49>() .bind<I50, Impl50>() .bind<I51, Impl51>() .bind<I52, Impl52>() .bind<I53, Impl53>() .bind<I54, Impl54>() .bind<I55, Impl55>() .bind<I56, Impl56>() .bind<I57, Impl57>() .bind<I58, Impl58>() .bind<I59, Impl59>() .bind<I60, Impl60>() .bind<I61, Impl61>() .bind<I62, Impl62>() .bind<I63, Impl63>() .bind<I64, Impl64>() .bind<I65, Impl65>() .bind<I66, Impl66>() .bind<I67, Impl67>() .bind<I68, Impl68>() .bind<I69, Impl69>() .bind<I70, Impl70>() .bind<I71, Impl71>() .bind<I72, Impl72>() .bind<I73, Impl73>() .bind<I74, Impl74>() .bind<I75, Impl75>() .bind<I76, Impl76>() .bind<I77, Impl77>() .bind<I78, Impl78>() .bind<I79, Impl79>() .bind<I80, Impl80>() .bind<I81, Impl81>() .bind<I82, Impl82>() .bind<I83, Impl83>() .bind<I84, Impl84>() .bind<I85, Impl85>() .bind<I86, Impl86>() .bind<I87, Impl87>() .bind<I88, Impl88>() .bind<I89, Impl89>() .bind<I90, Impl90>() .bind<I91, Impl91>() .bind<I92, Impl92>() .bind<I93, Impl93>() .bind<I94, Impl94>() .bind<I95, Impl95>() .bind<I96, Impl96>() .bind<I97, Impl97>() .bind<I98, Impl98>() .bind<I99, Impl99>(); } int main() { fruit::Injector<Complex> injector{module()}; injector.get<Complex>(); }
99.945783
249
0.620095
dan-42
5ef22ff91aec9f8c9a014c91b8f85944407c0115
893
cpp
C++
src/storage/appstatedb.cpp
nunchuk-io/libnunchuk
4d29efe25b5ba3b392ebebc31e58b43daa96560e
[ "MIT" ]
44
2020-11-13T19:34:31.000Z
2022-03-03T18:06:45.000Z
src/storage/appstatedb.cpp
nunchuk-io/libnunchuk
4d29efe25b5ba3b392ebebc31e58b43daa96560e
[ "MIT" ]
13
2020-12-03T17:27:23.000Z
2022-03-01T02:16:28.000Z
src/storage/appstatedb.cpp
nunchuk-io/libnunchuk
4d29efe25b5ba3b392ebebc31e58b43daa96560e
[ "MIT" ]
7
2020-11-25T08:23:48.000Z
2022-02-22T10:36:42.000Z
// Copyright (c) 2020 Enigmo // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "appstatedb.h" namespace nunchuk { void NunchukAppStateDb::Init() { CreateTable(); } int NunchukAppStateDb::GetChainTip() const { return GetInt(DbKeys::CHAIN_TIP); } bool NunchukAppStateDb::SetChainTip(int value) { return PutInt(DbKeys::CHAIN_TIP, value); } std::string NunchukAppStateDb::GetSelectedWallet() const { return GetString(DbKeys::SELECTED_WALLET); } bool NunchukAppStateDb::SetSelectedWallet(const std::string& value) { return PutString(DbKeys::SELECTED_WALLET, value); } int64_t NunchukAppStateDb::GetStorageVersion() const { return GetInt(DbKeys::VERSION); } bool NunchukAppStateDb::SetStorageVersion(int64_t value) { return PutInt(DbKeys::VERSION, value); } } // namespace nunchuk
27.060606
80
0.764838
nunchuk-io
5ef539e73db3d1a9fe40c316b995530498fb6af3
194
cpp
C++
atcoder/abc116_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
atcoder/abc116_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
atcoder/abc116_a.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> using namespace std; int n[4]; int main(){ for(int i= 0; i < 3; i++){ scanf("%d", &n[i]); } sort(n, n + 3); cout << (n[0] * n[1]) / 2 << endl; return 0; }
16.166667
36
0.469072
cosmicray001
5efa6dc76165da7ec08042ea40e80f0cef03ceb1
568
cpp
C++
leetcode/968. Binary Tree Cameras/s2.cpp
zhuohuwu0603/leetcode_cpp_lzl124631x
6a579328810ef4651de00fde0505934d3028d9c7
[ "Fair" ]
787
2017-05-12T05:19:57.000Z
2022-03-30T12:19:52.000Z
leetcode/968. Binary Tree Cameras/s2.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
8
2020-03-16T05:55:38.000Z
2022-03-09T17:19:17.000Z
leetcode/968. Binary Tree Cameras/s2.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
247
2017-04-30T15:07:50.000Z
2022-03-30T09:58:57.000Z
// OJ: https://leetcode.com/problems/binary-tree-cameras/ // Author: github.com/lzl124631x // Time: O(N) // Space: O(logN) class Solution { private: int ans = 0; int postorder(TreeNode *root) { if (!root) return 1; int left = postorder(root->left); int right = postorder(root->right); if (left == 0 || right == 0) { ++ans; return 2; } else return left == 2 || right == 2 ? 1 : 0; } public: int minCameraCover(TreeNode* root) { return postorder(root) == 0 ? ans + 1 : ans; } };
27.047619
57
0.538732
zhuohuwu0603
5efdd863cb351fa9f374bb229d969fbde03ea2cd
2,918
cc
C++
src/third_party/starboard/rdk/shared/main_rdk.cc
rmaddali991/rdk-cobalt
b2f08a80c136be75295338aeb71895d06bb6d374
[ "Apache-2.0" ]
1
2022-01-25T21:22:47.000Z
2022-01-25T21:22:47.000Z
src/third_party/starboard/rdk/shared/main_rdk.cc
rmaddali991/rdk-cobalt
b2f08a80c136be75295338aeb71895d06bb6d374
[ "Apache-2.0" ]
null
null
null
src/third_party/starboard/rdk/shared/main_rdk.cc
rmaddali991/rdk-cobalt
b2f08a80c136be75295338aeb71895d06bb6d374
[ "Apache-2.0" ]
1
2021-09-14T22:35:29.000Z
2021-09-14T22:35:29.000Z
// // Copyright 2020 Comcast Cable Communications Management, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 // // Copyright 2016 The Cobalt Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <gst/gst.h> #include <signal.h> #include "starboard/configuration.h" #include "starboard/shared/signal/crash_signals.h" #include "starboard/shared/signal/suspend_signals.h" #include "third_party/starboard/rdk/shared/application_rdk.h" namespace third_party { namespace starboard { namespace rdk { namespace shared { static struct sigaction old_actions[2]; static void RequestStop(int signal_id) { SbSystemRequestStop(0); } static void InstallStopSignalHandlers() { struct sigaction action = {0}; action.sa_handler = RequestStop; action.sa_flags = 0; ::sigemptyset(&action.sa_mask); ::sigaction(SIGINT, &action, &old_actions[0]); ::sigaction(SIGTERM, &action, &old_actions[1]); } static void UninstallStopSignalHandlers() { ::sigaction(SIGINT, &old_actions[0], NULL); ::sigaction(SIGTERM, &old_actions[1], NULL); } } // namespace shared } // namespace rdk } // namespace starboard } // namespace third_party extern "C" SB_EXPORT_PLATFORM int main(int argc, char** argv) { tzset(); GError* error = NULL; gst_init_check(NULL, NULL, &error); g_free(error); // starboard::shared::signal::InstallCrashSignalHandlers(); starboard::shared::signal::InstallSuspendSignalHandlers(); third_party::starboard::rdk::shared::InstallStopSignalHandlers(); third_party::starboard::rdk::shared::Application application; int result = application.Run(argc, argv); third_party::starboard::rdk::shared::UninstallStopSignalHandlers(); // starboard::shared::signal::UninstallCrashSignalHandlers(); starboard::shared::signal::UninstallSuspendSignalHandlers(); gst_deinit(); return result; }
31.717391
75
0.745716
rmaddali991
6f01fdd29d35bd789567ccff1060a27e0f159cca
1,735
cpp
C++
mycontainer1.cpp
bruennijs/ise.cppworkshop
c54a60ad3468f83aeb45b347657b3f246d7190cc
[ "MIT" ]
null
null
null
mycontainer1.cpp
bruennijs/ise.cppworkshop
c54a60ad3468f83aeb45b347657b3f246d7190cc
[ "MIT" ]
null
null
null
mycontainer1.cpp
bruennijs/ise.cppworkshop
c54a60ad3468f83aeb45b347657b3f246d7190cc
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <list> class MoveableString { public: MoveableString() { } ~MoveableString() { } std::string m_data; }; class Moveable { public: Moveable() { std::cout << "Moveable" << std::endl; this->m_data = new char[1024]; } ~Moveable() { std::cout << "~Moveable" << std::endl; if (this->m_data != nullptr) { delete this->m_data; } } Moveable& operator=(const Moveable& assign) { std::cout << "Moveable lvalue assigmnent" << std::endl; } /* Moveable& operator=(Moveable&& assign) { std::cout << "Moveable rvalue assigmnent" << std::endl; } */ char* m_data; }; /* template<typename E> class MyVector { public: MyVector() {} ~MyVector() { std::cout << "~MyVector" << std::endl; } MyVector(const MyVector<E>& v) : m_val(v.m_val) std::cout << "MyVector(copy)" << std::endl; } MyVector<E>& operator=(const MyVector<E> && v) { std::cout << "MyVector(copy)" << std::endl; } MyVector<E>& operator+(const MyVector<E>& obj) { std::cout << "operator+" << std::endl; this->m_val += obj.m_val; } std::list<Moveable> m_dl; }; */ template<typename E> class MyContainer { public: MyContainer() { std::cout << "MyContainer" << std::endl; } ~MyContainer() { std::cout << "~MyContainer" << std::endl; } MyContainer(const MyContainer<E>& v) : m_data(v.m_data) { std::cout << "MyContainer(copy)" << std::endl; } MyContainer<E>& operator=(const MyContainer<E> & v) { std::cout << "MyContainer assignment" << std::endl; this->m_data = v.m_data; } /* data */ E m_data; }; int main() { MyContainer<Moveable> v1; MyContainer<Moveable> v3; MyContainer<Moveable> v2 = v1; //MyVector<Moveable> v3 = v1 + v2; }
14.338843
57
0.607493
bruennijs
6f08ad7f772de4bac4598f6d7ae02cd456c0dc62
1,057
cpp
C++
TicTacToeMinMax/Field.cpp
SzymonOzog/TicTacToeCustomSizeMinMax
095cf6037c23a421c1d97b93901f17d0c3562137
[ "CC0-1.0" ]
null
null
null
TicTacToeMinMax/Field.cpp
SzymonOzog/TicTacToeCustomSizeMinMax
095cf6037c23a421c1d97b93901f17d0c3562137
[ "CC0-1.0" ]
null
null
null
TicTacToeMinMax/Field.cpp
SzymonOzog/TicTacToeCustomSizeMinMax
095cf6037c23a421c1d97b93901f17d0c3562137
[ "CC0-1.0" ]
null
null
null
#include "Field.h" #include "WinChecker.h" #include <cmath> Field::Field(int side) { pointsNeededToWin = side < 4 ? side : 4; fieldSide = side; winCheckers.push_back(new RowChecker(this)); winCheckers.push_back(new ColumnChecker(this)); winCheckers.push_back(new ForwardDiagonalChecker(this)); winCheckers.push_back(new BackwardDiagonalChecker(this)); int size = side * side; vecField.reserve(size); while (size--) vecField.emplace_back(player::None); } bool Field::isCoordWorthChecking(int coord) { int row = getRow(coord); int column = getColumn(coord); for (int y = row - 2; y <= row + 2; y++) for (int x = column - 2; x <= column + 2; x++) if (isCoordTaken(y, x)) return true; return false; } bool Field::hasWon() { for (auto winChecker : winCheckers) if (winChecker->checkAllLines()) return true; return false; } bool Field::hasWon(int i) { for (auto winChecker : winCheckers) if (winChecker->checkForWin(i)) return true; return false; } void Field::nullify() { for (auto& p : vecField) p = player::None; }
21.14
58
0.687796
SzymonOzog
6f0cf0a401c181ae1522a363c994f5dbe8b911a3
28,915
cpp
C++
src/mesh/meshblock.cpp
cnstahl/athena
52a7ead1ee9000fe0fcc61824e26adae93fac227
[ "BSD-3-Clause" ]
null
null
null
src/mesh/meshblock.cpp
cnstahl/athena
52a7ead1ee9000fe0fcc61824e26adae93fac227
[ "BSD-3-Clause" ]
null
null
null
src/mesh/meshblock.cpp
cnstahl/athena
52a7ead1ee9000fe0fcc61824e26adae93fac227
[ "BSD-3-Clause" ]
null
null
null
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== //! \file mesh.cpp // \brief implementation of functions in MeshBlock class // C/C++ headers #include <iostream> #include <sstream> #include <stdexcept> // runtime_error #include <string> // c_str() #include <algorithm> // sort #include <iomanip> #include <stdlib.h> #include <string.h> // memcpy // Athena++ classes headers #include "../athena.hpp" #include "../globals.hpp" #include "../athena_arrays.hpp" #include "../coordinates/coordinates.hpp" #include "../hydro/hydro.hpp" #include "../field/field.hpp" #include "../bvals/bvals.hpp" #include "../eos/eos.hpp" #include "../parameter_input.hpp" #include "../utils/buffer_utils.hpp" #include "../reconstruct/reconstruction.hpp" #include "mesh_refinement.hpp" #include "meshblock_tree.hpp" #include "mesh.hpp" //---------------------------------------------------------------------------------------- // MeshBlock constructor: constructs coordinate, boundary condition, hydro, field // and mesh refinement objects. MeshBlock::MeshBlock(int igid, int ilid, LogicalLocation iloc, RegionSize input_block, enum BoundaryFlag *input_bcs, Mesh *pm, ParameterInput *pin, bool ref_flag) { std::stringstream msg; int root_level; pmy_mesh = pm; root_level = pm->root_level; block_size = input_block; for(int i=0; i<6; i++) block_bcs[i] = input_bcs[i]; prev=NULL; next=NULL; gid=igid; lid=ilid; loc=iloc; cost=1.0; nuser_out_var = 0; nreal_user_meshblock_data_ = 0; nint_user_meshblock_data_ = 0; // initialize grid indices is = NGHOST; ie = is + block_size.nx1 - 1; if (block_size.nx2 > 1) { js = NGHOST; je = js + block_size.nx2 - 1; } else { js = je = 0; } if (block_size.nx3 > 1) { ks = NGHOST; ke = ks + block_size.nx3 - 1; } else { ks = ke = 0; } if(pm->multilevel==true) { cnghost=(NGHOST+1)/2+1; cis=cnghost; cie=cis+block_size.nx1/2-1; cjs=cje=cks=cke=0; if(block_size.nx2>1) // 2D or 3D cjs=cnghost, cje=cjs+block_size.nx2/2-1; if(block_size.nx3>1) // 3D cks=cnghost, cke=cks+block_size.nx3/2-1; } // construct objects stored in MeshBlock class. Note in particular that the initial // conditions for the simulation are set in problem generator called from main, not // in the Hydro constructor // mesh-related objects if (COORDINATE_SYSTEM == "cartesian") { pcoord = new Cartesian(this, pin, false); } else if (COORDINATE_SYSTEM == "cylindrical") { pcoord = new Cylindrical(this, pin, false); } else if (COORDINATE_SYSTEM == "spherical_polar") { pcoord = new SphericalPolar(this, pin, false); } else if (COORDINATE_SYSTEM == "minkowski") { pcoord = new Minkowski(this, pin, false); } else if (COORDINATE_SYSTEM == "schwarzschild") { pcoord = new Schwarzschild(this, pin, false); } else if (COORDINATE_SYSTEM == "kerr-schild") { pcoord = new KerrSchild(this, pin, false); } else if (COORDINATE_SYSTEM == "gr_user") { pcoord = new GRUser(this, pin, false); } pbval = new BoundaryValues(this, pin); if (block_bcs[INNER_X2] == POLAR_BNDRY||block_bcs[INNER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_north_polar_blocks = pmy_mesh->nrbx3 * (1 << level); polar_neighbor_north = new PolarNeighborBlock[num_north_polar_blocks]; } if (block_bcs[OUTER_X2] == POLAR_BNDRY||block_bcs[OUTER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_south_polar_blocks = pmy_mesh->nrbx3 * (1 << level); polar_neighbor_south = new PolarNeighborBlock[num_south_polar_blocks]; } precon = new Reconstruction(this, pin); if(pm->multilevel==true) pmr = new MeshRefinement(this, pin); // physics-related objects phydro = new Hydro(this, pin); if (MAGNETIC_FIELDS_ENABLED) pfield = new Field(this, pin); peos = new EquationOfState(this, pin); // Create user mesh data InitUserMeshBlockData(pin); return; } //---------------------------------------------------------------------------------------- // MeshBlock constructor for restarts MeshBlock::MeshBlock(int igid, int ilid, Mesh *pm, ParameterInput *pin, LogicalLocation iloc, RegionSize input_block, enum BoundaryFlag *input_bcs, Real icost, char *mbdata) { std::stringstream msg; pmy_mesh = pm; prev=NULL; next=NULL; gid=igid; lid=ilid; loc=iloc; cost=icost; block_size = input_block; for(int i=0; i<6; i++) block_bcs[i] = input_bcs[i]; nuser_out_var = 0; nreal_user_meshblock_data_ = 0; nint_user_meshblock_data_ = 0; // initialize grid indices is = NGHOST; ie = is + block_size.nx1 - 1; if (block_size.nx2 > 1) { js = NGHOST; je = js + block_size.nx2 - 1; } else { js = je = 0; } if (block_size.nx3 > 1) { ks = NGHOST; ke = ks + block_size.nx3 - 1; } else { ks = ke = 0; } if(pm->multilevel==true) { cnghost=(NGHOST+1)/2+1; cis=cnghost; cie=cis+block_size.nx1/2-1; cjs=cje=cks=cke=0; if(block_size.nx2>1) // 2D or 3D cjs=cnghost, cje=cjs+block_size.nx2/2-1; if(block_size.nx3>1) // 3D cks=cnghost, cke=cks+block_size.nx3/2-1; } // (re-)create mesh-related objects in MeshBlock if (COORDINATE_SYSTEM == "cartesian") { pcoord = new Cartesian(this, pin, false); } else if (COORDINATE_SYSTEM == "cylindrical") { pcoord = new Cylindrical(this, pin, false); } else if (COORDINATE_SYSTEM == "spherical_polar") { pcoord = new SphericalPolar(this, pin, false); } else if (COORDINATE_SYSTEM == "minkowski") { pcoord = new Minkowski(this, pin, false); } else if (COORDINATE_SYSTEM == "schwarzschild") { pcoord = new Schwarzschild(this, pin, false); } else if (COORDINATE_SYSTEM == "kerr-schild") { pcoord = new KerrSchild(this, pin, false); } else if (COORDINATE_SYSTEM == "gr_user") { pcoord = new GRUser(this, pin, false); } pbval = new BoundaryValues(this, pin); if (block_bcs[INNER_X2] == POLAR_BNDRY||block_bcs[INNER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_north_polar_blocks = pmy_mesh->nrbx3 * (1 << level); polar_neighbor_north = new PolarNeighborBlock[num_north_polar_blocks]; } if (block_bcs[OUTER_X2] == POLAR_BNDRY||block_bcs[OUTER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_south_polar_blocks = pmy_mesh->nrbx3 * (1 << level); polar_neighbor_south = new PolarNeighborBlock[num_south_polar_blocks]; } precon = new Reconstruction(this, pin); if(pm->multilevel==true) pmr = new MeshRefinement(this, pin); // (re-)create physics-related objects in MeshBlock phydro = new Hydro(this, pin); if (MAGNETIC_FIELDS_ENABLED) pfield = new Field(this, pin); peos = new EquationOfState(this, pin); InitUserMeshBlockData(pin); // load hydro and field data int os=0; memcpy(phydro->u.data(), &(mbdata[os]), phydro->u.GetSizeInBytes()); // load it into the half-step arrays too memcpy(phydro->u1.data(), &(mbdata[os]), phydro->u1.GetSizeInBytes()); os += phydro->u.GetSizeInBytes(); if (GENERAL_RELATIVITY) { memcpy(phydro->w.data(), &(mbdata[os]), phydro->w.GetSizeInBytes()); os += phydro->w.GetSizeInBytes(); memcpy(phydro->w1.data(), &(mbdata[os]), phydro->w1.GetSizeInBytes()); os += phydro->w1.GetSizeInBytes(); } if (MAGNETIC_FIELDS_ENABLED) { memcpy(pfield->b.x1f.data(), &(mbdata[os]), pfield->b.x1f.GetSizeInBytes()); memcpy(pfield->b1.x1f.data(), &(mbdata[os]), pfield->b1.x1f.GetSizeInBytes()); os += pfield->b.x1f.GetSizeInBytes(); memcpy(pfield->b.x2f.data(), &(mbdata[os]), pfield->b.x2f.GetSizeInBytes()); memcpy(pfield->b1.x2f.data(), &(mbdata[os]), pfield->b1.x2f.GetSizeInBytes()); os += pfield->b.x2f.GetSizeInBytes(); memcpy(pfield->b.x3f.data(), &(mbdata[os]), pfield->b.x3f.GetSizeInBytes()); memcpy(pfield->b1.x3f.data(), &(mbdata[os]), pfield->b1.x3f.GetSizeInBytes()); os += pfield->b.x3f.GetSizeInBytes(); } // NEW_PHYSICS: add load of new physics from restart file here // load user MeshBlock data for(int n=0; n<nint_user_meshblock_data_; n++) { memcpy(iuser_meshblock_data[n].data(), &(mbdata[os]), iuser_meshblock_data[n].GetSizeInBytes()); os+=iuser_meshblock_data[n].GetSizeInBytes(); } for(int n=0; n<nreal_user_meshblock_data_; n++) { memcpy(ruser_meshblock_data[n].data(), &(mbdata[os]), ruser_meshblock_data[n].GetSizeInBytes()); os+=ruser_meshblock_data[n].GetSizeInBytes(); } return; } //---------------------------------------------------------------------------------------- // MeshBlock destructor MeshBlock::~MeshBlock() { if(prev!=NULL) prev->next=next; if(next!=NULL) next->prev=prev; delete pcoord; if (block_bcs[INNER_X2] == POLAR_BNDRY||block_bcs[INNER_X2] == POLAR_BNDRY_WEDGE) delete[] polar_neighbor_north; if (block_bcs[OUTER_X2] == POLAR_BNDRY||block_bcs[OUTER_X2] == POLAR_BNDRY_WEDGE) delete[] polar_neighbor_south; delete pbval; delete precon; if (pmy_mesh->multilevel == true) delete pmr; delete phydro; if (MAGNETIC_FIELDS_ENABLED) delete pfield; delete peos; // delete user output variables array if(nuser_out_var > 0) { user_out_var.DeleteAthenaArray(); delete [] user_out_var_names_; } // delete user MeshBlock data for(int n=0; n<nreal_user_meshblock_data_; n++) ruser_meshblock_data[n].DeleteAthenaArray(); if(nreal_user_meshblock_data_>0) delete [] ruser_meshblock_data; for(int n=0; n<nint_user_meshblock_data_; n++) iuser_meshblock_data[n].DeleteAthenaArray(); if(nint_user_meshblock_data_>0) delete [] iuser_meshblock_data; } //---------------------------------------------------------------------------------------- //! \fn void MeshBlock::AllocateRealUserMeshBlockDataField(int n) // \brief Allocate Real AthenaArrays for user-defned data in MeshBlock void MeshBlock::AllocateRealUserMeshBlockDataField(int n) { if(nreal_user_meshblock_data_!=0) { std::stringstream msg; msg << "### FATAL ERROR in MeshBlock::AllocateRealUserMeshBlockDataField" << std::endl << "User MeshBlock data arrays are already allocated" << std::endl; throw std::runtime_error(msg.str().c_str()); } nreal_user_meshblock_data_=n; ruser_meshblock_data = new AthenaArray<Real>[n]; return; } //---------------------------------------------------------------------------------------- //! \fn void MeshBlock::AllocateIntUserMeshBlockDataField(int n) // \brief Allocate integer AthenaArrays for user-defned data in MeshBlock void MeshBlock::AllocateIntUserMeshBlockDataField(int n) { if(nint_user_meshblock_data_!=0) { std::stringstream msg; msg << "### FATAL ERROR in MeshBlock::AllocateIntusermeshblockDataField" << std::endl << "User MeshBlock data arrays are already allocated" << std::endl; throw std::runtime_error(msg.str().c_str()); return; } nint_user_meshblock_data_=n; iuser_meshblock_data = new AthenaArray<int>[n]; return; } //---------------------------------------------------------------------------------------- //! \fn void MeshBlock::AllocateUserOutputVariables(int n) // \brief Allocate user-defined output variables void MeshBlock::AllocateUserOutputVariables(int n) { if(n<=0) return; if(nuser_out_var!=0) { std::stringstream msg; msg << "### FATAL ERROR in MeshBlock::AllocateUserOutputVariables" << std::endl << "User output variables are already allocated." << std::endl; throw std::runtime_error(msg.str().c_str()); return; } nuser_out_var=n; int ncells1 = block_size.nx1 + 2*(NGHOST); int ncells2 = 1, ncells3 = 1; if (block_size.nx2 > 1) ncells2 = block_size.nx2 + 2*(NGHOST); if (block_size.nx3 > 1) ncells3 = block_size.nx3 + 2*(NGHOST); user_out_var.NewAthenaArray(nuser_out_var,ncells3,ncells2,ncells1); user_out_var_names_ = new std::string[n]; return; } //---------------------------------------------------------------------------------------- //! \fn void MeshBlock::SetUserOutputVariableName(int n, const char *name) // \brief set the user-defined output variable name void MeshBlock::SetUserOutputVariableName(int n, const char *name) { if(n>=nuser_out_var) { std::stringstream msg; msg << "### FATAL ERROR in MeshBlock::SetUserOutputVariableName" << std::endl << "User output variable is not allocated." << std::endl; throw std::runtime_error(msg.str().c_str()); return; } user_out_var_names_[n]=name; return; } //---------------------------------------------------------------------------------------- //! \fn size_t MeshBlock::GetBlockSizeInBytes(void) // \brief Calculate the block data size required for restart. size_t MeshBlock::GetBlockSizeInBytes(void) { size_t size; size=phydro->u.GetSizeInBytes(); if (GENERAL_RELATIVITY) { size+=phydro->w.GetSizeInBytes(); size+=phydro->w1.GetSizeInBytes(); } if (MAGNETIC_FIELDS_ENABLED) size+=(pfield->b.x1f.GetSizeInBytes()+pfield->b.x2f.GetSizeInBytes() +pfield->b.x3f.GetSizeInBytes()); // NEW_PHYSICS: modify the size counter here when new physics is introduced // calculate user MeshBlock data size for(int n=0; n<nint_user_meshblock_data_; n++) size+=iuser_meshblock_data[n].GetSizeInBytes(); for(int n=0; n<nreal_user_meshblock_data_; n++) size+=ruser_meshblock_data[n].GetSizeInBytes(); return size; } //---------------------------------------------------------------------------------------- // \!fn void NeighborBlock::SetNeighbor(int irank, int ilevel, int igid, int ilid, // int iox1, int iox2, int iox3, enum NeighborType itype, // int ibid, int itargetid, int ifi1=0, int ifi2=0, // bool ipolar=false) // \brief Set neighbor information void NeighborBlock::SetNeighbor(int irank, int ilevel, int igid, int ilid, int iox1, int iox2, int iox3, enum NeighborType itype, int ibid, int itargetid, bool ipolar, int ifi1=0, int ifi2=0) { rank=irank; level=ilevel; gid=igid; lid=ilid; ox1=iox1; ox2=iox2; ox3=iox3; type=itype; bufid=ibid; targetid=itargetid; polar=ipolar; fi1=ifi1; fi2=ifi2; if(type==NEIGHBOR_FACE) { if(ox1==-1) fid=INNER_X1; else if(ox1==1) fid=OUTER_X1; else if(ox2==-1) fid=INNER_X2; else if(ox2==1) fid=OUTER_X2; else if(ox3==-1) fid=INNER_X3; else if(ox3==1) fid=OUTER_X3; } if(type==NEIGHBOR_EDGE) { if(ox3==0) eid=( ((ox1+1)>>1) | ((ox2+1)&2)); else if(ox2==0) eid=(4+(((ox1+1)>>1) | ((ox3+1)&2))); else if(ox1==0) eid=(8+(((ox2+1)>>1) | ((ox3+1)&2))); } return; } //---------------------------------------------------------------------------------------- // \!fn void MeshBlock::SearchAndSetNeighbors(MeshBlockTree &tree, int *ranklist, int *nslist) // \brief Search and set all the neighbor blocks void MeshBlock::SearchAndSetNeighbors(MeshBlockTree &tree, int *ranklist, int *nslist) { MeshBlockTree* neibt; int myox1, myox2=0, myox3=0, myfx1, myfx2, myfx3; myfx1=(int)(loc.lx1&1L); myfx2=(int)(loc.lx2&1L); myfx3=(int)(loc.lx3&1L); myox1=((int)(loc.lx1&1L))*2-1; if(block_size.nx2>1) myox2=((int)(loc.lx2&1L))*2-1; if(block_size.nx3>1) myox3=((int)(loc.lx3&1L))*2-1; long int nrbx1=pmy_mesh->nrbx1, nrbx2=pmy_mesh->nrbx2, nrbx3=pmy_mesh->nrbx3; int nf1=1, nf2=1; if(pmy_mesh->multilevel==true) { if(block_size.nx2>1) nf1=2; if(block_size.nx3>1) nf2=2; } int bufid=0; nneighbor=0; for(int k=0; k<=2; k++) { for(int j=0; j<=2; j++) { for(int i=0; i<=2; i++) nblevel[k][j][i]=-1; } } nblevel[1][1][1]=loc.level; // x1 face for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,n,0,0,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf1*nf2; continue;} if(neibt->flag==false) { // neighbor at finer level int fface=1-(n+1)/2; // 0 for OUTER_X1, 1 for INNER_X1 nblevel[1][1][n+1]=neibt->loc.level+1; for(int f2=0;f2<nf2;f2++) { for(int f1=0;f1<nf1;f1++) { MeshBlockTree* nf=neibt->GetLeaf(fface,f1,f2); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(-n,0,0,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], n, 0, 0, NEIGHBOR_FACE, bufid, tbid, false, f1, f2); bufid++; nneighbor++; } } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[1][1][n+1]=nlevel; int tbid; if(nlevel==loc.level) { // neighbor at same level tbid=FindBufferID(-n,0,0,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(-n,0,0,myfx2,myfx3,pmy_mesh->maxneighbor_); } neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], n, 0, 0, NEIGHBOR_FACE, bufid, tbid, false); bufid+=nf1*nf2; nneighbor++; } } if(block_size.nx2==1) return; // x2 face for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,0,n,0,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf1*nf2; continue;} if(neibt->flag==false) { // neighbor at finer level int fface=1-(n+1)/2; // 0 for OUTER_X2, 1 for INNER_X2 nblevel[1][n+1][1]=neibt->loc.level+1; for(int f2=0;f2<nf2;f2++) { for(int f1=0;f1<nf1;f1++) { MeshBlockTree* nf=neibt->GetLeaf(f1,fface,f2); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(0,-n,0,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], 0, n, 0, NEIGHBOR_FACE, bufid, tbid, false, f1, f2); bufid++; nneighbor++; } } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[1][n+1][1]=nlevel; int tbid; bool polar=false; if(nlevel==loc.level) { // neighbor at same level if ((n == -1 and block_bcs[INNER_X2] == POLAR_BNDRY) or (n == 1 and block_bcs[OUTER_X2] == POLAR_BNDRY)) { polar = true; // neighbor is across top or bottom pole } tbid=FindBufferID(0,polar?n:-n,0,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(0,-n,0,myfx1,myfx3,pmy_mesh->maxneighbor_); } neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], 0, n, 0, NEIGHBOR_FACE, bufid, tbid, polar); bufid+=nf1*nf2; nneighbor++; } } // x3 face if(block_size.nx3>1) { for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,0,0,n,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf1*nf2; continue;} if(neibt->flag==false) { // neighbor at finer level int fface=1-(n+1)/2; // 0 for OUTER_X3, 1 for INNER_X3 nblevel[n+1][1][1]=neibt->loc.level+1; for(int f2=0;f2<nf2;f2++) { for(int f1=0;f1<nf1;f1++) { MeshBlockTree* nf=neibt->GetLeaf(f1,f2,fface); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(0,0,-n,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], 0, 0, n, NEIGHBOR_FACE, bufid, tbid, false, f1, f2); bufid++; nneighbor++; } } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[n+1][1][1]=nlevel; int tbid; if(nlevel==loc.level) { // neighbor at same level tbid=FindBufferID(0,0,-n,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(0,0,-n,myfx1,myfx2,pmy_mesh->maxneighbor_); } neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], 0, 0, n, NEIGHBOR_FACE, bufid, tbid, false); bufid+=nf1*nf2; nneighbor++; } } } // x1x2 edge for(int m=-1; m<=1; m+=2) { for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,n,m,0,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf2; continue;} if(neibt->flag==false) { // neighbor at finer level int ff1=1-(n+1)/2; // 0 for OUTER_X1, 1 for INNER_X1 int ff2=1-(m+1)/2; // 0 for OUTER_X2, 1 for INNER_X2 nblevel[1][m+1][n+1]=neibt->loc.level+1; for(int f1=0;f1<nf2;f1++) { MeshBlockTree* nf=neibt->GetLeaf(ff1,ff2,f1); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(-n,-m,0,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], n, m, 0, NEIGHBOR_EDGE, bufid, tbid, false, f1, 0); bufid++; nneighbor++; } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[1][m+1][n+1]=nlevel; int tbid; bool polar=false; if(nlevel==loc.level) { // neighbor at same level if ((m == -1 and block_bcs[INNER_X2] == POLAR_BNDRY) or (m == 1 and block_bcs[OUTER_X2] == POLAR_BNDRY)) { polar = true; // neighbor is across top or bottom pole } tbid=FindBufferID(-n,polar?m:-m,0,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(-n,polar?m:-m,0,myfx3,0,pmy_mesh->maxneighbor_); } if(nlevel>=loc.level || (myox1==n && myox2==m)) { neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], n, m, 0, NEIGHBOR_EDGE, bufid, tbid, polar); nneighbor++; } bufid+=nf2; } } } // polar neighbors if (block_bcs[INNER_X2] == POLAR_BNDRY||block_bcs[INNER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_north_polar_blocks = nrbx3 * (1 << level); for (int n = 0; n < num_north_polar_blocks; ++n) { LogicalLocation neighbor_loc; neighbor_loc.lx1 = loc.lx1; neighbor_loc.lx2 = loc.lx2; neighbor_loc.lx3 = n; neighbor_loc.level = loc.level; neibt = tree.FindMeshBlock(neighbor_loc); int nid = neibt->gid; polar_neighbor_north[neibt->loc.lx3].rank = ranklist[nid]; polar_neighbor_north[neibt->loc.lx3].lid = nid - nslist[ranklist[nid]]; polar_neighbor_north[neibt->loc.lx3].gid = nid; polar_neighbor_north[neibt->loc.lx3].north = true; } } if (block_bcs[OUTER_X2] == POLAR_BNDRY||block_bcs[OUTER_X2] == POLAR_BNDRY_WEDGE) { int level = loc.level - pmy_mesh->root_level; int num_south_polar_blocks = nrbx3 * (1 << level); for (int n = 0; n < num_south_polar_blocks; ++n) { LogicalLocation neighbor_loc; neighbor_loc.lx1 = loc.lx1; neighbor_loc.lx2 = loc.lx2; neighbor_loc.lx3 = n; neighbor_loc.level = loc.level; neibt = tree.FindMeshBlock(neighbor_loc); int nid = neibt->gid; polar_neighbor_south[neibt->loc.lx3].rank = ranklist[nid]; polar_neighbor_south[neibt->loc.lx3].lid = nid - nslist[ranklist[nid]]; polar_neighbor_south[neibt->loc.lx3].gid = nid; polar_neighbor_south[neibt->loc.lx3].north = false; } } if(block_size.nx3==1) return; // x1x3 edge for(int m=-1; m<=1; m+=2) { for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,n,0,m,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf1; continue;} if(neibt->flag==false) { // neighbor at finer level int ff1=1-(n+1)/2; // 0 for OUTER_X1, 1 for INNER_X1 int ff2=1-(m+1)/2; // 0 for OUTER_X3, 1 for INNER_X3 nblevel[m+1][1][n+1]=neibt->loc.level+1; for(int f1=0;f1<nf1;f1++) { MeshBlockTree* nf=neibt->GetLeaf(ff1,f1,ff2); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(-n,0,-m,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], n, 0, m, NEIGHBOR_EDGE, bufid, tbid, false, f1, 0); bufid++; nneighbor++; } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[m+1][1][n+1]=nlevel; int tbid; if(nlevel==loc.level) { // neighbor at same level tbid=FindBufferID(-n,0,-m,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(-n,0,-m,myfx2,0,pmy_mesh->maxneighbor_); } if(nlevel>=loc.level || (myox1==n && myox3==m)) { neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], n, 0, m, NEIGHBOR_EDGE, bufid, tbid, false); nneighbor++; } bufid+=nf1; } } } // x2x3 edge for(int m=-1; m<=1; m+=2) { for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,0,n,m,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid+=nf1; continue;} if(neibt->flag==false) { // neighbor at finer level int ff1=1-(n+1)/2; // 0 for OUTER_X2, 1 for INNER_X2 int ff2=1-(m+1)/2; // 0 for OUTER_X3, 1 for INNER_X3 nblevel[m+1][n+1][1]=neibt->loc.level+1; for(int f1=0;f1<nf1;f1++) { MeshBlockTree* nf=neibt->GetLeaf(f1,ff1,ff2); int fid = nf->gid; int nlevel=nf->loc.level; int tbid=FindBufferID(0,-n,-m,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[fid], nlevel, fid, fid-nslist[ranklist[fid]], 0, n, m, NEIGHBOR_EDGE, bufid, tbid, false, f1, 0); bufid++; nneighbor++; } } else { // neighbor at same or coarser level int nlevel=neibt->loc.level; int nid=neibt->gid; nblevel[m+1][n+1][1]=nlevel; int tbid; bool polar=false; if(nlevel==loc.level) { // neighbor at same level if ((n == -1 and block_bcs[INNER_X2] == POLAR_BNDRY) or (n == 1 and block_bcs[OUTER_X2] == POLAR_BNDRY)) { polar = true; // neighbor is across top or bottom pole } tbid=FindBufferID(0,polar?n:-n,-m,0,0,pmy_mesh->maxneighbor_); } else { // neighbor at coarser level tbid=FindBufferID(0,-n,-m,myfx1,0,pmy_mesh->maxneighbor_); } if(nlevel>=loc.level || (myox2==n && myox3==m)) { neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], 0, n, m, NEIGHBOR_EDGE, bufid, tbid, polar); nneighbor++; } bufid+=nf1; } } } // corners for(int l=-1; l<=1; l+=2) { for(int m=-1; m<=1; m+=2) { for(int n=-1; n<=1; n+=2) { neibt=tree.FindNeighbor(loc,n,m,l,block_bcs,nrbx1,nrbx2,nrbx3,pmy_mesh->root_level); if(neibt==NULL) { bufid++; continue;} bool polar=false; if ((m == -1 and block_bcs[INNER_X2] == POLAR_BNDRY) or (m == 1 and block_bcs[OUTER_X2] == POLAR_BNDRY)) { polar = true; // neighbor is across top or bottom pole } if(neibt->flag==false) { // neighbor at finer level int ff1=1-(n+1)/2; // 0 for OUTER_X1, 1 for INNER_X1 int ff2=1-(m+1)/2; // 0 for OUTER_X2, 1 for INNER_X2 int ff3=1-(l+1)/2; // 0 for OUTER_X3, 1 for INNER_X3 neibt=neibt->GetLeaf(ff1,ff2,ff3); } int nlevel=neibt->loc.level; nblevel[l+1][m+1][n+1]=nlevel; if(nlevel>=loc.level || (myox1==n && myox2==m && myox3==l)) { int nid=neibt->gid; int tbid=FindBufferID(-n,polar?m:-m,-l,0,0,pmy_mesh->maxneighbor_); neighbor[nneighbor].SetNeighbor(ranklist[nid], nlevel, nid, nid-nslist[ranklist[nid]], n, m, l, NEIGHBOR_CORNER, bufid, tbid, polar); nneighbor++; } bufid++; } } } return; }
36.92848
114
0.602628
cnstahl
6f190c690e6104dc25b2a3f14b4035a8f6fdaf30
5,486
hpp
C++
bst/inc/RBT.hpp
kraylas/shit-code
d0565116deacd91497722659e0151112361d90f7
[ "MIT" ]
null
null
null
bst/inc/RBT.hpp
kraylas/shit-code
d0565116deacd91497722659e0151112361d90f7
[ "MIT" ]
null
null
null
bst/inc/RBT.hpp
kraylas/shit-code
d0565116deacd91497722659e0151112361d90f7
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <cassert> #include <compare> #include <cstddef> #include <cstdint> #include <cstdlib> #include <functional> #include <type_traits> #include <utility> #include <iostream> #include "utils.hpp" namespace RBT { enum class Color : std::uint8_t { RED, BLACK }; template <typename KeyType, typename ValueType> struct RBTNode { using ptr_RBTNode = RBTNode<KeyType, ValueType> *; KeyType key; ValueType value; ptr_RBTNode ch[2], fa; Color col{Color::RED}; template <typename K, typename V> requires KUtils::is_rmcvref_same_v<K, KeyType> && KUtils::is_rmcvref_same_v<V, ValueType> RBTNode(K &&key, V &&value) : fa{nullptr}, key{std::forward<K>(key)}, value{std::forward<V>(value)} { ch[0] = ch[1] = nullptr; } bool d() { return fa->ch[1] == this; } // void up() { // std::cout << "up" << std::endl; //} }; template <typename KeyType, typename ValueType, typename CompType = std::less<KeyType>> requires KUtils::Ops<KeyType, CompType> class RBTreeMap { public: using Node = RBTNode<KeyType, ValueType>; using ptr_Node = Node *; ptr_Node root{nullptr}; void rot(ptr_Node x, bool d) { ptr_Node y = x->ch[!d], z = x->fa; x->ch[!d] = y->ch[d]; if (y->ch[d] != NULL) y->ch[d]->fa = x; y->fa = z; if (z == NULL) root = y; else z->ch[x->d()] = y; y->ch[d] = x; x->fa = y; if constexpr (requires { x->up(); }) { x->up(); y->up(); } } template <typename K, typename V> requires KUtils::is_rmcvref_same_v<K, KeyType> && KUtils::is_rmcvref_same_v<V, ValueType> static ptr_Node getNode(K &&key, V &&value) { return new Node(std::forward<K>(key), std::forward<V>(value)); } static void destroyNode(ptr_Node p) { // std::cout << "destroy :{" << p->key << ", " << p->value << "}" << std::endl; delete p; } template <typename K, typename V> requires KUtils::is_rmcvref_same_v<K, KeyType> && KUtils::is_rmcvref_same_v<V, ValueType> void insert(K &&key, V &&value) { if (root == nullptr) { root = getNode(std::forward<K>(key), std::forward<V>(value)); root->col = Color::BLACK; return; } ptr_Node t = root, p = getNode(std::forward<K>(key), std::forward<V>(value)), z = nullptr; bool d; while (!eq(t->key, p->key) && t->ch[d = CompType{}(t->key, p->key)]) t = t->ch[d]; if (eq(t->key, p->key)) { t->value = std::move(p->value); return; } p->fa = t; t->ch[d] = p; if constexpr (requires { t->up(); }) { t->up(); } while ((t = p->fa) && (t->col == Color::RED)) { z = t->fa; bool d1 = t->d(), d2 = p->d(); ptr_Node u = z->ch[!d1]; if (u && u->col == Color::RED) { u->col = Color::BLACK; t->col = Color::BLACK; z->col = Color::RED; p = z; continue; } if (d1 ^ d2) { rot(t, d1); std::swap(p, t); } t->col = Color::BLACK; z->col = Color::RED; rot(z, !d1); } root->col = Color::BLACK; } static bool eq(const KeyType &l, const KeyType &r) { return (!CompType{}(l, r)) && (!CompType{}(r, l)); } ptr_Node search(const KeyType &key) { ptr_Node t = root; while (t && !eq(key, t->key)) t = t->ch[CompType{}(t->key, key)]; return t; } ValueType *get(const KeyType &key) { auto p = search(key); return p ? &p->value : nullptr; } void fixup(ptr_Node t, ptr_Node z) { ptr_Node b; while ((!t || t->col == Color::BLACK) && t != root) { int d = z->ch[1] == t; b = z->ch[!d]; if (b->col == Color::RED) { b->col = Color::BLACK; z->col = Color::RED; rot(z, d); b = z->ch[!d]; } if ((b->ch[0] == NULL || b->ch[0]->col == Color::BLACK) && (b->ch[1] == NULL || b->ch[1]->col == Color::BLACK)) { b->col = Color::RED; t = z; z = t->fa; } else { if (!b->ch[!d] || b->ch[!d]->col == Color::BLACK) { b->ch[d]->col = Color::BLACK; b->col = Color::RED; rot(b, !d); b = z->ch[!d]; } b->col = z->col; z->col = Color::BLACK; b->ch[!d]->col = Color::BLACK; rot(z, d); t = root; break; } } if (t) t->col = Color::BLACK; } void remove(const KeyType &key) { ptr_Node t = root, p, z, b, g; Color Tmp; if ((t = search(key)) == nullptr) { // std::cout << "rm :" << key << " Unsuccess" << std::endl; return; } if (t->ch[0] && t->ch[1]) { p = t->ch[1], z = t->fa; while (p->ch[0] != NULL) p = p->ch[0]; if (z != NULL) z->ch[t->d()] = p; else root = p; g = p->ch[1]; b = p->fa; Tmp = p->col; if (b == t) b = p; else { if (g) g->fa = b; b->ch[0] = g; p->ch[1] = t->ch[1]; t->ch[1]->fa = p; if constexpr (requires { b->up(); }) { b->up(); } } p->fa = z; p->col = t->col; p->ch[0] = t->ch[0]; t->ch[0]->fa = p; if (Tmp == Color::BLACK) fixup(g, b); destroyNode(t); return; } p = t->ch[t->ch[1] != nullptr]; z = t->fa; Tmp = t->col; if (p) p->fa = z; if (z) z->ch[t->d()] = p; else root = p; if (Tmp == Color::BLACK) fixup(p, z); destroyNode(t); } static void destroyTree(ptr_Node p) { if (p == nullptr) return; if (p->ch[0]) destroyTree(p->ch[0]); if (p->ch[1]) destroyTree(p->ch[1]); destroyNode(p); } // void dfs(ptr_Node x, int dep) { // if (x == nullptr) return; // dfs(x->ch[0], dep + 1); // // std::cout << "dep:" << dep << " {" << x->key << ", " << x->value << "} "; // dfs(x->ch[1], dep + 1); // } // void travel() { // dfs(root, 1); // std::cout << std::endl; // } ~RBTreeMap() { destroyTree(root); } }; } // namespace RBT
24.274336
116
0.52479
kraylas
6f1d24ded8c40501fe66e1e7ad5b85884940a93f
7,089
cpp
C++
src/std_sequence_containers.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
src/std_sequence_containers.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
src/std_sequence_containers.cpp
tyoungjr/Catch2Practice
6c602b0b57edaf2299043b4ef3c11d9507ce167b
[ "MIT" ]
null
null
null
// // Created by tyoun on 10/25/2021. // #include <catch2/catch.hpp> #include <array> #include <vector> #include <utility> #include <cstdint> #include <iostream> #include <unordered_set> #include "../include/print_std_library_containers.h" std::array<int, 10> static_array{}; // braced initialization will initialize array with zeroes TEST_CASE("std::array") { REQUIRE(static_array[0] == 0); SECTION("unitialized without braced initializers") { std::array<int, 10> local_array; REQUIRE(local_array[0] != 0); } SECTION("initialized with braced initializers") { std::array<int, 10> local_array { 1, 1,2, 3}; REQUIRE(local_array[0] == 1); REQUIRE(local_array[1] == 1); REQUIRE(local_array[2] == 2); REQUIRE(local_array[3] == 3); REQUIRE(local_array[4] == 0); } } // size_t object guarantees that its maximum value is sufficient to represent // the maximum size in bytes of all objects TEST_CASE("std::array access") { std::array<int, 4> fib { 1, 1, 0, 3}; SECTION("operator[] can get and set elemetns") { fib[2] = 2; REQUIRE(fib[2] == 2); // fib[4] = 5; } SECTION("at() can get and set elements") { fib.at(2) = 2; REQUIRE(fib.at(2) == 2); REQUIRE_THROWS_AS(fib.at(4), std::out_of_range); } SECTION("get can get and set elements") { std::get<2>(fib) = 2; REQUIRE(std::get<2>(fib) == 2); } SECTION(" sexy fibbers") { std::array fibonacci{1, 1, 2, 3, 5}; std::cout << fibonacci[4] << "\n"; } } TEST_CASE("std::array has convienence methods" ) { std::array<int, 4> fib { 0, 1, 2, 0}; SECTION("front") { fib.front() = 1; REQUIRE(fib.front() == 1); REQUIRE(fib.front() == fib[0]); } SECTION("back") { fib.front() = 1; REQUIRE(fib.front() == 1); REQUIRE(fib.front() == fib[0]); } } TEST_CASE("We can obtain a pointer to the first element using") { std::array<char, 9> color { 'o', 'c', 't', 'a', 'r','i','n','e'}; const auto* color_ptr = color.data(); SECTION("data") { REQUIRE(*color_ptr == 'o'); } SECTION("address-of front") { REQUIRE(&color.front() == color_ptr); } SECTION("address-of at(0)") { REQUIRE(&color.at(0) == color_ptr); } SECTION("address-of [0]") { REQUIRE(&color[0] == color_ptr); } } //ITERATORS TEST_CASE("std::array begin/end form a half open range") { std::array<int, 0> e{}; REQUIRE(e.begin() == e.end()); } TEST_CASE("std::array iterators are pointer-like") { std::array<int, 3> easy_as { 1, 2, 3}; auto iter = easy_as.begin(); REQUIRE(*iter == 1); ++iter; REQUIRE(*iter == 2); ++iter; REQUIRE(*iter == 3); REQUIRE(iter == easy_as.end()); } TEST_CASE("std::array iterator can be used as a range expression ") { std::array<int, 5> fib{1,1,2,3,5}; int sum{}; for (const auto element: fib) sum += element; REQUIRE(sum == 12); } /****************************************************/ /* the big std vector */ TEST_CASE("std vector supports default construction") { std::vector<const char *> vec; REQUIRE(vec.empty()); } TEST_CASE("std::vector supports braced initialization") { std::vector<int> fib { 1,1,2,3, 5}; REQUIRE(fib[4] == 5); } TEST_CASE("std::vector supports") { SECTION("braced initialization") { std::vector<int> five_nine{ 5, 9}; REQUIRE(five_nine[0] == 5); REQUIRE(five_nine[1] == 9); } SECTION("fill constructor" ) { std::vector<int> five_nines(5, 9); REQUIRE(five_nines[0] == 9); REQUIRE(five_nines[4] == 9); } } TEST_CASE("std::vector supports construction from iterators") { std::array<int, 5> fib_arr{1, 1, 2,3 , 5}; std::vector<int> fib_vec(fib_arr.begin(), fib_arr.end()); REQUIRE(fib_vec[4] == 5); REQUIRE(fib_vec.size() == fib_arr.size()); } TEST_CASE("std::vector assign replaces existing elements") { std::vector<int> message { 13, 80, 110 , 114, 102,110, 101 }; REQUIRE(message.size() == 7); message.assign({67, 97, 101, 115, 97, 114}); REQUIRE(message[5] == 114); REQUIRE(message.size() == 6); } TEST_CASE("std::vector insert places new elements") { std::vector<int> zeros(3, 0); auto third_element = zeros.begin() + 2; zeros.insert(third_element, 10); REQUIRE(zeros[2] == 10); REQUIRE(zeros.size() == 4); } TEST_CASE("std::vector push_back places new element") { std::vector<int> zeros(3, 0); zeros.push_back(10); REQUIRE(zeros[3] == 10); } TEST_CASE("std::vector emplace methods forwards arguments") { std::vector<std::pair<int, int>> factors; factors.emplace_back(2, 30); factors.emplace_back(3, 20); factors.emplace_back(4, 15); factors.emplace(factors.begin(), 1, 60); REQUIRE(factors[0].first == 1); REQUIRE(factors[0].second == 60); } TEST_CASE("std::vector exposes size management methods") { std::vector<std::array<uint8_t, 1024>> kb_store; REQUIRE(kb_store.max_size() > 0); REQUIRE(kb_store.empty()); size_t elements{ 1024}; kb_store.reserve(elements); REQUIRE(kb_store.empty()); REQUIRE(kb_store.empty() == elements); kb_store.emplace_back(); kb_store.emplace_back(); kb_store.emplace_back(); REQUIRE(kb_store.size() == 3); kb_store.shrink_to_fit(); REQUIRE(kb_store.capacity() >= 3); kb_store.clear(); REQUIRE(kb_store.empty()); REQUIRE(kb_store.capacity() >= 3); } TEST_CASE("OK I forgot the pop back ...") { std::vector<int> v; v.push_back(42); std::vector<int> u {1,2,3}; v.pop_back(); for(auto x: u) { std::cout << x << "\n"; } } // passing an array into a function using std::unordered_set; using std::array; using std::vector; unordered_set<int> unique(const array<int, 12>& numbers) { unordered_set<int> uniqueNumbers; for (auto n : numbers) { uniqueNumbers.insert(n); } return uniqueNumbers; } TEST_CASE("passing arrays into functions") { array numbers{1, 2, 42, 8, 0, -7, 2, 4, 10, 2, -100, 5}; auto uniqueNumbers = unique(numbers); std::cout << uniqueNumbers.size() << "\n"; } unordered_set<int> unique(const vector<int>& numbers) { unordered_set<int> uniqueNumbers; for (auto n : numbers) { uniqueNumbers.insert(n); } return uniqueNumbers; } TEST_CASE("passing vectors to functions") { vector numbers { 1, 2, 42, 8, 0,-7, 2, 5, 10, 2, 3, -100, 5}; auto uniqueNumbers = unique(numbers); std::cout << uniqueNumbers.size() << "\n"; } TEST_CASE("printing container template function") { vector vec{1.0f, 2.0f, 3.0f}; std::cout << vec << "\n"; } TEST_CASE("printing map template function") { std::map<std::string, float> planetDistances { { "Venus", 0.733f }, { "Earth", 1.0f}, { "Mars", 1.5}, }; std::cout << planetDistances << "\n"; }
24.277397
94
0.58217
tyoungjr
6f1dd9506205d4f86165f2477eb7d24aee7c6d15
4,176
cpp
C++
src/core/Window.cpp
AndrijaAda99/Bubo
662bb8e602f18a81ea6d8f367cb697c60b3e6670
[ "Apache-2.0" ]
null
null
null
src/core/Window.cpp
AndrijaAda99/Bubo
662bb8e602f18a81ea6d8f367cb697c60b3e6670
[ "Apache-2.0" ]
null
null
null
src/core/Window.cpp
AndrijaAda99/Bubo
662bb8e602f18a81ea6d8f367cb697c60b3e6670
[ "Apache-2.0" ]
null
null
null
#include "core/Window.h" #include "events/MouseEvent.h" #include "events/WindowEvent.h" #include "events/KeyEvent.h" namespace bubo { Window::Window(const WindowProperties_t &windowProperties) { init(windowProperties); BUBO_TRACE("Window initialized!"); } Window::~Window() { shutdown(); BUBO_TRACE("Window successfully closed."); } void Window::init(const WindowProperties_t &windowProperties) { int success = glfwInit(); BUBO_ASSERT(success, "Could not initialize GLFW!") glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_SAMPLES, 4); m_windowData.width = windowProperties.width; m_windowData.height = windowProperties.height; m_windowData.title = windowProperties.title; BUBO_INFO("Creating window: {0} ({1}, {2})", windowProperties.title, windowProperties.width, windowProperties.height); m_window = glfwCreateWindow((int) getWidth(), (int) getHeight(), m_windowData.title.c_str(), nullptr, nullptr); BUBO_ASSERT(m_window, "Could not create GLFW window!") m_mouse.xPos = getWidth() / 2.0f; m_mouse.yPos = getHeight() / 2.0f; glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwMakeContextCurrent(m_window); glfwSetWindowUserPointer(m_window, &m_windowData); success = gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); BUBO_ASSERT(success, "Could not initialize GLAD!") glfwSetWindowSizeCallback(m_window, [](GLFWwindow* window, int width, int height){ WindowData_t& windowData = *(WindowData_t*) glfwGetWindowUserPointer(window); windowData.width = width; windowData.height = height; WindowResizeEvent event(width, height); windowData.callbackFunc(event); }); glfwSetWindowCloseCallback(m_window, [](GLFWwindow* window){ WindowData_t& windowData = *(WindowData_t*) glfwGetWindowUserPointer(window); WindowCloseEvent event; windowData.callbackFunc(event); }); glfwSetCursorPosCallback(m_window, [](GLFWwindow* window, double xPos, double yPos){ WindowData_t& windowData = *(WindowData_t*) glfwGetWindowUserPointer(window); MouseMovedEvent event((float) xPos, (float) yPos); windowData.callbackFunc(event); }); glfwSetMouseButtonCallback(m_window, [](GLFWwindow* window, int button, int action, int mods) { WindowData_t& windowData = *(WindowData_t*) glfwGetWindowUserPointer(window); if (action == GLFW_PRESS) { MouseButtonPressedEvent event((MouseKeycode(button))); windowData.callbackFunc(event); } else if (action == GLFW_RELEASE) { MouseButtonReleasedEvent event((MouseKeycode(button))); windowData.callbackFunc(event); } }); glfwSetKeyCallback(m_window, [](GLFWwindow* window, int key, int scancode, int action, int mods) { WindowData_t& windowData = *(WindowData_t*) glfwGetWindowUserPointer(window); if (action == GLFW_PRESS) { KeyPressedEvent event((Keycode(key))); windowData.callbackFunc(event); } else if (action == GLFW_RELEASE) { KeyReleasedEvent event((Keycode(key))); windowData.callbackFunc(event); } }); } void Window::shutdown() { glfwDestroyWindow(m_window); glfwTerminate(); } void Window::update() { glfwPollEvents(); glfwSwapBuffers(m_window); } void Window::setVSync(bool value) { if (value) { glfwSwapInterval(1); } else { glfwSwapInterval(0); } m_windowData.isVSync = value; } }
35.092437
106
0.610632
AndrijaAda99
6f26716f8ce835e63dd95904ee486c940f3e90b7
4,378
cpp
C++
src/mod/debug/penetration.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
33
2016-02-18T04:27:53.000Z
2022-01-15T18:59:53.000Z
src/mod/debug/penetration.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
5
2018-01-10T18:41:38.000Z
2020-10-01T13:34:53.000Z
src/mod/debug/penetration.cpp
fugueinheels/sigsegv-mvm
092a69d44a3ed9aacd14886037f4093a27ff816b
[ "BSD-2-Clause" ]
14
2017-08-06T23:02:49.000Z
2021-08-24T00:24:16.000Z
#include "mod.h" #include "stub/tfplayer.h" #include "stub/tfweaponbase.h" #include "util/scope.h" namespace Mod::Debug::Penetration { struct penetrated_target_list { CBaseEntity *ent; // +0x00 float fraction; // +0x04 }; struct CBulletPenetrateEnum { void **vtable; // +0x00 Ray_t *ray; // +0x04 int pen_type; // +0x08 CTFPlayer *player; // +0x0c bool bool_0x10; // +0x10 CUtlVector<penetrated_target_list> vec; // +0x14, actually: CUtlSortVector<penetrated_target_list, PenetratedTargetLess> int dword_0x28; // +0x28 bool bool_0x2c; // +0x2c }; RefCount rc_CTFPlayer_FireBullet; DETOUR_DECL_MEMBER(void, CTFPlayer_FireBullet, CTFWeaponBase *weapon, const FireBulletsInfo_t& info, bool bDoEffects, int nDamageType, int nCustomDamageType) { DevMsg("\nCTFPlayer::FireBullet BEGIN\n"); DevMsg(" nCustomDamageType = %d\n", nCustomDamageType); int pen_type = nCustomDamageType; if (weapon != nullptr && weapon->GetPenetrateType() != 0) { pen_type = weapon->GetPenetrateType(); } DevMsg(" pen_type = %d\n", pen_type); bool has_pen = ((unsigned int)pen_type - 0xbu <= 1u); DevMsg(" has_pen = %s\n", (has_pen ? "true" : "false")); SCOPED_INCREMENT(rc_CTFPlayer_FireBullet); DETOUR_MEMBER_CALL(CTFPlayer_FireBullet)(weapon, info, bDoEffects, nDamageType, nCustomDamageType); DevMsg("CTFPlayer::FireBullet END\n"); } RefCount rc_IEngineTrace_EnumerateEntities; DETOUR_DECL_MEMBER(void, IEngineTrace_EnumerateEntities_ray, const Ray_t& ray, bool triggers, IEntityEnumerator *pEnumerator) { DevMsg(" IEngineTrace::EnumerateEntities BEGIN\n"); SCOPED_INCREMENT(rc_IEngineTrace_EnumerateEntities); DETOUR_MEMBER_CALL(IEngineTrace_EnumerateEntities_ray)(ray, triggers, pEnumerator); auto pen = reinterpret_cast<CBulletPenetrateEnum *>(pEnumerator); FOR_EACH_VEC(pen->vec, i) { DevMsg(" pen[%d]: %.2f #%d (class '%s' name '%s')\n", i, pen->vec[i].fraction, ENTINDEX(pen->vec[i].ent), pen->vec[i].ent->GetClassname(), STRING(pen->vec[i].ent->GetEntityName())); } DevMsg(" IEngineTrace::EnumerateEntities END\n"); } DETOUR_DECL_MEMBER(bool, CBulletPenetrateEnum_EnumEntity, IHandleEntity *pHandleEntity) { auto pen = reinterpret_cast<CBulletPenetrateEnum *>(this); auto ent = reinterpret_cast<CBaseEntity *>(pHandleEntity); int count_before = pen->vec.Count(); bool result = DETOUR_MEMBER_CALL(CBulletPenetrateEnum_EnumEntity)(pHandleEntity); if (rc_CTFPlayer_FireBullet > 0 && rc_IEngineTrace_EnumerateEntities > 0) { bool was_added = (pen->vec.Count() != count_before); if (was_added) { DevMsg(" CBulletPenetrateEnum::EnumEntity: ADDED #%d (class '%s' name '%s')\n", ENTINDEX(ent), ent->GetClassname(), STRING(ent->GetEntityName())); } else { DevMsg(" CBulletPenetrateEnum::EnumEntity: SKIPPED #%d (class '%s' name '%s')\n", ENTINDEX(ent), ent->GetClassname(), STRING(ent->GetEntityName())); } } return result; } class CDmgAccumulator; DETOUR_DECL_MEMBER(void, CBaseEntity_DispatchTraceAttack, const CTakeDamageInfo& info, const Vector& vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator) { auto ent = reinterpret_cast<CBaseEntity *>(this); if (rc_CTFPlayer_FireBullet > 0) { DevMsg(" CBaseEntity::DispatchTraceAttack: ent #%d (m_iPlayerPenetrationCount = %d)\n", ENTINDEX(ent), info.GetPlayerPenetrationCount()); } DETOUR_MEMBER_CALL(CBaseEntity_DispatchTraceAttack)(info, vecDir, ptr, pAccumulator); } class CMod : public IMod { public: CMod() : IMod("Debug:Penetration") { MOD_ADD_DETOUR_MEMBER(CTFPlayer_FireBullet, "CTFPlayer::FireBullet"); MOD_ADD_DETOUR_MEMBER(IEngineTrace_EnumerateEntities_ray, "IEngineTrace::EnumerateEntities_ray"); MOD_ADD_DETOUR_MEMBER(CBulletPenetrateEnum_EnumEntity, "CBulletPenetrateEnum::EnumEntity"); MOD_ADD_DETOUR_MEMBER(CBaseEntity_DispatchTraceAttack, "CBaseEntity::DispatchTraceAttack"); } }; CMod s_Mod; ConVar cvar_enable("sig_debug_penetration", "0", FCVAR_NOTIFY, "Debug: penetration", [](IConVar *pConVar, const char *pOldValue, float flOldValue){ s_Mod.Toggle(static_cast<ConVar *>(pConVar)->GetBool()); }); }
34.746032
159
0.694838
fugueinheels
6f2bd87de10eeeb166a68241bfc5ff16358dd56b
1,848
cpp
C++
Source/GIS/LevelSet.cpp
hustztz/Urho3D
90abf7d8f176da9f9b828bb7ea9f46d1058ed009
[ "MIT" ]
null
null
null
Source/GIS/LevelSet.cpp
hustztz/Urho3D
90abf7d8f176da9f9b828bb7ea9f46d1058ed009
[ "MIT" ]
null
null
null
Source/GIS/LevelSet.cpp
hustztz/Urho3D
90abf7d8f176da9f9b828bb7ea9f46d1058ed009
[ "MIT" ]
null
null
null
#include "LevelSet.h" GIS::LevelSet::LevelSet( GIS::ElevationConfig & config ) { config.GetValue(ConfigKey::TILE_ORIGIN, &tileOrigin_); int numLevels = 0; if ( config.GetValue(ConfigKey::NUM_LEVELS, &numLevels)) { levels_.reserve(numLevels); config.GetValue(ConfigKey::LEVEL_ZERO_TILE_DELTA, &levelZeroTileDelta_ ); auto lat = levelZeroTileDelta_.GetLatitude(); auto lon = levelZeroTileDelta_.GetLongitude(); for (int i = 0; i < numLevels; ++i) { config.SetValue(ConfigKey::LEVEL_NAME, std::to_string(i)); config.SetValue(ConfigKey::LEVEL_NUMBER, i); config.SetValue(ConfigKey::TILE_DELTA, LatLon{ lat, lon }); levels_.push_back(Level{ config }); lat = Angle::FromDegrees(lat.GetDegrees() / 2); lon = Angle::FromDegrees(lon.GetDegrees() / 2); } } config.GetValue(ConfigKey::SECTOR, &sector_); } const GIS::Sector & GIS::LevelSet::GetSector() const noexcept { return sector_; } const GIS::Level & GIS::LevelSet::GetLevel(int index) const { if (index >= 0 && index < levels_.size()) return levels_[index]; else throw std::out_of_range{ "LevelSet::GetLevel" }; } GIS::Level & GIS::LevelSet::GetLevel(int index) { return levels_[index]; } const GIS::LatLon & GIS::LevelSet::GetTileOrigin() const noexcept { return tileOrigin_; } GIS::Level & GIS::LevelSet::GetTargetLevel(double targetSize) { auto & lastLevel = levels_[levels_.size() - 1]; if( lastLevel.GetTexelSize() >= targetSize ) return lastLevel; for (auto & level : levels_) { if (level.GetTexelSize() <= targetSize) return level; } return lastLevel; } uint32_t GIS::LevelSet::GetLevelCount() const noexcept { return static_cast<uint32_t>( levels_.size() ); } auto GIS::LevelSet::GetLastLevel() const -> const Level & { return levels_.back(); } auto GIS::LevelSet::GetLastLevel() -> Level & { return levels_.back(); }
24.315789
75
0.70184
hustztz
6f2d2ed8548721a77cd722b4a369e52296c19b3c
2,148
cpp
C++
framework/src/Core/Network/Udp/UdpSocketServer.cpp
gautier-lefebvre/cppframework
bc1c3405913343274d79240b17ab75ae3f2adf56
[ "MIT" ]
null
null
null
framework/src/Core/Network/Udp/UdpSocketServer.cpp
gautier-lefebvre/cppframework
bc1c3405913343274d79240b17ab75ae3f2adf56
[ "MIT" ]
3
2015-12-21T09:04:49.000Z
2015-12-21T19:22:47.000Z
framework/src/Core/Network/Udp/UdpSocketServer.cpp
gautier-lefebvre/cppframework
bc1c3405913343274d79240b17ab75ae3f2adf56
[ "MIT" ]
null
null
null
#include "Core/Network/Udp/UdpSocketServer.hh" #include "Core/Network/Udp/UdpSocketClient.hh" #include "Core/Network/Exception.hh" using namespace fwk; UdpSocketServer::UdpSocketServer(void): AUdpSocket(), APooled<UdpSocketServer>() {} UdpSocketServer::~UdpSocketServer(void) { this->reinit(); } void UdpSocketServer::reinit(void) { this->AUdpSocket::reinit(); } void UdpSocketServer::bind(uint16_t port) { if (port == 80) { throw NetworkException("bind: cannot bind port 80"); } sockaddr_in sin; sin.sin_addr.s_addr = htonl(INADDR_ANY); sin.sin_port = htons(port); sin.sin_family = AF_INET; if (::bind(this->_fd, reinterpret_cast<sockaddr*>(&sin), sizeof(sin)) == -1) { throw NetworkException(std::string("bind: ") + strerror(errno)); } } ssize_t UdpSocketServer::sendto(UdpSocketClient* client) { SCOPELOCK(this); ByteArray* datagram = client->nextDatagram(); if (datagram == nullptr) { return 0; } ssize_t ret = ::sendto(this->_fd, datagram->getBytes(), datagram->getSize(), MSG_NOSIGNAL, reinterpret_cast<const sockaddr*>(&(client->socketAddress())), sizeof(sockaddr_in)); ByteArray::returnToPool(datagram); if (ret < 0) { throw NetworkException(std::string("sendto: ") + strerror(errno)); } return ret; } ByteArray* UdpSocketServer::recvfrom(struct sockaddr_in& addr) { SCOPELOCK(this); ByteArray* datagram = nullptr; socklen_t addrlen = sizeof(sockaddr_in); // read data in buffer ssize_t ret = ::recvfrom(this->_fd, this->_buffer->atStart(), this->_buffer->getSizeMax(), 0, reinterpret_cast<sockaddr*>(&(addr)), &addrlen); if (ret < 0) { throw NetworkException(std::string("recvfrom: ") + strerror(errno)); } else if (static_cast<size_t>(ret) > AUdpSocketIO::BUFFER_SIZE) { throw NetworkException(std::string("recvfrom: received a datagram bigger than the buffer size (discarded)")); } // copy buffer to datagram resized to the number of bytes read. size_t size = static_cast<size_t>(ret); datagram = ByteArray::getFromPool(size, true); datagram->push(this->_buffer->atStart(), size, false); return datagram; }
27.538462
177
0.695065
gautier-lefebvre
6f2d4d7ec9d1bc1a22bcc0300ec98488607e3c66
65
hpp
C++
clove/components/core/platform/include/Clove/Platform/Windows/CloveWindows.hpp
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
33
2020-01-09T04:57:29.000Z
2021-08-14T08:02:43.000Z
clove/components/core/platform/include/Clove/Platform/Windows/CloveWindows.hpp
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
234
2019-10-25T06:04:35.000Z
2021-08-18T05:47:41.000Z
clove/components/core/platform/include/Clove/Platform/Windows/CloveWindows.hpp
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
4
2020-02-11T15:28:42.000Z
2020-09-07T16:22:58.000Z
#define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <Windows.h>
21.666667
27
0.830769
mondoo
6f2daeb28f5468d7c69a6a4bee7a48ccfa47aad9
13,202
cpp
C++
library/src/level2/rocsparse_csrmv.cpp
akilaMD/rocSPARSE
2694e68938cefa711a50b286fd9fd0baff712099
[ "MIT" ]
null
null
null
library/src/level2/rocsparse_csrmv.cpp
akilaMD/rocSPARSE
2694e68938cefa711a50b286fd9fd0baff712099
[ "MIT" ]
null
null
null
library/src/level2/rocsparse_csrmv.cpp
akilaMD/rocSPARSE
2694e68938cefa711a50b286fd9fd0baff712099
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright (c) 2018 Advanced Micro Devices, Inc. * * 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 "definitions.h" #include "rocsparse.h" #include "rocsparse_csrmv.hpp" /* * =========================================================================== * C wrapper * =========================================================================== */ extern "C" rocsparse_status rocsparse_scsrmv_analysis(rocsparse_handle handle, rocsparse_operation trans, rocsparse_int m, rocsparse_int n, rocsparse_int nnz, const rocsparse_mat_descr descr, const float* csr_val, const rocsparse_int* csr_row_ptr, const rocsparse_int* csr_col_ind, rocsparse_mat_info info) { return rocsparse_csrmv_analysis_template( handle, trans, m, n, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info); } extern "C" rocsparse_status rocsparse_dcsrmv_analysis(rocsparse_handle handle, rocsparse_operation trans, rocsparse_int m, rocsparse_int n, rocsparse_int nnz, const rocsparse_mat_descr descr, const double* csr_val, const rocsparse_int* csr_row_ptr, const rocsparse_int* csr_col_ind, rocsparse_mat_info info) { return rocsparse_csrmv_analysis_template( handle, trans, m, n, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info); } extern "C" rocsparse_status rocsparse_ccsrmv_analysis(rocsparse_handle handle, rocsparse_operation trans, rocsparse_int m, rocsparse_int n, rocsparse_int nnz, const rocsparse_mat_descr descr, const rocsparse_float_complex* csr_val, const rocsparse_int* csr_row_ptr, const rocsparse_int* csr_col_ind, rocsparse_mat_info info) { return rocsparse_csrmv_analysis_template( handle, trans, m, n, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info); } extern "C" rocsparse_status rocsparse_zcsrmv_analysis(rocsparse_handle handle, rocsparse_operation trans, rocsparse_int m, rocsparse_int n, rocsparse_int nnz, const rocsparse_mat_descr descr, const rocsparse_double_complex* csr_val, const rocsparse_int* csr_row_ptr, const rocsparse_int* csr_col_ind, rocsparse_mat_info info) { return rocsparse_csrmv_analysis_template( handle, trans, m, n, nnz, descr, csr_val, csr_row_ptr, csr_col_ind, info); } extern "C" rocsparse_status rocsparse_csrmv_clear(rocsparse_handle handle, rocsparse_mat_info info) { // Check for valid handle and matrix descriptor if(handle == nullptr) { return rocsparse_status_invalid_handle; } else if(info == nullptr) { return rocsparse_status_invalid_pointer; } // Logging log_trace(handle, "rocsparse_csrmv_clear", (const void*&)info); // Destroy csrmv info struct RETURN_IF_ROCSPARSE_ERROR(rocsparse_destroy_csrmv_info(info->csrmv_info)); info->csrmv_info = nullptr; return rocsparse_status_success; } extern "C" rocsparse_status rocsparse_scsrmv(rocsparse_handle handle, rocsparse_operation trans, rocsparse_int m, rocsparse_int n, rocsparse_int nnz, const float* alpha, const rocsparse_mat_descr descr, const float* csr_val, const rocsparse_int* csr_row_ptr, const rocsparse_int* csr_col_ind, rocsparse_mat_info info, const float* x, const float* beta, float* y) { return rocsparse_csrmv_template(handle, trans, m, n, nnz, alpha, descr, csr_val, csr_row_ptr, csr_col_ind, info, x, beta, y); } extern "C" rocsparse_status rocsparse_dcsrmv(rocsparse_handle handle, rocsparse_operation trans, rocsparse_int m, rocsparse_int n, rocsparse_int nnz, const double* alpha, const rocsparse_mat_descr descr, const double* csr_val, const rocsparse_int* csr_row_ptr, const rocsparse_int* csr_col_ind, rocsparse_mat_info info, const double* x, const double* beta, double* y) { return rocsparse_csrmv_template(handle, trans, m, n, nnz, alpha, descr, csr_val, csr_row_ptr, csr_col_ind, info, x, beta, y); } extern "C" rocsparse_status rocsparse_ccsrmv(rocsparse_handle handle, rocsparse_operation trans, rocsparse_int m, rocsparse_int n, rocsparse_int nnz, const rocsparse_float_complex* alpha, const rocsparse_mat_descr descr, const rocsparse_float_complex* csr_val, const rocsparse_int* csr_row_ptr, const rocsparse_int* csr_col_ind, rocsparse_mat_info info, const rocsparse_float_complex* x, const rocsparse_float_complex* beta, rocsparse_float_complex* y) { return rocsparse_csrmv_template(handle, trans, m, n, nnz, alpha, descr, csr_val, csr_row_ptr, csr_col_ind, info, x, beta, y); } extern "C" rocsparse_status rocsparse_zcsrmv(rocsparse_handle handle, rocsparse_operation trans, rocsparse_int m, rocsparse_int n, rocsparse_int nnz, const rocsparse_double_complex* alpha, const rocsparse_mat_descr descr, const rocsparse_double_complex* csr_val, const rocsparse_int* csr_row_ptr, const rocsparse_int* csr_col_ind, rocsparse_mat_info info, const rocsparse_double_complex* x, const rocsparse_double_complex* beta, rocsparse_double_complex* y) { return rocsparse_csrmv_template(handle, trans, m, n, nnz, alpha, descr, csr_val, csr_row_ptr, csr_col_ind, info, x, beta, y); }
55.238494
99
0.348508
akilaMD
6f2e459b1555628e9f17111de92544156c04247a
1,923
hpp
C++
include/sphere.hpp
lebarsfa/vpython-wx
38df062e5532b79f632f4f2a1abae86754c264a9
[ "BSL-1.0" ]
68
2015-01-17T05:41:58.000Z
2021-04-24T08:35:24.000Z
include/sphere.hpp
lebarsfa/vpython-wx
38df062e5532b79f632f4f2a1abae86754c264a9
[ "BSL-1.0" ]
16
2015-01-02T19:36:06.000Z
2018-09-09T21:01:25.000Z
include/sphere.hpp
lebarsfa/vpython-wx
38df062e5532b79f632f4f2a1abae86754c264a9
[ "BSL-1.0" ]
37
2015-02-04T04:23:00.000Z
2020-06-07T03:24:41.000Z
#ifndef VPYTHON_SPHERE_HPP #define VPYTHON_SPHERE_HPP // Copyright (c) 2000, 2001, 2002, 2003 by David Scherer and others. // Copyright (c) 2003, 2004 by Jonathan Brandmeyer and others. // See the file license.txt for complete license terms. // See the file authors.txt for a complete list of contributors. #include "axial.hpp" #include "util/displaylist.hpp" namespace cvisual { /** A simple monochrome sphere. */ class sphere : public axial { private: /** The level-of-detail cache. It is stored for the life of the program, and initialized when the first sphere is rendered. At one time there were going to be additional entries for the textured case, but that was not implemented. */ //static displaylist lod_cache[6]; /// True until the first sphere is rendered, then false. static void init_model(view& scene); public: /** Construct a unit sphere at the origin. */ sphere(); sphere( const sphere& other); virtual ~sphere(); protected: /** Renders a simple sphere with the #2 level of detail. */ virtual void gl_pick_render( view&); /** Renders the sphere. All of the spheres share the same basic set of * models, and then use matrix transforms to shape and position them. */ virtual void gl_render( view&); /** Extent reported using extent::add_sphere(). */ virtual void grow_extent( extent&); /** Exposed for the benefit of the ellipsoid object, which overrides it. * The default is to use <radius, radius, radius> for the scale. */ virtual vector get_scale(); /** Returns true if this object should not be drawn. Conditions are: * zero radius, or visible is false. (overridden by the ellipsoid class). */ virtual bool degenerate(); virtual void get_material_matrix( const view&, tmatrix& out ); PRIMITIVE_TYPEINFO_DECL; }; } // !namespace cvisual #endif // !defined VPYTHON_SPHERE_HPP
31.52459
79
0.699428
lebarsfa
6f3a5ec123a79ff128b9824f2d70b379f023af64
6,711
cpp
C++
kernel/devices/pci/PciCapabilities.cpp
DeanoBurrito/northport
6da490b02bfe7d0a12a25316db879ecc249be1c7
[ "MIT" ]
19
2021-12-10T12:48:44.000Z
2022-03-30T09:17:14.000Z
kernel/devices/pci/PciCapabilities.cpp
DeanoBurrito/northport
6da490b02bfe7d0a12a25316db879ecc249be1c7
[ "MIT" ]
24
2021-11-30T10:00:05.000Z
2022-03-29T10:19:21.000Z
kernel/devices/pci/PciCapabilities.cpp
DeanoBurrito/northport
6da490b02bfe7d0a12a25316db879ecc249be1c7
[ "MIT" ]
2
2021-11-24T00:52:10.000Z
2021-12-27T23:47:32.000Z
#include <devices/pci/PciCapabilities.h> #include <devices/PciBridge.h> namespace Kernel::Devices::Pci { sl::Opt<PciCap*> FindPciCap(PciAddress addr, uint8_t withId, PciCap* start) { uint16_t statusReg = addr.ReadReg(1) >> 16; if ((statusReg & (1 << 4)) == 0) return {}; //capabilities list not available PciCap* cap = EnsureHigherHalfAddr(sl::NativePtr(addr.addr).As<PciCap>(addr.ReadReg(0xD) & 0xFF)); bool returnNextMatch = (start == nullptr); while ((uint64_t)cap != EnsureHigherHalfAddr(addr.addr)) { if (cap->capabilityId == withId && returnNextMatch) return cap; if (cap == start) returnNextMatch = true; cap = EnsureHigherHalfAddr(sl::NativePtr(addr.addr).As<PciCap>(cap->nextOffset)); } return {}; } bool PciCapMsi::Enabled() const { const uint16_t control = sl::MemRead<uint16_t>((uintptr_t)this + 2); return control & 0b1; } void PciCapMsi::Enable(bool yes) { uint16_t control = sl::MemRead<uint16_t>((uintptr_t)this + 2); control &= ~0b1; if (yes) control |= 0b1; sl::MemWrite<uint16_t>((uintptr_t)this + 2, control); } size_t PciCapMsi::VectorsRequested() const { const uint16_t control = sl::MemRead<uint16_t>((uintptr_t)this + 2); return 1 << ((control >> 1) & 0b111); } void PciCapMsi::SetVectorsEnabled(size_t count) { uint16_t control = sl::MemRead<uint16_t>((uintptr_t)this + 2); control &= 0xFF8F; switch (count) { case 1: control |= (0b000) << 4; break; case 2: control |= (0b001) << 4; break; case 4: control |= (0b010) << 4; break; case 8: control |= (0b011) << 4; break; case 16: control |= (0b100) << 4; break; case 32: control |= (0b101) << 4; break; default: return; } sl::MemWrite<uint16_t>((uintptr_t)this + 2, control); } bool PciCapMsi::Has64BitAddress() const { const uint16_t control = sl::MemRead<uint16_t>((uintptr_t)this + 2); return control & (1 << 7); } void PciCapMsi::SetAddress(sl::NativePtr ptr) { sl::MemWrite<uint32_t>((uintptr_t)this + 4, ptr.raw & 0xFFFF'FFFF); if (Has64BitAddress()) sl::MemWrite<uint32_t>((uintptr_t)this + 8, ptr.raw >> 32); } void PciCapMsi::SetData(uint16_t data) { if (Has64BitAddress()) sl::MemWrite((uintptr_t)this + 0xC, data); else sl::MemWrite((uintptr_t)this + 8, data); } bool PciCapMsi::Masked(size_t index) const { const uint16_t control = sl::MemRead<uint16_t>((uintptr_t)this + 2); if ((control & (1 << 8)) == 0) return false; if (index >= 32) return false; if (Has64BitAddress()) return sl::MemRead<uint32_t>((uintptr_t)this + 0x10) & (1 << index); else return sl::MemRead<uint32_t>((uintptr_t)this + 0xC) & (1 << index); } void PciCapMsi::Mask(size_t index, bool masked) { const uint16_t control = sl::MemRead<uint16_t>((uintptr_t)this + 2); if ((control & (1 << 8)) == 0) return; if (index >= 32) return; const uintptr_t addr = (uintptr_t)this + (Has64BitAddress() ? 0x10 : 0xC); uint32_t value = sl::MemRead<uint32_t>(addr) & ~(1 << index); if (masked) value |= 1 << index; sl::MemWrite<uint32_t>(addr, value); } bool PciCapMsi::Pending(size_t index) const { const uint16_t control = sl::MemRead<uint16_t>((uintptr_t)this + 2); if ((control & (1 << 8)) == 0) return false; if (index >= 32) return false; if (Has64BitAddress()) return sl::MemRead<uint32_t>((uintptr_t)this + 0x14) & (1 << index); else return sl::MemRead<uint32_t>((uintptr_t)this + 0x10) & (1 << index); } sl::NativePtr PciCapMsiX::GetTableEntry(size_t index, PciBar* bars) const { const size_t count = (sl::MemRead<uint32_t>((uintptr_t)this + 2) & 0x3FF) + 1; if (index >= count) return nullptr; const size_t bir = sl::MemRead<uint32_t>((uintptr_t)this + 4) & 0b111; const uintptr_t tableOffset = sl::MemRead<uint32_t>((uintptr_t)this + 4) & ~0b111; return bars[bir].address + tableOffset + index * 16; } bool PciCapMsiX::Enabled() const { return sl::MemRead<uint32_t>((uintptr_t)this + 2) & (1 << 15); } void PciCapMsiX::Enable(bool yes) { uint16_t control = sl::MemRead<uint16_t>((uintptr_t)this + 2); control &= 0x7F; if (yes) control |= 1 << 15; sl::MemWrite((uintptr_t)this + 2, control); } size_t PciCapMsiX::Vectors() const { return (sl::MemRead<uint32_t>((uintptr_t)this + 2) & 0x3FF) + 1; } void PciCapMsiX::SetVector(size_t index, uint64_t address, uint16_t data, PciBar* bars) { sl::NativePtr entryAddr = GetTableEntry(index, bars); if (entryAddr.ptr == nullptr) return; sl::MemWrite<uint64_t>(entryAddr, address); sl::MemWrite<uint32_t>(entryAddr.raw + 8, data); } bool PciCapMsiX::Masked(size_t index, PciBar* bars) const { sl::NativePtr entryAddr = GetTableEntry(index, bars); if (entryAddr.ptr == nullptr) return false; return sl::MemRead<uint16_t>(entryAddr.raw + 12) & 0b1; } void PciCapMsiX::Mask(size_t index, bool masked, PciBar* bars) { sl::NativePtr entryAddr = GetTableEntry(index, bars); if (entryAddr.ptr == nullptr) return; uint16_t value = sl::MemRead<uint16_t>(entryAddr.raw + 12); value &= 0b1; if (masked) value |= 0b1; sl::MemWrite(entryAddr.raw + 12, value); } bool PciCapMsiX::Pending(size_t index, PciBar* bars) const { const size_t count = (sl::MemRead<uint32_t>((uintptr_t)this + 2) & 0x3FF) + 1; if (index >= count) return false; const size_t bir = sl::MemRead<uint32_t>((uintptr_t)this + 4) & 0b111; const uintptr_t arrayOffset = sl::MemRead<uint32_t>((uintptr_t)this + 4) & ~0b111; const sl::NativePtr arrayAddr = bars[bir].address + arrayOffset; return (sl::MemRead<uint64_t>(arrayAddr) + index / 64) & (1 << index % 64); } }
31.805687
106
0.554016
DeanoBurrito
6f3b10fd913ba92540b381a7af8e05f4c197853b
4,287
cpp
C++
tests/NEO/SignerTests.cpp
vladyslav-iosdev/wallet-core
6f8f175a380bdf9756f38bfd82fedd9b73b67580
[ "MIT" ]
1,306
2019-08-08T13:25:24.000Z
2022-03-31T23:32:28.000Z
tests/NEO/SignerTests.cpp
vladyslav-iosdev/wallet-core
6f8f175a380bdf9756f38bfd82fedd9b73b67580
[ "MIT" ]
1,179
2019-08-08T07:06:10.000Z
2022-03-31T12:33:47.000Z
tests/NEO/SignerTests.cpp
vladyslav-iosdev/wallet-core
6f8f175a380bdf9756f38bfd82fedd9b73b67580
[ "MIT" ]
811
2019-08-08T13:27:44.000Z
2022-03-31T21:22:53.000Z
// Copyright © 2017-2020 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "PublicKey.h" #include "HexCoding.h" #include "NEO/Address.h" #include "NEO/Signer.h" #include <gtest/gtest.h> using namespace std; using namespace TW; using namespace TW::NEO; TEST(NEOSigner, FromPublicPrivateKey) { auto hexPrvKey = "4646464646464646464646464646464646464646464646464646464646464646"; auto hexPubKey = "031bec1250aa8f78275f99a6663688f31085848d0ed92f1203e447125f927b7486"; auto signer = Signer(PrivateKey(parse_hex(hexPrvKey))); auto prvKey = signer.getPrivateKey(); auto pubKey = signer.getPublicKey(); EXPECT_EQ(hexPrvKey, hex(prvKey.bytes)); EXPECT_EQ(hexPubKey, hex(pubKey.bytes)); auto address = signer.getAddress(); EXPECT_TRUE(Address::isValid(address.string())); EXPECT_EQ(Address(pubKey), address); } TEST(NEOSigner, SigningData) { auto signer = Signer(PrivateKey(parse_hex("4646464646464646464646464646464646464646464646464646464646464646"))); auto verScript = "ba7908ddfe5a1177f2c9d3fa1d3dc71c9c289a3325b3bdd977e20c50136959ed02d1411efa5e8b897d970ef7e2325e6c0a3fdee4eb421223f0d86e455879a9ad"; auto invocationScript = string("401642b3d538e138f34b32330e381a7fe3f5151fcf958f2030991e72e2e25043143e4a1ebd239634efba279c96fa0ab04a15aa15179d73a7ef5a886ac8a06af484401642b3d538e138f34b32330e381a7fe3f5151fcf958f2030991e72e2e25043143e4a1ebd239634efba279c96fa0ab04a15aa15179d73a7ef5a886ac8a06af484401642b3d538e138f34b32330e381a7fe3f5151fcf958f2030991e72e2e25043143e4a1ebd239634efba279c96fa0ab04a15aa15179d73a7ef5a886ac8a06af484"); invocationScript = string(invocationScript.rbegin(), invocationScript.rend()); EXPECT_EQ(verScript, hex(signer.sign(parse_hex(invocationScript)))); } TEST(NEOAccount, validity) { auto hexPrvKey = "4646464646464646464646464646464646464646464646464646464646464646"; auto hexPubKey = "031bec1250aa8f78275f99a6663688f31085848d0ed92f1203e447125f927b7486"; auto signer = Signer(PrivateKey(parse_hex(hexPrvKey))); auto prvKey = signer.getPrivateKey(); auto pubKey = signer.getPublicKey(); EXPECT_EQ(hexPrvKey, hex(prvKey.bytes)); EXPECT_EQ(hexPubKey, hex(pubKey.bytes)); } TEST(NEOSigner, SigningTransaction) { auto signer = Signer(PrivateKey(parse_hex("F18B2F726000E86B4950EBEA7BFF151F69635951BC4A31C44F28EE6AF7AEC128"))); auto transaction = Transaction(); transaction.type = TransactionType::TT_ContractTransaction; transaction.version = 0x00; CoinReference coin; coin.prevHash = load(parse_hex("9c85b39cd5677e2bfd6bf8a711e8da93a2f1d172b2a52c6ca87757a4bccc24de")); //reverse hash coin.prevIndex = (uint16_t) 1; transaction.inInputs.push_back(coin); { TransactionOutput out; out.assetId = load(parse_hex("9b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc5")); out.value = (int64_t) 1 * 100000000; auto scriptHash = TW::NEO::Address("Ad9A1xPbuA5YBFr1XPznDwBwQzdckAjCev").toScriptHash(); out.scriptHash = load(scriptHash); transaction.outputs.push_back(out); } { TransactionOutput out; out.assetId = load(parse_hex("9b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc5")); out.value = (int64_t) 892 * 100000000; auto scriptHash = TW::NEO::Address("AdtSLMBqACP4jv8tRWwyweXGpyGG46eMXV").toScriptHash(); out.scriptHash = load(scriptHash); transaction.outputs.push_back(out); } signer.sign(transaction); auto signedTx = transaction.serialize(); EXPECT_EQ(hex(signedTx), "800000019c85b39cd5677e2bfd6bf8a711e8da93a2f1d172b2a52c6ca87757a4bccc24de0100029b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc500e1f50500000000ea610aa6db39bd8c8556c9569d94b5e5a5d0ad199b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc500fcbbc414000000f2908c7efc0c9e43ffa7e79170ba37e501e1b4ac0141405046619c8e20e1fdeec92ce95f3019f6e7cc057294eb16b2d5e55c105bf32eb27e1fc01c1858576228f1fef8c0945a8ad69688e52a4ed19f5b85f5eff7e961d7232102a41c2aea8568864b106553729d32b1317ec463aa23e7a3521455d95992e17a7aac"); }
50.435294
557
0.804759
vladyslav-iosdev
6f3fd83769469def7e39feeb43f9bec6bb6d4790
2,350
cpp
C++
lib/frame_window_filtering/disparity_morphology.cpp
itko/scanbox
9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3
[ "BSD-3-Clause" ]
1
2020-01-09T09:30:23.000Z
2020-01-09T09:30:23.000Z
lib/frame_window_filtering/disparity_morphology.cpp
itko/scanbox
9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3
[ "BSD-3-Clause" ]
23
2018-03-19T20:54:52.000Z
2018-05-16T12:36:59.000Z
lib/frame_window_filtering/disparity_morphology.cpp
itko/scanbox
9a00c11eafb4cc2faa69bfcc76bdf0d8e295dcf3
[ "BSD-3-Clause" ]
1
2018-03-14T20:00:43.000Z
2018-03-14T20:00:43.000Z
/// \file /// Maintainer: Felice Serena /// /// #include "disparity_morphology.h" #include <boost/log/trivial.hpp> #include <iostream> #include <opencv2/core/eigen.hpp> #include <opencv2/imgproc/imgproc.hpp> namespace MouseTrack { FrameWindow DisparityMorphology::operator()(const FrameWindow &window) const { FrameWindow result = window; int op = opencvOperation(); cv::Mat kernel = getStructuringElement( opencvKernelShape(), cv::Size(2 * diameter() + 1, 2 * diameter() + 1), cv::Point(diameter(), diameter())); for (size_t i = 0; i < window.frames().size(); ++i) { Frame &f = result.frames()[i]; auto &disp = f.normalizedDisparityMap; cv::Mat raw, processed; cv::eigen2cv(disp, raw); cv::morphologyEx(raw, processed, op, kernel); cv::cv2eigen(processed, f.normalizedDisparityMap); } return result; } int DisparityMorphology::diameter() const { return _diameter; } void DisparityMorphology::diameter(int _new) { _diameter = _new; } DisparityMorphology::Morph DisparityMorphology::operation() const { return _operation; } void DisparityMorphology::operation(Morph _new) { _operation = _new; } DisparityMorphology::KernelShape DisparityMorphology::kernelShape() const { return _kernelShape; } void DisparityMorphology::kernelShape(KernelShape _new) { _kernelShape = _new; } int DisparityMorphology::opencvOperation() const { switch (operation()) { case Morph::open: return cv::MORPH_OPEN; case Morph::close: return cv::MORPH_CLOSE; default: BOOST_LOG_TRIVIAL(warning) << "Unexpected value for morphology operation encountered " << operation() << ". Please add to switch statement."; throw "Unexpected morphology operation encountered, please add to switch " "statement."; } } int DisparityMorphology::opencvKernelShape() const { switch (kernelShape()) { case KernelShape::rect: return cv::MORPH_RECT; case KernelShape::ellipse: return cv::MORPH_ELLIPSE; case KernelShape::cross: return cv::MORPH_CROSS; default: BOOST_LOG_TRIVIAL(warning) << "Unexpected value for morphology kernel shape encountered " << operation() << ". Please add to switch statement."; throw "Unexpected morphology kernel shape encountered, please add to " "switch statement."; } } } // namespace MouseTrack
30.519481
80
0.701277
itko
6f4713c130917dcea35d3d2c842b4dc3b0f5e7a3
2,833
cpp
C++
src/services/svc-mdns.cpp
RDobrinov/espurna32
b0bcf5bb80324e3c96a8a7f756014804b618730e
[ "NTP", "Unlicense" ]
null
null
null
src/services/svc-mdns.cpp
RDobrinov/espurna32
b0bcf5bb80324e3c96a8a7f756014804b618730e
[ "NTP", "Unlicense" ]
null
null
null
src/services/svc-mdns.cpp
RDobrinov/espurna32
b0bcf5bb80324e3c96a8a7f756014804b618730e
[ "NTP", "Unlicense" ]
null
null
null
/* MDNS MODULE Copyright (C) 2017-2019 by Xose Pérez <xose dot perez at gmail dot com> */ // ----------------------------------------------------------------------------- // mDNS Server // ----------------------------------------------------------------------------- #include "config/hardware.h" #if MDNS_SERVER_SUPPORT #include <ESPmDNS.h> #include "espurna32.hpp" #include "config/version.h" #if MQTT_SUPPORT void _mdnsFindMQTT() { int count = MDNS.queryService("mqtt", "tcp"); DEBUG_MSG_P(PSTR("[MQTT] MQTT brokers found: %d\n"), count); for (int i=0; i<count; i++) { DEBUG_MSG_P(PSTR("[MQTT] Broker at %s:%d\n"), MDNS.IP(i).toString().c_str(), MDNS.port(i)); mqttSetBrokerIfNone(MDNS.IP(i), MDNS.port(i)); } } #endif void _mdnsServerStart() { if (MDNS.begin((char *) getSetting("hostname").c_str())) { DEBUG_MSG_P(PSTR("[MDNS] Service is ready\n")); } else { DEBUG_MSG_P(PSTR("[MDNS] Service FAIL\n")); } } // ----------------------------------------------------------------------------- void _mdnsServerServices() { #if WEB_SUPPORT MDNS.addService("http", "tcp", getSetting("webPort", WEB_PORT).toInt()); #endif #if TELNET_SUPPORT MDNS.addService("telnet", "tcp", TELNET_PORT); #endif // Public ESPurna related txt for OTA discovery MDNS.addServiceTxt("arduino", "tcp", "app_name", APP_NAME); MDNS.addServiceTxt("arduino", "tcp", "app_version", APP_VERSION); MDNS.addServiceTxt("arduino", "tcp", "build_date", buildTime()); MDNS.addServiceTxt("arduino", "tcp", "mac", WiFi.macAddress()); MDNS.addServiceTxt("arduino", "tcp", "target_board", getBoardName()); { char buffer[6] = {0}; itoa(spi_flash_get_chip_size() / 1024, buffer, 10); MDNS.addServiceTxt("arduino", "tcp", "mem_size", (const char *) buffer); } { char buffer[6] = {0}; itoa(ESP.getFlashChipSize() / 1024, buffer, 10); MDNS.addServiceTxt("arduino", "tcp", "sdk_size", (const char *) buffer); } { char buffer[6] = {0}; itoa(ESP.getFreeSketchSpace(), buffer, 10); MDNS.addServiceTxt("arduino", "tcp", "free_space", (const char *) buffer); } } void mdnsServerSetup() { wifiRegister([](justwifi_messages_t code, char * parameter) { if (code == MESSAGE_CONNECTED) { _mdnsServerStart(); _mdnsServerServices(); #if MQTT_SUPPORT _mdnsFindMQTT(); #endif // MQTT_SUPPORT } if (code == MESSAGE_ACCESSPOINT_CREATED) { _mdnsServerStart(); _mdnsServerServices(); } if ( (code == MESSAGE_ACCESSPOINT_DESTROYED) || (code == MESSAGE_DISCONNECTED) ) MDNS.end(); }); } #endif // MDNS_SERVER_SUPPORT
27.504854
99
0.549594
RDobrinov
6f4b12abd36a6e78d7c1c194358d03b9974b8ade
1,085
cpp
C++
LeetCode/680.valid_palindrome_2.cpp
PieroNarciso/cprogramming
d3a53ce2afce6f853e0b7cc394190d5be6427902
[ "MIT" ]
2
2021-05-22T17:47:01.000Z
2021-05-27T17:10:58.000Z
LeetCode/680.valid_palindrome_2.cpp
PieroNarciso/cprogramming
d3a53ce2afce6f853e0b7cc394190d5be6427902
[ "MIT" ]
null
null
null
LeetCode/680.valid_palindrome_2.cpp
PieroNarciso/cprogramming
d3a53ce2afce6f853e0b7cc394190d5be6427902
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; bool validPalindrome(string s) { if (s.size() <= 1) return true; int start = 0; int end = s.size() - 1; int count = 0; while (start < end && count <= 1) { if (s[start] != s[end]) { end--; count++; } else if (s[start] == s[end]) { end--; start++; } } if (count <= 1) { return true; } else { start = 0; end = s.size() - 1; count = 0; while (start < end && count <= 1) { if (s[start] != s[end]) { start++; count++; } else if (s[start] == s[end]) { end--; start++; } } if (count <= 1) return true; return false; } } int main(int argc, const char** argv) { cout << validPalindrome("aba") << " " << true << endl; cout << validPalindrome("abca") << " " << true << endl; cout << validPalindrome("abc") << " " << false << endl; cout << validPalindrome("a") << " " << true << endl; cout << validPalindrome("racecar") << " " << true << endl; cout << validPalindrome("rececab") << " " << false << endl; cout << validPalindrome("deeeee") << " " << true << endl; return 0; }
21.7
60
0.517972
PieroNarciso
6f4d1b8a026c8333c161f9cfc4a43f3bfd437630
5,603
hpp
C++
src/core/Patchwork.hpp
tfwu/AOGDetector
296bdeefa3e111596ea824396203d15c5c0c4577
[ "MIT" ]
33
2016-01-11T22:42:41.000Z
2020-12-27T17:19:26.000Z
src/core/Patchwork.hpp
mrgloom/AOGDetector
296bdeefa3e111596ea824396203d15c5c0c4577
[ "MIT" ]
null
null
null
src/core/Patchwork.hpp
mrgloom/AOGDetector
296bdeefa3e111596ea824396203d15c5c0c4577
[ "MIT" ]
16
2015-11-15T14:48:28.000Z
2021-09-16T12:59:07.000Z
// This file is adapted from FFLDv2 (the Fast Fourier Linear Detector version 2) // Copyright (c) 2013 Idiap Research Institute, <http://www.idiap.ch/> // Written by Charles Dubout <charles.dubout@idiap.ch> #ifndef RGM_PATCHWORK_HPP_ #define RGM_PATCHWORK_HPP_ #include <utility> extern "C" { #include <fftw3.h> } #include "FeaturePyramid.hpp" #include "Rectangle.hpp" namespace RGM { /// The Patchwork class computes full convolutions much faster using FFT class Patchwork { public: /// Type of a patchwork plane cell (fixed-size complex vector of size NbFeatures). typedef Eigen::Array<CScalar, FeaturePyramid::NbFeatures, 1> Cell; /// Type of a patchwork plane (matrix of cells). typedef Eigen::Matrix<Cell, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> Plane; /// Type of a patchwork filter (plane + original filter size). typedef std::pair<Plane, std::pair<int, int> > Filter; #if RGM_USE_PCA_DIM typedef Eigen::Array<CScalar, FeaturePyramid::NbPCAFeatures, 1> PCACell; typedef Eigen::Matrix<PCACell, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> PCAPlane; typedef std::pair<PCAPlane, std::pair<int, int> > PCAFilter; #endif /// Constructs an empty patchwork. An empty patchwork has no plane. Patchwork(); /// Constructs a patchwork from a pyramid. /// @param[in] pyramid The pyramid of features. /// @param[in] withPCA The setting for applying PCA projected features: 0 - no pca, 1 - only pca, 2 - both /// @note If the pyramid is larger than the last maxRows and maxCols passed to the Init method /// the Patchwork will be empty. /// @note Assumes that the features of the pyramid levels are zero in the padded regions but for /// the last feature, which is assumed to be one. Patchwork(const FeaturePyramid & pyramid, int withPCA=0); /// Returns the amount of horizontal zero padding (in cells). int padx() const; /// Returns the amount of vertical zero padding (in cells). int pady() const; /// Returns the number of levels per octave in the pyramid. int interval() const; /// Returns whether the patchwork is empty. An empty patchwork has no plane. bool empty() const; /// Returns the convolutions of the patchwork with filters (useful to compute the SVM margins). /// @param[in] filters The filters. /// @param[out] convolutions The convolutions (filters x levels). void convolve(const std::vector<Filter *> & filters, std::vector<std::vector<Matrix> > & convolutions) const; /// Initializes the FFTW library. /// @param[in] maxRows Maximum number of rows of a pyramid level (including padding). /// @param[in] maxCols Maximum number of columns of a pyramid level (including padding). /// @param[in] withPCA The setting for applying PCA projected features: 0 - no pca, 1 - only pca, 2 - both /// @returns Whether the initialization was successful. /// @note Must be called before any other method (including constructors). static bool InitFFTW(int maxRows, int maxCols, int withPCA=0); /// Returns the current maximum number of rows of a pyramid level (including padding). static int MaxRows(); /// Returns the current maximum number of columns of a pyramid level (including padding). static int MaxCols(); /// Returns a transformed version of a filter to be used by the @c convolve method. /// @param[in] filter Filter to transform. /// @param[out] result Transformed filter. /// @note If Init was not already called or if the filter is larger than the last maxRows and /// maxCols passed to the Init method the result will be empty. static void TransformFilter(const FeaturePyramid::Level & filter, Filter & result); #if RGM_USE_PCA_DIM bool emptyPCA() const; void convolve(const std::vector<PCAFilter *> & filters, std::vector<std::vector<Matrix> > & convolutions) const; static void TransformPCAFilter(const FeaturePyramid::PCALevel & filter, PCAFilter & result); #endif private: #if RGM_USE_PCA_DIM static bool InitFFTWForPCA(int maxRows, int maxCols); #endif int padx_; int pady_; int interval_; std::vector<std::pair<Rectangle2i, int> > rectangles_; std::vector<Plane> planes_; #if RGM_USE_PCA_DIM std::vector<PCAPlane> PCAplanes_; #endif static int MaxRows_; static int MaxCols_; static int HalfCols_; #ifndef RGM_USE_DOUBLE static fftwf_plan Forwards_; static fftwf_plan Inverse_; #if RGM_USE_PCA_DIM static fftwf_plan PCAForwards_; static fftwf_plan PCAInverse_; #endif #else static fftw_plan Forwards_; static fftw_plan Inverse_; #if RGM_USE_PCA_DIM static fftw_plan PCAForwards_; static fftw_plan PCAInverse_; #endif #endif }; // class Patchwork } // namespace RGM // Some compilers complain about the lack of a NumTraits for Eigen::Array<CScalar, NbFeatures, 1> namespace Eigen { template <> struct NumTraits<Array<RGM::CScalar, RGM::FeaturePyramid::NbFeatures, 1> > : GenericNumTraits<Array<RGM::CScalar, RGM::FeaturePyramid::NbFeatures, 1> > { static inline RGM::Scalar dummy_precision() { return 0; // Never actually called } }; #if RGM_USE_PCA_DIM template <> struct NumTraits<Array<RGM::CScalar, RGM::FeaturePyramid::NbPCAFeatures, 1> > : GenericNumTraits<Array<RGM::CScalar, RGM::FeaturePyramid::NbPCAFeatures, 1> > { static inline RGM::Scalar dummy_precision() { return 0; // Never actually called } }; #endif } // namespace Eigen #endif // RGM_PATCHWORK_HPP_
33.957576
110
0.704087
tfwu
6f534a2bc172a3dc5c80a02a292e44e0f461e39b
5,748
cpp
C++
RLSimion/Common/named-var-set.cpp
xcillero001/SimionZoo
b343b08f3356e1aa230d4132b0abb58aac4c5e98
[ "MIT" ]
1
2019-02-21T10:40:28.000Z
2019-02-21T10:40:28.000Z
RLSimion/Common/named-var-set.cpp
JosuGom3z/SimionZoo
b343b08f3356e1aa230d4132b0abb58aac4c5e98
[ "MIT" ]
null
null
null
RLSimion/Common/named-var-set.cpp
JosuGom3z/SimionZoo
b343b08f3356e1aa230d4132b0abb58aac4c5e98
[ "MIT" ]
null
null
null
#include "named-var-set.h" #include "wire.h" #include "wire-handler.h" #include <algorithm> #include <stdexcept> #include "../../tools/System/CrossPlatform.h" using namespace std; NamedVarProperties::NamedVarProperties() { CrossPlatform::Strcpy_s(m_name, VAR_NAME_MAX_LENGTH, "N/A"); CrossPlatform::Strcpy_s(m_units, VAR_NAME_MAX_LENGTH, "N/A"); m_min = std::numeric_limits<double>::lowest(); m_max = std::numeric_limits<double>::max(); } NamedVarProperties::NamedVarProperties(const char* name, const char* units, double min, double max, bool bCircular) { CrossPlatform::Sprintf_s(m_name, VAR_NAME_MAX_LENGTH, name); CrossPlatform::Sprintf_s(m_units, VAR_NAME_MAX_LENGTH, units); m_min = min; m_max = max; m_bCircular = bCircular; //default value } void NamedVarProperties::setName(const char* name) { CrossPlatform::Strcpy_s(m_name, VAR_NAME_MAX_LENGTH, name); } NamedVarProperties* Descriptor::getProperties(const char* name) { for (size_t i = 0; i<m_descriptor.size(); i++) { if (strcmp(m_descriptor[i]->getName(), name) == 0) return m_descriptor[i]; } //check if a wire with that name exists Wire* pWire = m_pWireHandler->wireGet(name); if (pWire != nullptr) { NamedVarProperties* pProperties = pWire->getProperties(); if (pProperties==nullptr) return &wireDummyProperties; return pProperties; } else throw std::runtime_error("Wrong variable name given to Descriptor::getVarIndex()"); } size_t Descriptor::addVariable(const char* name, const char* units, double min, double max, bool bCircular) { size_t index = (int) m_descriptor.size(); m_descriptor.push_back(new NamedVarProperties(name, units, min, max, bCircular)); return index; } NamedVarSet* Descriptor::getInstance() { NamedVarSet* pNew = new NamedVarSet(*this); return pNew; } NamedVarSet::NamedVarSet(Descriptor& descriptor): m_descriptor(descriptor) { //m_descriptor= new NamedVarProperties[numVars]; m_pValues= new double[descriptor.size()]; for (size_t i = 0; i < descriptor.size(); i++) m_pValues[i] = 0.0; m_numVars= (int)descriptor.size(); } NamedVarSet::~NamedVarSet() { if (m_pValues) delete [] m_pValues; } NamedVarProperties* NamedVarSet::getProperties(const char* varName) const { return m_descriptor.getProperties(varName); } double NamedVarSet::normalize(const char* varName, double value) const { NamedVarProperties* pProperties = getProperties(varName); double range = std::max(0.01, pProperties->getRangeWidth()); return (value - pProperties->getMin()) / range; } double NamedVarSet::denormalize(const char* varName, double value) const { NamedVarProperties* pProperties = getProperties(varName); double range = pProperties->getRangeWidth(); return pProperties->getMin() + value * range; } void NamedVarSet::setNormalized(const char* varName, double value) { double denormalizedValue = denormalize(varName, value); set(varName, denormalizedValue); } void NamedVarSet::set(const char* varName, double value) { for (size_t i = 0; i < m_descriptor.size(); i++) { if (!strcmp(m_descriptor[i].getName(), varName)) { set(i, value); return; } } //check if a wire with that name exists WireHandler* pWireHandler = m_descriptor.getWireHandler(); if (pWireHandler != nullptr) { Wire* pWire = pWireHandler->wireGet(varName); if (pWire != nullptr) pWire->setValue(value); else throw std::runtime_error("Incorrect variable name in NamedVarSet::set()"); } else throw std::runtime_error("Incorrect variable name in NamedVarSet::set()"); } void NamedVarSet::set(size_t i, double value) { if (i >= 0 && i < m_numVars) { if (!m_descriptor[i].isCircular()) { m_pValues[i] = std::min(m_descriptor[i].getMax() , std::max(m_descriptor[i].getMin(), value)); } else { if (value > m_descriptor[i].getMax()) value -= m_descriptor[i].getRangeWidth(); else if (value < m_descriptor[i].getMin()) value += m_descriptor[i].getRangeWidth(); m_pValues[i] = value; } } else throw std::runtime_error("Incorrect variable index in NamedVarSet::set()"); } double NamedVarSet::getNormalized(const char* varName) const { return normalize(varName, get(varName)); } double NamedVarSet::get(size_t i) const { if (i >= 0 && i<m_numVars) return m_pValues[i]; throw std::runtime_error("Incorrect variable index in NamedVarSet::get()"); } double NamedVarSet::get(const char* varName) const { for (size_t i = 0; i < m_descriptor.size(); i++) { if (!strcmp(m_descriptor[i].getName(), varName)) return m_pValues[i]; } WireHandler* pWireHandler = m_descriptor.getWireHandler(); if (pWireHandler != nullptr) { Wire* pWire= pWireHandler->wireGet(varName); if (pWire != nullptr) return pWire->getValue(); else throw std::runtime_error("Incorrect variable name in NamedVarSet::get()"); } else throw std::runtime_error("Incorrect variable name in NamedVarSet::get()"); } double* NamedVarSet::getValuePtr(size_t i) { if (i >= 0 && i<m_numVars) return &m_pValues[i]; throw std::runtime_error("Incorrect variable index in NamedVarSet::getValuePtr()"); } double& NamedVarSet::getRef(size_t i) { if (i >= 0 && i<m_numVars) return m_pValues[i]; throw std::runtime_error("Incorrect variable index in NamedVarSet::getRef()"); } double NamedVarSet::getSumValue() const { double sum = 0.0; for (size_t i = 0; i < m_numVars; i++) sum += m_pValues[i]; return sum; } void NamedVarSet::copy(const NamedVarSet* nvs) { if(m_numVars != nvs->getNumVars()) throw std::runtime_error("Missmatched array lenghts in NamedVarSet::copy()"); for (size_t i = 0; i<m_numVars; i++) { set(i, nvs->get(i)); } } void NamedVarSet::addOffset(double offset) { for (size_t i = 0; i<m_numVars; i++) { set(i, this->get(i) + offset); } }
24.991304
115
0.709986
xcillero001
6f53f478c54127fe674d24559593dc5fb5dd7e83
129
cc
C++
tensorflow-yolo-ios/dependencies/tensorflow/core/platform/posix/net.cc
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/tensorflow/core/platform/posix/net.cc
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/tensorflow/core/platform/posix/net.cc
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:3cc7fcb7f8a9a1e665dce3cb98580bd376e1c6dfd73287c5c623743400561d9b size 3402
32.25
75
0.883721
initialz
6f547ad130111112210b243c95ec816c8ce6c908
774
cpp
C++
breeze/testing/brz/test_descriptor.cpp
gennaroprota/breeze
7afe88a30dc8ac8b97a76a192dc9b189d9752e8b
[ "BSD-3-Clause" ]
1
2021-04-03T22:35:52.000Z
2021-04-03T22:35:52.000Z
breeze/testing/brz/test_descriptor.cpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
null
null
null
breeze/testing/brz/test_descriptor.cpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
1
2021-10-01T04:26:48.000Z
2021-10-01T04:26:48.000Z
// =========================================================================== // Copyright 2016 Gennaro Prota // // Licensed under the 3-Clause BSD License. // (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or // <https://opensource.org/licenses/BSD-3-Clause>.) // ___________________________________________________________________________ #include "breeze/testing/test_descriptor.hpp" namespace breeze_ns { test_descriptor::test_descriptor( test_function f, char const * name ) : m_function( f ), m_name( name ) { } test_descriptor::test_function test_descriptor::function() const noexcept { return m_function ; } std::string test_descriptor::name() const { return m_name ; } }
24.967742
78
0.609819
gennaroprota
6f59ce012956abb6322c028101f43206f4ec15a5
2,671
cpp
C++
products/BellHybrid/apps/application-bell-settings/presenter/TimeUnitsPresenter.cpp
GravisZro/MuditaOS
4230da15e69350c3ef9e742ec587e5f70154fabd
[ "BSL-1.0" ]
369
2021-11-10T09:20:29.000Z
2022-03-30T06:36:58.000Z
products/BellHybrid/apps/application-bell-settings/presenter/TimeUnitsPresenter.cpp
GravisZro/MuditaOS
4230da15e69350c3ef9e742ec587e5f70154fabd
[ "BSL-1.0" ]
149
2021-11-10T08:38:35.000Z
2022-03-31T23:01:52.000Z
products/BellHybrid/apps/application-bell-settings/presenter/TimeUnitsPresenter.cpp
GravisZro/MuditaOS
4230da15e69350c3ef9e742ec587e5f70154fabd
[ "BSL-1.0" ]
41
2021-11-10T08:30:37.000Z
2022-03-29T08:12:46.000Z
// Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "models/TemperatureUnitModel.hpp" #include "presenter/TimeUnitsPresenter.hpp" #include <common/layouts/HomeScreenLayouts.hpp> #include <common/models/LayoutModel.hpp> #include <appmgr/messages/ChangeHomescreenLayoutMessage.hpp> #include <service-appmgr/Constants.hpp> namespace app::bell_settings { TimeUnitsWindowPresenter::TimeUnitsWindowPresenter( app::ApplicationCommon *app, std::shared_ptr<TimeUnitsModel> pagesProvider, std::unique_ptr<AbstractTemperatureUnitModel> temperatureUnitModel, std::unique_ptr<AbstractLayoutModel> layoutModel) : app{app}, pagesProvider(std::move(pagesProvider)), temperatureUnitModel{std::move(temperatureUnitModel)}, layoutModel{std::move(layoutModel)} {} auto TimeUnitsWindowPresenter::getPagesProvider() const -> std::shared_ptr<gui::ListItemProvider> { return pagesProvider; } auto TimeUnitsWindowPresenter::clearData() -> void { pagesProvider->clearData(); } auto TimeUnitsWindowPresenter::saveData() -> void { pagesProvider->saveData(); temperatureUnitModel->set(pagesProvider->getTemperatureUnit()); auto timeFormat = pagesProvider->getTimeFormat(); auto currentLayout = layoutModel->getValue(); auto isCurrentLayout12h = true; if (timeFormat == utils::time::Locale::TimeFormat::FormatTime24H) { for (const auto &layout : gui::factory::getLayoutsFormat24h()) { if (layout.first == currentLayout) { isCurrentLayout12h = false; break; } } if (isCurrentLayout12h) { std::string fallbackLayout; if (currentLayout->rfind("Classic", 0) == 0) { fallbackLayout = "Classic"; } else if (currentLayout->rfind("Vertical", 0) == 0) { fallbackLayout = "VerticalSimple"; } auto layoutChangeRequest = std::make_shared<ChangeHomescreenLayoutMessage>(fallbackLayout); app->bus.sendUnicast(layoutChangeRequest, service::name::appmgr); } } } auto TimeUnitsWindowPresenter::loadData() -> void { pagesProvider->loadData(); pagesProvider->setTemperatureUnit(temperatureUnitModel->get()); } auto TimeUnitsWindowPresenter::createData() -> void { pagesProvider->createData(); } } // namespace app::bell_settings
36.094595
115
0.639461
GravisZro
6f5a7dcf0f2218a5b0fa5cbde81e46d3a0d43f48
1,403
cpp
C++
test/postconditions.cpp
jdgarciauc3m/min-contracts
184b0c2f9f131fb802596d7fd7d6f9d954552a5e
[ "Apache-2.0" ]
null
null
null
test/postconditions.cpp
jdgarciauc3m/min-contracts
184b0c2f9f131fb802596d7fd7d6f9d954552a5e
[ "Apache-2.0" ]
null
null
null
test/postconditions.cpp
jdgarciauc3m/min-contracts
184b0c2f9f131fb802596d7fd7d6f9d954552a5e
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 J. Daniel Garcia // // 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 "mincontracts/mincontracts.hpp" #include <cmath> #include <gtest/gtest.h> double mysqrt_2(double x) { CONTRACT_PRE(x >= 0); auto result = std::sqrt(x); CONTRACT_POST(result > 0);// Wrong on purpose CONTRACT_POST(result <= x); return result; } double mysqrt_3(double x) { CONTRACT_PRE(x >= 0); auto post = CONTRACT_POST_RESULT(r, r > 0 && r <= x); return post(std::sqrt(x)); } TEST(postconditions, ok) {// NOLINT auto r = mysqrt_2(1); ASSERT_EQ(1, r); } TEST(postconditions, fail) {// NOLINT ASSERT_DEATH(mysqrt_2(0), "Postcondition"); // NOLINT } TEST(postconditions_result, ok) {// NOLINT auto r = mysqrt_3(1); ASSERT_EQ(1, r); } TEST(postconditions_result, fail) {// NOLINT ASSERT_DEATH(mysqrt_3(0), "Postcondition"); // NOLINT }
26.980769
78
0.686386
jdgarciauc3m
6f5acec3eb86ab29356830c499e089dbf22e7986
10,688
cpp
C++
src/xalanc/PlatformSupport/XalanParsedURI.cpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
24
2015-07-29T22:49:17.000Z
2022-03-25T10:14:17.000Z
src/xalanc/PlatformSupport/XalanParsedURI.cpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
14
2019-05-10T16:25:50.000Z
2021-11-24T18:04:47.000Z
src/xalanc/PlatformSupport/XalanParsedURI.cpp
ulisesten/xalanc
a722de08e61ce66965c4a828242f7d1250950621
[ "Apache-2.0" ]
28
2015-04-20T15:50:51.000Z
2022-01-26T14:56:55.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 "XalanParsedURI.hpp" #include "DOMStringHelper.hpp" #include "XalanUnicode.hpp" namespace XALAN_CPP_NAMESPACE { /* Merge the components back into a complete URI string */ XalanDOMString& XalanParsedURI::make(XalanDOMString& uri) const { uri.erase(); if (m_defined & d_scheme) { uri += m_scheme; uri += XalanUnicode::charColon; } if (m_defined & d_authority) { uri += XalanUnicode::charSolidus; uri += XalanUnicode::charSolidus; uri += m_authority; } uri += m_path; if (m_defined & d_query) { uri += XalanUnicode::charQuestionMark; uri += m_query; } if (m_defined & d_fragment) { uri += XalanUnicode::charNumberSign; uri += m_fragment; } return uri; } /* Parse a URI into component parts. Essentially implements the regex ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? */ void XalanParsedURI::parse( const XalanDOMChar* uriString, XalanDOMString::size_type uriStringLen ) { XalanDOMString::size_type index = 0; // Clear the components present mask m_defined = 0; // Scheme portion while (index < uriStringLen && uriString[index] != XalanUnicode::charColon && uriString[index] != XalanUnicode::charSolidus && uriString[index] != XalanUnicode::charQuestionMark && uriString[index] != XalanUnicode::charNumberSign) { ++index; } if (index > 0 && uriString[index] == XalanUnicode::charColon) { m_scheme = XalanDOMString(uriString, getMemoryManager(), index); ++index; m_defined |= d_scheme; } else { index = 0; m_scheme.clear(); } // Authority portion if (index < uriStringLen - 1 && uriString[index] == XalanUnicode::charSolidus && uriString[index+1] == XalanUnicode::charSolidus) { index += 2; XalanDOMString::size_type authority = index; while (index < uriStringLen && uriString[index] != XalanUnicode::charSolidus && uriString[index] != XalanUnicode::charQuestionMark && uriString[index] != XalanUnicode::charNumberSign) { ++index; } if (index != authority) { m_authority = XalanDOMString(uriString + authority, getMemoryManager(), index - authority); m_defined |= d_authority; } else m_authority.clear(); } else { m_authority.clear(); } // Path portion XalanDOMString::size_type path = index; while (index < uriStringLen && uriString[index] != XalanUnicode::charQuestionMark && uriString[index] != XalanUnicode::charNumberSign) { ++index; } m_path = XalanDOMString(uriString + path,getMemoryManager(), index - path); // Query portion if (index < uriStringLen && uriString[index] == XalanUnicode::charQuestionMark) { ++index; XalanDOMString::size_type query = index; while (index < uriStringLen && uriString[index] != XalanUnicode::charNumberSign) { ++index; } m_query = XalanDOMString(uriString + query,getMemoryManager(), index - query); m_defined |= d_query; } else { m_query.clear(); } // Fragment portion if (index < uriStringLen && uriString[index] == XalanUnicode::charNumberSign) { ++index; m_fragment = XalanDOMString(uriString + index, getMemoryManager(), uriStringLen - index); m_defined |= d_fragment; } else { m_fragment.clear(); } } /* Resolve this URI relative to another according to RFC2396, section 5.2 */ void XalanParsedURI::resolve( const XalanParsedURI &base ) { if (base.isSchemeDefined() == false) { // Protect against a base URI that is relative... // This might become an assert or an exception. } // Handle references to the current document (step 2) else if ((m_defined & (d_scheme | d_authority | d_query)) == 0 && m_path.empty()) { m_defined = base.m_defined; if (base.m_defined & d_scheme) m_scheme = base.m_scheme; if (base.m_defined & d_authority) m_authority = base.m_authority; m_path = base.m_path; if (base.m_defined & d_query) m_query = base.m_query; // There is an error/unclarity in the specification in step 2 in that // it doesn't state that the fragment should be inherited; however // it is clear from the examples that it should be if (!(m_defined & d_fragment)) { m_fragment = base.m_fragment; } m_defined |= base.m_defined; } // A defined scheme component implies that this is an absolute URI (step 3) // Also allow a scheme without authority that matches the base scheme to be // interpreted as a relative URI else if (!(m_defined & d_scheme) || ( (base.m_defined & d_scheme) && !(m_defined & d_authority) && equalsIgnoreCaseASCII(m_scheme, base.m_scheme))) { // Inherit the base scheme if (base.m_defined & d_scheme) { m_scheme = base.m_scheme; m_defined |= d_scheme; } // Step 4: If the authority is unm_defined then inherit it, otherwise skip to step 7 if (!(m_defined & d_authority)) { // Inherit the base authority if (base.m_defined & d_authority) { m_authority = base.m_authority; m_defined |= d_authority; } // Step 5: if the path starts with a / then it is absolute if (!(m_path.length() > 0 && m_path[0] == XalanUnicode::charSolidus)) { // Step 6: merge relative path components // a) strip off characters after the right most slash in the base path XalanDOMString::size_type pathEnd = base.m_path.length(); while (pathEnd > 0 && base.m_path[pathEnd - 1] != XalanUnicode::charSolidus) { --pathEnd; } if (pathEnd > 0) { // b) append relative path // This inserts the path portion from base... m_path.insert(0, base.m_path, 0, pathEnd); } else { // TODO, maybe raise an error here as this // is a severely wonky looking URI } // c)->g remove various "./" and "../" segments for (XalanDOMString::size_type index = 0; index < m_path.length(); ) { // remove '<segment>/../' and ./ if (m_path[index] == XalanUnicode::charFullStop) { if (index < m_path.length()-1 && m_path[index+1] == XalanUnicode::charSolidus) // ./ { m_path.erase(index,2); continue; } else if (index == m_path.length()-1) // trailing /. { m_path.erase(index,1); continue; } // Note: also strips leading ../ in an attempt to get // something out of a bad m_path else if (index < m_path.length()-2 && m_path[index+1] == XalanUnicode::charFullStop && m_path[index+2] == XalanUnicode::charSolidus) // ../ { const XalanDOMString::size_type end = index + 2; if (index > 0) --index; for ( ; index > 0 && m_path[index-1] != XalanUnicode::charSolidus; index--) ; if (index > 0) --index; m_path.erase(index, end - index); continue; } else if (index == m_path.length()-2 && m_path[index+1] == XalanUnicode::charFullStop) // trailing /.. { const XalanDOMString::size_type end = index + 2; if (index > 0) --index; for ( ; index > 0 && m_path[index-1] != XalanUnicode::charSolidus; index--) ; m_path.erase(index, end - index); continue; } } for ( ; index < m_path.length() && m_path[index] != XalanUnicode::charSolidus ; ++index) { } ++index; } } } } } /* Static helper function to perform a resolve without mucking about with this class */ XalanDOMString& XalanParsedURI::resolve( const XalanDOMChar *relative, XalanDOMString::size_type relativeLen, const XalanDOMChar *base, XalanDOMString::size_type baseLen, XalanDOMString& theResult ) { XalanParsedURI relativeURI(relative, relativeLen, theResult.getMemoryManager()); XalanParsedURI baseURI(base, baseLen, theResult.getMemoryManager()); relativeURI.resolve(baseURI); return relativeURI.make(theResult); } }
33.4
108
0.526291
ulisesten
6f69f9d2c5e707b8b64d304648f4ac8cefa6f546
4,802
cpp
C++
runtime/containers/HashSet.cpp
rschleitzer/scaly
7537cdf44f7a63ad1a560975017ee1c897c73787
[ "MIT" ]
null
null
null
runtime/containers/HashSet.cpp
rschleitzer/scaly
7537cdf44f7a63ad1a560975017ee1c897c73787
[ "MIT" ]
null
null
null
runtime/containers/HashSet.cpp
rschleitzer/scaly
7537cdf44f7a63ad1a560975017ee1c897c73787
[ "MIT" ]
null
null
null
namespace scaly::containers { using namespace scaly::memory; // https://planetmath.org/goodhashtableprimes static size_t HASH_PRIMES[] = { 3, 5, 11, 23, 53, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741, }; bool is_prime(size_t candidate) { if ((candidate & 1) != 0) { auto limit = (size_t)std::sqrt((double)candidate); size_t divisor = 3; while (divisor <= limit) { divisor += 2; if ((candidate % divisor) == 0) { return false; } } return true; } return candidate == 2; } size_t get_prime(size_t size) { for (int i = 0; i < 30; i++) { if (HASH_PRIMES[i] >= size) { return HASH_PRIMES[i]; } } size_t i = size | 1; while (i < std::numeric_limits<size_t>::max()) { if (is_prime(i)) { return i; } i += 2; } return size; } // FNV-1a hash inline size_t hash(char* data, size_t length) { size_t hash = 0xcbf29ce484222325; size_t prime = 0x100000001b3; for(int i = 0; i < length; ++i) { char value = data[i]; hash = hash ^ value; hash *= prime; } return hash; } // template<class T> struct List; template<class T> struct Slot { T value; size_t hash_code; }; template<class T> struct HashSet : Object { size_t length; Vector<List<Slot<T>>>* slots; Page* slots_page; static HashSet<T>* create(Page* _rp) { return new(alignof(HashSet<T>), _rp) HashSet<T> { .length = 0, .slots = nullptr, }; } static HashSet<T>* from_vector(Page* _rp, Vector<T>& vector) { auto hash_set = create(_rp); if (vector.length > 0) { hash_set->reallocate(vector.length); for (size_t i = 0; i < vector.length; i++) { hash_set->add_internal(*(vector[i])); } } return hash_set; } void reallocate(size_t size) { auto hash_size = get_prime(size); this->slots_page = Page::get(this)->allocate_exclusive_page(); if (hash_size < 97) hash_size = 97; Vector<List<Slot<T>>>* slots = Vector<List<Slot<T>>>::create(this->slots_page, hash_size); if (this->slots != nullptr) { auto vector_iterator = VectorIterator<List<Slot<T>>>::create(this->slots); while (auto element = vector_iterator.next()) { auto list_iterator = ListIterator<Slot<T>>::create(element->head); while (auto item = list_iterator.next()) { auto hash_code = item->hash_code; auto slot_number = hash_code % slots->length; auto slot_list = slots->get(slot_number); if (slot_list == nullptr) { slot_list = List<Slot<T>>::create(Page::get(this->slots_page)); slots->set(slot_number, *slot_list); } slot_list->add(this->slots_page, *item); } } Page::get(this)->deallocate_exclusive_page(Page::get(this->slots)); } this->slots = slots; } bool add(T value) { auto hash_size = get_prime(this->length + 1); if (this->slots == nullptr || hash_size > this->slots->length) reallocate(this->length + 1); return add_internal(value); } bool add_internal(T value) { auto hash_code = value.hash(); auto slot_number = hash_code % this->slots->length; auto slot_list = this->slots->get(slot_number); if (slot_list == nullptr) this->slots->set(slot_number, *List<Slot<T>>::create(this->slots_page)); auto iterator = slot_list->get_iterator(); while (Slot<T>* item = iterator.next()) { if (value.equals(item->value)) { return false; } } slot_list->add(this->slots_page, Slot<T> { .value = value, .hash_code = hash_code, }); this->length++; return true; } bool contains(T& value) { if (this->slots == nullptr) return false; auto hash = value.hash(); auto slot_number = hash % this->slots->length; auto slot = this->slots->get(slot_number); auto iterator = slot->get_iterator(); while (Slot<T>* item = iterator.next()) { if (value.equals(item->value)) { return true; } } return false; } }; }
28.754491
98
0.526447
rschleitzer
6f6d5587e2e046708ccca2587b3dce6656d99f82
2,528
cpp
C++
operator.cpp
zhanghexie/design-patterns
ff8841dd555116f49da00876f0c68865c916a251
[ "MIT" ]
null
null
null
operator.cpp
zhanghexie/design-patterns
ff8841dd555116f49da00876f0c68865c916a251
[ "MIT" ]
null
null
null
operator.cpp
zhanghexie/design-patterns
ff8841dd555116f49da00876f0c68865c916a251
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; // 运算父类 class Operator { private: double _numberA; double _numberB; public: double getA(){ return _numberA; } void setA(double number){ _numberA = number; } double getB(){ return _numberB; } void setB(double number){ _numberB = number; } virtual double getResult(double A, double B){ cout<<"wi"<<endl; return 0; } }; // +运算具体实现 class OperatorAdd:public Operator{ public: double getResult(double A,double B){ this->setA(A); this->setB(B); return this->getA()+this->getB(); } }; // -运算具体实现 class OperatorSub:public Operator{ public: double getResult(double A,double B){ this->setA(A); this->setB(B); return this->getA()-this->getB(); } }; // ×运算具体实现 class OperatorMul:public Operator{ public: double getResult(double A,double B){ this->setA(A); this->setB(B); return this->getA()*this->getB(); } }; // /运算具体实现 class OperatorDev:public Operator{ public: double getResult(double A,double B){ if(B==0){ throw"除数不能为零"; } this->setA(A); this->setB(B); return this->getA()/this->getB(); } }; // 操作符工厂类 class OperationFactory{ public: static Operator* OperatorCreate (char c){ Operator* op; switch (c) { case '+': op = new OperatorAdd; break; case '-': op = new OperatorSub; break; case '*': op = new OperatorMul; break; case '/': op = new OperatorDev; break; default: throw"出现错误"; return NULL; break; } return op; } }; // 客户端程序 int main(){ cout<<"+:"<<OperationFactory::OperatorCreate('+')->getResult(8,4)<<endl; cout<<"-:"<<OperationFactory::OperatorCreate('-')->getResult(8,4)<<endl; cout<<"*:"<<OperationFactory::OperatorCreate('*')->getResult(8,4)<<endl; cout<<"/:"<<OperationFactory::OperatorCreate('/')->getResult(8,4)<<endl; cout<<"a:"<<OperationFactory::OperatorCreate('a')->getResult(8,4)<<endl; }
23.626168
76
0.474288
zhanghexie
6f6e7528dd300da390ef4e8d77cbe99c31053fe0
7,907
hpp
C++
nvmctrl.hpp
Skrywerbeer/SAMl21-Scoped-headers
804affebc2f732aca80ff217f8672db52773217e
[ "MIT" ]
null
null
null
nvmctrl.hpp
Skrywerbeer/SAMl21-Scoped-headers
804affebc2f732aca80ff217f8672db52773217e
[ "MIT" ]
null
null
null
nvmctrl.hpp
Skrywerbeer/SAMl21-Scoped-headers
804affebc2f732aca80ff217f8672db52773217e
[ "MIT" ]
null
null
null
// **************************************** // File: nvmctrl.hpp // Written by: Johan Grobler // Started: 13/9/2017 // Updated: 17/9/2017 // **************************************** // Non-Voltile Memory Conrtoller special // function registers of the ATSAML21J18 // MCU. // **************************************** #ifndef NVMCTRL_HPP_ #define NVMCTRL_HPP #include "sfr.hpp" // **************************************** // Base addresses and offsets. // **************************************** namespace NVMCTRL { // Base address. const uint32_t NVMCTRL_BASE = 0x41004000; // Control A Register offset. const uint8_t CTRLA_OFFSET = 0x00; // Control B Register offset. const uint8_t CTRLB_OFFSET = 0x04; // NVM Parameter Register offset. const uint8_t PARAM_OFFSET = 0x08; // Interrupt Enable Clear Register offset. const uint8_t INTENCLR_OFFSET = 0x0c; // Interrupt Enable Set Register offset. const uint8_t INTENSET_OFFSET = 0x10; // Interrupt Flag Status and Clear Register offset. const uint8_t INTFLAG_OFFSET = 0x14; // Status Register offset. const uint8_t STATUS_OFFSET = 0x18; // Address Register offset. const uint8_t ADDR_OFFSET = 0x1c; // Lock Section Register offset. const uint8_t LOCK_OFFSET = 0x20; } // **************************************** // Control A Register. // **************************************** namespace NVMCTRL { rw_sfr16 CTRLA = __sfr16(NVMCTRL::NVMCTRL_BASE, NVMCTRL::CTRLA_OFFSET); } // **************************************** // Control A bits. // **************************************** namespace NVMCTRL_CTRLA { // Command Execution. const uint8_t CMDEX_MASK = 0xa5; const uint8_t CMDEX_SHIFT = 8; // Commands. const uint8_t ER = 0x02; // Erase Row. const uint8_t WP = 0x04; // Write Page. const uint8_t EAR = 0x05; // Erase Auxiliary Row. const uint8_t WAP = 0x06; // Write Auxiliary Page. const uint8_t WL = 0x0f; // Write Lockbits. const uint8_t RWWEEWP = 0x1a; // RWWEE Erase Row. const uint8_t RWWEEWP = 0x1c; // RWWEE Write Page. const uint8_t LR = 0x40; // Lock Region. const uint8_t UR = 0x41; // Unlock Region. const uint8_t SPRM = 0x42; // Set Power Reduction Mode. const uint8_t CPRM = 0x42; // Clear Power Reduction Mode. const uint8_t PBC = 0x44; // Page Buffer Clear. const uint8_t SSB = 0x45; // Set Security Bit. const uint8_t INVALL = 0x46; // Invalidates all cache lines. const uint8_t LDR = 0x47; // Lock Data Region. const uint8_t UDR = 0x48; // Unlock Data Region. } // **************************************** // Control B Register. // **************************************** namespace NVMCTRL { rw_sfr32 CTRLB = __sfr32(NVMCTRL::NVMCTRL_BASE, NVMCTRL::CTRLB_OFFSET); } // **************************************** // Control B bits. // **************************************** namespace NVMCTRL_CTRLB { // Cache Disable. const uint32_t CACHEDIS = (1 << 18); // NVMCTRL Read Mode. const uint32_t READMODE1 = (1 << 17); const uint32_t READMODE0 = (1 << 16); // Power Reduction Mode during Sleep. const uint32_t SLEEPPRM1 = (1 << 9); const uint32_t SLEEPPRM0 = (1 << 8); // Manual Write. const uint32_t MANW = (1 << 7); // NVM Read Wait States. const uint32_t RWS_MASK = 0x1e; const uint8_t RWS_SHIFT = 1; const uint32_t RWS3 = (1 << 4); const uint32_t RWS2 = (1 << 3); const uint32_t RWS1 = (1 << 2); const uint32_t RWS0 = (1 << 1); } // **************************************** // NVM Parameter Register. // **************************************** namespace NVMCTRL { ro_sfr32 PARAM = __sfr32(NVMCTRL::NVMCTRL_BASE, NVMCTRL::PARAM_OFFSET); } // **************************************** // NVM Parameter bits. // **************************************** namespace NVMCTRL_PARAM { // Read While Write EEPROM emulation area Pages. const uint32_t RWWEEP_MASK = 0xfff00000; const uint32_t RWWEEP = 20; const uint32_t RWWEEP11 = (1 << 31); const uint32_t RWWEEP10 = (1 << 30); const uint32_t RWWEEP9 = (1 << 29); const uint32_t RWWEEP8 = (1 << 28); const uint32_t RWWEEP7 = (1 << 27); const uint32_t RWWEEP6 = (1 << 26); const uint32_t RWWEEP5 = (1 << 25); const uint32_t RWWEEP4 = (1 << 24); const uint32_t RWWEEP3 = (1 << 23); const uint32_t RWWEEP2 = (1 << 22); const uint32_t RWWEEP1 = (1 << 21); const uint32_t RWWEEP0 = (1 << 20); // Page Size. const uint32_t PSZ_MASK = 0x70000; const uint32_t PSZ = 16; const uint32_t PSZ2 = (1 << 18); const uint32_t PSZ1 = (1 << 17); const uint32_t PSZ0 = (1 << 16); // NVM Pages. const uint32_t NVMP_MASK = 0xffff; } // **************************************** // Interrupt Enable Clear Register. // **************************************** namespace NVMCTRL { rw_sfr8 INTENCLR = __sfr8(NVMCTRL::NVMCTRL_BASE, NVMCTRL::INTENCLR_OFFSET); } // **************************************** // Interrupt Enable Clear bits. // **************************************** namespace NVMCTRL_INTENCLR { // Error Interrupt Disable. const uint8_t ERROR = (1 << 1); } // **************************************** // Interrupt Enable Set Register. // **************************************** namespace NVMCTRL { rw_sfr8 INTENSET = __sfr8(NVMCTRL::NVMCTRL_BASE, NVMCTRL::INTENSET_OFFSET); } // **************************************** // Interrupt Enable Set bits. // **************************************** namespace NVMCTRL_INTENSET { // Error Interrupt Enable. const uint8_t ERROR = (1 << 1); } // **************************************** // Interrupt Flag Status and Clear Register. // **************************************** namespace NVMCTRL { rw_sfr8 INTFLAG = __sfr8(NVMCTRL::NVMCTRL_BASE, NVMCTRL::INTFLAG_OFFSET); } // **************************************** // Interrupt Flag Status and Clear bits. // **************************************** namespace NVMCTRL_INTFLAG { // Error Interrupt. const uint8_t ERROR = (1 << 1); } // **************************************** // Status Register. // **************************************** namespace NVMCTRL { rw_sfr16 STATUS = __sfr16(NVMCTRL::NVMCTRL_BASE, NVMCTRL::STATUS_OFFSET); } // **************************************** // Status bits. // **************************************** namespace NVMCTRL_STATUS { // Security Bits Status. const uint16_t SB = (1 << 8); // NVM Error. const uint16_t NVME = (1 << 4); // Lock Error Status. const uint16_t LOCKE = (1 << 3); // Programming Error Status. const uint16_t PROGE = (1 << 2); // NVM Page Buffer Active Loading. const uint16_t LOAD = (1 << 1); // Power Reduction Mode. const uint16_t PRM = (1 << 0); } // **************************************** // Address Register. // **************************************** namespace NVMCTRL { rw_sfr32 ADDR = __sfr32(NVMCTRL::NVMCTRL_BASE, NVMCTRL::ADDR_OFFSET); } // **************************************** // Address bits. // **************************************** namespace NVMCTRL_ADDR { // NVM Address. const uint32_t ADDR = 0x003fffff; // TODO: Add individual bits, maybe. } // **************************************** // Lock Section Register. // **************************************** namespace NVMCTRL { ro_sfr16 LOCK = __sfr16(NVMCTRL::NVMCTRL_BASE, NVMCTRL::LOCK_OFFSET); } // **************************************** // Lock Section bits. // **************************************** namespace NVMCTRL_LOCK { // Region Lock Bits. const uint16_t LOCK15 = (1 << 15); const uint16_t LOCK14 = (1 << 14); const uint16_t LOCK13 = (1 << 13); const uint16_t LOCK12 = (1 << 12); const uint16_t LOCK11 = (1 << 11); const uint16_t LOCK10 = (1 << 10); const uint16_t LOCK9 = (1 << 9); const uint16_t LOCK8 = (1 << 8); const uint16_t LOCK7 = (1 << 7); const uint16_t LOCK6 = (1 << 6); const uint16_t LOCK5 = (1 << 5); const uint16_t LOCK4 = (1 << 4); const uint16_t LOCK3 = (1 << 3); const uint16_t LOCK2 = (1 << 2); const uint16_t LOCK1 = (1 << 1); const uint16_t LOCK0 = (1 << 0); } #endif // NVMCTRL_HPP
30.528958
76
0.53636
Skrywerbeer
6f71d05d82f1f1b6e9dbfcaed69fc6f480c4a935
1,146
cc
C++
TestOutput/Subfolder/Windows.SharedLibrary.cc
hannes-harnisch/Snakify
41254edddf2e0da0f4cc6d5e715b63701c7e17d1
[ "MIT" ]
null
null
null
TestOutput/Subfolder/Windows.SharedLibrary.cc
hannes-harnisch/Snakify
41254edddf2e0da0f4cc6d5e715b63701c7e17d1
[ "MIT" ]
null
null
null
TestOutput/Subfolder/Windows.SharedLibrary.cc
hannes-harnisch/Snakify
41254edddf2e0da0f4cc6d5e715b63701c7e17d1
[ "MIT" ]
null
null
null
module; #include "Core/Macros.hh" #include "Windows.API.hh" #include <string_view> export module Vitro.Windows.SharedLibrary; import Vitro.App.SharedLibraryBase; import Vitro.Core.Unique; import Vitro.Windows.Utils; namespace vt::windows { export class SharedLibrary : public SharedLibraryBase { public: [[nodiscard]] bool reload() final override { library = make_library(); return library.get() != nullptr; } void* handle() final override { return library.get(); } protected: SharedLibrary(std::string_view path) : path(widen_string(path)), library(make_library()) {} void* load_symbol_address(std::string_view symbol) const final override { return ::GetProcAddress(library.get(), symbol.data()); } private: std::wstring path; Unique<HMODULE, ::FreeLibrary> library; decltype(library) make_library() const { auto raw_library = ::LoadLibraryW(path.data()); decltype(library) fresh_library(raw_library); vt_ensure(raw_library, "Failed to find shared library '{}'.", narrow_string(path)); return fresh_library; } }; }
22.038462
91
0.67801
hannes-harnisch
4cfa63858fd2c35c81208f00ae7f292a0ea48f71
707
cpp
C++
src/chargemon.cpp
kimmoli/chargemon
c441bec10531de8ff13226df5c48236e3a58e04b
[ "MIT" ]
2
2018-04-02T14:48:32.000Z
2018-08-29T19:44:16.000Z
src/chargemon.cpp
kimmoli/chargemon
c441bec10531de8ff13226df5c48236e3a58e04b
[ "MIT" ]
10
2016-03-15T11:13:42.000Z
2021-11-14T13:00:36.000Z
src/chargemon.cpp
kimmoli/chargemon
c441bec10531de8ff13226df5c48236e3a58e04b
[ "MIT" ]
4
2016-03-15T10:32:13.000Z
2018-08-29T08:29:09.000Z
/* * Charge monitor (C) 2014-2019 Kimmo Lindholm * LICENSE MIT */ #ifdef QT_QML_DEBUG #include <QtQuick> #endif #include <sailfishapp.h> #include <QtQml> #include <QScopedPointer> #include <QQuickView> #include <QQmlEngine> #include <QGuiApplication> #include <QQmlContext> #include <QCoreApplication> #include "cmon.h" int main(int argc, char *argv[]) { qmlRegisterType<Cmon>("harbour.chargemon", 1, 0, "Cmon"); QScopedPointer<QGuiApplication> app(SailfishApp::application(argc, argv)); QScopedPointer<QQuickView> view(SailfishApp::createView()); view->setSource(SailfishApp::pathTo("qml/chargemon.qml")); view->show(); return app->exec(); }
22.09375
79
0.681754
kimmoli
4cffff380a8068b1638ddbc355b7c1e132d489ff
1,494
cpp
C++
testing/bench_ext_pushpull.cpp
arthurbiancarelli/liblsl
c217f93060e2ac1bde84dd3aa5bcfd9bc8460f1f
[ "MIT" ]
null
null
null
testing/bench_ext_pushpull.cpp
arthurbiancarelli/liblsl
c217f93060e2ac1bde84dd3aa5bcfd9bc8460f1f
[ "MIT" ]
null
null
null
testing/bench_ext_pushpull.cpp
arthurbiancarelli/liblsl
c217f93060e2ac1bde84dd3aa5bcfd9bc8460f1f
[ "MIT" ]
null
null
null
#include "catch.hpp" #include "helper_type.hpp" #include <atomic> #include <list> #include <lsl_cpp.h> #include <string> #include <thread> TEMPLATE_TEST_CASE("pushpull", "[basic][throughput]", char, float, std::string) { const std::size_t max_nchan = 128, chunk_size = 128; const std::size_t param_nchan[] = {1, max_nchan}; const std::size_t param_inlets[] = {0, 1, 10}; const TestType data[max_nchan * chunk_size] = {TestType()}; //TestType data_out[max_n * chunk_size]; const char *name = SampleType<TestType>::fmt_string(); lsl::channel_format_t cf = (lsl::channel_format_t)SampleType<TestType>::chan_fmt; for (auto nchan : param_nchan) { lsl::stream_outlet out( lsl::stream_info(name, "PushPull", (int) nchan, lsl::IRREGULAR_RATE, cf, "streamid")); auto found_stream_info(lsl::resolve_stream("name", name, 1, 2.0)); REQUIRE(!found_stream_info.empty()); std::list<lsl::stream_inlet> inlet_list; for (auto n_inlets : param_inlets) { while (inlet_list.size() < n_inlets) { inlet_list.emplace_front(found_stream_info[0], 1, false); inlet_list.front().open_stream(.5); } BENCHMARK("push_sample_nchan_" + std::to_string(nchan)+"_inlets_"+std::to_string(n_inlets)) { for (size_t s = 0; s < chunk_size; s++) out.push_sample(data); }; BENCHMARK("push_chunk_nchan_" + std::to_string(nchan)+"_inlets_"+std::to_string(n_inlets)) { out.push_chunk_multiplexed(data, chunk_size); }; for(auto &inlet: inlet_list) inlet.flush(); } } }
33.2
96
0.697456
arthurbiancarelli
98048a5af18a9553730de157db8aa33d687fe8e8
12,809
cpp
C++
src/matrix.cpp
tenglvjun/math
6865d39512ff8836281fa00980fb5fa85ced2a35
[ "MIT" ]
null
null
null
src/matrix.cpp
tenglvjun/math
6865d39512ff8836281fa00980fb5fa85ced2a35
[ "MIT" ]
null
null
null
src/matrix.cpp
tenglvjun/math
6865d39512ff8836281fa00980fb5fa85ced2a35
[ "MIT" ]
null
null
null
#include "matrix.h" #include <memory.h> #include <assert.h> #include <cmath> #include <iostream> #include "math_tools.h" #include "math_def.h" GeoMatrix::GeoMatrix(const unsigned int row, const unsigned int col) : m_data(nullptr), m_row(0), m_col(0) { Init(row, col); } GeoMatrix::GeoMatrix(const unsigned int row, const unsigned int col, const double *data) : m_data(nullptr), m_row(0), m_col(0) { Init(row, col); for (unsigned int i = 0; i < m_row; i++) { for (unsigned int j = 0; j < m_col; j++) { m_data[i][j] = data[m_col * i + j]; } } } GeoMatrix::GeoMatrix(const GeoMatrix &m) { Init(m.m_row, m.m_col); for (unsigned int row = 0; row < m_row; row++) { for (unsigned int col = 0; col < m_col; col++) { m_data[row][col] = m[row][col]; } } } GeoMatrix::~GeoMatrix() { Clear(); } GeoMatrix &GeoMatrix::operator=(const GeoMatrix &m) { if (&m == this) { return *this; } Clear(); Init(m.m_row, m.m_col); for (unsigned int row = 0; row < m_row; row++) { for (unsigned int col = 0; col < m_col; col++) { m_data[row][col] = m[row][col]; } } return *this; } double *GeoMatrix::operator[](const unsigned int idx) const { assert(m_data && (idx < m_row)); return m_data[idx]; } double *GeoMatrix::operator[](const unsigned int idx) { assert(m_data && (idx < m_row)); return m_data[idx]; } GeoVector3D GeoMatrix::operator*(const GeoVector3D &v) const { assert((GeoVector3D::Size() == m_col) && (m_col == m_row)); GeoVector3D ret; ret[0] = m_data[0][0] * v[0] + m_data[0][1] * v[1] + m_data[0][2] * v[2]; ret[1] = m_data[1][0] * v[0] + m_data[1][1] * v[1] + m_data[1][2] * v[2]; ret[2] = m_data[2][0] * v[0] + m_data[2][1] * v[1] + m_data[2][2] * v[2]; return ret; } GeoVector2D GeoMatrix::operator*(const GeoVector2D &v) const { assert((GeoVector2D::Size() == m_col) && (m_col == m_row)); GeoVector2D ret; ret[0] = m_data[0][0] * v[0] + m_data[0][1] * v[1]; ret[1] = m_data[1][0] * v[0] + m_data[1][1] * v[1]; return ret; } GeoVector4D GeoMatrix::operator*(const GeoVector4D &v) const { assert((GeoVector4D::Size() == m_col) && (m_col == m_row)); GeoVector4D ret; ret[0] = m_data[0][0] * v[0] + m_data[0][1] * v[1] + m_data[0][2] * v[2] + m_data[0][3] * v[3]; ret[1] = m_data[1][0] * v[0] + m_data[1][1] * v[1] + m_data[1][2] * v[2] + m_data[1][3] * v[3]; ret[2] = m_data[2][0] * v[0] + m_data[2][1] * v[1] + m_data[2][2] * v[2] + m_data[2][3] * v[3]; ret[3] = m_data[3][0] * v[0] + m_data[3][1] * v[1] + m_data[3][2] * v[2] + m_data[3][3] * v[3]; return ret; } GeoMatrix GeoMatrix::operator*(const GeoMatrix &m) const { assert(m_col == m.Rows()); GeoMatrix ret(m_row, m.Cols()); for (unsigned int i = 0; i < m_row; i++) { for (unsigned int j = 0; j < m.Cols(); j++) { for (unsigned int k = 0; k < m_col; k++) { ret[i][j] += (m_data[i][k] * m[k][j]); } } } return ret; } void GeoMatrix::operator*=(const double s) { for (unsigned int i = 0; i < m_row; i++) { for (unsigned int j = 0; j < m_col; j++) { m_data[i][j] *= s; } } } GeoMatrix GeoMatrix::operator*(const double s) { GeoMatrix ret(m_row, m_col); for (unsigned int i = 0; i < m_row; i++) { for (unsigned int j = 0; j < m_col; j++) { ret[i][j] *= s; } } return ret; } void GeoMatrix::operator+=(const GeoMatrix &m) { assert((m_col == m.Cols()) && (m_row == m.Rows())); for (unsigned int i = 0; i < m_row; i++) { for (unsigned int j = 0; j < m_col; j++) { m_data[i][j] += m[i][j]; } } } void GeoMatrix::SetIdentity() { assert((m_row == m_col) && (m_row > 0)); for (unsigned int row = 0; row < m_row; row++) { for (unsigned int col = 0; col < m_col; col++) { if (row == col) { m_data[row][col] = 1.0f; } else { m_data[row][col] = 0.0f; } } } } void GeoMatrix::Zeros() { for (unsigned int row = 0; row < m_row; row++) { m_data[row] = new double[m_col]; for (unsigned int col = 0; col < m_col; col++) { m_data[row][col] = 0.0f; } } } void GeoMatrix::Resharp(const unsigned int row, const unsigned int col) { if (m_row == row && m_col == col) { Zeros(); return; } Clear(); Init(row, col); } void GeoMatrix::Flatten(std::vector<float> &data) const { for (unsigned int j = 0; j < m_col; j++) { for (unsigned int i = 0; i < m_row; i++) { data.push_back((float)(m_data[i][j])); } } } GeoMatrix GeoMatrix::SubMatrix(const unsigned int sRow, const unsigned int eRow, const unsigned int sCol, const unsigned int eCol) { GeoMatrix m(eRow - sRow, eCol - sCol); for (unsigned int i = sRow; i < eRow; i++) { for (unsigned int j = sCol; j < eCol; j++) { m[i - sRow][j - sCol] = m_data[i][j]; } } return m; } unsigned int GeoMatrix::Rows() const { return m_row; } unsigned int GeoMatrix::Cols() const { return m_col; } bool GeoMatrix::LUDecompose(GeoMatrix &up, GeoMatrix &low) const { if (!IsSquare()) { return false; } up.Resharp(m_row, m_col); low.Resharp(m_row, m_col); unsigned int n = m_row; double sum; for (unsigned int i = 0; i < n; i++) { // Upper Triangular for (unsigned int k = i; k < n; k++) { // Summation of L(i, j) * U(j, k) sum = 0.0f; for (unsigned int j = 0; j < i; j++) sum += (low[i][j] * up[j][k]); // Evaluating U(i, k) up[i][k] = m_data[i][k] - sum; if ((i == k) && (MathTools::IsZero(up[i][k]))) { return false; } } // Lower Triangular for (unsigned int k = i; k < n; k++) { if (i == k) { low[i][i] = 1; // Diagonal as 1 } else { // Summation of L(k, j) * U(j, i) sum = 0; for (unsigned int j = 0; j < i; j++) { sum += (low[k][j] * up[j][i]); } // Evaluating L(k, i) low[k][i] = (m_data[k][i] - sum) / up[i][i]; } } } return true; } double GeoMatrix::Det() const { GeoMatrix up(m_row, m_col); GeoMatrix low(m_row, m_col); if (!LUDecompose(up, low)) { return 0; } double det = 1.0f; for (unsigned int i = 0; i < m_row; i++) { det *= up[i][i]; } return det; } bool GeoMatrix::Inverse(GeoMatrix &inverse) const { GeoMatrix up(m_row, m_col); GeoMatrix low(m_row, m_col); if (!LUDecompose(up, low)) { return false; } inverse.Resharp(m_row, m_col); for (unsigned int i = 0; i < m_row; i++) { GeoVector b(m_col); for (unsigned int j = 0; j < m_col; j++) { b[j] = (i == j) ? 1 : 0; } GeoVector ret = GeoMatrix::SolveLinearEquation(up, low, b); inverse.SetVector(i, ret, false); } return true; } bool GeoMatrix::IsSquare() const { assert((m_col > 0) && (m_col > 0)); return (m_col == m_row); } GeoMatrix &GeoMatrix::Transpose() { assert((m_col > 0) && (m_col > 0)); GeoMatrix tmp(m_col, m_row); Transpose(tmp); (*this) = (tmp); return *this; } void GeoMatrix::Transpose(GeoMatrix &transpose) const { transpose.Resharp(m_col, m_row); for (unsigned int row = 0; row < m_row; row++) { for (unsigned int col = 0; col < m_col; col++) { transpose[col][row] = m_data[row][col]; } } } void GeoMatrix::SetVector(const unsigned int idx, const GeoVector &v, bool isRow) { if (isRow) { assert(m_col == v.Dim()); for (unsigned int col = 0; col < m_col; col++) { m_data[idx][col] = v[col]; } } else { assert(m_row == v.Dim()); for (unsigned int row = 0; row < m_row; row++) { m_data[row][idx] = v[row]; } } } bool GeoMatrix::SolveLinearEquation(const GeoVector &b, GeoVector &x) const { assert(b.Dim() == x.Dim()); GeoMatrix up(m_row, m_col); GeoMatrix low(m_row, m_col); if (!LUDecompose(up, low)) { return false; } x = GeoMatrix::SolveLinearEquation(up, low, b); return true; } void GeoMatrix::Dump() const { std::cout.precision(5); for (unsigned int i = 0; i < m_row; i++) { for (unsigned int j = 0; j < m_col; j++) { std::cout << m_data[i][j] << " "; } std::cout << std::endl; } } void GeoMatrix::Clear() { for (unsigned int row = 0; row < m_row; row++) { SAFE_DELETE_ARRAY(m_data[row]); } SAFE_DELETE(m_data); m_row = 0; m_col = 0; } void GeoMatrix::Init(const unsigned int row, const unsigned int col) { m_row = row; m_col = col; m_data = new double *[m_row]; Zeros(); } GeoMatrix GeoMatrix::TranslateMatrix(const GeoVector3D &trans) { GeoMatrix matrix(4, 4); matrix.SetIdentity(); matrix[0][3] = trans[0]; matrix[1][3] = trans[1]; matrix[2][3] = trans[2]; return matrix; } GeoMatrix GeoMatrix::TranslateMatrix(const GeoVector4D &trans) { GeoMatrix matrix(4, 4); matrix.SetIdentity(); matrix[0][3] = trans[0]; matrix[1][3] = trans[1]; matrix[2][3] = trans[2]; return matrix; } GeoMatrix GeoMatrix::RotateMatrix(const double angle, const GeoVector3D &axis) { GeoMatrix matrix(4, 4); double c = cos(angle); double s = sin(angle); matrix[0][0] = c + (1 - c) * axis[0] * axis[0]; matrix[0][1] = (1 - c) * axis[0] * axis[1] - s * axis[2]; matrix[0][2] = (1 - c) * axis[0] * axis[2] + s * axis[1]; matrix[1][0] = (1 - c) * axis[0] * axis[1] + s * axis[2]; matrix[1][1] = c + (1 - c) * axis[1] * axis[1]; matrix[1][2] = (1 - c) * axis[1] * axis[2] - s * axis[0]; matrix[2][0] = (1 - c) * axis[0] * axis[2] - s * axis[1]; matrix[2][1] = (1 - c) * axis[1] * axis[2] + s * axis[0]; matrix[2][2] = c + (1 - c) * axis[2] * axis[2]; matrix[3][3] = 1.0f; return matrix; } GeoMatrix GeoMatrix::ScaleMatrix(const double s) { GeoMatrix ret(4, 4); ret.SetIdentity(); ret[0][0] = s; ret[1][1] = s; ret[2][2] = s; return ret; } GeoVector GeoMatrix::SolveLinearEquation(const GeoMatrix &up, const GeoMatrix &low, const GeoVector &b) { double sum; // Solve Lower GeoVector y(b.Dim()); for (int row = 0; row < (int)low.Rows(); row++) { sum = 0.0f; for (int col = 0; col < row; col++) { sum += low[row][col] * y[col]; } y[row] = (b[row] - sum) / low[row][row]; } GeoVector ret(y.Dim()); //Solve Upper for (int row = (int)(up.Rows() - 1); row >= 0; row--) { sum = 0.0f; for (int col = (int)(up.Cols() - 1); col > row; col--) { sum += up[row][col] * ret[col]; } ret[row] = (y[row] - sum) / up[row][row]; } return ret; } GeoVector4D operator*(const GeoVector4D &v, const GeoMatrix &m) { assert((GeoVector4D::Size() == m.Cols()) && (m.IsSquare())); GeoVector4D ret; ret[0] = m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2] + m[0][3] * v[3]; ret[1] = m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2] + m[1][3] * v[3]; ret[2] = m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2] + m[2][3] * v[3]; ret[3] = m[3][0] * v[0] + m[3][1] * v[1] + m[3][2] * v[2] + m[3][3] * v[3]; return ret; } GeoVector3D operator*(const GeoVector3D &v, const GeoMatrix &m) { assert((GeoVector3D::Size() == m.Cols()) && (m.IsSquare())); GeoVector3D ret; ret[0] = m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2]; ret[1] = m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2]; ret[2] = m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2]; return ret; } GeoVector2D operator*(const GeoVector2D &v, const GeoMatrix &m) { assert((GeoVector2D::Size() == m.Cols()) && (m.IsSquare())); GeoVector2D ret; ret[0] = m[0][0] * v[0] + m[0][1] * v[1]; ret[1] = m[1][0] * v[0] + m[1][1] * v[1]; return ret; }
21.312812
130
0.487626
tenglvjun
980492efb2ca86c09bbc14d218251b3a45554a25
5,158
hpp
C++
store.servers/src/rs256-secure-server.hpp
once-ler/Store-cpp
27d65057b2984c61a4b8be9d96d8fa6d70de1fb7
[ "BSD-3-Clause" ]
3
2019-08-18T19:14:02.000Z
2019-09-20T05:38:58.000Z
store.servers/src/rs256-secure-server.hpp
once-ler/Store-cpp
27d65057b2984c61a4b8be9d96d8fa6d70de1fb7
[ "BSD-3-Clause" ]
null
null
null
store.servers/src/rs256-secure-server.hpp
once-ler/Store-cpp
27d65057b2984c61a4b8be9d96d8fa6d70de1fb7
[ "BSD-3-Clause" ]
1
2019-09-20T05:39:01.000Z
2019-09-20T05:39:01.000Z
#pragma once #include <regex> #include "store.common/src/web_token.hpp" #include "store.servers/src/http-server.hpp" #include "store.servers/src/session.hpp" #include "store.servers/src/replies.hpp" #include "store.models/src/ioc/service_provider.hpp" using namespace store::common; using namespace store::servers::util; namespace ioc = store::ioc; namespace store::servers { namespace secured::routes { using Route = std::pair<string, function<void((struct evhttp_request*, vector<string>, session_t&))>>; Route getSession = { "^/api/session(\\?.*)?", [](struct evhttp_request* req, vector<string> segments = {}, session_t& sess){ if (evhttp_request_get_command(req) != EVHTTP_REQ_GET) { evhttp_send_error(req, HTTP_BADREQUEST, "Bad Request"); return; } json j = sess; store::servers::replyOK(req, j.dump(2), "application/json"); } }; } class RS256SecureServer : public HTTPServer { using HTTPServer::HTTPServer; public: RS256SecureServer() : HTTPServer() { using namespace secured::routes; rs256KeyPair = ioc::ServiceProvider->GetInstance<RS256KeyPair>(); routes = { getSession }; unsecureRoutes = {}; } map<string, function<void((struct evhttp_request*, vector<string>, session_t&))>> routes{}; // For delivering assets map<string, function<void((struct evhttp_request*, vector<string>))>> unsecureRoutes{}; void ProcessRequest(struct evhttp_request* req) override { // Handle CORS preflight. if (evhttp_request_get_command(req) == EVHTTP_REQ_OPTIONS) { auto origin = evhttp_find_header(req->input_headers, "Origin"); evhttp_add_header (evhttp_request_get_output_headers(req), "Access-Control-Allow-Origin", origin != NULL ? origin : "null"); evhttp_add_header (evhttp_request_get_output_headers(req), "Vary", "origin"); evhttp_add_header (evhttp_request_get_output_headers(req), "Access-Control-Allow-Credentials", "true"); evhttp_add_header (evhttp_request_get_output_headers(req), "Access-Control-Allow-Methods", "POST, GET, OPTIONS"); evhttp_add_header (evhttp_request_get_output_headers(req), "Access-Control-Allow-Headers", "Origin, Accept, Content-Type, x-access-token"); evhttp_add_header (evhttp_request_get_output_headers(req), "Access-Control-Max-Age", "86400"); evhttp_send_reply(req, HTTP_OK, "OK", NULL); return; } // Check whether route can be unsecured. bool uri_matched = tryMatchUri(req); if (uri_matched) return; // Secure session required. json j; bool authenticated = isAuthenticated(req, j); if (!authenticated) { evhttp_send_error(req, 401, NULL); return; } // localhost:1718/a/b/c // uri -> /a/b/c // Pass the decrypted payload to expose fields such as "user" if needed. uri_matched = tryMatchUri(req, j); if (uri_matched) return; evhttp_send_error(req, HTTP_NOTFOUND, "Not Found"); } private: shared_ptr<RS256KeyPair> rs256KeyPair; bool isAuthenticated(struct evhttp_request* req, json& j) { const char* val = evhttp_find_header(req->input_headers, "x-access-token"); if (val != NULL) return isRS256Authenticated(rs256KeyPair->publicKey, val, j); // x-access-token not found in header. Expect in querystring if jsonp. map<string, string> querystrings = tryGetQueryString(req); string xtoken = querystrings["x-access-token"]; if (xtoken.size() > 0) return isRS256Authenticated(rs256KeyPair->publicKey, xtoken, j); return false; } // Secure routes. bool tryMatchUri(struct evhttp_request* req, json& j) { const char* uri = evhttp_request_uri(req); string uri_str = string{uri}; bool uri_matched = false; session_t sess = j; for (const auto& a : routes) { std::smatch seg_match; vector<string> segments; if (std::regex_search(uri_str, seg_match, std::regex((a.first)))) { for (size_t i = 0; i < seg_match.size(); ++i) segments.emplace_back(seg_match[i]); uri_matched = true; a.second(req, segments, sess); break; } } return uri_matched; } // Unsecure routes. bool tryMatchUri(struct evhttp_request* req) { const char* uri = evhttp_request_uri(req); string uri_str = string{uri}; bool uri_matched = false; for (const auto& a : unsecureRoutes) { std::smatch seg_match; vector<string> segments; if (std::regex_search(uri_str, seg_match, std::regex((a.first)))) { for (size_t i = 0; i < seg_match.size(); ++i) segments.emplace_back(seg_match[i]); uri_matched = true; a.second(req, segments); break; } } return uri_matched; } }; }
31.072289
106
0.620396
once-ler
980e45bcc8a334783d08781cb88a8be0339e8aa7
7,660
hxx
C++
include/itkSmoothBinarySurfaceImageFilter.hxx
Bonelab/ITKMorphometry
ee1480bc1a93425ae7fff1c9595b0688fc58abc5
[ "Apache-2.0" ]
null
null
null
include/itkSmoothBinarySurfaceImageFilter.hxx
Bonelab/ITKMorphometry
ee1480bc1a93425ae7fff1c9595b0688fc58abc5
[ "Apache-2.0" ]
null
null
null
include/itkSmoothBinarySurfaceImageFilter.hxx
Bonelab/ITKMorphometry
ee1480bc1a93425ae7fff1c9595b0688fc58abc5
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkSmoothBinarySurfaceImageFilter_hxx #define itkSmoothBinarySurfaceImageFilter_hxx #include "itkSmoothBinarySurfaceImageFilter.h" #include "itkImageScanlineIterator.h" #include "itkShapedNeighborhoodIterator.h" #include <queue> #include <vector> namespace itk { template <typename TInputImage> SmoothBinarySurfaceImageFilter<TInputImage> ::SmoothBinarySurfaceImageFilter() : Superclass() {} template <typename TInputImage> void SmoothBinarySurfaceImageFilter<TInputImage> ::GenerateInputRequestedRegion() { Superclass::GenerateInputRequestedRegion(); if (this->GetInput()) { auto * image = const_cast<InputImageType *>(this->GetInput()); image->SetRequestedRegionToLargestPossibleRegion(); } } template <typename TInputImage> void SmoothBinarySurfaceImageFilter<TInputImage> ::EnlargeOutputRequestedRegion(DataObject * output) { Superclass::EnlargeOutputRequestedRegion(output); output->SetRequestedRegionToLargestPossibleRegion(); } template <typename TInputImage> void SmoothBinarySurfaceImageFilter<TInputImage> ::DynamicThreadedGenerateData (const ImageRegionType &outputRegionForThread) { /* Create iterators */ TInputImage * output = this->GetOutput(); const TInputImage * input = this->GetInput(); ImageScanlineConstIterator<TInputImage> inputIt(input, outputRegionForThread); ImageScanlineIterator<TInputImage> outputIt(output, outputRegionForThread); while (!inputIt.IsAtEnd()) { while (!inputIt.IsAtEndOfLine()) { outputIt.Set(inputIt.Get()/1.1); ++inputIt; ++outputIt; } inputIt.NextLine(); outputIt.NextLine(); } } template <typename TInputImage> void SmoothBinarySurfaceImageFilter<TInputImage> ::AfterThreadedGenerateData() { TInputImage * output = this->GetOutput(); const TInputImage * input = this->GetInput(); typename TInputImage::Pointer temp_image = TInputImage::New(); temp_image->SetRegions(output->GetRequestedRegion()); temp_image->Allocate(); temp_image->FillBuffer(itk::NumericTraits<typename TInputImage::PixelType>::Zero); /* Narrow band */ RealType gamma = 3.0; // using QueueType = std::vector<IndexType>; std::vector<IndexType> current, next; ImageScanlineIterator<TInputImage> outputIt(output, output->GetRequestedRegion()); ImageScanlineIterator<TInputImage> tempIt(temp_image, output->GetRequestedRegion()); while (!outputIt.IsAtEnd()) { while (!outputIt.IsAtEndOfLine()) { if (std::abs(outputIt.Get()) < gamma) { next.push_back(outputIt.GetIndex()); } tempIt.Set(outputIt.Get()); ++outputIt; ++tempIt; } outputIt.NextLine(); tempIt.NextLine(); } std::cout << next.size() << std::endl; RealType size = 1.; for(auto &s: output->GetRequestedRegion().GetSize()){ size *= s; } StencilsType stencils = this->GenerateStencils(); auto spacing = output->GetSpacing(); auto region = output->GetRequestedRegion(); RealType error = NumericTraits<RealType>::max(); unsigned long i = 0; while ( (error > 1e-12) && (i < 1000) ) { error = 0.; int l = 0; int t = 0; std::swap(current, next); while (!current.empty()) { IndexType index = current.back(); current.pop_back(); // RealType margin = std::tanh(input->GetPixel(index) / 3.0); RealType margin = input->GetPixel(index); RealType sign = (margin >= 0) ? (+1.) : (-1.); RealType lastSolution; if (i%2) { lastSolution = output->GetPixel(index); } else { lastSolution = temp_image->GetPixel(index); } RealType a = 0.; RealType b = 0.; RealType c = 0.; // −1/12 4/3 −5/2 4/3 −1/12 // Vector< RealType, 2*Order > coefficients = {{-1./12., 4./3., 4./3., -1./12.}}; // std::vector< RealType> coefficients = {{-1./12., 4./3., 4./3., -1./12.}}; // 1/90 −3/20 3/2 −49/18 3/2 −3/20 1/90 std::vector< RealType> coefficients = {{1./90., -3/20., 3./2., 3./2., -3./20., 1./90.}}; for (unsigned int i = 0; i < InputImageDimension; ++i) { RealType q = 0; for (unsigned int j = 0; j < 2*Order; ++j) { IndexType thisIndex = index + stencils[i][j]; RealType qq = region.IsInside(thisIndex) ? (output->GetPixel(thisIndex)) : (lastSolution); q += qq*coefficients[j]; } // a += std::pow(-5./2./spacing[i]/spacing[i], 2); a += std::pow(-49./18./spacing[i]/spacing[i], 2); b += 2. * -5./2./spacing[i]/spacing[i] * q/spacing[i]/spacing[i]; c += std::pow(q/spacing[i]/spacing[i], 2); } /* Discrim */ RealType solution; RealType discrim = b*b - 4.*a*c; if (discrim < 0.0) { solution = -b / (2.*a); // std::cout << a << " " << b << " " << c << std::endl; // itkExceptionMacro(<< "Discriminator is negative..."); t++; } else { RealType s1 = (-b + std::sqrt(discrim)) / (2.*a); RealType s2 = (-b - std::sqrt(discrim)) / (2.*a); solution = sign*std::max(sign*s1, sign*s2); l++; } /* Solution */ // RealType s1 = (-b + std::sqrt(discrim)) / (2.*a); // RealType s2 = (-b - std::sqrt(discrim)) / (2.*a); // RealType solution = sign*std::max(sign*s1, sign*s2); // RealType solution = -b / (2.*a); RealType w = 0.95; RealType propSolution = solution; solution = (1.-w) * solution + w * lastSolution; if (sign > 0) { solution = std::max(solution, margin); } else { solution = std::min(solution, margin); } // output->SetPixel(index, solution); if (i%2) { temp_image->SetPixel(index, solution); // lastSolution = output->GetPixel(index); } else{ output->SetPixel(index, solution); // lastSolution = temp_image->GetPixel(index); } // std::cout << lastSolution << " " << solution << " " << margin << std::endl; next.push_back(index); error += std::abs(lastSolution - propSolution); // error += std::abs(lastSolution - solution); } error /= (RealType)(size); i++; std::cout << error << std::endl; std::cout << l << " " << t << std::endl; } } template <typename TInputImage> typename SmoothBinarySurfaceImageFilter<TInputImage>::StencilsType SmoothBinarySurfaceImageFilter<TInputImage> ::GenerateStencils() { StencilsType stencils; for (unsigned int i = 0; i < InputImageDimension; ++i) { StencilType stencil; unsigned int k = 0; for (int j = -1*(int)Order; j <= (int)Order; ++j) { if (j == 0) { k = 1; continue; } OffsetType offset; offset.Fill(0); offset.SetElement(i, j); stencil[j + Order - k] = offset; } stencils[i] = stencil; } return stencils; } } // end namespace itk #endif // itkSmoothBinarySurfaceImageFilter_hxx
29.921875
100
0.610574
Bonelab
9817001af4dcbe142760ce94ac6808dac7d2ad02
2,832
cpp
C++
src/random_object.cpp
scwfri/natalie
11e874607a8ac7b934e57c4c7e5790623afaee7a
[ "MIT" ]
7
2022-03-08T08:47:54.000Z
2022-03-29T15:08:36.000Z
src/random_object.cpp
scwfri/natalie
11e874607a8ac7b934e57c4c7e5790623afaee7a
[ "MIT" ]
12
2022-03-10T13:04:42.000Z
2022-03-24T01:40:23.000Z
src/random_object.cpp
scwfri/natalie
11e874607a8ac7b934e57c4c7e5790623afaee7a
[ "MIT" ]
5
2022-03-13T17:46:16.000Z
2022-03-31T07:28:26.000Z
#include "natalie.hpp" #include <natalie/random_object.hpp> #include <random> namespace Natalie { Value RandomObject::initialize(Env *env, Value seed) { if (!seed) { m_seed = (nat_int_t)std::random_device()(); } else { if (seed->is_float()) { seed = seed->as_float()->to_i(env); } m_seed = IntegerObject::convert_to_nat_int_t(env, seed); } if (m_generator) delete m_generator; this->m_generator = new std::mt19937(m_seed); return this; } Value RandomObject::rand(Env *env, Value arg) { if (arg) { if (arg->is_float()) { double max = arg->as_float()->to_double(); if (max <= 0) { env->raise("ArgumentError", "invalid argument - {}", arg->inspect_str(env)); } return generate_random(0.0, max); } else if (arg->is_range()) { Value min = arg->as_range()->begin(); Value max = arg->as_range()->end(); // TODO: There can be different types of objects that respond to + and - (according to the docs) // I'm not sure how we should handle those though (coerce via to_int or to_f?) if (min->is_numeric() && max->is_numeric()) { if (min.send(env, ">"_s, { max })->is_true()) { env->raise("ArgumentError", "invalid argument - {}", arg->inspect_str(env)); } if (min->is_float() || max->is_float()) { double min_rand, max_rand; if (min->is_float()) { min_rand = min->as_float()->to_double(); } else { min_rand = (double)min->as_integer()->to_nat_int_t(); } if (max->is_float()) { max_rand = max->as_float()->to_double(); } else { max_rand = (double)max->as_integer()->to_nat_int_t(); } return generate_random(min_rand, max_rand); } else { nat_int_t min_rand = min->as_integer()->to_nat_int_t(); nat_int_t max_rand = max->as_integer()->to_nat_int_t(); if (arg->as_range()->exclude_end()) { max_rand -= 1; } return generate_random(min_rand, max_rand); } } env->raise("ArgumentError", "bad value for range"); } nat_int_t max = IntegerObject::convert_to_nat_int_t(env, arg); if (max <= 0) { env->raise("ArgumentError", "invalid argument - {}", arg->inspect_str(env)); } return generate_random(0, max - 1); } else { return generate_random(0.0, 1.0); } } }
35.4
108
0.491172
scwfri
981fdb72c88b75efe1a3fed99f68cac73bed709d
1,635
cpp
C++
backup/2/leetcode/c++/sum-of-nodes-with-even-valued-grandparent.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/leetcode/c++/sum-of-nodes-with-even-valued-grandparent.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/leetcode/c++/sum-of-nodes-with-even-valued-grandparent.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/leetcode/sum-of-nodes-with-even-valued-grandparent.html . /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int sumEvenGrandparent(TreeNode *root) { if (!root) { return 0; } auto left = root->left; auto right = root->right; int s1 = sumEvenGrandparent(left); int s2 = sumEvenGrandparent(right); int s = s1 + s2; if (root->val % 2 == 0) { if (left) { if (left->left) { s += left->left->val; } if (left->right) { s += left->right->val; } } if (right) { if (right->left) { s += right->left->val; } if (right->right) { s += right->right->val; } } } return s; } };
34.0625
345
0.526606
yangyanzhan
98204080566ef43c3fe933280661d997ee0167d2
59
cpp
C++
build/CMakeTmp/check_qt_application.cpp
TradingLab/tldbinit
1029ed59d97ca1200346b8dc94969777e567cd2b
[ "Apache-2.0" ]
null
null
null
build/CMakeTmp/check_qt_application.cpp
TradingLab/tldbinit
1029ed59d97ca1200346b8dc94969777e567cd2b
[ "Apache-2.0" ]
null
null
null
build/CMakeTmp/check_qt_application.cpp
TradingLab/tldbinit
1029ed59d97ca1200346b8dc94969777e567cd2b
[ "Apache-2.0" ]
null
null
null
#include <QtCore/QtGlobal> int main() { return 0; }
9.833333
26
0.59322
TradingLab
9821015105397b3217ca6269618e750c78ff3ca4
2,107
cpp
C++
src/layers/shuffle_channel_layer.cpp
ktts16/mini-caffe
58a5007d7921c69c9c3105b20b92b2136af26a4e
[ "BSD-3-Clause" ]
413
2015-07-09T09:33:07.000Z
2022-03-10T02:26:27.000Z
src/layers/shuffle_channel_layer.cpp
ktts16/mini-caffe
58a5007d7921c69c9c3105b20b92b2136af26a4e
[ "BSD-3-Clause" ]
65
2015-07-10T01:38:10.000Z
2020-08-06T07:27:42.000Z
src/layers/shuffle_channel_layer.cpp
ktts16/mini-caffe
58a5007d7921c69c9c3105b20b92b2136af26a4e
[ "BSD-3-Clause" ]
196
2015-08-18T07:59:33.000Z
2021-07-27T02:44:21.000Z
#include <algorithm> #include <vector> #include "./shuffle_channel_layer.hpp" #include "../util//math_functions.hpp" namespace caffe { void ShuffleChannelLayer::LayerSetUp(const vector<Blob*> &bottom, const vector<Blob*> &top) { group_ = this->layer_param_.shuffle_channel_param().group(); CHECK_GT(group_, 0) << "group must be greater than 0"; //temp_blob_.ReshapeLike(*bottom[0]); top[0]->ReshapeLike(*bottom[0]); } static void Resize_cpu(real_t* output, const real_t* input, int group_row, int group_column, int len) { for (int i = 0; i < group_row; ++i) { // 2 for(int j = 0; j < group_column ; ++j) { // 3 const real_t* p_i = input + (i * group_column + j ) * len; real_t* p_o = output + (j * group_row + i ) * len; caffe_copy(len, p_i, p_o); } } } void ShuffleChannelLayer::Reshape(const vector<Blob*> &bottom, const vector<Blob*> &top) { int channels_ = bottom[0]->channels(); int height_ = bottom[0]->height(); int width_ = bottom[0]->width(); top[0]->Reshape(bottom[0]->num(), channels_, height_, width_); } void ShuffleChannelLayer::Forward_cpu(const vector<Blob*>& bottom, const vector<Blob*>& top) { const real_t* bottom_data = bottom[0]->cpu_data(); real_t* top_data = top[0]->mutable_cpu_data(); const int num = bottom[0]->shape(0); const int feature_map_size = bottom[0]->count(1); const int sp_sz = bottom[0]->count(2); const int chs = bottom[0]->shape(1); int group_row = group_; int group_column = int(chs / group_row); CHECK_EQ(chs, (group_column * group_row)) << "Wrong group size."; //Dtype* temp_data = temp_blob_.mutable_cpu_data(); for(int n = 0; n < num; ++n) { Resize_cpu(top_data + n*feature_map_size, bottom_data + n*feature_map_size, group_row, group_column, sp_sz); } //caffe_copy(bottom[0]->count(), temp_blob_.cpu_data(), top_data); } #ifndef USE_CUDA STUB_GPU(ShuffleChannelLayer); #endif REGISTER_LAYER_CLASS(ShuffleChannel); } // namespace caffe
32.921875
111
0.633128
ktts16
9821474a8ffa4f55b9bfcf96b90b83f32ba2151a
7,250
cpp
C++
day_15/src/ofApp.cpp
andymasteroffish/inktober_2020
e836c33cf739e119d79570d7e870e97a52c2883a
[ "MIT" ]
16
2020-10-09T12:02:06.000Z
2022-01-06T01:49:03.000Z
day_15/src/ofApp.cpp
andymasteroffish/inktober_2020
e836c33cf739e119d79570d7e870e97a52c2883a
[ "MIT" ]
null
null
null
day_15/src/ofApp.cpp
andymasteroffish/inktober_2020
e836c33cf739e119d79570d7e870e97a52c2883a
[ "MIT" ]
null
null
null
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofBackground(250); for (int i=0; i<NUM_COLS; i++){ gcode[i].setup(100); gcode[i].show_transit_lines = false; gcode[i].show_do_not_reverse = true; } gcode[PURPLE].demo_col = ofColor::purple; gcode[LIGHT_PURPLE].demo_col = ofColor::magenta; gcode[RED].demo_col = ofColor::red; gcode[BLACK].demo_col = ofColor::black; float outter_circle_size = 300; int ring_pnts = 100; //tentacles int num_tentacles = 5; for (int i=0; i<num_tentacles; i++){ float angle = 0.5+(TWO_PI/(float)num_tentacles) * i; Tentacle tent; tent.setup(angle, 600); tentacles.push_back(tent); tent.make_gcode(&gcode[PURPLE], &gcode[LIGHT_PURPLE]); } //rings Circle outter_circle; outter_circle.setup(ofVec2f(ofGetWidth()/2, ofGetHeight()/2), outter_circle_size, ring_pnts, 0); Circle inner_circle; inner_circle.setup(ofVec2f(ofGetWidth()/2, ofGetHeight()/2), 70); //teeth int num_triangles = 500; for (float i=0; i<num_triangles; i++){ //float prc = 1.0 - i/(float)num_triangles; float angle = 0.47 + i*0.2;// prc * TWO_PI * 3; float dist = outter_circle_size + 30 - i*0.5;//100 + 200 * prc; float size = 60 - i*0.08;//20 + 25 * prc; Triangle tri; tri.setup(angle, dist, size); //chop 'em tri.trim(triangles, tentacles); tri.trim_inside(outter_circle.border); tri.trim_outside(inner_circle.border); tri.make_gcode(&gcode[RED]); triangles.push_back(tri); } //outter ring Circle outter_circle2; outter_circle2.setup(ofVec2f(ofGetWidth()/2, ofGetHeight()/2), outter_circle_size+30, ring_pnts, PI/16); for (int i=0; i<ring_pnts; i++){ ofVec2f a = outter_circle.border[i]; ofVec2f b = outter_circle2.border[i]; GLine line; line.set(a,b); for (int t=0; t<tentacles.size(); t++){ line.clip_outside_polygon(tentacles[t].border); } gcode[PURPLE].line(line); } for (int t=0; t<tentacles.size(); t++){ outter_circle.trim_outside(tentacles[t].border); outter_circle2.trim_outside(tentacles[t].border); } outter_circle.make_gcode(&gcode[PURPLE]); outter_circle2.make_gcode(&gcode[PURPLE]); //hexagon mouth float angle_step = TWO_PI/5; for(float d = 5; d<69; d+=4){ gcode[BLACK].begin_shape(); for (int i=0; i<5; i++){ float angle = 0.3 + angle_step*i + sin(d*0.01)*TWO_PI; gcode[BLACK].vertex(ofGetWidth()/2+cos(angle)*d, ofGetHeight()/2+sin(angle)*d); } gcode[BLACK].end_shape(true); } //shoot some lines int num_noise_lines = 40; angle_step = TWO_PI/num_noise_lines; for (int k=0; k<num_noise_lines; k++){ float angle = angle_step * k; float start_dist = outter_circle_size+50; if (k%2==0){ start_dist += 100; } ofVec2f start_pos = ofVec2f(ofGetWidth()/2+cos(angle)*start_dist, ofGetHeight()/2+sin(angle)*start_dist); ofVec2f pos = ofVec2f(start_pos); ofVec2f prev_pos; int num_steps = 300;//ofRandom(100, 400); float stepDist = 2; float curve_range = 0.02; float curve = 0.005;//ofRandom(-curve_range,curve_range); vector<GLine> lines; for (int i=0; i<num_steps; i++){ pos.x += cos(angle) * stepDist; pos.y += sin(angle) * stepDist; angle += curve; //angle += (1-ofNoise(start_pos.x, start_pos.y, i*0.005) *2) * 0.02; if (ofDistSquared(pos.x, pos.y, ofGetWidth()/2, ofGetHeight()/2) < powf(start_dist,2)){ break; } if (i!=0){ //if (ofRandomuf() < 0.5){ GLine line; line.set(pos, prev_pos); for (int t=0; t<tentacles.size(); t++){ line.clip_outside_polygon(tentacles[t].border); } lines.push_back(line); //gcode.line(line); //} } prev_pos.set(pos); if (pos.x < -10 || pos.x >ofGetWidth()+10 || pos.y < -10 || pos.y >= ofGetHeight()+10){ break; } } //draw it bool is_on = ofRandomuf() < 0.5; int counter = 0; for (int i=0; i<lines.size(); i++){ counter--; if(counter <= 0){ is_on = !is_on; if (is_on){ counter = ofRandom(5,12); }else{ counter = ofRandom(4,10); } } if (is_on){ gcode[BLACK].line(lines[i]); } } } for (int i=0; i<NUM_COLS; i++){ ofRectangle safe_zone; safe_zone.set(20, 20, ofGetWidth()-20, ofGetHeight()-20); gcode[i].set_outwards_only_bounds(safe_zone); gcode[i].sort(); gcode[i].save("inktober_15_"+ofToString(i)+".nc"); } } //-------------------------------------------------------------- void ofApp::update(){ } //-------------------------------------------------------------- void ofApp::draw(){ for (int i=0; i<NUM_COLS; i++){ gcode[i].draw(); } // ofSetColor(0,100,0); // ofNoFill(); // for (int i=0; i<tentacles.size(); i++){ // tentacles[i].draw(); // } // // // ofSetColor(255,0,0); // ofNoFill(); // for (int i=0; i<triangles.size(); i++){ // triangles[i].test_draw(); // } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
27.358491
113
0.452966
andymasteroffish
982689cfbb60495a477caab60651c602e58226a4
3,974
cpp
C++
src/Engine/App/AssetRegistry.cpp
kimkulling/osre
b738c87e37d0b1d2d0779a412b88ce68517c4328
[ "MIT" ]
118
2015-05-12T15:12:14.000Z
2021-11-14T15:41:11.000Z
src/Engine/App/AssetRegistry.cpp
kimkulling/osre
b738c87e37d0b1d2d0779a412b88ce68517c4328
[ "MIT" ]
76
2015-06-06T18:04:24.000Z
2022-01-14T20:17:37.000Z
src/Engine/App/AssetRegistry.cpp
kimkulling/osre
b738c87e37d0b1d2d0779a412b88ce68517c4328
[ "MIT" ]
7
2016-06-28T09:14:38.000Z
2021-03-12T02:07:52.000Z
/*----------------------------------------------------------------------------------------------- The MIT License (MIT) Copyright (c) 2015-2021 OSRE ( Open Source Render Engine ) by Kim Kulling 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 <osre/App/AssetRegistry.h> #include <osre/Common/Logger.h> #include <osre/Common/StringUtils.h> #include <osre/IO/Uri.h> #include <osre/IO/Stream.h> namespace OSRE { namespace App { using namespace ::OSRE::Common; AssetRegistry *AssetRegistry::s_instance = nullptr; static const String Tag = "AssetRegistry"; AssetRegistry *AssetRegistry::create() { if ( nullptr == s_instance ) { s_instance = new AssetRegistry; } return s_instance; } void AssetRegistry::destroy() { if ( nullptr==s_instance ) { return; } delete s_instance; s_instance = nullptr; } bool AssetRegistry::registerAssetPath( const String &mount, const String &path ) { if ( nullptr == s_instance ) { return false; } const ui32 hashId( StringUtils::hashName( mount ) ); s_instance->m_name2pathMap.insert( hashId, path ); return true; } bool AssetRegistry::hasPath( const String &mount ) { if ( nullptr == s_instance ) { return false; } const ui32 hashId( StringUtils::hashName( mount ) ); if ( !s_instance->m_name2pathMap.hasKey( hashId ) ) { return false; } return true; } static const String Dummy(""); String AssetRegistry::getPath( const String &mount ) { if ( nullptr == s_instance ) { return Dummy; } const HashId hashId( StringUtils::hashName( mount ) ); if ( !s_instance->m_name2pathMap.hasKey( hashId ) ) { return Dummy; } String path; if ( s_instance->m_name2pathMap.getValue( hashId, path ) ) { return path; } return Dummy; } String AssetRegistry::resolvePathFromUri( const IO::Uri &location ) { if ( location.isEmpty() ) { return Dummy; } const String pathToCheck( location.getAbsPath() ); String absPath( pathToCheck ); const String::size_type pos = pathToCheck.find( "/" ); String mountPoint = pathToCheck.substr( 0, pos ); String::size_type offset = pos + mountPoint.size() + 1; if ( hasPath( mountPoint ) ) { absPath = getPath( mountPoint ); if ( absPath[ absPath.size()-1 ]!='/' ) { absPath += '/'; offset++; } const String rest = pathToCheck.substr( pos+1, pathToCheck.size() - pos-1 ); absPath += rest; } return absPath; } bool AssetRegistry::clear() { if ( nullptr == s_instance ) { return false; } s_instance->m_name2pathMap.clear(); return true; } AssetRegistry::AssetRegistry() : m_name2pathMap() { // empty } AssetRegistry::~AssetRegistry() { // empty } } // Namespace Assets } // Namespace OSRE
27.985915
97
0.638903
kimkulling
9828a78dcc719784a1e07d059d2c2bd1aa853a37
2,629
cpp
C++
debugger/src/gui_plugin/qt_wrapper.cpp
hossameldin1995/riscv_vhdl
aab7196a6b9962626ed7314b7c86b93760e76f83
[ "Apache-2.0" ]
2
2020-08-12T17:01:28.000Z
2020-10-06T02:50:49.000Z
debugger/src/gui_plugin/qt_wrapper.cpp
hossameldin1995/riscv_vhdl
aab7196a6b9962626ed7314b7c86b93760e76f83
[ "Apache-2.0" ]
null
null
null
debugger/src/gui_plugin/qt_wrapper.cpp
hossameldin1995/riscv_vhdl
aab7196a6b9962626ed7314b7c86b93760e76f83
[ "Apache-2.0" ]
1
2021-11-18T17:40:35.000Z
2021-11-18T17:40:35.000Z
/* * Copyright 2018 Sergey Khabarov, sergeykhbr@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "api_core.h" #include "qt_wrapper.h" #include "moc_qt_wrapper.h" #include <string> #include <QtWidgets/QApplication> #define QT_EXEC_IMPL namespace debugger { static event_def eventAppDestroyed_; /** It's a blocking event that runs only once */ void ui_events_update(void *args) { QtWrapper *ui = reinterpret_cast<QtWrapper *>(args); ui->eventsUpdate(); RISCV_event_set(&eventAppDestroyed_); //RISCV_event_close(&eventAppDestroyed_); } QtWrapper::QtWrapper(IGui *igui) : QObject() { igui_ = igui; exiting_ = false; pextRequest_ = extRequest_; RISCV_event_create(&eventAppDestroyed_, "eventAppDestroyed_"); } QtWrapper::~QtWrapper() { } void QtWrapper::postInit(AttributeType *gui_cfg) { RISCV_register_timer(1, 1, ui_events_update, this); } void QtWrapper::eventsUpdate() { int argc = 0; char *argv[] = {0}; QApplication app(argc, argv); app.setQuitOnLastWindowClosed(true); mainWindow_ = new DbgMainWindow(igui_); connect(mainWindow_, SIGNAL(signalAboutToClose()), this, SLOT(slotMainWindowAboutToClose())); mainWindow_->show(); app.exec(); RISCV_unregister_timer(ui_events_update); delete mainWindow_; app.quit(); } void QtWrapper::gracefulClose() { if (!exiting_) { /** Exit through console command 'exit' */ mainWindow_->close(); RISCV_event_wait_ms(&eventAppDestroyed_, 10000); } } void QtWrapper::externalCommand(AttributeType *req) { size_t free_cnt = sizeof(extRequest_) - (pextRequest_ - extRequest_); if (free_cnt <= req->size()) { pextRequest_ = extRequest_; } memcpy(pextRequest_, req->to_string(), req->size() + 1); emit signalExternalCommand(pextRequest_); pextRequest_ += req->size() + 1; } void QtWrapper::slotMainWindowAboutToClose() { if (exiting_) { return; } /** Exit from GUI button push */ exiting_ = true; RISCV_break_simulation(); } } // namespace debugger
26.555556
76
0.689996
hossameldin1995
982a75a9741b990d28e90c87657a0f1083614c4c
18,269
cpp
C++
contracts/contracts/rem.system/src/producer_pay.cpp
kushnirenko/remprotocol
ec450227a40bb18527b473266b07b982efc1d093
[ "MIT" ]
1
2020-07-13T04:53:53.000Z
2020-07-13T04:53:53.000Z
contracts/contracts/rem.system/src/producer_pay.cpp
kushnirenko/remprotocol
ec450227a40bb18527b473266b07b982efc1d093
[ "MIT" ]
1
2020-05-20T20:14:13.000Z
2020-05-20T20:14:13.000Z
contracts/contracts/rem.system/src/producer_pay.cpp
kushnirenko/remprotocol
ec450227a40bb18527b473266b07b982efc1d093
[ "MIT" ]
1
2020-05-13T14:06:06.000Z
2020-05-13T14:06:06.000Z
#include <rem.system/rem.system.hpp> #include <rem.token/rem.token.hpp> #include <cmath> #include <numeric> namespace eosiosystem { const static int producer_repetitions = 12; const static int blocks_per_round = system_contract::max_block_producers * producer_repetitions; using eosio::current_time_point; using eosio::microseconds; using eosio::token; int64_t system_contract::share_pervote_reward_between_producers(int64_t amount) { const auto reward_period_without_producing = microseconds(_grotation.rotation_period.count() * _grotation.standby_prods_to_rotate); const auto ct = current_time_point(); int64_t total_reward_distributed = 0; for (const auto& p: _gstate.last_schedule) { const auto reward = int64_t(amount * p.second); total_reward_distributed += reward; const auto& prod = _producers.get(p.first.value); if (ct - prod.last_block_time <= reward_period_without_producing) { _producers.modify(prod, eosio::same_payer, [&](auto &p) { p.pending_pervote_reward += reward; }); } } for (const auto& p: _gstate.standby) { const auto reward = int64_t(amount * p.second); total_reward_distributed += reward; const auto& prod = _producers.get(p.first.value); if (ct - prod.last_block_time <= reward_period_without_producing) { _producers.modify(prod, eosio::same_payer, [&](auto &p) { p.pending_pervote_reward += reward; }); } } check(total_reward_distributed <= amount, "distributed reward above the given amount"); return total_reward_distributed; } void system_contract::update_pervote_shares() { auto share_accumulator = [this](double l, const std::pair<name, double>& r) -> double { const auto& prod = _producers.get(r.first.value); return l + prod.total_votes; }; double total_share = 0.0; total_share = std::accumulate(std::begin(_gstate.last_schedule), std::end(_gstate.last_schedule), total_share, share_accumulator); total_share = std::accumulate(std::begin(_gstate.standby), std::end(_gstate.standby), total_share, share_accumulator); _gstate.total_active_producer_vote_weight = total_share; auto update_pervote_share = [this](auto& p) { const auto& prod_name = p.first; const auto& prod = _producers.get(prod_name.value); const double share = prod.total_votes / _gstate.total_active_producer_vote_weight; // need to cut precision because sum of all shares can be greater that 1 due to floating point arithmetics p.second = std::floor(share * 100000.0) / 100000.0; }; std::for_each(std::begin(_gstate.last_schedule), std::end(_gstate.last_schedule), update_pervote_share); std::for_each(std::begin(_gstate.standby), std::end(_gstate.standby), update_pervote_share); } void system_contract::update_standby() { std::vector<std::pair<name, double>> rotation; std::transform(std::begin(_grotation.standby_rotation), std::end(_grotation.standby_rotation), std::back_inserter(rotation), [](const auto& auth) { return std::make_pair(auth.producer_name, 0.0); }); _gstate.standby.clear(); _gstate.standby.reserve(rotation.size()); auto name_double_comparator = [](const std::pair<name, double>& l, const std::pair<name, double>& r) { return l.first < r.first; }; std::sort(std::begin(rotation), std::end(rotation), name_double_comparator); std::set_difference(std::begin(rotation), std::end(rotation), std::begin(_gstate.last_schedule), std::end(_gstate.last_schedule), std::back_inserter(_gstate.standby), name_double_comparator); } int64_t system_contract::share_perstake_reward_between_guardians(int64_t amount) { using namespace eosio; int64_t total_reward_distributed = 0; const auto sorted_voters = _voters.get_index<"bystake"_n>(); _gstate.total_guardians_stake = 0; for (auto it = sorted_voters.rbegin(); it != sorted_voters.rend() && it->staked >= _gremstate.guardian_stake_threshold; it++) { if ( vote_is_reasserted( it->last_reassertion_time ) ) { _gstate.total_guardians_stake += it->staked; } } for (auto it = sorted_voters.rbegin(); it != sorted_voters.rend() && it->staked >= _gremstate.guardian_stake_threshold; it++) { if ( vote_is_reasserted( it->last_reassertion_time ) ) { const int64_t pending_perstake_reward = amount * ( double(it->staked) / double(_gstate.total_guardians_stake) ); _voters.modify( *it, same_payer, [&](auto &v) { v.pending_perstake_reward += pending_perstake_reward; }); total_reward_distributed += pending_perstake_reward; } } check(total_reward_distributed <= amount, "distributed reward above the given amount"); return total_reward_distributed; } void system_contract::onblock( ignore<block_header> ) { using namespace eosio; require_auth(get_self()); block_timestamp timestamp; name producer; uint16_t confirmed; checksum256 previous; checksum256 transaction_mroot; checksum256 action_mroot; uint32_t schedule_version = 0; _ds >> timestamp >> producer >> confirmed >> previous >> transaction_mroot >> action_mroot >> schedule_version; // _gstate2.last_block_num is not used anywhere in the system contract code anymore. // Although this field is deprecated, we will continue updating it for now until the last_block_num field // is eventually completely removed, at which point this line can be removed. _gstate2.last_block_num = timestamp; /** until activated stake crosses this threshold no new rewards are paid */ if( _gstate.total_activated_stake < min_activated_stake ) return; //end of round: count all unpaid blocks produced within this round if (timestamp.slot >= _gstate.current_round_start_time.slot + blocks_per_round) { const auto rounds_passed = (timestamp.slot - _gstate.current_round_start_time.slot) / blocks_per_round; _gstate.current_round_start_time = block_timestamp(_gstate.current_round_start_time.slot + (rounds_passed * blocks_per_round)); for (const auto p: _gstate.last_schedule) { const auto& prod = _producers.get(p.first.value); _producers.modify(prod, same_payer, [&](auto& p) { p.unpaid_blocks += p.current_round_unpaid_blocks; p.current_round_unpaid_blocks = 0; }); } } if (schedule_version > _gstate.last_schedule_version) { std::vector<name> active_producers = eosio::get_active_producers(); for (size_t producer_index = 0; producer_index < _gstate.last_schedule.size(); producer_index++) { const auto producer_name = _gstate.last_schedule[producer_index].first; const auto& prod = _producers.get(producer_name.value); if( std::find(active_producers.begin(), active_producers.end(), producer_name) == active_producers.end() ) { _producers.modify(prod, same_payer, [&](auto& p) { p.top21_chosen_time = time_point(eosio::seconds(0)); }); } //blocks from full rounds const auto full_rounds_passed = (timestamp.slot - prod.last_expected_produced_blocks_update.slot) / blocks_per_round; uint32_t expected_produced_blocks = full_rounds_passed * producer_repetitions; if ((timestamp.slot - prod.last_expected_produced_blocks_update.slot) % blocks_per_round != 0) { //if last round is incomplete, calculate number of blocks produced in this round by prod const auto current_round_start_position = _gstate.current_round_start_time.slot % blocks_per_round; const auto producer_first_block_position = producer_repetitions * producer_index; const uint32_t current_round_blocks_before_producer_start_producing = current_round_start_position <= producer_first_block_position ? producer_first_block_position - current_round_start_position : blocks_per_round - (current_round_start_position - producer_first_block_position); const auto total_current_round_blocks = timestamp.slot - _gstate.current_round_start_time.slot; if (current_round_blocks_before_producer_start_producing < total_current_round_blocks) { expected_produced_blocks += std::min(total_current_round_blocks - current_round_blocks_before_producer_start_producing, uint32_t(producer_repetitions)); } else if (blocks_per_round - current_round_blocks_before_producer_start_producing < producer_repetitions) { expected_produced_blocks += std::min(producer_repetitions - (blocks_per_round - current_round_blocks_before_producer_start_producing), total_current_round_blocks); } } _producers.modify(prod, same_payer, [&](auto& p) { p.expected_produced_blocks += expected_produced_blocks; p.last_expected_produced_blocks_update = timestamp; p.unpaid_blocks += p.current_round_unpaid_blocks; p.current_round_unpaid_blocks = 0; }); } _gstate.current_round_start_time = timestamp; _gstate.last_schedule_version = schedule_version; for (size_t i = 0; i < active_producers.size(); i++) { const auto& prod_name = active_producers[i]; const auto& prod = _producers.get(prod_name.value); auto res = std::find_if(_gstate.last_schedule.begin(), _gstate.last_schedule.end(), [&prod_name](const std::pair<eosio::name, double>& element){ return element.first == prod_name;}); if( res == _gstate.last_schedule.end() ) { _producers.modify(prod, same_payer, [&](auto& p) { p.top21_chosen_time = current_time_point(); }); } } if (active_producers.size() != _gstate.last_schedule.size()) { _gstate.last_schedule.resize(active_producers.size()); } for (size_t i = 0; i < active_producers.size(); i++) { const auto& prod_name = active_producers[i]; const auto& prod = _producers.get(prod_name.value); _gstate.last_schedule[i] = std::make_pair(prod_name, 0.0); _producers.modify(prod, same_payer, [&](auto& p) { p.last_expected_produced_blocks_update = timestamp; }); } get_rotated_schedule(); update_standby(); update_pervote_shares(); } if( _gstate.last_pervote_bucket_fill == time_point() ) /// start the presses _gstate.last_pervote_bucket_fill = current_time_point(); /** * At startup the initial producer may not be one that is registered / elected * and therefore there may be no producer object for them. */ auto prod = _producers.find( producer.value ); if ( prod != _producers.end() ) { _gstate.total_unpaid_blocks++; _producers.modify( prod, same_payer, [&](auto& p ) { p.current_round_unpaid_blocks++; p.last_block_time = timestamp; }); } /// only update block producers once every minute, block_timestamp is in half seconds if( timestamp.slot - _gstate.last_producer_schedule_update.slot > 120 ) { update_elected_producers( timestamp ); if( (timestamp.slot - _gstate.last_name_close.slot) > blocks_per_day ) { name_bid_table bids(get_self(), get_self().value); auto idx = bids.get_index<"highbid"_n>(); auto highest = idx.lower_bound( std::numeric_limits<uint64_t>::max()/2 ); if( highest != idx.end() && highest->high_bid > 0 && (current_time_point() - highest->last_bid_time) > microseconds(useconds_per_day) && _gstate.thresh_activated_stake_time > time_point() && (current_time_point() - _gstate.thresh_activated_stake_time) > microseconds(14 * useconds_per_day) ) { _gstate.last_name_close = timestamp; channel_namebid_to_rex( highest->high_bid ); idx.modify( highest, same_payer, [&]( auto& b ){ b.high_bid = -b.high_bid; }); } } } } using namespace eosio; void system_contract::claim_perstake( const name& guardian ) { const auto& voter = _voters.get( guardian.value ); const auto ct = current_time_point(); check( ct - voter.last_claim_time > microseconds(useconds_per_day), "already claimed rewards within past day" ); _gstate.perstake_bucket -= voter.pending_perstake_reward; if ( voter.pending_perstake_reward > 0 ) { token::transfer_action transfer_act{ token_account, { {spay_account, active_permission}, {guardian, active_permission} } }; transfer_act.send( spay_account, guardian, asset(voter.pending_perstake_reward, core_symbol()), "guardian stake pay" ); } _voters.modify( voter, same_payer, [&](auto& v) { v.last_claim_time = ct; v.pending_perstake_reward = 0; }); } void system_contract::claim_pervote( const name& producer ) { const auto& prod = _producers.get( producer.value ); const auto ct = current_time_point(); check( ct - prod.last_claim_time > microseconds(useconds_per_day), "already claimed rewards within past day" ); int64_t producer_per_vote_pay = prod.pending_pervote_reward; auto expected_produced_blocks = prod.expected_produced_blocks; if (std::find_if(std::begin(_gstate.last_schedule), std::end(_gstate.last_schedule), [&producer](const auto& prod){ return prod.first.value == producer.value; }) != std::end(_gstate.last_schedule)) { const auto full_rounds_passed = (_gstate.current_round_start_time.slot - prod.last_expected_produced_blocks_update.slot) / blocks_per_round; expected_produced_blocks += full_rounds_passed * producer_repetitions; } if (prod.unpaid_blocks != expected_produced_blocks && expected_produced_blocks > 0) { producer_per_vote_pay = (prod.pending_pervote_reward * prod.unpaid_blocks) / expected_produced_blocks; } const auto punishment = prod.pending_pervote_reward - producer_per_vote_pay; if ( producer_per_vote_pay > 0 ) { token::transfer_action transfer_act{ token_account, { {vpay_account, active_permission}, {producer, active_permission} } }; transfer_act.send( vpay_account, producer, asset(producer_per_vote_pay, core_symbol()), "producer vote pay" ); } if ( punishment > 0 ) { string punishment_memo = "punishment transfer: missed " + std::to_string(expected_produced_blocks - prod.unpaid_blocks) + " blocks out of " + std::to_string(expected_produced_blocks); token::transfer_action transfer_act{ token_account, { {vpay_account, active_permission} } }; transfer_act.send( vpay_account, saving_account, asset(punishment, core_symbol()), punishment_memo ); } _gstate.pervote_bucket -= producer_per_vote_pay; _gstate.total_unpaid_blocks -= prod.unpaid_blocks; _producers.modify( prod, same_payer, [&](auto& p) { p.last_claim_time = ct; p.last_expected_produced_blocks_update = _gstate.current_round_start_time; p.unpaid_blocks = 0; p.expected_produced_blocks = 0; p.pending_pervote_reward = 0; }); } void system_contract::claimrewards( const name& owner ) { require_auth( owner ); check( _gstate.total_activated_stake >= min_activated_stake, "cannot claim rewards until the chain is activated (at least 15% of all tokens participate in voting)" ); auto voter = _voters.find( owner.value ); if( voter != _voters.end() ) { claim_perstake( owner ); } auto prod = _producers.find( owner.value ); if( prod != _producers.end() ) { claim_pervote( owner ); } } void system_contract::torewards( const name& payer, const asset& amount ) { require_auth( payer ); check( amount.is_valid(), "invalid amount" ); check( amount.symbol == core_symbol(), "invalid symbol" ); check( amount.amount > 0, "amount must be positive" ); const auto to_per_stake_pay = share_perstake_reward_between_guardians( amount.amount * _gremstate.per_stake_share ); const auto to_per_vote_pay = share_pervote_reward_between_producers( amount.amount * _gremstate.per_vote_share ); const auto to_rem = amount.amount - (to_per_stake_pay + to_per_vote_pay); if( amount.amount > 0 ) { token::transfer_action transfer_act{ token_account, { {payer, active_permission} } }; if( to_rem > 0 ) { transfer_act.send( payer, saving_account, asset(to_rem, amount.symbol), "Remme Savings" ); } if( to_per_stake_pay > 0 ) { transfer_act.send( payer, spay_account, asset(to_per_stake_pay, amount.symbol), "fund per-stake bucket" ); } if( to_per_vote_pay > 0 ) { transfer_act.send( payer, vpay_account, asset(to_per_vote_pay, amount.symbol), "fund per-vote bucket" ); } } _gstate.pervote_bucket += to_per_vote_pay; _gstate.perstake_bucket += to_per_stake_pay; } } //namespace eosiosystem
49.375676
192
0.647873
kushnirenko
982af8ecf9502e6c01bf5fb2971827969a5708f1
1,045
hpp
C++
binspector/fuzzer.hpp
sur5r/binspector
9eeb9af463254edf1056d59944c49d00770e36f0
[ "BSL-1.0" ]
119
2015-01-14T18:03:20.000Z
2022-03-18T14:02:46.000Z
binspector/fuzzer.hpp
sur5r/binspector
9eeb9af463254edf1056d59944c49d00770e36f0
[ "BSL-1.0" ]
8
2015-03-06T01:18:39.000Z
2021-05-04T21:55:34.000Z
binspector/fuzzer.hpp
sur5r/binspector
9eeb9af463254edf1056d59944c49d00770e36f0
[ "BSL-1.0" ]
22
2015-01-09T16:18:38.000Z
2022-03-13T13:41:04.000Z
/* Copyright 2014 Adobe Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ /****************************************************************************************************/ #ifndef BINSPECTOR_FUZZER_HPP #define BINSPECTOR_FUZZER_HPP // boost #include <boost/filesystem.hpp> // application #include <binspector/forest.hpp> /****************************************************************************************************/ void fuzz(const inspection_forest_t& forest, const boost::filesystem::path& input_path, const boost::filesystem::path& output_root, bool path_hash, bool recurse); /****************************************************************************************************/ // BINSPECTOR_FUZZER_HPP #endif /****************************************************************************************************/
34.833333
102
0.396172
sur5r
982ff1eb1b47c7de70e0623986d562615065e2ac
8,073
cpp
C++
PEOperator/ThreadAnalysisFile.cpp
JokerRound/PEOperator
19dcbaa42ea2888369e380d01652ea815eadfdd4
[ "MIT" ]
null
null
null
PEOperator/ThreadAnalysisFile.cpp
JokerRound/PEOperator
19dcbaa42ea2888369e380d01652ea815eadfdd4
[ "MIT" ]
null
null
null
PEOperator/ThreadAnalysisFile.cpp
JokerRound/PEOperator
19dcbaa42ea2888369e380d01652ea815eadfdd4
[ "MIT" ]
1
2022-02-08T09:07:50.000Z
2022-02-08T09:07:50.000Z
#include "stdafx.h" #include "ThreadAnalysisFile.h" #include "PEOperatorDlg.h" CThreadAnalysisFile::CThreadAnalysisFile() { } CThreadAnalysisFile::~CThreadAnalysisFile() { } bool CThreadAnalysisFile::OnThreadEventRun(LPVOID lpParam) { #ifdef DEBUG DWORD dwError = -1; CString csErrorMessage; #endif // DEBUG // Analysis parament. CPEOperatorDlg *pPEOperatorDlg = (CPEOperatorDlg *)lpParam; BOOL bRet = FALSE; // Main work loop while (TRUE) { // Wait for the event. bRet = pPEOperatorDlg->CheckAnalysisFileEvent(); if (!bRet) { break; } // Check quit info is true or not. bRet = pPEOperatorDlg->GetProcessQuitInfo(); if (bRet) { break; } // Get file's handle. HANDLE hTargetFile = CreateFile(pPEOperatorDlg->GetTargetFileName(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hTargetFile) { #ifdef DEBUG dwError = GetLastError(); GetErrorMessage(dwError, csErrorMessage); OutputDebugStringWithInfo(csErrorMessage, __FILET__, __LINE__); #endif // DEBUG CString csOperationNotify = _T("Please choice a file."); pPEOperatorDlg->SendMessage(WM_UPDATEUI, (WPARAM)_T("Open file failed." "Please check it.")); continue; } CFile fTargetFile(hTargetFile); // Get file info. //****************************************************** //* Alarm * This memory will free when main dialog close. //****************************************************** PTARGETFILEINFO pstTargetFileInfo = new TARGETFILEINFO; CFileStatus TargetFileStatus; fTargetFile.GetStatus(TargetFileStatus); CPath pathFilePath = pPEOperatorDlg->GetTargetFileName(); CPath pathFileName = pPEOperatorDlg->GetTargetFileName(); pathFileName.StripPath(); pathFilePath.RemoveFileSpec(); // File path and name. pstTargetFileInfo->csFileName_ = pathFileName.m_strPath; pstTargetFileInfo->csFilePath_ = pathFilePath.m_strPath; // Carete time. pstTargetFileInfo->csCreatTime_.Format( _T("%d:%d:%d, %d.%d.%d"), TargetFileStatus.m_ctime.GetHour(), TargetFileStatus.m_ctime.GetMinute(), TargetFileStatus.m_ctime.GetSecond(), TargetFileStatus.m_ctime.GetDay(), TargetFileStatus.m_ctime.GetMonth(), TargetFileStatus.m_ctime.GetYear()); pstTargetFileInfo->csLastAccessedTime_.Format( _T("%d:%d:%d, %d.%d.%d"), TargetFileStatus.m_atime.GetHour(), TargetFileStatus.m_atime.GetMinute(), TargetFileStatus.m_atime.GetSecond(), TargetFileStatus.m_atime.GetDay(), TargetFileStatus.m_atime.GetMonth(), TargetFileStatus.m_atime.GetYear()); pstTargetFileInfo->csLastModifyTime_.Format(_T("%d:%d:%d, %d.%d.%d"), TargetFileStatus.m_mtime.GetHour(), TargetFileStatus.m_mtime.GetMinute(), TargetFileStatus.m_mtime.GetSecond(), TargetFileStatus.m_mtime.GetDay(), TargetFileStatus.m_mtime.GetMonth(), TargetFileStatus.m_mtime.GetYear()); pstTargetFileInfo->csSize_.Format(_T("%I64u"), TargetFileStatus.m_size); // Begin to analysis. BOOL bHasError = FALSE; do { // Read dos header. IMAGE_DOS_HEADER stDosHeader = { 0 }; fTargetFile.Read(&stDosHeader, sizeof(stDosHeader)); // Check the magic member. if (0x5a4d != stDosHeader.e_magic) { bHasError = TRUE; break; } // Move the pointer of file to NT header. fTargetFile.Seek(stDosHeader.e_lfanew, CFile::begin); // Read PE fingerprint DWORD dwPEFingerprint; fTargetFile.Read(&dwPEFingerprint, sizeof(dwPEFingerprint)); // Check PE fingerprint. if (0x4550 != dwPEFingerprint) { bHasError = TRUE; break; } // Move the pointer of file to type of optional header. int iOptionalHeaderTyepPos = stDosHeader.e_lfanew + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER); fTargetFile.Seek(iOptionalHeaderTyepPos, CFile::begin); // Read Optional header type. WORD wOptionalHeaderType = 0; fTargetFile.Read(&wOptionalHeaderType, sizeof(WORD)); // Move the pointer of file to NT header. fTargetFile.Seek(stDosHeader.e_lfanew, CFile::begin); // Create struct of PE file 32bit. if (0x10b == wOptionalHeaderType) { //************************************************************** //* Alarm * This memory will free when main dialog close. //************************************************************** PPEFILESTRUCT32 pstPEFileStruct32 = new PEFILESTRUCT32; pstPEFileStruct32->stDosHeader_ = stDosHeader; // Read NT headers. fTargetFile.Read(&pstPEFileStruct32->stNtHeader_, sizeof(pstPEFileStruct32->stNtHeader_)); // Main dislog gets the PE file info. pPEOperatorDlg->SetPEFileStruct32(pstPEFileStruct32); // Read section info. WORD wSectionNumber = pstPEFileStruct32->stNtHeader_.FileHeader.NumberOfSections; WORD cntI = 0; while (cntI < wSectionNumber) { //********************************************************** //* Alarm * This memory will free when // CPESectionInfo destroy. //********************************************************** IMAGE_SECTION_HEADER stSectionInfo = { 0 }; fTargetFile.Read(&stSectionInfo, sizeof(stSectionInfo)); pPEOperatorDlg->m_vctSectionInfo.push_back(stSectionInfo); cntI++; } } // TODO: Create struct of PE file 64bit. else if (0x20b == wOptionalHeaderType) { } // Another else { bHasError = TRUE; break; } } while (FALSE); // do "Begin to analysis" END // Close file handle. fTargetFile.Close(); // Deal with analysis failed. if (bHasError) { CString csOperationNotify = _T("Target file don't belong PE."); pPEOperatorDlg->SendMessage( WM_UPDATEUI, MDUI_OPERATIONNOTIFY, (WPARAM)&csOperationNotify); continue; } pstTargetFileInfo->csIsPEFile_ = _T("Yes"); // Main dialog gets file info. pPEOperatorDlg->SetTargetFileInfo(pstTargetFileInfo); // Notify analysis completed to main dailog. pPEOperatorDlg->SendMessage(WM_FILEHADANALYSISED); } //! while "Main work loop" END return true; } //! CThreadAnalysisFile::OnThreadEventRun END
36.040179
80
0.503778
JokerRound
98301e097fdeb4530c3eab82151022723e861abf
14,784
cpp
C++
src/widgets/portfiltersettingswidget.cpp
dehnhardt/mioconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
16
2018-07-16T14:13:10.000Z
2021-02-07T06:43:57.000Z
src/widgets/portfiltersettingswidget.cpp
dehnhardt/iconnconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
16
2017-09-06T19:38:15.000Z
2021-01-04T17:54:02.000Z
src/widgets/portfiltersettingswidget.cpp
dehnhardt/mioconfig
6d1ac1d85379eaf168d2c2fce81b09f020500605
[ "MIT" ]
10
2018-03-03T14:50:03.000Z
2020-09-30T18:08:55.000Z
#include "portfiltersettingswidget.h" #include "controls/midicontrollercombodelegate.h" #include "ui_portfiltersettingswidget.h" #include <QLabel> PortFilterSettingsWidget::PortFilterSettingsWidget(pk::PortDirection direction, QWidget *parent) : QWidget(parent), ui(new Ui::PortFilterSettingsWidget), portFilterDirection(direction) { ui->setupUi(this); const QString style = "QTableView { \ gridline-color: #aaaaa8; \ padding: 0; \ font-size: 8pt; \ } \ QTableView::indicator{ \ width: 14; \ height: 14; \ border-radius: 7px; \ border: 0; \ } \ QTableView::indicator:enabled{ \ background-color: #c9c9c9; \ } \ QTableView::indicator:checked{ \ background-color: #a23232; \ }"; MidiControllerComboDelegate *comboDelegate = new MidiControllerComboDelegate(); ui->m_pTblMidiControllerFilter->setItemDelegateForColumn(0, comboDelegate); ui->m_pTblMidiControllerFilter->horizontalHeader()->setSectionResizeMode( QHeaderView::ResizeToContents); ui->m_pTblMidiControllerFilter->verticalHeader()->setSectionResizeMode( QHeaderView::ResizeToContents); ui->m_pTblMidiControllerFilter->setStyleSheet(style); ui->m_pTblMidiControllerFilter->setFocusPolicy(Qt::NoFocus); ui->m_pTblMidiChannelMessageFilter->horizontalHeader() ->setSectionResizeMode(QHeaderView::ResizeToContents); ui->m_pTblMidiChannelMessageFilter->verticalHeader()->setSectionResizeMode( QHeaderView::ResizeToContents); ui->m_pTblMidiChannelMessageFilter->setStyleSheet(style); ui->m_pTblMidiChannelMessageFilter->setFocusPolicy(Qt::NoFocus); createConnections(); } PortFilterSettingsWidget::~PortFilterSettingsWidget() { ui->m_pTblMidiChannelMessageFilter->model()->deleteLater(); delete ui; } void PortFilterSettingsWidget::setMIDISystemMessagesFilter( MIDISystemMessagesFilter *midiSystemMessagesFilter) { this->m_pMidiSystemMessagesFilter = midiSystemMessagesFilter; ui->m_pCbFilterMidiActiveSensingEvents->setChecked( midiSystemMessagesFilter->filterMidiActiveSensingEvents); ui->m_pCbFilterMidiRealtimeEvents->setChecked( midiSystemMessagesFilter->filterMidiRealtimeEvents); ui->m_pCbFilterMidiResetEvents->setChecked( midiSystemMessagesFilter->filterMidiResetEvents); ui->m_pCbFilterMidiSongPositionPointer->setChecked( midiSystemMessagesFilter->filterMidiSongPositionPointerEvents); ui->m_pCbFilterMidiSongSelectEvents->setChecked( midiSystemMessagesFilter->filterMidiSongSelectEvents); ui->m_pCbFilterMidiSysexEvents->setChecked( midiSystemMessagesFilter->filterMidiSysExEvents); ui->m_pCbFilterMidiTimeCodeEvents->setChecked( midiSystemMessagesFilter->filterMidiTimeCodeEvents); ui->m_pCbFilterMidiTuneRequestEvents->setChecked( midiSystemMessagesFilter->filterMidiTuneRequestEvents); } void PortFilterSettingsWidget::setMidiControllerFilter( MIDIControllerFilter **midiControllerFilter) { MidiControllerFilterTM *midiControllerFilterTM = new MidiControllerFilterTM(midiControllerFilter); ui->m_pTblMidiControllerFilter->setModel(midiControllerFilterTM); int numberOfMidiContollers = static_cast<int>(sizeof(*midiControllerFilter)); for (int i = 0; i < numberOfMidiContollers; i++) { QModelIndex modelIndex = ui->m_pTblMidiControllerFilter->model()->index(i, 0, QModelIndex()); ui->m_pTblMidiControllerFilter->openPersistentEditor(modelIndex); } connect(midiControllerFilterTM, &MidiControllerFilterTM::modelDataChanged, this, [=]() { emit filterDataChanged(portFilterDirection); }); } void PortFilterSettingsWidget::setMidiChannelMessagesFilter( MIDIChannelMessagesFilter **midiChannelMessagesFilter) { MidiChannelMessagesFilterTM *midiChannelMessagesFilterTM = new MidiChannelMessagesFilterTM(midiChannelMessagesFilter); ui->m_pTblMidiChannelMessageFilter->setModel(midiChannelMessagesFilterTM); connect(midiChannelMessagesFilterTM, &MidiChannelMessagesFilterTM::modelDataChanged, this, [=]() { emit filterDataChanged(portFilterDirection); }); } MIDISystemMessagesFilter * PortFilterSettingsWidget::getMIDISystemMessagesFilter() { MIDISystemMessagesFilter *midiSystemMessagesFilter = new MIDISystemMessagesFilter(); midiSystemMessagesFilter->filterMidiActiveSensingEvents = ui->m_pCbFilterMidiActiveSensingEvents->isChecked(); midiSystemMessagesFilter->filterMidiRealtimeEvents = ui->m_pCbFilterMidiRealtimeEvents->isChecked(); midiSystemMessagesFilter->filterMidiResetEvents = ui->m_pCbFilterMidiResetEvents->isChecked(); midiSystemMessagesFilter->filterMidiSongPositionPointerEvents = ui->m_pCbFilterMidiSongPositionPointer->isChecked(); midiSystemMessagesFilter->filterMidiSongSelectEvents = ui->m_pCbFilterMidiSongSelectEvents->isChecked(); midiSystemMessagesFilter->filterMidiSysExEvents = ui->m_pCbFilterMidiSysexEvents->isChecked(); midiSystemMessagesFilter->filterMidiTimeCodeEvents = ui->m_pCbFilterMidiTimeCodeEvents->isChecked(); midiSystemMessagesFilter->filterMidiTuneRequestEvents = ui->m_pCbFilterMidiTuneRequestEvents->isChecked(); return midiSystemMessagesFilter; } MIDIPortFilter *PortFilterSettingsWidget::getMidiPortFilter() { MIDIPortFilter *filter = new MIDIPortFilter(); return filter; } QTableWidgetItem *PortFilterSettingsWidget::getCheckStateItem(bool checked) { QTableWidgetItem *item = new QTableWidgetItem(); item->setCheckState(checked ? Qt::Checked : Qt::Unchecked); return item; } void PortFilterSettingsWidget::createConnections() { connect(ui->m_pCbFilterMidiResetEvents, &QCheckBox::stateChanged, this, [=](int state) { checkboxUpdated(state, ui->m_pCbFilterMidiResetEvents); }); connect(ui->m_pCbFilterMidiActiveSensingEvents, &QCheckBox::stateChanged, this, [=](int state) { checkboxUpdated(state, ui->m_pCbFilterMidiActiveSensingEvents); }); connect(ui->m_pCbFilterMidiRealtimeEvents, &QCheckBox::stateChanged, this, [=](int state) { checkboxUpdated(state, ui->m_pCbFilterMidiRealtimeEvents); }); connect(ui->m_pCbFilterMidiTuneRequestEvents, &QCheckBox::stateChanged, this, [=](int state) { checkboxUpdated(state, ui->m_pCbFilterMidiTuneRequestEvents); }); connect(ui->m_pCbFilterMidiSongSelectEvents, &QCheckBox::stateChanged, this, [=](int state) { checkboxUpdated(state, ui->m_pCbFilterMidiSongSelectEvents); }); connect(ui->m_pCbFilterMidiSongPositionPointer, &QCheckBox::stateChanged, this, [=](int state) { checkboxUpdated(state, ui->m_pCbFilterMidiSongPositionPointer); }); connect(ui->m_pCbFilterMidiTimeCodeEvents, &QCheckBox::stateChanged, this, [=](int state) { checkboxUpdated(state, ui->m_pCbFilterMidiTimeCodeEvents); }); connect(ui->m_pCbFilterMidiSysexEvents, &QCheckBox::stateChanged, this, [=](int state) { checkboxUpdated(state, ui->m_pCbFilterMidiSysexEvents); }); } void PortFilterSettingsWidget::checkboxUpdated(int state, QCheckBox *checkBox) { if (checkBox->objectName() == "m_pCbFilterMidiResetEvents") { this->m_pMidiSystemMessagesFilter->filterMidiResetEvents = state; } if (checkBox->objectName() == "m_pCbFilterMidiActiveSensingEvents") { this->m_pMidiSystemMessagesFilter->filterMidiActiveSensingEvents = state; } if (checkBox->objectName() == "m_pCbFilterMidiRealtimeEvents") { this->m_pMidiSystemMessagesFilter->filterMidiRealtimeEvents = state; } if (checkBox->objectName() == "m_pCbFilterMidiTuneRequestEvents") { this->m_pMidiSystemMessagesFilter->filterMidiTuneRequestEvents = state; } if (checkBox->objectName() == "m_pCbFilterMidiSongSelectEvents") { this->m_pMidiSystemMessagesFilter->filterMidiSongSelectEvents = state; } if (checkBox->objectName() == "m_pCbFilterMidiSongPositionPointer") { this->m_pMidiSystemMessagesFilter->filterMidiSongPositionPointerEvents = state; } if (checkBox->objectName() == "m_pCbFilterMidiTimeCodeEvents") { this->m_pMidiSystemMessagesFilter->filterMidiTimeCodeEvents = state; } if (checkBox->objectName() == "m_pCbFilterMidiSysexEvents") { this->m_pMidiSystemMessagesFilter->filterMidiSysExEvents = state; } emit filterDataChanged(this->portFilterDirection); } /* ************************ * MidiControllerFilterTM * **************************/ MidiControllerFilterTM::MidiControllerFilterTM( MIDIControllerFilter **midiControllerFilter) { this->m_ppMidiControllerFilter = midiControllerFilter; } MidiControllerFilterTM::~MidiControllerFilterTM() { delete[] m_ppMidiControllerFilter; } int MidiControllerFilterTM::rowCount(const QModelIndex &parent __attribute__((unused))) const { return sizeof(m_ppMidiControllerFilter); } int MidiControllerFilterTM::columnCount(const QModelIndex &) const { return MIDI_CHANNELS + 2; } QVariant MidiControllerFilterTM::data(const QModelIndex &index, int role) const { int row = index.row(); MIDIControllerFilter *midiControllerFilter = m_ppMidiControllerFilter[row]; switch (role) { case Qt::DisplayRole: if (index.column() == 0) { std::cout << "Model - controller number: " << midiControllerFilter->midiContollerNumber << std::endl; return midiControllerFilter->midiContollerNumber; } break; case Qt::CheckStateRole: if (index.column() == 1) { for (int channel = 0; channel < MIDI_CHANNELS; channel++) { if (!midiControllerFilter->channel[channel]) return Qt::Unchecked; } return Qt::Checked; } if (index.column() > 1) return midiControllerFilter->channel[index.column() - 2] ? Qt::Checked : Qt::Unchecked; break; case Qt::BackgroundRole: return QColor(220, 220, 220); } return QVariant(); } QVariant MidiControllerFilterTM::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { switch (section) { case 0: return QString(tr("MIDI-Controller")); case 1: return QString(tr("all")); default: return QString::number(section - 1); } } if (role == Qt::DisplayRole && orientation == Qt::Vertical) { return QString::number(section + 1); } return QVariant(); } bool MidiControllerFilterTM::setData(const QModelIndex &index, const QVariant &value, int role) { MIDIControllerFilter *midiControllerFilter = m_ppMidiControllerFilter[index.row()]; if (role == Qt::EditRole) { if (!hasIndex(index.row(), index.column())) return false; if (index.column() == 0) { midiControllerFilter->midiContollerNumber = value.toUInt(); emit modelDataChanged(); return true; } } if (role == Qt::CheckStateRole) { if (index.column() == 1) { for (int column = 0; column < MIDI_CHANNELS; column++) { midiControllerFilter->channel[column] = value.toBool(); } emit dataChanged(createIndex(index.row(), 2), createIndex(index.row(), MIDI_CHANNELS + 1)); emit modelDataChanged(); } else if (index.column() > 1) { midiControllerFilter->channel[index.column() - 2] = value.toBool(); emit dataChanged(createIndex(index.row(), 1), createIndex(index.row(), 1)); emit modelDataChanged(); } return true; } return false; } Qt::ItemFlags MidiControllerFilterTM::flags(const QModelIndex &index) const { if (index.column() > 0) return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled; return Qt::ItemIsEditable | QAbstractTableModel::flags(index); } /* ***************************** * MidiChannelMessagesFilterTM * *******************************/ MidiChannelMessagesFilterTM::MidiChannelMessagesFilterTM( MIDIChannelMessagesFilter **midiChannelMessagesFilter) { this->m_ppMidiChannelMessagesFilter = midiChannelMessagesFilter; } MidiChannelMessagesFilterTM::~MidiChannelMessagesFilterTM() { deleteLater(); } int MidiChannelMessagesFilterTM::rowCount(const QModelIndex &) const { return 6; } int MidiChannelMessagesFilterTM::columnCount(const QModelIndex &) const { return MIDI_CHANNELS; } QVariant MidiChannelMessagesFilterTM::data(const QModelIndex &index, int role) const { MIDIChannelMessagesFilter *midiChannelMessagesFilter = this->m_ppMidiChannelMessagesFilter[index.column()]; switch (role) { case Qt::CheckStateRole: switch (index.row()) { case 0: return boolToCheckState( midiChannelMessagesFilter->filterMidiPitchBendEvents); case 1: return boolToCheckState( midiChannelMessagesFilter->filterMidiChannelPressureEvents); case 2: return boolToCheckState( midiChannelMessagesFilter->filterMidiProgrammChangeEvents); case 3: return boolToCheckState( midiChannelMessagesFilter->filterMidiControlChangeEvents); case 4: return boolToCheckState( midiChannelMessagesFilter->filterMidiPolyKeyPressureEvents); case 5: return boolToCheckState( midiChannelMessagesFilter->filterMidiNoteOnOffEvents); } case Qt::BackgroundRole: return QColor(220, 220, 220); } return QVariant(); } QVariant MidiChannelMessagesFilterTM::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::DisplayRole && orientation == Qt::Vertical) { switch (section) { case 0: return QString(tr("Pitch Bend")); case 1: return QString(tr("Mono Key Pressure")); case 2: return QString(tr("Program Change")); case 3: return QString(tr("Control Change")); case 4: return QString(tr("Poly Key Pressure")); case 5: return QString(tr("Note On / Note Off")); default: return QVariant(); } } if (role == Qt::DisplayRole && orientation == Qt::Horizontal) { return QString::number(section + 1); } return QVariant(); } bool MidiChannelMessagesFilterTM::setData(const QModelIndex &index, const QVariant &value, int role) { MIDIChannelMessagesFilter *midiChannelMessagesFilter = this->m_ppMidiChannelMessagesFilter[index.column()]; if (role == Qt::CheckStateRole) { switch (index.row()) { case 0: midiChannelMessagesFilter->filterMidiPitchBendEvents = value.toBool(); break; case 1: midiChannelMessagesFilter->filterMidiChannelPressureEvents = value.toBool(); break; case 2: midiChannelMessagesFilter->filterMidiProgrammChangeEvents = value.toBool(); break; case 3: midiChannelMessagesFilter->filterMidiControlChangeEvents = value.toBool(); break; case 4: midiChannelMessagesFilter->filterMidiPolyKeyPressureEvents = value.toBool(); break; case 5: midiChannelMessagesFilter->filterMidiNoteOnOffEvents = value.toBool(); break; } emit modelDataChanged(); return true; } return false; } Qt::ItemFlags MidiChannelMessagesFilterTM::flags(const QModelIndex __attribute__((unused)) & index) const { return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled; } Qt::CheckState MidiChannelMessagesFilterTM::boolToCheckState(bool value) const { if (value) return Qt::Checked; else return Qt::Unchecked; }
33.753425
80
0.753314
dehnhardt
98330e664b439905402cc0bc827383cf5479bfad
186
cpp
C++
examples/infinite_loop.cpp
stateos/IntrOS
76ee5025442cefe37bc1434cdb95ea1b335ca667
[ "MIT" ]
36
2016-11-08T16:01:58.000Z
2022-02-24T05:26:32.000Z
examples/infinite_loop.cpp
stateos/IntrOS
76ee5025442cefe37bc1434cdb95ea1b335ca667
[ "MIT" ]
null
null
null
examples/infinite_loop.cpp
stateos/IntrOS
76ee5025442cefe37bc1434cdb95ea1b335ca667
[ "MIT" ]
9
2018-05-22T16:02:01.000Z
2022-02-24T05:26:37.000Z
#include <stm32f4_discovery.h> #include <os.h> using namespace device; using namespace intros; int main() { auto led = Led(); for (;;) { thisTask::delay(SEC); led.tick(); } }
10.941176
30
0.634409
stateos
98342bc3b11cdbf40f251abab736b2083858853c
2,723
cpp
C++
Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/10.cpp
jesushilarioh/DelMarCSi.cpp
6dd7905daea510452691fd25b0e3b0d2da0b06aa
[ "MIT" ]
3
2019-02-02T16:59:48.000Z
2019-02-28T14:50:08.000Z
Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/10.cpp
jesushilariohernandez/DelMarCSi.cpp
6dd7905daea510452691fd25b0e3b0d2da0b06aa
[ "MIT" ]
null
null
null
Chapter-4-Making-Decisions/Review Questions and Exercises/Programming Challenges/10.cpp
jesushilariohernandez/DelMarCSi.cpp
6dd7905daea510452691fd25b0e3b0d2da0b06aa
[ "MIT" ]
1
2021-07-25T09:50:07.000Z
2021-07-25T09:50:07.000Z
/******************************************************************** * * 10. Days in a Month * * Write a program that asks the user to enter the month * (letting the user enter an integer in the range of 1 * through 12) and the year. The program should then display * the number of days in that month. Use the following criteria to * identify leap years: * * 1. Determine whether the year is divisible by 100. * If it is, then it is a leap year if and only * if it is divisible by 400. For example, 2000 is a * leap year but 2100 is not. * * 2. If the year is not divisible by 100, then it is a * leap year if and if only it is divisible by 4. For * example, 2008 is a leap year but 2009 is not. * * Here is a sample run of the program: * Enter a month (1-12): 2 [Enter] * Enter a year: 2008 [Enter] * 29 days * * Jesus Hilario Hernandez * February 17, 2018 * ********************************************************************/ #include <iostream> using namespace std; int main() { // Variables int year, month; // Ask user to enter month cout << endl; cout << "Enter the month (1 - 12): "; cin >> month; cout << "Enter the year (up to 9000): "; cin >> year; cout << endl; // Error check for valid year if (year >= 0 && year <= 9000) { // Decision statement for month switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: cout << "31 days"; break; case 4: case 6: case 9: case 11: cout << "30 days"; break; case 2: // Decision statement for leap year if (year % 100 == 0) { if (year % 400 == 0) cout << "29 days" << endl; else cout << "28 days" << endl; } else if (year % 100 != 0) { if (year % 4 == 0) cout << "29 days" << endl; else cout << "28 days" << endl; } break; default: cout << "Invalid month. Rerun program. Try again." << endl; } } else cout << "Invalid year. Rerun program. Try again." << endl; // Format line break cout << endl; // Terminate program return 0; }
27.23
75
0.423797
jesushilarioh
98345aa435f375b031b936b25836e00ec0bfbf8a
10,792
cpp
C++
Source/Gui/TranslatorPanel.cpp
alvinahmadov/Dixter
6f98f1e84192e1e43eee409bdee6b3dac75d6443
[ "MIT" ]
4
2018-12-06T01:20:50.000Z
2019-08-04T10:19:23.000Z
Source/Gui/TranslatorPanel.cpp
alvinahmadov/Dixter
6f98f1e84192e1e43eee409bdee6b3dac75d6443
[ "MIT" ]
null
null
null
Source/Gui/TranslatorPanel.cpp
alvinahmadov/Dixter
6f98f1e84192e1e43eee409bdee6b3dac75d6443
[ "MIT" ]
null
null
null
/** * Copyright (C) 2015-2019 * Author Alvin Ahmadov <alvin.dev.ahmadov@gmail.com> * * This file is part of Dixter Project * License-Identifier: MIT License * See README.md for more information. */ #include <QBoxLayout> #include <QButtonGroup> #include <QGroupBox> #include "Configuration.hpp" #include "Constants.hpp" #include "Group.hpp" #include "Utilities.hpp" #include "Gui/TranslatorPanel.hpp" #include "Gui/TextEdit.hpp" #include "Gui/Label.hpp" #include "Gui/Button.hpp" #include "Gui/OptionBox.hpp" namespace Dixter { namespace NAlgoUtils = Utilities::Algorithms; namespace Gui { TTranslatorPanel::TTranslatorPanel(QWidget* parent, int width, int height, const QString& name) : APanel(parent, QSize(width, height)), m_grids(new GridGroup), m_widgets(new WidgetGroup) #ifdef USE_SPEECHD ,m_narrator(new VSynth::SpeechDispatcher("dix", "Dixter_conn", "Dixter_user", SPDConnectionMode::SPD_MODE_SINGLE)) #endif { init(); connectEvents(); name.isEmpty() ? setObjectName(g_translatorName) : setObjectName(name); } TTranslatorPanel::~TTranslatorPanel() { #ifdef USE_SPEECHD delete m_narrator; #endif delete m_grids; delete m_widgets; } void TTranslatorPanel::show(bool show) { m_widgets->forEach(&QWidget::setVisible, show); } APanel::TOptionBoxPtr TTranslatorPanel::getOptionBox(EWidgetID id) { return dxMAKE_SHARED(TOptionBox, m_widgets->get<TOptionBox>(g_controlGroup, id)); } void TTranslatorPanel::setValues() { auto __languageNames = std::vector<TUString>(); auto __languageDisplayNames = std::vector<TUString>(); auto __languageIds = std::vector<TUString>(); auto __voiceNames = std::vector<TUString>(); try { TConfigurationManager::getManager(EConfiguration::XML) ->accessor() ->getValues(NodeKey::kLangNameNode, __languageNames, NodeKey::kLangRoot) ->getValues(NodeKey::kLangNameDisplayNode, __languageDisplayNames, NodeKey::kLangRoot) ->getValues(NodeKey::kLangIdNode, __languageIds, NodeKey::kLangRoot) ->getValues(NodeKey::kVoiceNameNode, __voiceNames, NodeKey::kVoiceRoot); } catch (std::exception& e) { printerr(e.what()); } NAlgoUtils::foreachCompound(__languageNames, __languageDisplayNames, [](TUString& languageName, const TUString& languageDisplayName) { languageName.append(u" / ").append(languageDisplayName); }); m_widgets->get<TOptionBox>(g_widgetGroup, EWidgetID::LangboxWest)->setValues(__languageNames); m_widgets->get<TOptionBox>(g_widgetGroup, EWidgetID::LangboxEast)->setValues(__languageNames); m_widgets->get<TOptionBox>(g_widgetGroup, EWidgetID::VoiceBoxT)->setValues(__voiceNames); } void TTranslatorPanel::init() { // init widgets const QSize __buttonSize = QSize(150, 50); auto __voiceBox = m_widgets ->add<TOptionBox>(g_widgetGroup, new TOptionBox(nullptr, tr("Select voice...")), EWidgetID::VoiceBoxT); auto __texteditWest = m_widgets ->add<TTextEdit>(g_widgetGroup, new TTextEdit(this, tr("Translation")), EWidgetID::TranslatorAreaWest); auto __texteditEast = m_widgets ->add<TTextEdit>(g_widgetGroup, new TTextEdit(this, tr("Translation"), true), EWidgetID::TranslatorAreaEast); auto __languageBoxWest = m_widgets ->add<TOptionBox>(g_widgetGroup, new TOptionBox(tr("Select language...")), EWidgetID::LangboxWest); auto __languageBoxEast = m_widgets ->add<TOptionBox>(g_widgetGroup, new TOptionBox(tr("Select language...")), EWidgetID::LangboxEast); auto __widgetLayoutWest = new QVBoxLayout(); auto __widgetLayoutEast = new QVBoxLayout(); auto __widgetGroupWest = new QGroupBox(); auto __widgetGroupEast = new QGroupBox(); auto __buttonLayoutWest = new QHBoxLayout(); auto __buttonLayoutEast = new QHBoxLayout(); //Buttons auto __speakButtonWest = m_widgets ->add<TButton>(g_controlGroup, new TButton(QIcon(":Resources/icons/speak.png")), EWidgetID::ButtonSpeakWest); auto __translateButtonWest = m_widgets ->add<TButton>(g_controlGroup, new TButton(QIcon(":Resources/icons/translate.png")), EWidgetID::ButtonTranslateWest); auto __speakButtonEast = m_widgets ->add<TButton>(g_controlGroup, new TButton(QIcon(":Resources/icons/speak.png")), EWidgetID::ButtonSpeakEast); auto __translateButtonEast = m_widgets ->add<TButton>(g_controlGroup, new TButton(QIcon(":Resources/icons/translate.png")), EWidgetID::ButtonTranslateEast); __speakButtonWest->setFixedSize(__buttonSize); __speakButtonEast->setFixedSize(__buttonSize); __translateButtonWest->setFixedSize(__buttonSize); __translateButtonEast->setFixedSize(__buttonSize); // auto btnGroup = new QButtonGroup() __buttonLayoutWest->addWidget(__speakButtonWest); __buttonLayoutWest->addWidget(__translateButtonWest); __buttonLayoutEast->addWidget(__speakButtonEast); __buttonLayoutEast->addWidget(__translateButtonEast); // Set left box auto __optionBoxWest = new QHBoxLayout(); __optionBoxWest->addWidget(new TLabel(tr("From"), __languageBoxWest)); __optionBoxWest->addWidget(__languageBoxWest); __widgetLayoutWest->addLayout(__optionBoxWest); __widgetLayoutWest->addWidget(__texteditWest); __widgetLayoutWest->addLayout(__buttonLayoutWest); __widgetGroupWest->setLayout(__widgetLayoutWest); // Set central box auto __widgetLayoutCenter = new QVBoxLayout; auto __flipButton = m_widgets ->add<TButton>(g_controlGroup, new TButton(QIcon(":Resources/icons/flip.png")), EWidgetID::ButtonFlip); __flipButton->setFixedSize(__buttonSize); __widgetLayoutCenter->addSpacing(44); __widgetLayoutCenter->addWidget(__voiceBox, 0, Qt::AlignmentFlag::AlignTop); __widgetLayoutCenter->addWidget(__flipButton, 0, Qt::AlignmentFlag::AlignBottom); __widgetLayoutCenter->addSpacing(15); // Set right box auto __optionBoxEast = new QHBoxLayout(); __optionBoxEast->addWidget(new TLabel(tr("To"), __languageBoxEast)); __optionBoxEast->addWidget(__languageBoxEast); __widgetLayoutEast->addLayout(__optionBoxEast); __widgetLayoutEast->addWidget(__texteditEast); __widgetLayoutEast->addLayout(__buttonLayoutEast); __widgetGroupEast->setLayout(__widgetLayoutEast); // Main grid auto __mainGrid = m_grids->add<QHBoxLayout>(g_layoutGroup, new QHBoxLayout(this), EWidgetID::Grid); __mainGrid->addWidget(__widgetGroupWest); __mainGrid->addLayout(__widgetLayoutCenter); __mainGrid->addWidget(__widgetGroupEast); setValues(); setLayout(__mainGrid); } TStringPair TTranslatorPanel::getCurrentLanguage() { TString __languageId, __languageName; try { auto __languageBoxWest = m_widgets->get<TOptionBox>(g_widgetGroup, EWidgetID::LangboxWest); if (__languageBoxWest->isPlaceholderSet()) return {}; __languageName = __languageBoxWest->currentText().toStdString(); __languageId = getXmlManager({ g_langConfigPath }) ->accessor() ->getValue(NodeKey::kLangNameNode, __languageName, NodeKey::kLangRoot).asUTF8(); } catch (TException& e) { printerr(e.what()) } return std::make_pair(__languageId, __languageName); } void TTranslatorPanel::onBufferChange() { } void TTranslatorPanel::onFlip() { auto __texteditWest = m_widgets->get<TTextEdit>(g_widgetGroup, EWidgetID::TranslatorAreaWest); auto __languageBoxWest = m_widgets->get<TOptionBox>(g_widgetGroup, EWidgetID::LangboxWest); auto __texteditEast = m_widgets->get<TTextEdit>(g_widgetGroup, EWidgetID::TranslatorAreaEast); auto __languageBoxEast = m_widgets->get<TOptionBox>(g_widgetGroup, EWidgetID::LangboxEast); __languageBoxWest->swapCurrent(__languageBoxEast); __texteditWest->swapContent(__texteditEast); } void TTranslatorPanel::onSpeakWest() { auto __content = m_widgets->get<TTextEdit>(g_widgetGroup, EWidgetID::TranslatorAreaWest) ->getContent(); if (not __content.isEmpty()) { #ifdef USE_SPEECHD if (not __langId.empty()) m_narrator->setLanguage(TargetMode::DirAll, lang.first.c_str()); m_narrator->say(SPD_TEXT, __content); #endif } } void TTranslatorPanel::onTranslateWest() { } void TTranslatorPanel::onSpeakEast() { printl_log(__FUNCTION__) } void TTranslatorPanel::onTranslateEast() { printl_log(__FUNCTION__) } void TTranslatorPanel::onLanguageChangeFrom() { #ifdef USE_SPEECHD m_widgets->get<OptionBox>(g_widgetGroup, EWidgetID::LangboxWest)->onChanged(choiceEvent); TUString __langId {}; auto __pLangBox = m_widgets->get<OptionBox>(g_widgetGroup, EWidgetID::LangboxWest); auto __langName = __pLangBox->GetStringSelection(); try { auto confMgr = ConfigurationManager::getManager(); __langId = confMgr->xmlManager()->getValue(NodeKey::kLangRoot, NodeKey::kLangNameNode, __langName); } catch (...) {} m_narrator->setLanguage(TargetMode::DirAll, __langId); #endif } void TTranslatorPanel::onLanguageChangeTo() { } void TTranslatorPanel::onTextAreaEdit() { } void TTranslatorPanel::onVoiceChange() { #ifdef USE_SPEECHD QString __voiceId {}; auto __voiceName = m_widgets->get<OptionBox>(g_widgetGroup, EWidgetID::VoiceBoxT)->GetStringSelection(); try { auto confMgr = ConfigurationManager::getManager(); __voiceId = confMgr->xmlManager()->getValue(NodeKey::kVoiceRoot, NodeKey::kVoiceNameNode, __voiceName); #ifdef DIXTER_DEBUG delete confMgr; #endif } catch (...) {} if (not __voiceId.empty()) m_narrator->setSynthesisVoice(TargetMode::Single, __voiceId); printl_log(__voiceName) #endif } void TTranslatorPanel::connectEvents() { connect(m_widgets->get<TButton>(g_controlGroup, EWidgetID::ButtonFlip), SIGNAL(clicked()), SLOT(onFlip())); connect(m_widgets->get<TButton>(g_controlGroup, EWidgetID::ButtonSpeakWest), SIGNAL(clicked()), SLOT(onSpeakWest())); connect(m_widgets->get<TButton>(g_controlGroup, EWidgetID::ButtonTranslateWest), SIGNAL(clicked()), SLOT(onTranslateWest())); connect(m_widgets->get<TButton>(g_controlGroup, EWidgetID::ButtonSpeakEast), SIGNAL(clicked()), SLOT(onSpeakEast())); connect(m_widgets->get<TButton>(g_controlGroup, EWidgetID::ButtonTranslateEast), SIGNAL(clicked()), SLOT(onTranslateEast())); } QWidget* TTranslatorPanel::getWidget(EWidgetID id) { return m_widgets->get(id); } } // namespace Gui } //namespace Dixter
33.411765
119
0.71275
alvinahmadov
9838df6041c667e838fda18969face5723dd9981
532
cpp
C++
cpp source/gtavchacks/readprocess/main2.cpp
MEGAMINDMK/search-engine
0e2748a4a3169e7290d8712f3c7bcefc8aec2bc3
[ "Unlicense" ]
1
2017-12-13T07:30:08.000Z
2017-12-13T07:30:08.000Z
cpp source/gtavchacks/readprocess/main2.cpp
MEGAMINDMK/Softwares
0e2748a4a3169e7290d8712f3c7bcefc8aec2bc3
[ "Unlicense" ]
null
null
null
cpp source/gtavchacks/readprocess/main2.cpp
MEGAMINDMK/Softwares
0e2748a4a3169e7290d8712f3c7bcefc8aec2bc3
[ "Unlicense" ]
null
null
null
#include <iostream> #include <windows.h> #include <string> using namespace std; DWORD pid; DWORD Health = 0x99A0508; int MyHealth; int main() { HWND hWnd = FindWindow(0, "GTA: Vice City"); GetWindowThreadProcessId(hWnd, &pid); HANDLE pHandle = OpenProcess(PROCESS_VM_READ, FALSE, pid); while (true) { ReadProcessMemory(pHandle, (LPVOID)Health, &MyHealth, sizeof(MyHealth), 0); cout << MyHealth << endl; Sleep(100); system("CLS"); } system("Pause"); }
21.28
84
0.612782
MEGAMINDMK
983b36dc11c39bd91ad89176317bdc53f1ec9377
780
cpp
C++
src/plugins/robots/attabot/real_robot/real_kheperaiv_differential_steering_device.cpp
DiegoD616/argos3-ATTABOT
e909bf1432dbd6649450dbb95e4e9f68f375eefa
[ "MIT" ]
null
null
null
src/plugins/robots/attabot/real_robot/real_kheperaiv_differential_steering_device.cpp
DiegoD616/argos3-ATTABOT
e909bf1432dbd6649450dbb95e4e9f68f375eefa
[ "MIT" ]
null
null
null
src/plugins/robots/attabot/real_robot/real_kheperaiv_differential_steering_device.cpp
DiegoD616/argos3-ATTABOT
e909bf1432dbd6649450dbb95e4e9f68f375eefa
[ "MIT" ]
null
null
null
#include "real_attabot_differential_steering_device.h" #include <argos3/core/utility/logging/argos_log.h> #include <memory> /****************************************/ /****************************************/ CRealAttabotDifferentialSteeringDevice* CRealAttabotDifferentialSteeringDevice::GetInstance() { static std::unique_ptr<CRealAttabotDifferentialSteeringDevice> pcInstance( new CRealAttabotDifferentialSteeringDevice()); return pcInstance.get(); } /****************************************/ /****************************************/ CRealAttabotDifferentialSteeringDevice::CRealAttabotDifferentialSteeringDevice() : m_fVelocityLeft(0.0), m_fVelocityRight(0.0) {} /****************************************/ /****************************************/
33.913043
95
0.548718
DiegoD616
983c75c43839bcd1025b9d261a0e03d29dbb6898
2,097
hpp
C++
Nacro/SDK/FN_QuestTrackerSubEntry_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_QuestTrackerSubEntry_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_QuestTrackerSubEntry_parameters.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function QuestTrackerSubEntry.QuestTrackerSubEntry_C.GetHeightEstimate struct UQuestTrackerSubEntry_C_GetHeightEstimate_Params { float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function QuestTrackerSubEntry.QuestTrackerSubEntry_C.HandleRemoveFinished struct UQuestTrackerSubEntry_C_HandleRemoveFinished_Params { }; // Function QuestTrackerSubEntry.QuestTrackerSubEntry_C.HideIfEmpty struct UQuestTrackerSubEntry_C_HideIfEmpty_Params { }; // Function QuestTrackerSubEntry.QuestTrackerSubEntry_C.UpdateObjectiveText struct UQuestTrackerSubEntry_C_UpdateObjectiveText_Params { }; // Function QuestTrackerSubEntry.QuestTrackerSubEntry_C.Construct struct UQuestTrackerSubEntry_C_Construct_Params { }; // Function QuestTrackerSubEntry.QuestTrackerSubEntry_C.OnQuestsUpdated struct UQuestTrackerSubEntry_C_OnQuestsUpdated_Params { }; // Function QuestTrackerSubEntry.QuestTrackerSubEntry_C.OnPlayObjectiveCompletedAnimation struct UQuestTrackerSubEntry_C_OnPlayObjectiveCompletedAnimation_Params { }; // Function QuestTrackerSubEntry.QuestTrackerSubEntry_C.OnCompletionFlashFInished struct UQuestTrackerSubEntry_C_OnCompletionFlashFInished_Params { }; // Function QuestTrackerSubEntry.QuestTrackerSubEntry_C.PostCompletionDelay struct UQuestTrackerSubEntry_C_PostCompletionDelay_Params { }; // Function QuestTrackerSubEntry.QuestTrackerSubEntry_C.ExecuteUbergraph_QuestTrackerSubEntry struct UQuestTrackerSubEntry_C_ExecuteUbergraph_QuestTrackerSubEntry_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
28.337838
173
0.722938
Milxnor
983ce42da7277e132c994239f8fe6ea3e1a15e34
2,347
hpp
C++
include/socket/base/ev_timer.hpp
chensoft/libxio
17345e500cca5085641b5392ce8ef7dc65369d69
[ "MIT" ]
6
2018-07-28T08:03:24.000Z
2022-03-31T08:56:57.000Z
include/socket/base/ev_timer.hpp
chensoft/libxio
17345e500cca5085641b5392ce8ef7dc65369d69
[ "MIT" ]
null
null
null
include/socket/base/ev_timer.hpp
chensoft/libxio
17345e500cca5085641b5392ce8ef7dc65369d69
[ "MIT" ]
2
2019-05-21T02:26:36.000Z
2020-04-13T16:46:20.000Z
/** * Created by Jian Chen * @since 2017.02.03 * @author Jian Chen <admin@chensoft.com> * @link http://chensoft.com */ #pragma once #include "socket/base/ev_base.hpp" #include <functional> #include <chrono> namespace chen { class ev_timer: public ev_base { public: enum class Flag {Normal, Future, Repeat}; public: ev_timer(std::function<void ()> cb = nullptr); public: /** * Invoke callback only once after a period of time */ void timeout(const std::chrono::nanoseconds &value); /** * Invoke callback only once in a future calendar date */ void future(const std::chrono::nanoseconds &value); void future(const std::chrono::steady_clock::time_point &value); /** * Invoke callback repeatedly after a period of time */ void interval(const std::chrono::nanoseconds &value); public: /** * Attach callback */ void attach(std::function<void ()> cb); public: /** * Timer properties */ Flag flag() const { return this->_flag; } std::chrono::nanoseconds time() const { return this->_time; } std::chrono::steady_clock::time_point when() const { return this->_when; } /** * Calculate init value */ void setup(const std::chrono::steady_clock::time_point &now); /** * Check if timer expire */ bool expire(const std::chrono::steady_clock::time_point &now) const { return now >= this->_when; } /** * Update timer value */ void update(const std::chrono::steady_clock::time_point &now) { if (this->_flag == Flag::Repeat) this->_when += this->_time; } protected: /** * At least one event has occurred */ virtual void onEvent(int type) override; private: Flag _flag = Flag::Normal; std::chrono::nanoseconds _time; // the interval between two trigger points std::chrono::steady_clock::time_point _when; // the next trigger point std::function<void ()> _notify; }; }
23.237624
83
0.532595
chensoft
984208815cc54cf2cdf49e6c24a78550ecf64ccc
10,091
cpp
C++
Game15Puzzle.cpp
loiola0/artificial-intelligence-ufc
f356a6a572bdd0b3419b89c93a9c0bd45a669312
[ "MIT" ]
2
2021-11-08T22:06:06.000Z
2021-12-17T19:40:01.000Z
Game15Puzzle.cpp
loiola0/artificial-intelligence-ufc
f356a6a572bdd0b3419b89c93a9c0bd45a669312
[ "MIT" ]
null
null
null
Game15Puzzle.cpp
loiola0/artificial-intelligence-ufc
f356a6a572bdd0b3419b89c93a9c0bd45a669312
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <cstring> #include <stdlib.h> #include <set> #include <map> #include <ctime> #include <vector> #include <queue> #include <functional> #include <locale.h> #include <unistd.h> using namespace std; class Node; bool idfs(); bool A_estrela(); bool dfs(int k); bool gulosa(); bool bfs(); void read(); string print(Node *a); bool temSolucao(); int contaInversoes(int v[]); int meuSwap(int x); int Manhattan (Node *x); // para melhor desempenho em heurísticas void criaDic(); string meuHash(int v[]); bool igual(int a[],int b[]); bool nosIguais(Node *a, Node *b); void copiar(int a[],int b[]); int analisaLinha (char* linha); int obterValor(); //Movimentação necessária pair<int,int> tr[] = {make_pair(-1, 0), make_pair( 1, 0), make_pair( 0, 1), make_pair( 0,-1)}; int ar_i[16],z_i[2],ar_f[16],z_f[2]; vector<int> posFinal(16); map<string,int> setx; int main(){ setlocale(LC_ALL, "Portuguese"); read(); criaDic(); if(!temSolucao()){ printf("Sem solução!\n"); return 0; } //Procurando a solução para o puzzle int start_s=clock(); printf("Procurando solução..\n"); //Escolha qual algoritmo quer rodar e fazer o teste, basta descomentar para executa-lo bool ok = dfs(15); // bool ok = bfs(); // bool ok = idfs(); // bool ok = gulosa(); // bool ok = A_estrela(); if(!ok){ //No caso de não possui solução printf("Sem solução\n"); } else{ // Fornece informações de tempo e memória gastos para encontrar a solução int stop_s=clock(); cout << "Tempo: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000 << endl; printf("Memoria gasta: %dKB\n",obterValor()); } return 0; } /****Classe****/ class Node{ public: int array[16]; //tamango do puzzle 4x4 int zero[2]; //posicao do zero {i, j} int profundidade; //profundidade string caminho; //caminho percorrido após uma movimentação //descontructor ~Node(){ } //construtor Node(int array[],int zero[], int profundidade, string caminho){ copiar(array, this->array); this->zero[0]=zero[0]; this->zero[1]=zero[1]; this->profundidade = profundidade; if(profundidade == 0){ this->caminho = print(this); } else{ this->caminho = caminho + print(this); } } vector<Node*> make_desc(){ int i,j; vector<Node*> l; for(int k=0;k<4;k++){ int c[16],t[2]; //caminho de nós i=this->zero[0]+tr[k].first; j=this->zero[1]+tr[k].second; if(i>=0 && i<4 && j>=0 && j<4){ copiar(this->array,c); c[this->zero[0]*4+this->zero[1]]=c[i*4+j]; c[i*4+j]=0; t[0]=i; t[1]=j; //verifique se o nó já foi visto, se não foi visto, adicione //se for visto, mas a profundidade for menor do que a anterior, adicione também if(setx.find(meuHash(c))==setx.end()){ Node *tt = new Node(c,t,this->profundidade+1,this->caminho); l.push_back(tt); } else if(setx[meuHash(c)]>this->profundidade+1){ setx[meuHash(c)]=this->profundidade+1; Node *tt = new Node(c,t,this->profundidade+1,this->caminho); l.push_back(tt); } } } return l; } }; //Algoritmos //Depth first search(DFS) limited by k (Busca em profunidade com limitação) bool dfs(int k){ Node *end = new Node(ar_f,z_f,0,""); Node *start = new Node(ar_i,z_i,0,""); vector<Node*> l; vector<Node*> tt; l.push_back(start); Node *t; int flag; while(l.size()>0){ flag=0; t = l.back(); l.pop_back(); if(setx.find(meuHash(t->array))==setx.end()) setx.insert(make_pair(meuHash(t->array),t->profundidade)); else if(setx[meuHash(t->array)]>=t->profundidade){ setx[meuHash(t->array)]=t->profundidade; } else{ flag=1; } if(nosIguais(t,end)){ cout << t->caminho; printf("Profundidade: %d\n",t->profundidade); return true; } if(t->profundidade<k && !flag){ tt = t->make_desc(); for(int i=0;i<(int)tt.size();i++){ l.push_back(tt[i]); } } delete t; } return false; } //Breath first search(Busca por largura) bool bfs(){ Node *end = new Node(ar_f,z_f,0,""); Node *start = new Node(ar_i,z_i,0,""); queue<Node*> l; vector<Node*> tt; l.push(start); Node *t; int flag; while(l.size()>0){ flag = 0; t = l.front(); l.pop(); if(setx.find(meuHash(t->array))==setx.end()) setx.insert(make_pair(meuHash(t->array),t->profundidade)); else if(setx[meuHash(t->array)]>=t->profundidade){ setx[meuHash(t->array)]=t->profundidade; } else{ flag=1; } if(nosIguais(t,end)){ cout << t->caminho; printf("Profundidade: %d\n",t->profundidade); return true; } if(t->profundidade<80 && !flag){ tt = t->make_desc(); for(int i=0;i<(int)tt.size();i++){ l.push(tt[i]); } } delete t; } return false; } //Iterative Depth first search(Busca iterativa por profunidade) bool idfs(){ for(int i=0;i<80;i++){ if(dfs(i)){ return true; } setx.clear(); } return false; } struct f{ bool operator()(const pair<int,Node*>& a, pair<int,Node*>& b){ return a.first>b.first; } }; //Busca Gulosa Heurística Manhattan bool gulosa(){ Node *end = new Node(ar_f,z_f,0,""); Node *start = new Node(ar_i,z_i,0,""); priority_queue< pair<int,Node*>, vector <pair<int,Node*> > , f > pq; pq.push (make_pair(0, start)); Node *noAtual; int flag; while (!pq.empty()) { flag = 0; noAtual = pq.top().second; pq.pop(); if(setx.find(meuHash(noAtual->array))==setx.end()) setx.insert(make_pair(meuHash(noAtual->array),noAtual->profundidade)); if(setx[meuHash(noAtual->array)]>=noAtual->profundidade){ setx[meuHash(noAtual->array)]=noAtual->profundidade; } else{ flag=1; } if(nosIguais(noAtual,end)){ cout << noAtual->caminho; printf("Profundidade: %d\n",noAtual->profundidade); return true; } if(!flag){ vector<Node*> dsc = noAtual->make_desc(); for (int i=0; i<(int)dsc.size();i++) { pq.push(make_pair(Manhattan(dsc[i]),dsc[i])); } } delete noAtual; } return false; } //Busca A* com heurística Manhattan bool A_estrela () { //inicializa os nós do início e do fim Node *end = new Node(ar_f,z_f,0,""); Node *start = new Node(ar_i,z_i,0,""); //start->cost = 0; priority_queue< pair<int,Node*>, vector <pair<int,Node*> > , f > pq; pq.push (make_pair(0, start)); Node *noAtual; int flag; while (!pq.empty()) { flag = 0; noAtual = pq.top().second; pq.pop(); if(setx.find(meuHash(noAtual->array))==setx.end()) setx.insert(make_pair(meuHash(noAtual->array),noAtual->profundidade)); if(setx[meuHash(noAtual->array)]>=noAtual->profundidade){ setx[meuHash(noAtual->array)]=noAtual->profundidade; } else{ flag=1; } if(nosIguais(noAtual,end)){ cout << noAtual->caminho; printf("Profundidade: %d\n", noAtual->profundidade); return true; } if(!flag){ vector<Node*> dsc = noAtual->make_desc(); for (int i=0; i<(int)dsc.size();i++) { pq.push(make_pair(Manhattan(dsc[i])*1.1+dsc[i]->profundidade,dsc[i])); } } delete noAtual; } return false; } //Entrada dos dados void read(){ int x; printf("Por favor, digite a configuracao inicial 4x4:\n"); for(int i=0;i<16;i++){ scanf("%d",&x); if(!x){ z_i[0]=i/4; z_i[1]=i%4; } ar_i[i]=x; } printf("Por favor, digite a configuracao final 4x4:\n"); for(int i=0;i<16;i++){ scanf("%d",&x); if(!x){ z_f[0]=i/4; z_f[1]=i%4; } ar_f[i]=x; } } //Saída dos dados string print(Node *a){ if(a==NULL){ printf("Sem no\n"); return ""; } char s[1000];s[0]='\0'; for(int i=0;i<16;i++){ sprintf(s,"%s %2d ",s,a->array[i]); if(((i+1)%4)==0) sprintf(s,"%s\n",s); } sprintf(s,"%s\n",s); return string(s); } //Funções auxiliares //verifique se a configuração pode ser resolvida bool temSolucao(){ Node *end = new Node(ar_f,z_f,0,""); Node *start = new Node(ar_i,z_i,0,""); int inv_i,inv_f,br_i,br_f; inv_i = contaInversoes(start->array); inv_f = contaInversoes(end->array); br_i = meuSwap(start->zero[0]); br_f = meuSwap(end->zero[0]); if (((inv_i % 2 == 0) == (br_i % 2 == 1)) == ((inv_f % 2 == 0) == (br_f % 2 == 1))) return true; return false; } //contar o número de inversões int contaInversoes(int v[]){ int som=0; for(int i=0;i<16;i++){ for(int j=i+1;j<16;j++){ if(v[i]>v[j] && v[i]!=0 && v[j]!=0) som+=1; } } return som; } //muda x, uma vez que foi contado do fundo, começando em 1, para verificar a solubilidade int meuSwap(int x){ switch(x){ case 3:return 1; case 2:return 2; case 1:return 3; case 0:return 4; } return 0; } //cálculo da heurística de distância de manhattan int Manhattan (Node *x) { int acc = 0; for (int i=0; i<16; i++) { if (x->array[i]!=0) { int index= posFinal[x->array[i]]; int xf = index/4; int yf = index%4; int xa = i/4; int ya = i%4; acc+= abs(xf-xa) + abs(yf-ya); } } return acc; } // para melhor performance calculando as eurísticas, cria uma espécie de dicionário // para um dado bloco k, o índice é pos final [k] void criaDic() { for (int i=0; i < 16; i++) { int g = ar_f[i]; posFinal[g]=i; } } //retorna o array como uma string string meuHash(int v[]){ string s = ""; for(int i =0; i<16; i++) s += to_string(v[i]); return s; } //verifique se 2 matrizes de configurações são iguais bool igual(int a[], int b[]){ for(int i = 0; i < 16; i++) if(a[i] != b[i]) return false; return true; } //verifica se dois nós são iguais bool nosIguais(Node *a, Node *b){ if(a && b)return igual(a->array, b->array); return false; } //copia o array para o array b void copiar(int a[], int b[]){ for(int i=0;i<16;i++){ b[i]=a[i]; } } int analisaLinha (char* linha){ int i = strlen(linha); const char* p = linha; while (*p <'0' || *p > '9') p++; linha[i-3] = '\0'; i = atoi(p); return i; } int obterValor(){ FILE* file = fopen("/proc/self/status", "r"); int resultado = -1; char linha[128]; while (fgets(linha, 128, file) != NULL){ if (strncmp(linha, "VmRSS:", 6) == 0){ resultado = analisaLinha(linha); break; } } fclose(file); return resultado; }
20.021825
89
0.603211
loiola0
98460fc5f88b037a28e453b4e6f7b00863de1b2a
1,059
hpp
C++
include/libp2p/common/literals.hpp
Alexey-N-Chernyshov/cpp-libp2p
8b52253f9658560a4b1311b3ba327f02284a42a6
[ "Apache-2.0", "MIT" ]
null
null
null
include/libp2p/common/literals.hpp
Alexey-N-Chernyshov/cpp-libp2p
8b52253f9658560a4b1311b3ba327f02284a42a6
[ "Apache-2.0", "MIT" ]
null
null
null
include/libp2p/common/literals.hpp
Alexey-N-Chernyshov/cpp-libp2p
8b52253f9658560a4b1311b3ba327f02284a42a6
[ "Apache-2.0", "MIT" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef LIBP2P_LITERALS_HPP #define LIBP2P_LITERALS_HPP #include <cstdint> #include <vector> #include <libp2p/common/types.hpp> namespace libp2p { namespace multi { class Multiaddress; class Multihash; } // namespace multi namespace peer { class PeerId; } namespace common { /// Only for type casting in tests. No hash is computed Hash256 operator""_hash256(const char *c, size_t s); /// Only for type casting in tests. No hash is computed Hash512 operator""_hash512(const char *c, size_t s); std::vector<uint8_t> operator""_v(const char *c, size_t s); std::vector<uint8_t> operator""_unhex(const char *c, size_t s); multi::Multiaddress operator""_multiaddr(const char *c, size_t s); multi::Multihash operator""_multihash(const char *c, size_t s); peer::PeerId operator""_peerid(const char *c, size_t s); } // namespace common } // namespace libp2p #endif // LIBP2P_LITERALS_HPP
23.021739
70
0.694051
Alexey-N-Chernyshov
985037a14f29b5ae6859757d7ec7e47d49dc29d7
4,800
cpp
C++
ogsr_engine/COMMON_AI/PATH/patrol_path_storage.cpp
tiger-vlad/OGSR-Engine
2b9700d6af4ece2728acc108decb2f34d43a6231
[ "Apache-2.0" ]
1
2019-06-21T10:33:20.000Z
2019-06-21T10:33:20.000Z
ogsr_engine/COMMON_AI/PATH/patrol_path_storage.cpp
tiger-vlad/OGSR-Engine
2b9700d6af4ece2728acc108decb2f34d43a6231
[ "Apache-2.0" ]
null
null
null
ogsr_engine/COMMON_AI/PATH/patrol_path_storage.cpp
tiger-vlad/OGSR-Engine
2b9700d6af4ece2728acc108decb2f34d43a6231
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // Module : patrol_path_storage.cpp // Created : 15.06.2004 // Modified : 15.06.2004 // Author : Dmitriy Iassenev // Description : Patrol path storage //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "patrol_path_storage.h" #include "patrol_path.h" #include "patrol_point.h" #include "levelgamedef.h" #include "ai_space.h" #include "level_graph.h" #include "game_graph.h" CPatrolPathStorage::~CPatrolPathStorage () { delete_data (m_registry); } void CPatrolPathStorage::load_raw (const CLevelGraph *level_graph, const CGameLevelCrossTable *cross, const CGameGraph *game_graph, IReader &stream) { IReader *chunk = stream.open_chunk(WAY_PATROLPATH_CHUNK); if (!chunk) return; u32 chunk_iterator; for (IReader *sub_chunk = chunk->open_chunk_iterator(chunk_iterator); sub_chunk; sub_chunk = chunk->open_chunk_iterator(chunk_iterator,sub_chunk)) { R_ASSERT (sub_chunk->find_chunk(WAYOBJECT_CHUNK_VERSION)); R_ASSERT (sub_chunk->r_u16() == WAYOBJECT_VERSION); R_ASSERT (sub_chunk->find_chunk(WAYOBJECT_CHUNK_NAME)); shared_str patrol_name; sub_chunk->r_stringZ (patrol_name); VERIFY3 (m_registry.find(patrol_name) == m_registry.end(),"Duplicated patrol path found",*patrol_name); m_registry.insert ( std::make_pair( patrol_name, &xr_new<CPatrolPath>( patrol_name )->load_raw( level_graph, cross, game_graph, *sub_chunk ) ) ); } chunk->close (); } void CPatrolPathStorage::append_from_ini(CInifile &way_inifile) { PATROL_REGISTRY::value_type pair; int i = 0; int r = 0; for (const auto &it : way_inifile.sections()) { const shared_str patrol_name = it.first; if (m_registry.erase(patrol_name)) { r++; } m_registry.insert( std::make_pair( patrol_name, &xr_new<CPatrolPath>( patrol_name )->load_ini( *it.second ) ) ); i++; } Msg("Loaded %d items from custom_waypoints, %d from all.spawn was replaced!", i, r); } void CPatrolPathStorage::load (IReader &stream) { IReader *chunk; chunk = stream.open_chunk(0); u32 size = chunk->r_u32(); chunk->close (); m_registry.clear (); PATROL_REGISTRY::value_type pair; chunk = stream.open_chunk(1); for (u32 i=0; i<size; ++i) { IReader *chunk1; chunk1 = chunk->open_chunk(i); IReader *chunk2; chunk2 = chunk1->open_chunk(0); load_data (pair.first,*chunk2); chunk2->close (); chunk2 = chunk1->open_chunk(1); load_data (pair.second,*chunk2); chunk2->close (); chunk1->close (); VERIFY3(m_registry.find(pair.first) == m_registry.end(),"Duplicated patrol path found ",*pair.first); #ifdef DEBUG pair.second->name (pair.first); #endif m_registry.insert (pair); } chunk->close (); } void CPatrolPathStorage::save (IWriter &stream) { stream.open_chunk (0); stream.w_u32 (m_registry.size()); stream.close_chunk (); stream.open_chunk (1); PATROL_REGISTRY::iterator I = m_registry.begin(); PATROL_REGISTRY::iterator E = m_registry.end(); for (int i=0; I != E; ++I, ++i) { stream.open_chunk (i); stream.open_chunk (0); save_data ((*I).first,stream); stream.close_chunk (); stream.open_chunk (1); save_data ((*I).second,stream); stream.close_chunk (); stream.close_chunk (); } stream.close_chunk (); } void CPatrolPathStorage::remove_path( shared_str patrol_name ) { m_registry.erase( patrol_name ); } void CPatrolPathStorage::add_path( shared_str patrol_name, CPatrolPath *path ) { remove_path( patrol_name ); m_registry.insert( std::make_pair( patrol_name, path ) ); } const CPatrolPath* CPatrolPathStorage::safe_path( shared_str patrol_name, bool no_assert, bool on_level ) const { auto it = m_registry.find( patrol_name ); if ( it == m_registry.end() ) return path( patrol_name, no_assert ); for ( auto& it2 : (*it).second->vertices() ) { auto& pp = it2.second->data(); if ( on_level || ( ai().game_graph().valid_vertex_id( pp.m_game_vertex_id ) && ai().game_graph().vertex( pp.m_game_vertex_id )->level_id() == ai().level_graph().level_id() ) ) { if ( !ai().level_graph().valid_vertex_id( pp.m_level_vertex_id ) ) { u32 prev_vertex_id = pp.m_level_vertex_id; pp.m_level_vertex_id = ai().level_graph().vertex( pp.m_position ); Msg( "* [%s]: path[%s] pp[%s] level_vertex_id[%u] -> %u", __FUNCTION__, patrol_name.c_str(), pp.m_name.c_str(), prev_vertex_id, pp.m_level_vertex_id ); } } else return path( patrol_name, no_assert ); } return path( patrol_name, no_assert ); }
25.531915
181
0.641875
tiger-vlad
9852e6ce0c07b1308e383043a1504518586acdfe
777
cpp
C++
src/main/cpp/autonomous/AutoBaseLine.cpp
Team3512/Robot-2017
1e5f3c1dcd78464d0c967aa17ca0e479775f7ed3
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/autonomous/AutoBaseLine.cpp
Team3512/Robot-2017
1e5f3c1dcd78464d0c967aa17ca0e479775f7ed3
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/autonomous/AutoBaseLine.cpp
Team3512/Robot-2017
1e5f3c1dcd78464d0c967aa17ca0e479775f7ed3
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2016-2021 FRC Team 3512. All Rights Reserved. #include "Robot.hpp" constexpr double kSafetyInches = 10.0; // Drives forward until passing white line 120 inches away from start void Robot::AutoBaseLine() { robotDrive.StartClosedLoop(); shifter.Set(false); // false = high gear gearPunch.Set(frc::DoubleSolenoid::kForward); // Move forward robotDrive.ResetEncoders(); robotDrive.ResetGyro(); shifter.Set(true); // low gear robotDrive.SetPositionReference(kRobotLength + 120.0 + kSafetyInches); robotDrive.SetAngleReference(0); while (!robotDrive.PosAtReference()) { m_autonChooser.YieldToMain(); if (!IsAutonomousEnabled()) { return; } } robotDrive.StopClosedLoop(); }
25.9
74
0.675676
Team3512
9855218d27807b581da5d1f58a4e439ff444e345
304
cpp
C++
core/xnet/env.cpp
forrestsong/fpay_demo
7b254a1389b011c799497ad7d08bb8d8d349e557
[ "MIT" ]
1
2018-08-12T15:08:49.000Z
2018-08-12T15:08:49.000Z
core/xnet/env.cpp
forrestsong/fpay_demo
7b254a1389b011c799497ad7d08bb8d8d349e557
[ "MIT" ]
null
null
null
core/xnet/env.cpp
forrestsong/fpay_demo
7b254a1389b011c799497ad7d08bb8d8d349e557
[ "MIT" ]
null
null
null
#include <iostream> #include "IOLoop.h" #include "SignalHandler.h" #include "env.h" int env::SocketErrorLogLevel = 0; time_t env::now = time(NULL); std::string env::strTime = ""; unsigned int env::msec = 0; uint64_t env::usec = 0; IOLoop* env::_loop = NULL; SignalHandler* env::_signalHandler = NULL;
21.714286
42
0.700658
forrestsong
985a0b9d65797ab47cdf40363ae2fd2855d88c2d
416
cpp
C++
Kawakawa/Excalibur/Core/Object/System/CameraSystem.cpp
JiaqiJin/KawaiiDesune
e5c3031898f96f1ec5370b41371b2c1cf22c3586
[ "MIT" ]
null
null
null
Kawakawa/Excalibur/Core/Object/System/CameraSystem.cpp
JiaqiJin/KawaiiDesune
e5c3031898f96f1ec5370b41371b2c1cf22c3586
[ "MIT" ]
null
null
null
Kawakawa/Excalibur/Core/Object/System/CameraSystem.cpp
JiaqiJin/KawaiiDesune
e5c3031898f96f1ec5370b41371b2c1cf22c3586
[ "MIT" ]
null
null
null
#include "CameraSystem.h" namespace Excalibur { CameraSystem::CameraSystem(World* world) : m_World(world) { } int CameraSystem::Initialize() { return 0; } void CameraSystem::Finalize() { m_MainCamera = nullptr; } std::shared_ptr<Entity> CameraSystem::GetMainCamera() { return m_MainCamera; } void CameraSystem::SetMainCamera(std::shared_ptr<Entity> camera) { m_MainCamera = camera; } }
13.866667
65
0.704327
JiaqiJin
985c7580f09279333a49b64f260e36cbda9522cd
730
cpp
C++
Contests/Codeforces/CF1011/A.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Contests/Codeforces/CF1011/A.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Contests/Codeforces/CF1011/A.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) const int maxN=51; const int inf=2147483647; const int meminf=1061109567; char str[maxN]; int n,K; int F[maxN][maxN]; int main() { scanf("%d%d",&n,&K); scanf("%s",str+1); sort(&str[1],&str[n+1]); n=unique(&str[1],&str[n+1])-str-1; mem(F,63); F[0][0]=0; for (int i=1;i<=n;i++) for (int j=1;j<=K;j++) for (int k=0;k<i;k++) if (str[i]-str[k]>=2) F[i][j]=min(F[i][j],F[k][j-1]+str[i]-'a'+1); int Ans=meminf; for (int i=1;i<=n;i++) Ans=min(Ans,F[i][K]); if (Ans==meminf) printf("-1\n"); else printf("%d\n",Ans); return 0; }
18.25
49
0.591781
SYCstudio
985eb7be388d30e5a22ea2a1476c73eefc86cabd
10,253
cpp
C++
xfa/src/fxbarcode/datamatrix/BC_SymbolInfo.cpp
f100cleveland/external_pdfium
12eec9c70519554387f199aa1eef42ed15478d02
[ "BSD-3-Clause" ]
1
2018-01-12T03:24:59.000Z
2018-01-12T03:24:59.000Z
xfa/src/fxbarcode/datamatrix/BC_SymbolInfo.cpp
f100cleveland/external_pdfium
12eec9c70519554387f199aa1eef42ed15478d02
[ "BSD-3-Clause" ]
null
null
null
xfa/src/fxbarcode/datamatrix/BC_SymbolInfo.cpp
f100cleveland/external_pdfium
12eec9c70519554387f199aa1eef42ed15478d02
[ "BSD-3-Clause" ]
1
2020-07-30T12:07:00.000Z
2020-07-30T12:07:00.000Z
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com // Original code is licensed as follows: /* * Copyright 2006 Jeremias Maerki * * 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 "xfa/src/fxbarcode/barcode.h" #include "xfa/src/fxbarcode/BC_Dimension.h" #include "xfa/src/fxbarcode/common/BC_CommonBitMatrix.h" #include "BC_Encoder.h" #include "BC_SymbolShapeHint.h" #include "BC_SymbolInfo.h" #include "BC_DataMatrixSymbolInfo144.h" #define SYMBOLS_COUNT 30 CBC_SymbolInfo* CBC_SymbolInfo::m_PROD_SYMBOLS[30] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; CBC_SymbolInfo* CBC_SymbolInfo::m_symbols[30] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; void CBC_SymbolInfo::Initialize() { m_PROD_SYMBOLS[0] = new CBC_SymbolInfo(FALSE, 3, 5, 8, 8, 1); m_PROD_SYMBOLS[1] = new CBC_SymbolInfo(FALSE, 5, 7, 10, 10, 1); m_PROD_SYMBOLS[2] = new CBC_SymbolInfo(TRUE, 5, 7, 16, 6, 1); m_PROD_SYMBOLS[3] = new CBC_SymbolInfo(FALSE, 8, 10, 12, 12, 1); m_PROD_SYMBOLS[4] = new CBC_SymbolInfo(TRUE, 10, 11, 14, 6, 2); m_PROD_SYMBOLS[5] = new CBC_SymbolInfo(FALSE, 12, 12, 14, 14, 1); m_PROD_SYMBOLS[6] = new CBC_SymbolInfo(TRUE, 16, 14, 24, 10, 1); m_PROD_SYMBOLS[7] = new CBC_SymbolInfo(FALSE, 18, 14, 16, 16, 1); m_PROD_SYMBOLS[8] = new CBC_SymbolInfo(FALSE, 22, 18, 18, 18, 1); m_PROD_SYMBOLS[9] = new CBC_SymbolInfo(TRUE, 22, 18, 16, 10, 2); m_PROD_SYMBOLS[10] = new CBC_SymbolInfo(FALSE, 30, 20, 20, 20, 1); m_PROD_SYMBOLS[11] = new CBC_SymbolInfo(TRUE, 32, 24, 16, 14, 2); m_PROD_SYMBOLS[12] = new CBC_SymbolInfo(FALSE, 36, 24, 22, 22, 1); m_PROD_SYMBOLS[13] = new CBC_SymbolInfo(FALSE, 44, 28, 24, 24, 1); m_PROD_SYMBOLS[14] = new CBC_SymbolInfo(TRUE, 49, 28, 22, 14, 2); m_PROD_SYMBOLS[15] = new CBC_SymbolInfo(FALSE, 62, 36, 14, 14, 4); m_PROD_SYMBOLS[16] = new CBC_SymbolInfo(FALSE, 86, 42, 16, 16, 4); m_PROD_SYMBOLS[17] = new CBC_SymbolInfo(FALSE, 114, 48, 18, 18, 4); m_PROD_SYMBOLS[18] = new CBC_SymbolInfo(FALSE, 144, 56, 20, 20, 4); m_PROD_SYMBOLS[19] = new CBC_SymbolInfo(FALSE, 174, 68, 22, 22, 4); m_PROD_SYMBOLS[20] = new CBC_SymbolInfo(FALSE, 204, 84, 24, 24, 4, 102, 42); m_PROD_SYMBOLS[21] = new CBC_SymbolInfo(FALSE, 280, 112, 14, 14, 16, 140, 56); m_PROD_SYMBOLS[22] = new CBC_SymbolInfo(FALSE, 368, 144, 16, 16, 16, 92, 36); m_PROD_SYMBOLS[23] = new CBC_SymbolInfo(FALSE, 456, 192, 18, 18, 16, 114, 48); m_PROD_SYMBOLS[24] = new CBC_SymbolInfo(FALSE, 576, 224, 20, 20, 16, 144, 56); m_PROD_SYMBOLS[25] = new CBC_SymbolInfo(FALSE, 696, 272, 22, 22, 16, 174, 68); m_PROD_SYMBOLS[26] = new CBC_SymbolInfo(FALSE, 816, 336, 24, 24, 16, 136, 56); m_PROD_SYMBOLS[27] = new CBC_SymbolInfo(FALSE, 1050, 408, 18, 18, 36, 175, 68); m_PROD_SYMBOLS[28] = new CBC_SymbolInfo(FALSE, 1304, 496, 20, 20, 36, 163, 62); m_PROD_SYMBOLS[29] = new CBC_DataMatrixSymbolInfo144(); for (int32_t i = 0; i < SYMBOLS_COUNT; i++) { m_symbols[i] = m_PROD_SYMBOLS[i]; } } void CBC_SymbolInfo::Finalize() { for (int32_t i = 0; i < SYMBOLS_COUNT; i++) { delete m_PROD_SYMBOLS[i]; m_PROD_SYMBOLS[i] = NULL; m_symbols[i] = NULL; } } CBC_SymbolInfo::CBC_SymbolInfo(FX_BOOL rectangular, int32_t dataCapacity, int32_t errorCodewords, int32_t matrixWidth, int32_t matrixHeight, int32_t dataRegions) { m_rectangular = rectangular; m_dataCapacity = dataCapacity; m_errorCodewords = errorCodewords; m_matrixWidth = matrixWidth; m_matrixHeight = matrixHeight; m_dataRegions = dataRegions; m_rsBlockData = dataCapacity; m_rsBlockError = errorCodewords; } CBC_SymbolInfo::CBC_SymbolInfo(FX_BOOL rectangular, int32_t dataCapacity, int32_t errorCodewords, int32_t matrixWidth, int32_t matrixHeight, int32_t dataRegions, int32_t rsBlockData, int32_t rsBlockError) { m_rectangular = rectangular; m_dataCapacity = dataCapacity; m_errorCodewords = errorCodewords; m_matrixWidth = matrixWidth; m_matrixHeight = matrixHeight; m_dataRegions = dataRegions; m_rsBlockData = rsBlockData; m_rsBlockError = rsBlockError; } CBC_SymbolInfo::~CBC_SymbolInfo() {} CBC_SymbolInfo* CBC_SymbolInfo::lookup(int32_t dataCodewords, int32_t& e) { return lookup(dataCodewords, FORCE_NONE, TRUE, e); } CBC_SymbolInfo* CBC_SymbolInfo::lookup(int32_t dataCodewords, SymbolShapeHint shape, int32_t& e) { return lookup(dataCodewords, shape, TRUE, e); } CBC_SymbolInfo* CBC_SymbolInfo::lookup(int32_t dataCodewords, FX_BOOL allowRectangular, FX_BOOL fail, int32_t& e) { SymbolShapeHint shape = allowRectangular ? FORCE_NONE : FORCE_SQUARE; return lookup(dataCodewords, shape, fail, e); } CBC_SymbolInfo* CBC_SymbolInfo::lookup(int32_t dataCodewords, SymbolShapeHint shape, FX_BOOL fail, int32_t& e) { return lookup(dataCodewords, shape, NULL, NULL, fail, e); } CBC_SymbolInfo* CBC_SymbolInfo::lookup(int32_t dataCodewords, SymbolShapeHint shape, CBC_Dimension* minSize, CBC_Dimension* maxSize, FX_BOOL fail, int32_t& e) { for (int32_t i = 0; i < SYMBOLS_COUNT; i++) { CBC_SymbolInfo* symbol = m_symbols[i]; if (shape == FORCE_SQUARE && symbol->m_rectangular) { continue; } if (shape == FORCE_RECTANGLE && !symbol->m_rectangular) { continue; } if (minSize != NULL && (symbol->getSymbolWidth(e) < minSize->getWidth() || symbol->getSymbolHeight(e) < minSize->getHeight())) { BC_EXCEPTION_CHECK_ReturnValue(e, NULL); continue; } if (maxSize != NULL && (symbol->getSymbolWidth(e) > maxSize->getWidth() || symbol->getSymbolHeight(e) > maxSize->getHeight())) { BC_EXCEPTION_CHECK_ReturnValue(e, NULL); continue; } if (dataCodewords <= symbol->m_dataCapacity) { return symbol; } } if (fail) { e = BCExceptionIllegalDataCodewords; return NULL; } return NULL; } int32_t CBC_SymbolInfo::getHorizontalDataRegions(int32_t& e) { switch (m_dataRegions) { case 1: return 1; case 2: return 2; case 4: return 2; case 16: return 4; case 36: return 6; default: e = BCExceptionCannotHandleThisNumberOfDataRegions; return 0; } } int32_t CBC_SymbolInfo::getVerticalDataRegions(int32_t& e) { switch (m_dataRegions) { case 1: return 1; case 2: return 1; case 4: return 2; case 16: return 4; case 36: return 6; default: e = BCExceptionCannotHandleThisNumberOfDataRegions; return 0; } } int32_t CBC_SymbolInfo::getSymbolDataWidth(int32_t& e) { return getHorizontalDataRegions(e) * m_matrixWidth; } int32_t CBC_SymbolInfo::getSymbolDataHeight(int32_t& e) { return getVerticalDataRegions(e) * m_matrixHeight; } int32_t CBC_SymbolInfo::getSymbolWidth(int32_t& e) { return getSymbolDataWidth(e) + (getHorizontalDataRegions(e) * 2); } int32_t CBC_SymbolInfo::getSymbolHeight(int32_t& e) { return getSymbolDataHeight(e) + (getVerticalDataRegions(e) * 2); } int32_t CBC_SymbolInfo::getCodewordCount() { return m_dataCapacity + m_errorCodewords; } int32_t CBC_SymbolInfo::getInterleavedBlockCount() { return m_dataCapacity / m_rsBlockData; } int32_t CBC_SymbolInfo::getDataLengthForInterleavedBlock(int32_t index) { return m_rsBlockData; } int32_t CBC_SymbolInfo::getErrorLengthForInterleavedBlock(int32_t index) { return m_rsBlockError; } CFX_WideString CBC_SymbolInfo::toString(int32_t& e) { CFX_WideString sb; sb += (FX_WCHAR*)(m_rectangular ? "Rectangular Symbol:" : "Square Symbol:"); sb += (FX_WCHAR*)" data region "; sb += m_matrixWidth; sb += (FX_WCHAR)'x'; sb += m_matrixHeight; sb += (FX_WCHAR*)", symbol size "; sb += getSymbolWidth(e); BC_EXCEPTION_CHECK_ReturnValue(e, (FX_WCHAR*)""); sb += (FX_WCHAR)'x'; sb += getSymbolHeight(e); BC_EXCEPTION_CHECK_ReturnValue(e, (FX_WCHAR*)""); sb += (FX_WCHAR*)", symbol data size "; sb += getSymbolDataWidth(e); BC_EXCEPTION_CHECK_ReturnValue(e, (FX_WCHAR*)""); sb += (FX_WCHAR)'x'; sb += getSymbolDataHeight(e); BC_EXCEPTION_CHECK_ReturnValue(e, (FX_WCHAR*)""); sb += (FX_WCHAR*)", codewords "; sb += m_dataCapacity; sb += (FX_WCHAR)'+'; sb += m_errorCodewords; return sb; }
39.894942
81
0.627329
f100cleveland
9862551214aa4d28d9d1ccd3872b85e1f097a981
3,752
cpp
C++
main.cpp
vega1986/wcalc_expression_parser
e9645a5fa8086c4108ce4dc1f3ad7da3cead6480
[ "MIT" ]
null
null
null
main.cpp
vega1986/wcalc_expression_parser
e9645a5fa8086c4108ce4dc1f3ad7da3cead6480
[ "MIT" ]
null
null
null
main.cpp
vega1986/wcalc_expression_parser
e9645a5fa8086c4108ce4dc1f3ad7da3cead6480
[ "MIT" ]
null
null
null
#include <cstdlib> #include <sstream> #include <iostream> #include <queue> // #include "kernel.h" #include "ctexpression/ctkernel.h" // #define use_string_interpreter 0 int main(int argc, char *argv[]) { using namespace std; using namespace compile_time_expression_structure; #if 0 // istringstream ist {"7*(2+4*(1+2*(3+6)))"}; // istringstream ist {"7*(2+5)"}; double real_expression_result = +7*(2+2*(1+3*(2+5))) - 30*3; istringstream ist {"+7*{2+2*(1+3*(2+5))} - 30*3"}; // istringstream ist {"7*46 - 30*3"}; // istringstream ist {"5*4 - 4*3"}; // istringstream ist {"(-5)*4-4*3"}; calculator::WExpression expr(ist); double val {expr.result()}; cout << "res wcalc: " << val << endl; cout << "res cpp: " << real_expression_result << endl; bool exit_instruction_received {false}; while (cin) { cout << calculator::command_prompt_symbol << ' '; std::queue<string> queue_str; while (cin) { char sym {0}; cin >> sym; while (cin && sym==calculator::command_stop_expression) cin >> sym; if (sym == calculator::command_quit_instruction) { exit_instruction_received = true; break; } else cin.unget(); string str; while (cin) { cin >> sym; if (sym == calculator::command_stop_expression) break; str += sym; } queue_str.emplace(std::move(str)); // istringstream ist{str}; // try // { // calculator::WExpression expr(ist); // double val {expr.result()}; // cout << " = " << val << endl; // } // catch(exception& e) // { // cout << " = " << "...failed - " << e.what() << endl; // } } } #endif #if 0 while (cin) { char sym {0}; cin >> sym; while (cin && sym==calculator::command_stop_expression) cin >> sym; if (sym == calculator::command_quit_instruction) break; else cin.unget(); string str; while (cin) { cin >> sym; if (sym == calculator::command_stop_expression) break; str += sym; } istringstream ist{str}; try { std::map<std::string, double> vars {{"x", 3.1}, {"y", 4.2}, {"r", 6.3}}; calculator::WExpression expr(ist, vars); double val {expr.result()}; cout << " = " << val << endl; } catch(exception& e) { cout << " = " << "...failed - " << e.what() << endl; } } #else while (cin) { char sym {0}; cin >> sym; while (cin && sym==command_stop_expression) cin >> sym; if (sym == command_quit_instruction) break; else cin.unget(); string str; while (cin) { cin >> sym; if (sym == command_stop_expression) break; str += sym; } istringstream ist{str}; try { CTExpression cte(ist); cte.set_variable(variableId::x, 3.1); cte.set_variable(variableId::y, 4.2); cte.set_variable(variableId::r, 6.3); double val {cte.value()}; cout << " = " << val << endl; } catch(exception& e) { cout << " = " << "...failed: '" << e.what() << "'" << endl; } } #endif return EXIT_SUCCESS; }
25.875862
79
0.452292
vega1986
98647a9fd20bb76d081f2cb841782bcd9340933e
3,107
cpp
C++
test/PAGSmokeTest.cpp
cy-j/libpag
9b1636a0a67ad5e009d60c6c348034790d247692
[ "BSL-1.0", "CC0-1.0", "MIT" ]
2
2022-02-26T16:10:30.000Z
2022-03-18T01:28:40.000Z
test/PAGSmokeTest.cpp
cy-j/libpag
9b1636a0a67ad5e009d60c6c348034790d247692
[ "BSL-1.0", "CC0-1.0", "MIT" ]
null
null
null
test/PAGSmokeTest.cpp
cy-j/libpag
9b1636a0a67ad5e009d60c6c348034790d247692
[ "BSL-1.0", "CC0-1.0", "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////////////// // // Tencent is pleased to support the open source community by making libpag available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. 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. // ///////////////////////////////////////////////////////////////////////////////////////////////// #ifdef SMOKE_TEST #include <fstream> #include <vector> #include "TestUtils.h" #include "base/utils/TimeUtil.h" #include "framework/pag_test.h" #include "framework/utils/Baseline.h" #include "framework/utils/PAGTestUtils.h" namespace pag { /** * 用例描述: smoke文件夹下文件是否渲染正常 */ PAG_TEST(PAGSmokeTest, RenderFrames) { std::vector<std::string> files; GetAllPAGFiles("../resources/smoke", files); int size = static_cast<int>(files.size()); for (int i = 0; i < size; i++) { auto fileName = files[i].substr(files[i].rfind("/") + 1, files[i].size()); auto pagFile = PAGFile::Load(files[i]); auto width = pagFile->width(); auto height = pagFile->height(); if (std::min(width, height) > 360) { if (width > height) { width = static_cast<int>( ceilf(static_cast<float>(width) * 360.0f / static_cast<float>(height))); height = 360; } else { height = static_cast<int>( ceilf(static_cast<float>(height) * 360.0f / static_cast<float>(width))); width = 360; } } ASSERT_NE(pagFile, nullptr); auto pagSurface = PAGSurface::MakeOffscreen(width, height); ASSERT_NE(pagSurface, nullptr); auto pagPlayer = std::make_shared<PAGPlayer>(); pagPlayer->setSurface(pagSurface); pagPlayer->setComposition(pagFile); Frame totalFrames = TimeToFrame(pagFile->duration(), pagFile->frameRate()); Frame currentFrame = 0; std::string errorMsg = ""; while (currentFrame < totalFrames) { // 添加0.1帧目的是保证progress不会由于精度问题帧数计算错误,frame应该使用totalFrames作为总体帧数。因为对于 // file来说总时长为[0,totalFrames],对应于[0,1],因此归一化时,分母应该为totalFrames pagPlayer->setProgress((static_cast<float>(currentFrame) + 0.1) * 1.0 / static_cast<float>(totalFrames)); pagPlayer->flush(); auto snapshot = MakeSnapshot(pagSurface); auto result = Baseline::Compare(snapshot, "PAGSmokeTest/" + std::to_string(currentFrame) + ""); if (!result) { errorMsg += (std::to_string(currentFrame) + ";"); } currentFrame++; } EXPECT_EQ(errorMsg, "") << fileName << " frame fail"; } } } // namespace pag #endif
36.988095
97
0.619569
cy-j
986cf9d18eb8becd9ea2150c7940ec2db9eada36
2,607
cpp
C++
core/src/view/TileView.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
2
2020-10-16T10:15:37.000Z
2021-01-21T13:06:00.000Z
core/src/view/TileView.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
null
null
null
core/src/view/TileView.cpp
voei/megamol
569b7b58c1f9bc5405b79549b86f84009329f668
[ "BSD-3-Clause" ]
1
2021-01-28T01:19:54.000Z
2021-01-28T01:19:54.000Z
/* * TileView.cpp * * Copyright (C) 2010 by VISUS (Universitaet Stuttgart). * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "mmcore/view/TileView.h" #include "vislib/memutils.h" using namespace megamol::core; using vislib::graphics::CameraParameters; /* * view::TileView::TileView */ view::TileView::TileView(void) : AbstractTileView(), firstFrame(false), outCtrl(NULL) { } /* * view::TileView::~TileView */ view::TileView::~TileView(void) { this->Release(); } /* * view::TileView::Render */ void view::TileView::Render(const mmcRenderViewContext& context) { view::CallRenderView *crv = this->getCallRenderView(); if (crv == NULL) return; // false ? if (this->firstFrame) { this->initTileViewParameters(); this->firstFrame = false; } this->checkParameters(); crv->ResetAll(); crv->SetTime(static_cast<float>(context.Time)); crv->SetInstanceTime(context.InstanceTime); crv->SetProjection(this->getProjType(), this->getEye()); crv->SetGpuAffinity(context.GpuAffinity); if ((this->getVirtWidth() != 0) && (this->getVirtHeight() != 0) && (this->getTileW() != 0) && (this->getTileH() != 0)) { crv->SetTile(this->getVirtWidth(), this->getVirtHeight(), this->getTileX(), this->getTileY(), this->getTileW(), this->getTileH()); } if (this->outCtrl == NULL) { crv->SetOutputBuffer(GL_BACK, this->getViewportWidth(), this->getViewportHeight()); // TODO: Fix me! } else { crv->SetOutputBuffer(*this->outCtrl); } (*crv)(view::CallRenderView::CALL_RENDER); } /* * view::TileView::create */ bool view::TileView::create(void) { this->firstFrame = true; return true; } /* * view::TileView::release */ void view::TileView::release(void) { // intentionally empty } /* * view::TileView::OnRenderView */ bool view::TileView::OnRenderView(Call& call) { view::CallRenderView *crv = dynamic_cast<view::CallRenderView *>(&call); if (crv == NULL) return false; this->outCtrl = crv; mmcRenderViewContext c; ::ZeroMemory(&c, sizeof(mmcRenderViewContext)); c.Size = sizeof(mmcRenderViewContext); c.Time = crv->Time(); if (c.Time < 0.0f) c.Time = this->DefaultTime(crv->InstanceTime()); c.InstanceTime = crv->InstanceTime(); // TODO: Affinity this->Render(c); // TODO: Fix me! this->outCtrl = NULL; return true; } /* * view::TileView::unpackMouseCoordinates */ void view::TileView::unpackMouseCoordinates(float &x, float &y) { x *= this->getTileW(); y *= this->getTileH(); }
23.070796
108
0.632528
voei
986de253998848da15157e3b571e0ea914336a35
4,668
cpp
C++
src/moore.cpp
poluyan/MultiDimFloodFill
388b38a4bfb643b708524d04ab296a40e4d3e087
[ "Apache-2.0" ]
null
null
null
src/moore.cpp
poluyan/MultiDimFloodFill
388b38a4bfb643b708524d04ab296a40e4d3e087
[ "Apache-2.0" ]
null
null
null
src/moore.cpp
poluyan/MultiDimFloodFill
388b38a4bfb643b708524d04ab296a40e4d3e087
[ "Apache-2.0" ]
null
null
null
#include "moore.h" #include "pdf.h" void FloodFill_MultipleGrids_Moore(const std::vector<std::vector<double>> &grids, std::vector<std::vector<int>> &points, std::set<std::vector<int>> &visited, std::vector<std::vector<double>> &samples, const std::vector<double> &dx, size_t &counter, size_t &fe_count, bool outside_bounds) { /// generate all permutations std::vector<std::vector<int>> variable_values(grids.size(), std::vector<int>(3)); for(size_t i = 0; i != variable_values.size(); i++) { variable_values[i][0] = -1; variable_values[i][1] = 0; variable_values[i][2] = 1; } std::vector<std::vector<int>> permut = iterate(variable_values); while(!points.empty()) { auto t = points.back(); points.pop_back(); auto it = visited.find(t); if(!(it == visited.end())) { counter++; continue; } visited.insert(t); std::vector<double> dot(t.size()); for(size_t i = 0; i != dot.size(); i++) { dot[i] = grids[i][t[i]] + dx[i]; } bool val = pdf(dot); fe_count++; if(val) { std::vector<int> point = t; samples.push_back(dot); // n-dimensional Moore distance with r = 1 for(size_t i = 0; i != permut.size(); i++) { point = t; if(outside_bounds) { for(size_t j = 0; j != point.size(); j++) { point[j] = point[j] + permut[i][j]; if(point[j] < 0) { point[j] = grids[j].size() - 1; } if(point[j] > static_cast<int>(grids[j].size() - 1)) { point[j] = 0; } } } else { bool flag = true; for(size_t j = 0; j != point.size(); j++) { point[j] = point[j] + permut[i][j]; if(point[j] < 0 || point[j] > static_cast<int>(grids[j].size() - 1)) { flag = false; break; } } if(!flag) continue; } points.push_back(point); } } } } void b4MultipleGrids_Moore(const std::vector<double> &init_point, size_t grid_sizes, bool outside_bounds) { size_t dim = init_point.size(); std::vector<double> grid(dim, grid_sizes); std::vector<std::vector<double>> grids(grid.size()); std::vector<double> dx(grid.size()); double lb = -3, ub = 3; for(size_t i = 0; i != grids.size(); i++) { size_t num_points = grid[i]; std::vector<double> onegrid(num_points); double startp = lb; double endp = ub; double es = endp - startp; for(size_t j = 0; j != onegrid.size(); j++) { onegrid[j] = startp + j*es/(num_points); } grids[i] = onegrid; dx[i] = es/(num_points*2); } // finding start dot over created grid std::vector<int> startdot(init_point.size()); for(size_t i = 0; i != startdot.size(); i++) { std::vector<double> val(grids[i].size()); for(size_t j = 0; j != val.size(); j++) { val[j] = grids[i][j] + dx[i]; } auto pos1 = std::lower_bound(val.begin(), val.end(), init_point[i]); startdot[i] = std::distance(val.begin(), pos1) - 1; } std::vector<std::vector<int>> points; std::vector<std::vector<int>> boundary; points.push_back(startdot); std::set<std::vector<int>> visited; std::vector<std::vector<double> > samples; size_t counter = 0; size_t fe_count = 0; FloodFill_MultipleGrids_Moore(grids, points, visited, samples, dx, counter, fe_count, outside_bounds); std::cout << counter << std::endl; std::cout << "fe count: " << fe_count << std::endl; std::cout << "samples: " << samples.size() << std::endl; std::cout << samples.size()/double(fe_count) << std::endl; //print2file2d("maps/sample2d.dat", samples); }
31.328859
106
0.442588
poluyan
987b5047e513fc893fa90e342c6c2422d33d0512
1,371
cpp
C++
hard/23_merge_k_sorted_lists.cpp
pdu/leetcode_cpp
c487df7561f92562b20a31317957f47e0a20c485
[ "Apache-2.0" ]
4
2019-07-22T03:53:23.000Z
2019-10-17T01:37:41.000Z
hard/23_merge_k_sorted_lists.cpp
pdu/leetcode_cpp
c487df7561f92562b20a31317957f47e0a20c485
[ "Apache-2.0" ]
null
null
null
hard/23_merge_k_sorted_lists.cpp
pdu/leetcode_cpp
c487df7561f92562b20a31317957f47e0a20c485
[ "Apache-2.0" ]
2
2020-03-10T03:30:41.000Z
2020-11-10T06:51:34.000Z
// step 1: clarify // // quite straightforward // // step 2: solutions // // set the pointer to each of the list head, put all the values into the priority_queue // pop the minimum value one and move the related pointer to the next position // time complexity: O(n * logk), n is the total number // space complexity: O(k) // // step 3: coding // // can put a soldier to make the code easier // // step 4: testing #include <vector> #include <queue> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {} }; class Solution { public: ListNode* mergeKLists(vector<ListNode*>& lists) { priority_queue<pair<int, int>, vector<pair<int, int>> ,greater<pair<int, int>>> min_heap; for (int i = 0; i < lists.size(); ++i) if (lists[i] != nullptr) min_heap.emplace(lists[i]->val, i); ListNode head(0); ListNode* curr = &head; while (!min_heap.empty()) { auto top = min_heap.top(); min_heap.pop(); curr->next = lists[top.second]; curr = curr->next; lists[top.second] = lists[top.second]->next; if (lists[top.second] != nullptr) min_heap.emplace(lists[top.second]->val, top.second); } curr->next = nullptr; return head.next; } };
26.882353
97
0.585704
pdu
987fd977e4e261af31b0736f215f562fb8f784a3
7,443
cpp
C++
Source/System/CacheManager.cpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
6
2017-12-31T17:28:40.000Z
2021-12-04T06:11:34.000Z
Source/System/CacheManager.cpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
null
null
null
Source/System/CacheManager.cpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
null
null
null
#include "Precompiled.hpp" #include "CacheManager.hpp" #include "MainGlobal.hpp" namespace { // Log error messages. #define LogInitializeError() "Failed to initialize the cache manager! " #define LogRecreateCacheError() "Failed to recreate the cache! " // Cache registry filename. const char* CacheRegistryFile = "d39bf4ad-b0b4-4807-99a5-75941ce8a997"; // Cache registry format type (also the header's magic word). const char* FormatType = "CacheRegistry"; // Cache registry version. Increasing it will cause upgrade of the cache, if not available it will be recreated. unsigned int RegistryVersion = 1; // Cache integrity version. Increasing it will force the whole cache to recreate. unsigned int IntegrityVersion = 1; } CacheManager::CacheManager() : m_initialized(false) { } CacheManager::~CacheManager() { Cleanup(); } bool CacheManager::Initialize() { Cleanup(); // Emergency cleanup call on failure. auto EmergenyCleanup = MakeScopeGuard([&]() { // Cleanup if initialization failed. if(!m_initialized) { Cleanup(); } }); // Load the cache. if(!LoadCache()) { Log() << "Recreating the cache..."; // Recreate the cache if it doesn't exist or it can't be used for some reason. if(!RecreateCache()) { Log() << LogInitializeError() << "Couldn't recreate the cache!"; return false; } } // Success! m_initialized = true; return true; } void CacheManager::Cleanup() { // Save cache registry. SaveCache(); // Cleanup members. ClearContainer(m_registry); m_initialized = false; } std::string CacheManager::Lookup(std::string filename) { // Find an existing entry. auto it = m_registry.find(filename); if(it != m_registry.end()) { std::string identifier = boost::uuids::to_string(it->second); return identifier; } // Create a new identifier. boost::uuids::uuid uuid; std::string identifier; do { uuid = boost::uuids::random_generator()(); identifier = boost::uuids::to_string(uuid); } while(boost::filesystem::exists(Main::GetCacheDir() + identifier)); // Add a new cache entry. m_registry.insert(std::make_pair(filename, uuid)); return identifier; } bool CacheManager::LoadCache() { // Open the cache registry. std::ifstream registryFile(Main::GetCacheDir() + CacheRegistryFile); if(!registryFile.is_open()) { Log() << "Can't open the cache registry!"; return false; } // Read the file header. std::string formatType; unsigned int registryVersion; unsigned int integrityVersion; registryFile >> formatType; registryFile >> registryVersion; registryFile >> integrityVersion; if(!registryFile.good()) { Log() << "Can't read the cache registry header!"; return false; } // Validate the header. if(formatType != FormatType) { Log() << "Invalid cache registry header!"; return false; } if(registryVersion != registryVersion) { Log() << "Invalid cache registry version."; return false; } if(integrityVersion != IntegrityVersion) { Log() << "Cache integrity version mismatch."; return false; } // Move to next line after reading the header. registryFile >> std::ws; // Setup scope guard to clear registry entries we could've added past this point. auto clearRegistryEntires = MakeScopeGuard([&]() { ClearContainer(m_registry); }); // Read the cache registry. std::string line; while(!registryFile.eof()) { // Read the line. std::getline(registryFile, line); if(line.empty()) continue; // Create the tokenizer. boost::escaped_list_separator<char> separator('\\', ' ', '\"'); boost::tokenizer<boost::escaped_list_separator<char>> tokens(line, separator); // Next token read function. auto token = tokens.begin(); auto ReadNextToken = [&](std::string& output) -> bool { if(token != tokens.end()) { output = *token++; return true; } return false; }; // Read the registry entry tokens. std::string identifier; std::string filename; if(!ReadNextToken(identifier) || !ReadNextToken(filename)) { Log() << "Can't read a cache registry entry!"; return false; } // Check if cache file is valid. if(!ValidateCache(identifier)) { Log() << "Discarded an invalid cache registry entry."; continue; } // Convert identifier to UUID structure. boost::uuids::uuid uuid = boost::uuids::string_generator()(identifier); // Add a cache registry entry. m_registry.insert(std::make_pair(filename, uuid)); } // Disable scope guard. clearRegistryEntires.Disable(); return true; } bool CacheManager::RecreateCache() { boost::system::error_code error; // Remove the cache directory and it's content. boost::filesystem::remove_all(Main::GetCacheDir(), error); if(error) { Log() << LogRecreateCacheError() << "Can't remove the cache directory."; return false; } // Create an empty cache directory. boost::filesystem::create_directory(Main::GetCacheDir(), error); if(error) { Log() << LogRecreateCacheError() << "Can't create the cache directory."; return false; } // Create the cache registry. std::ofstream registryFile(Main::GetCacheDir() + CacheRegistryFile); if(!registryFile.is_open()) { Log() << LogRecreateCacheError() << "Can't create the cache registry."; return false; } registryFile.flush(); registryFile.close(); return true; } bool CacheManager::SaveCache() { if(!m_initialized) return false; // Open the cache registry. std::ofstream registryFile(Main::GetCacheDir() + CacheRegistryFile); if(!registryFile.is_open()) { Log() << "Can't open the cache registry."; return false; } // Write the file header. registryFile << FormatType << ' '; registryFile << RegistryVersion << ' '; registryFile << IntegrityVersion << '\n'; // Write the cache entries. for(auto it = m_registry.begin(); it != m_registry.end(); ++it) { std::string identifier = boost::uuids::to_string(it->second); // Check if cache file is valid. if(!ValidateCache(identifier)) { Log() << "Tried to write an invalid cache entry."; continue; } // Write a cache entry. registryFile << it->second << ' '; registryFile << '"' << it->first << '"' << '\n'; } return true; } bool CacheManager::ValidateCache(std::string identifier) { std::string file = Main::GetCacheDir() + identifier; // Make sure the cache exists. if(!boost::filesystem::exists(file)) { return false; } // Make sure it's not empty. if(boost::filesystem::file_size(file) == 0) { return false; } return true; }
23.703822
116
0.593847
gunstarpl
9880b1c76cf919d2e52f8cfc208134f59555b22b
8,810
hpp
C++
scripting/src/SceneGraph/LuaSceneBuilder.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
36
2015-03-12T10:42:36.000Z
2022-01-12T04:20:40.000Z
scripting/src/SceneGraph/LuaSceneBuilder.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
1
2015-12-17T00:25:43.000Z
2016-02-20T12:00:57.000Z
scripting/src/SceneGraph/LuaSceneBuilder.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
6
2017-06-17T07:57:53.000Z
2019-04-09T21:11:24.000Z
/* * Copyright (c) 2013, Hernan Saez * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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. */ #ifndef CRIMILD_SCRIPTING_SCENE_BUILDER_LUA_ #define CRIMILD_SCRIPTING_SCENE_BUILDER_LUA_ #include "Foundation/Scripted.hpp" #include <Streaming/SceneBuilder.hpp> namespace crimild { class Node; class Group; class NodeComponent; namespace scripting { /** \deprecated Use LuaObjectBuilderRegistry instead */ class LuaNodeBuilderRegistry : public StaticSingleton< LuaNodeBuilderRegistry > { public: using NodeBuilderFunction = std::function< SharedPointer< Node > ( crimild::scripting::ScriptEvaluator & ) >; public: LuaNodeBuilderRegistry( void ); virtual ~LuaNodeBuilderRegistry( void ); template< typename T > void registerNodeBuilder( std::string type ) { _nodeBuilders[ type ] = []( crimild::scripting::ScriptEvaluator &eval ) { auto node = crimild::alloc< T >(); node->load( eval ); return node; }; } void registerCustomNodeBuilder( std::string type, NodeBuilderFunction builder ) { _nodeBuilders[ type ] = builder; } NodeBuilderFunction getBuilder( std::string type ) { return _nodeBuilders[ type ]; } public: template< class T > class RegistrationHelper { public: RegistrationHelper( const char *name ) { LuaNodeBuilderRegistry::getInstance()->registerNodeBuilder< T >( name ); } ~RegistrationHelper( void ) { } }; public: void flush( void ); private: std::map< std::string, NodeBuilderFunction > _nodeBuilders; }; #define CRIMILD_SCRIPTING_REGISTER_NODE_BUILDER( X ) \ static crimild::scripting::LuaNodeBuilderRegistry::RegistrationHelper< X > __nodeRegistrationHelper( #X ); /** \deprecated Use LuaObjectBuilderRegistry instead */ class LuaComponentBuilderRegistry : public StaticSingleton< LuaComponentBuilderRegistry > { public: using ComponentBuilderFunction = std::function< SharedPointer< NodeComponent > ( crimild::scripting::ScriptEvaluator & ) >; public: LuaComponentBuilderRegistry( void ); virtual ~LuaComponentBuilderRegistry( void ); template< typename T > void registerComponentBuilder( std::string type ) { _componentBuilders[ type ] = []( crimild::scripting::ScriptEvaluator &eval ) { return crimild::alloc< T >( eval ); }; } void registerCustomComponentBuilder( std::string type, ComponentBuilderFunction builder ) { _componentBuilders[ type ] = builder; } ComponentBuilderFunction getBuilder( std::string type ) { return _componentBuilders[ type ]; } public: template< class T > class RegistrationHelper { public: RegistrationHelper( const char *name ) { LuaComponentBuilderRegistry::getInstance()->registerComponentBuilder< T >( name ); } ~RegistrationHelper( void ) { } }; public: void flush( void ); private: std::map< std::string, ComponentBuilderFunction > _componentBuilders; }; #define CRIMILD_SCRIPTING_REGISTER_COMPONENT_BUILDER( X ) \ static crimild::scripting::LuaComponentBuilderRegistry::RegistrationHelper< X > __componentRegistrationHelper( #X ); class LuaObjectBuilderRegistry : public StaticSingleton< LuaObjectBuilderRegistry > { public: using BuilderFunction = std::function< SharedPointer< SharedObject > ( crimild::scripting::ScriptEvaluator & ) >; public: LuaObjectBuilderRegistry( void ); virtual ~LuaObjectBuilderRegistry( void ); template< typename T > void registerBuilder( std::string type ) { _builders[ type ] = []( crimild::scripting::ScriptEvaluator &eval ) { return crimild::alloc< T >( eval ); }; } void registerCustomBuilder( std::string type, BuilderFunction builder ) { _builders[ type ] = builder; } BuilderFunction getBuilder( std::string type ) { return _builders[ type ]; } public: void flush( void ); private: std::map< std::string, BuilderFunction > _builders; }; #define CRIMILD_SCRIPTING_REGISTER_BUILDER( X ) \ crimild::scripting::LuaObjectBuilderRegistry::getInstance()->registerBuilder< X >( #X ); #define CRIMILD_SCRIPTING_REGISTER_CUSTOM_BUILDER( X, BUILDER_FUNC ) \ crimild::scripting::LuaObjectBuilderRegistry::getInstance()->registerCustomBuilder( #X, BUILDER_FUNC ); class LuaSceneBuilder : public crimild::scripting::Scripted, public crimild::SceneBuilder { private: using NodeBuilderFunction = std::function< SharedPointer< Node > ( crimild::scripting::ScriptEvaluator & ) >; using ComponentBuilderFunction = std::function< SharedPointer< NodeComponent > ( crimild::scripting::ScriptEvaluator & ) >; public: LuaSceneBuilder( std::string rootNodeName = "scene" ); virtual ~LuaSceneBuilder( void ); virtual void reset( void ) override; virtual SharedPointer< Node > fromFile( const std::string &filename ) override; public: template< typename T > void generateNodeBuilder( std::string type ) { _nodeBuilders[ type ] = []( crimild::scripting::ScriptEvaluator &eval ) { auto node = crimild::alloc< T >(); node->load( eval ); return node; }; } template< typename T > void registerComponent( void ) { registerComponentBuilder< T >( []( crimild::scripting::ScriptEvaluator &eval ) { return crimild::alloc< T >( eval ); }); } template< typename T > void registerComponentBuilder( ComponentBuilderFunction builder ) { _componentBuilders[ T::_COMPONENT_NAME() ] = builder; } private: SharedPointer< Node > buildNode( ScriptEvaluator &eval, Group *parent ); void setTransformation( ScriptEvaluator &eval, SharedPointer< Node > const &node ); void buildNodeComponents( ScriptEvaluator &eval, SharedPointer< Node > const &node ); private: std::string _rootNodeName; std::map< std::string, NodeBuilderFunction > _nodeBuilders; std::map< std::string, ComponentBuilderFunction > _componentBuilders; }; } } #endif
36.106557
135
0.605221
hhsaez
9882c8ace1f7470eb207ba3eccd0a20d351c4e5f
2,860
cpp
C++
src/dawn/IIR/AccessToNameMapper.cpp
Kayjukh/dawn
431a59ceeff062beb8390056c6bbd5b5d6d808d3
[ "MIT" ]
null
null
null
src/dawn/IIR/AccessToNameMapper.cpp
Kayjukh/dawn
431a59ceeff062beb8390056c6bbd5b5d6d808d3
[ "MIT" ]
null
null
null
src/dawn/IIR/AccessToNameMapper.cpp
Kayjukh/dawn
431a59ceeff062beb8390056c6bbd5b5d6d808d3
[ "MIT" ]
null
null
null
//===--------------------------------------------------------------------------------*- C++ -*-===// // _ // | | // __| | __ ___ ___ ___ // / _` |/ _` \ \ /\ / / '_ | // | (_| | (_| |\ V V /| | | | // \__,_|\__,_| \_/\_/ |_| |_| - Compiler Toolchain // // // This file is distributed under the MIT License (MIT). // See LICENSE.txt for details. // //===------------------------------------------------------------------------------------------===// #include "dawn/IIR/AccessToNameMapper.h" #include "dawn/IIR/StencilFunctionInstantiation.h" #include "dawn/IIR/StencilMetaInformation.h" namespace dawn { namespace iir { void AccessToNameMapper::visit(const std::shared_ptr<VarDeclStmt>& stmt) { insertAccessInfo(stmt); ASTVisitorForwarding::visit(stmt); } void AccessToNameMapper::visit(const std::shared_ptr<StencilFunCallExpr>& expr) { if(!curFunctionInstantiation_.empty()) { auto* stencilFunctionInstantiation = curFunctionInstantiation_.top()->getStencilFunctionInstantiation(expr).get(); curFunctionInstantiation_.push(stencilFunctionInstantiation); } else { auto* stencilFunctionInstantiation = metaData_.getStencilFunctionInstantiation(expr).get(); curFunctionInstantiation_.push(stencilFunctionInstantiation); } curFunctionInstantiation_.top()->getAST()->accept(*this); curFunctionInstantiation_.pop(); ASTVisitorForwarding::visit(expr); } void AccessToNameMapper::insertAccessInfo(const std::shared_ptr<Expr>& expr) { int accessID = (curFunctionInstantiation_.empty()) ? metaData_.getAccessIDFromExpr(expr) : curFunctionInstantiation_.top()->getAccessIDFromExpr(expr); std::string name = (curFunctionInstantiation_.empty()) ? metaData_.getNameFromAccessID(accessID) : curFunctionInstantiation_.top()->getNameFromAccessID(accessID); accessIDToName_.emplace(accessID, name); } void AccessToNameMapper::insertAccessInfo(const std::shared_ptr<Stmt>& stmt) { int accessID = (curFunctionInstantiation_.empty()) ? metaData_.getAccessIDFromStmt(stmt) : curFunctionInstantiation_.top()->getAccessIDFromStmt(stmt); std::string name = (curFunctionInstantiation_.empty()) ? metaData_.getNameFromAccessID(accessID) : curFunctionInstantiation_.top()->getNameFromAccessID(accessID); accessIDToName_.emplace(accessID, name); } void AccessToNameMapper::visit(const std::shared_ptr<VarAccessExpr>& expr) { insertAccessInfo(expr); } void AccessToNameMapper::visit(const std::shared_ptr<FieldAccessExpr>& expr) { insertAccessInfo(expr); } } // namespace iir } // namespace dawn
39.178082
100
0.615035
Kayjukh
98830ee90e34373b77453559e1a5a1c2170bb82e
4,623
cpp
C++
src/model/searchlistmodel.cpp
sailfish-os-apps/harbour-sailseries
df8fb67b720e4ba9f8c4644ebc03cf90bb745e3c
[ "MIT" ]
null
null
null
src/model/searchlistmodel.cpp
sailfish-os-apps/harbour-sailseries
df8fb67b720e4ba9f8c4644ebc03cf90bb745e3c
[ "MIT" ]
null
null
null
src/model/searchlistmodel.cpp
sailfish-os-apps/harbour-sailseries
df8fb67b720e4ba9f8c4644ebc03cf90bb745e3c
[ "MIT" ]
null
null
null
#include "searchlistmodel.h" SearchListModel::SearchListModel(QObject *parent, DatabaseManager *dbmanager, Api *api) : QObject(parent) { m_dbmanager = dbmanager; m_api = api; connect(m_api, SIGNAL(readyToPopulateSeries(QList<QVariantMap>)), this, SLOT(searchFinished(QList<QVariantMap>))); connect(m_api, SIGNAL(readyToStoreSeries(QList<QVariantMap>, QList<QVariantMap>, QList<QVariantMap>)), this, SLOT(getAllFinished(QList<QVariantMap>, QList<QVariantMap>, QList<QVariantMap>))); m_loading = false; m_added = false; } SearchListModel::~SearchListModel() { for (auto series : m_searchListModel) { delete series; series = 0; } } QQmlListProperty<SeriesData> SearchListModel::getSearchModel() { return QQmlListProperty<SeriesData>(this, &m_searchListModel, &SearchListModel::searchListCount, &SearchListModel::searchListAt); } // List handling methods void SearchListModel::searchListAppend(QQmlListProperty<SeriesData>* prop, SeriesData* val) { SearchListModel* searchModel = qobject_cast<SearchListModel*>(prop->object); searchModel->m_searchListModel.append(val); } SeriesData* SearchListModel::searchListAt(QQmlListProperty<SeriesData>* prop, int index) { return (qobject_cast<SearchListModel*>(prop->object))->m_searchListModel.at(index); } int SearchListModel::searchListCount(QQmlListProperty<SeriesData>* prop) { return qobject_cast<SearchListModel*>(prop->object)->m_searchListModel.size(); } void SearchListModel::searchListClear(QQmlListProperty<SeriesData>* prop) { qobject_cast<SearchListModel*>(prop->object)->m_searchListModel.clear(); } void SearchListModel::searchFinished(QList<QVariantMap> series) { populateSearchModel(series); } void SearchListModel::getAllFinished(QList<QVariantMap> series, QList<QVariantMap> episodes, QList<QVariantMap> banners) { storeSeries(series); storeEpisodes(episodes); storeBanners(banners); setLoading(false); emit updateModels(); } void SearchListModel::populateSearchModel(QList<QVariantMap> foundSeries) { if (!foundSeries.empty()) { for (auto series : foundSeries) { SeriesData* seriesData = new SeriesData(this, series); m_searchListModel.append(seriesData); } emit searchModelChanged(); setLoading(false); } } void SearchListModel::searchSeries(QString text) { setLoading(true); m_searchListModel.clear(); m_series.clear(); emit searchModelChanged(); m_api->searchSeries(text); } void SearchListModel::selectSeries(int index) { m_info = m_searchListModel.at(index); } void SearchListModel::getFullSeriesRecord(QString id) { m_api->getAll(id, "full"); setLoading(true); } void SearchListModel::storeSeries(QList<QVariantMap> series) { if (!series.isEmpty()) { m_dbmanager->insertSeries(series.first()); } } void SearchListModel::storeEpisodes(QList<QVariantMap> episodes) { auto seriesId = m_info->getID().toInt(); m_dbmanager->insertEpisodes(episodes, seriesId); setAdded(true); } void SearchListModel::storeBanners(QList<QVariantMap> banners) { auto seriesId = m_info->getID().toInt(); m_dbmanager->insertBanners(banners, seriesId); } QString SearchListModel::getID() { return m_info->getID(); } QString SearchListModel::getLanguage() { return m_info->getLanguage(); } QString SearchListModel::getSeriesName() { return m_info->getSeriesName(); } QString SearchListModel::getAliasNames() { return m_info->getAliasNames(); } QString SearchListModel::getBanner() { return m_info->getBanner(); } QString SearchListModel::getOverview() { return m_info->getOverview(); } QString SearchListModel::getFirstAired() { return m_info->getFirstAired(); } QString SearchListModel::getIMDB_ID() { return m_info->getIMDB_ID(); } QString SearchListModel::getZap2it_ID() { return m_info->getZap2it_ID(); } QString SearchListModel::getNetwork() { return m_info->getNetwork(); } bool SearchListModel::getLoading() { return m_loading; } void SearchListModel::setLoading(bool state) { m_loading = state; emit loadingChanged(); } bool SearchListModel::getAdded() { return m_added; } void SearchListModel::setAdded(bool cond) { if (m_added != cond) { m_added = cond; emit addedChanged(); } } void SearchListModel::clearList() { m_searchListModel.clear(); emit searchModelChanged(); } void SearchListModel::checkIfAdded(QString id, QString name) { setAdded(m_dbmanager->isAlreadyAdded(id.toInt(), name)); }
26.722543
133
0.718797
sailfish-os-apps
9887816891913384f92ed443f1518d4f74bd709f
18,089
cpp
C++
src/xtd.core.native.win32/src/xtd/native/win32/socket.cpp
gammasoft71/xtd
09e589a9dd2cb292d1e54c9c4f803c2b3ad22102
[ "MIT" ]
251
2019-04-20T02:02:24.000Z
2022-03-31T09:52:08.000Z
src/xtd.core.native.win32/src/xtd/native/win32/socket.cpp
gammasoft71/xtd
09e589a9dd2cb292d1e54c9c4f803c2b3ad22102
[ "MIT" ]
29
2021-01-07T12:52:12.000Z
2022-03-29T08:42:14.000Z
src/xtd.core.native.win32/src/xtd/native/win32/socket.cpp
gammasoft71/xtd
09e589a9dd2cb292d1e54c9c4f803c2b3ad22102
[ "MIT" ]
27
2019-11-21T02:37:44.000Z
2022-03-30T22:59:14.000Z
#define __XTD_CORE_NATIVE_LIBRARY__ #include <xtd/native/socket.h> #include <xtd/native/address_family_constants.h> #include <xtd/native/protocol_type_constants.h> #include <xtd/native/select_mode_constants.h> #include <xtd/native/socket_option_name_constants.h> #include <xtd/native/socket_option_level_constants.h> #include <xtd/native/socket_shutdown_constants.h> #include <xtd/native/socket_type_constants.h> #undef __XTD_CORE_NATIVE_LIBRARY__ #include <map> #include <Winsock2.h> #include <Windows.h> using namespace std; using namespace xtd::native; namespace { static int32_t protocol_type_to_native(int32_t protocol_type) { static map<int32_t, int32_t> protocol_types = {{PROTOCOL_TYPE_UNKNOWN, IPPROTO_IP}, {PROTOCOL_TYPE_IP, IPPROTO_IP}, {PROTOCOL_TYPE_ICMP, IPPROTO_ICMP}, {PROTOCOL_TYPE_IGMP, IPPROTO_IGMP}, {PROTOCOL_TYPE_GGP, IPPROTO_GGP}, {PROTOCOL_TYPE_IP_V4, IPPROTO_IPV4}, {PROTOCOL_TYPE_IP_V6, IPPROTO_IPV6}, {PROTOCOL_TYPE_TCP, IPPROTO_TCP}, {PROTOCOL_TYPE_PUP, IPPROTO_PUP}, {PROTOCOL_TYPE_UDP, IPPROTO_UDP}, {PROTOCOL_TYPE_IDP, IPPROTO_IDP}, {PROTOCOL_TYPE_IP_V6, IPPROTO_IPV6}, {PROTOCOL_TYPE_IP_V6_ROUTING_HEADER, IPPROTO_ROUTING}, {PROTOCOL_TYPE_IP_V6_FRAGMENT_HEADER, IPPROTO_FRAGMENT}, {PROTOCOL_TYPE_IP_SEC_ENCAPSULATING_SECURITY_PAYLOAD, IPPROTO_ESP}, {PROTOCOL_TYPE_IP_SEC_AUTHENTICATION_HEADER, IPPROTO_AH}, {PROTOCOL_TYPE_ICMP_V6, IPPROTO_ICMPV6}, {PROTOCOL_TYPE_IP_V6_NO_NEXT_HEADER, IPPROTO_NONE}, {PROTOCOL_TYPE_IP_V6_DESTINATION_OPTIONS, IPPROTO_DSTOPTS}, {PROTOCOL_TYPE_ND, IPPROTO_ND}, {PROTOCOL_TYPE_RAW, IPPROTO_RAW}, {PROTOCOL_TYPE_SPX, IPPROTO_IP}, {PROTOCOL_TYPE_SPX_2, IPPROTO_IP}}; auto it = protocol_types.find(protocol_type); if (it == protocol_types.end()) return IPPROTO_IP; return it->second; } static int32_t socket_option_name_to_native(int32_t socket_option_name) { static map<int32_t, int32_t> socket_option_names = {{SOCKET_OPTION_NAME_DEBUG, SO_DEBUG}, {SOCKET_OPTION_NAME_ACCEPT_CONNECTION, SO_ACCEPTCONN}, {SOCKET_OPTION_NAME_REUSE_ADDRESS, SO_REUSEADDR}, {SOCKET_OPTION_NAME_KEEP_ALIVE, SO_KEEPALIVE}, {SOCKET_OPTION_NAME_DONT_ROUTE, SO_DONTROUTE}, {SOCKET_OPTION_NAME_BROADCAST, SO_BROADCAST}, {SOCKET_OPTION_NAME_USE_LOOPBACK, SO_USELOOPBACK}, {SOCKET_OPTION_NAME_LINGER, SO_LINGER}, {SOCKET_OPTION_NAME_OUT_OF_BAND_INLINE, SO_OOBINLINE}, {SOCKET_OPTION_NAME_SEND_BUFFER, SO_SNDBUF}, {SOCKET_OPTION_NAME_RECEIVE_BUFFER, SO_RCVBUF}, {SOCKET_OPTION_NAME_SEND_LOW_WATER, SO_SNDLOWAT}, {SOCKET_OPTION_NAME_RECEIVE_LOW_WATER, SO_RCVLOWAT}, {SOCKET_OPTION_NAME_SEND_TIMEOUT, SO_SNDTIMEO}, {SOCKET_OPTION_NAME_RECEIVE_TIMEOUT, SO_RCVTIMEO}, {SOCKET_OPTION_NAME_ERROR, SO_ERROR}, {SOCKET_OPTION_NAME_TYPE, SO_TYPE}}; auto it = socket_option_names.find(socket_option_name); if (it == socket_option_names.end()) return socket_option_name; return it->second; } static int32_t socket_option_level_to_native(int32_t socket_option_level) { static map<int32_t, int32_t> socket_option_levels = {{SOCKET_OPTION_LEVEL_SOCKET, SOL_SOCKET}, {SOCKET_OPTION_LEVEL_IP, IPPROTO_IP}, {SOCKET_OPTION_LEVEL_IP_V6, IPPROTO_IPV6}, {SOCKET_OPTION_LEVEL_TCP, IPPROTO_TCP}, {SOCKET_OPTION_LEVEL_UDP, IPPROTO_UDP}}; auto it = socket_option_levels.find(socket_option_level); if (it == socket_option_levels.end()) return SOL_SOCKET; return it->second; } static int32_t socket_type_to_native(int32_t socket_type) { static map<int32_t, int32_t> socket_types = {{SOCKET_TYPE_UNKNOWN, SOCK_STREAM}, {SOCKET_TYPE_STREAM, SOCK_STREAM}, {SOCKET_TYPE_DGRAM, SOCK_DGRAM}, {SOCKET_TYPE_RAW, SOCK_RAW}, {SOCKET_TYPE_RDM, SOCK_RDM}, {SOCKET_TYPE_SEQPACKET, SOCK_SEQPACKET}}; auto it = socket_types.find(socket_type); if (it == socket_types.end()) return SOCK_STREAM; return it->second; } } int32_t socket::address_family_to_native(int32_t address_family) { static map<int32_t, int32_t> address_families = {{ADDRESS_FAMILY_UNIX, AF_UNIX}, {ADDRESS_FAMILY_INTER_NETWORK, AF_INET}, {ADDRESS_FAMILY_IMP_LINK, AF_IMPLINK}, {ADDRESS_FAMILY_PUP, AF_PUP}, {ADDRESS_FAMILY_CHAOS, AF_CHAOS}, {ADDRESS_FAMILY_NS, AF_NS}, {ADDRESS_FAMILY_ISO, AF_ISO}, {ADDRESS_FAMILY_ECMA, AF_ECMA}, {ADDRESS_FAMILY_DATA_KIT, AF_DATAKIT}, {ADDRESS_FAMILY_CCITT, AF_CCITT}, {ADDRESS_FAMILY_SNA, AF_SNA}, {ADDRESS_FAMILY_DEC_NET, AF_DECnet}, {ADDRESS_FAMILY_DATA_LINK, AF_DLI}, {ADDRESS_FAMILY_LAT, AF_LAT}, {ADDRESS_FAMILY_HYPER_CHANNEL, AF_HYLINK}, {ADDRESS_FAMILY_APPLE_TALK, AF_APPLETALK}, {ADDRESS_FAMILY_NET_BIOS, AF_NETBIOS}, {ADDRESS_FAMILY_VOICE_VIEW, AF_VOICEVIEW}, {ADDRESS_FAMILY_FIRE_FOX, AF_FIREFOX}, {ADDRESS_FAMILY_BANYAN, AF_BAN}, {ADDRESS_FAMILY_ATM, AF_ATM}, {ADDRESS_FAMILY_INTER_NETWORK_V6, AF_INET6}, {ADDRESS_FAMILY_CLUSTER, AF_CLUSTER}, {ADDRESS_FAMILY_IEEE12844, AF_12844}, {ADDRESS_FAMILY_IRDA, AF_IRDA}, {ADDRESS_FAMILY_NETWORK_DESIGNERS, AF_NETDES}, {ADDRESS_FAMILY_MAX, AF_MAX}}; auto it = address_families.find(address_family); if (it == address_families.end()) return AF_UNSPEC; return it->second; } int32_t socket::native_to_address_family(int32_t address_family) { static map<int32_t, int32_t> address_families = {{AF_UNIX, ADDRESS_FAMILY_UNIX}, {AF_INET, ADDRESS_FAMILY_INTER_NETWORK}, {AF_IMPLINK, ADDRESS_FAMILY_IMP_LINK}, {AF_PUP, ADDRESS_FAMILY_PUP}, {AF_CHAOS, ADDRESS_FAMILY_CHAOS}, {AF_NS, ADDRESS_FAMILY_NS}, {AF_ISO, ADDRESS_FAMILY_ISO}, {AF_ECMA, ADDRESS_FAMILY_ECMA}, {AF_DATAKIT, ADDRESS_FAMILY_DATA_KIT}, {AF_CCITT, ADDRESS_FAMILY_CCITT}, {AF_SNA, ADDRESS_FAMILY_SNA}, {AF_DECnet, ADDRESS_FAMILY_DEC_NET}, {AF_DLI, ADDRESS_FAMILY_DATA_LINK}, {AF_LAT, ADDRESS_FAMILY_LAT}, {AF_HYLINK, ADDRESS_FAMILY_HYPER_CHANNEL}, {AF_APPLETALK, ADDRESS_FAMILY_APPLE_TALK}, {AF_NETBIOS, ADDRESS_FAMILY_NET_BIOS}, {AF_VOICEVIEW, ADDRESS_FAMILY_VOICE_VIEW}, {AF_FIREFOX, ADDRESS_FAMILY_FIRE_FOX}, {AF_BAN, ADDRESS_FAMILY_BANYAN}, {AF_ATM, ADDRESS_FAMILY_ATM}, {AF_INET6, ADDRESS_FAMILY_INTER_NETWORK_V6}, {AF_CLUSTER, ADDRESS_FAMILY_CLUSTER}, {AF_12844, ADDRESS_FAMILY_IEEE12844}, {AF_IRDA, ADDRESS_FAMILY_IRDA}, {AF_NETDES, ADDRESS_FAMILY_NETWORK_DESIGNERS}, {AF_MAX, ADDRESS_FAMILY_MAX}}; auto it = address_families.find(address_family); if (it == address_families.end()) return ADDRESS_FAMILY_UNSPECIFIED; return it->second; } intptr_t socket::accept(intptr_t handle, vector<uint8_t>& socket_address) { int32_t address_length = static_cast<int32_t>(socket_address.size()); intptr_t socket = static_cast<intptr_t>(::accept(static_cast<SOCKET>(handle), reinterpret_cast<SOCKADDR*>(socket_address.data()), &address_length)); if (socket_address.size() != static_cast<size_t>(address_length)) socket_address.resize(static_cast<size_t>(address_length)); return socket; } int32_t socket::bind(intptr_t handle, const vector<uint8_t>& socket_address) { return ::bind(static_cast<SOCKET>(handle), reinterpret_cast<const SOCKADDR*>(socket_address.data()), static_cast<int32_t>(socket_address.size())); } void socket::cleanup() { WSACleanup(); } int32_t socket::connect(intptr_t handle, const vector<uint8_t>& socket_address) { return ::connect(static_cast<SOCKET>(handle), reinterpret_cast<const SOCKADDR*>(socket_address.data()), static_cast<int32_t>(socket_address.size())); } intptr_t socket::create(int32_t address_family, int32_t socket_type, int32_t protocol_type) { return static_cast<intptr_t>(::socket(address_family_to_native(address_family), socket_type_to_native(socket_type), protocol_type_to_native(protocol_type))); } int32_t socket::destroy(intptr_t handle) { return ::closesocket(static_cast<SOCKET>(handle)); } size_t socket::get_available(intptr_t handle) { u_long nbr_bytes_available = 0; if (::ioctlsocket(static_cast<SOCKET>(handle), FIONREAD, &nbr_bytes_available) != 0) return static_cast<size_t>(-1); return static_cast<size_t>(nbr_bytes_available); } int32_t socket::get_last_error() { return WSAGetLastError(); } bool socket::get_os_supports_ip_v4() noexcept { SOCKET s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_IP); if (s == INVALID_SOCKET) return false; closesocket(s); return true; } bool socket::get_os_supports_ip_v6() noexcept { SOCKET s = ::socket(AF_INET6, SOCK_STREAM, IPPROTO_IP); if (s == INVALID_SOCKET) return false; closesocket(s); return true; } int32_t socket::get_raw_socket_option(intptr_t handle, int32_t socket_option_level, int32_t socket_option_name, intptr_t option, size_t& option_length) { return ::getsockopt(static_cast<SOCKET>(handle), socket_option_level, socket_option_name, reinterpret_cast<char*>(option), reinterpret_cast<int32_t*>(&option_length)); } int32_t socket::get_socket_option(intptr_t handle, int32_t socket_option_level, int32_t socket_option_name, intptr_t option, size_t& option_length) { return ::getsockopt(static_cast<SOCKET>(handle), socket_option_level_to_native(socket_option_level), socket_option_name_to_native(socket_option_name), reinterpret_cast<char*>(option), reinterpret_cast<int32_t*>(&option_length)); } int32_t socket::get_socket_linger_option(intptr_t handle, bool& enabled, uint32_t& linger_time) { LINGER l {static_cast<u_short>(enabled), static_cast<u_short>(linger_time)}; size_t linger_size = sizeof(LINGER); int32_t result = ::getsockopt(static_cast<SOCKET>(handle), SOL_SOCKET, SO_LINGER, reinterpret_cast<char*>(&l), reinterpret_cast<int32_t*>(&linger_size)); if (result == 0) { enabled = static_cast<bool>(l.l_onoff); linger_time = static_cast<uint32_t>(l.l_linger); } return result; } int32_t socket::get_socket_multicast_option(intptr_t handle, int32_t socket_option_name, uint32_t& multicast_address, uint32_t& interface_index) { struct multicast { uint32_t multicast_address; uint32_t interface_index; } m; size_t multicast_size = sizeof(multicast); int32_t result = getsockopt(static_cast<SOCKET>(handle), IPPROTO_IP, socket_option_name_to_native(socket_option_name), reinterpret_cast<char*>(&m), reinterpret_cast<int32_t*>(&multicast_size)); if (result == 0) { multicast_address = m.multicast_address; interface_index = m.interface_index; } return result; } int32_t socket::get_socket_ip_v6_multicast_option(intptr_t handle, int32_t socket_option_name, vector<uint8_t>& multicast_address, uint32_t& interface_index) { struct multicast { uint8_t multicast_address[16]; uint32_t interface_index; } m; size_t multicast_size = sizeof(multicast); int32_t result = getsockopt(static_cast<SOCKET>(handle), IPPROTO_IP, socket_option_name_to_native(socket_option_name), reinterpret_cast<char*>(&m), reinterpret_cast<int32_t*>(&multicast_size)); if (result == 0) { for (auto index = 0U; index < multicast_address.size(); ++index) multicast_address[index] = m.multicast_address[index]; interface_index = m.interface_index; } return result; } int32_t socket::io_control(intptr_t handle, int32_t io_control, vector<uint8_t>& option_in_value, vector<uint8_t>& option_out_value) { size_t option_out_value_size = 0; int32_t result = WSAIoctl(static_cast<SOCKET>(handle), io_control, option_in_value.data(), static_cast<int32_t>(option_in_value.size()), option_out_value.data(), static_cast<int32_t>(option_out_value.size()), reinterpret_cast<LPDWORD>(&option_out_value_size), nullptr, nullptr); if (option_out_value.size() != option_out_value_size) option_out_value.resize(option_out_value_size); return result; } int32_t socket::listen(intptr_t handle, size_t backlog) { int32_t backlog_value = backlog != static_cast<size_t>(-1) ? static_cast<int32_t>(backlog) : SOMAXCONN; return ::listen(static_cast<SOCKET>(handle), backlog_value); } int32_t socket::poll(intptr_t handle, int32_t microseconds, int32_t mode) { if (handle == 0 || microseconds < 0) return -1; timeval timeout = {microseconds / 1000000, microseconds % 1000000}; fd_set fdset; FD_ZERO(&fdset); FD_SET(static_cast<SOCKET>(handle), &fdset); switch (mode) { case SELECT_MODE_READ: return ::select(0, &fdset, nullptr, nullptr, microseconds == -1 ? nullptr : &timeout); case SELECT_MODE_WRITE: return ::select(0, nullptr, &fdset, nullptr, microseconds == -1 ? nullptr : &timeout); case SELECT_MODE_ERROR: return ::select(0, nullptr, nullptr, &fdset, microseconds == -1 ? nullptr : &timeout); default: return -1; } } int32_t socket::receive(intptr_t handle, vector<uint8_t>& buffer, size_t offset, size_t size, int32_t flags) { return static_cast<int32_t>(::recv(static_cast<SOCKET>(handle), reinterpret_cast<char*>(&buffer.data()[offset]), static_cast<int32_t>(size), flags)); } int32_t socket::receive_from(intptr_t handle, vector<uint8_t>& buffer, size_t offset, size_t size, int32_t flags, vector<uint8_t>& socket_address) { int32_t address_length = static_cast<int32_t>(socket_address.size()); int32_t result = static_cast<int32_t>(::recvfrom(static_cast<SOCKET>(handle), reinterpret_cast<char*>(&buffer.data()[offset]), static_cast<int32_t>(size), flags, reinterpret_cast<SOCKADDR*>(socket_address.data()), &address_length)); if (socket_address.size() != static_cast<size_t>(address_length)) socket_address.resize(static_cast<size_t>(address_length)); return result; } int32_t socket::select(vector<intptr_t>& check_read, vector<intptr_t>& check_write, vector<intptr_t>& check_error, int32_t microseconds) { size_t nfds = 0; fd_set read_fds; FD_ZERO(&read_fds); for (auto i = 0U; i < check_read.size() && i < FD_SETSIZE; i++) FD_SET(static_cast<SOCKET>(check_read[i]), &read_fds); if (check_read.size() > nfds) nfds = check_read.size(); fd_set write_fds; FD_ZERO(&write_fds); for (auto i = 0U; i < check_write.size() && i < FD_SETSIZE; i++) FD_SET(static_cast<SOCKET>(check_write[i]), &write_fds); if (check_write.size() > nfds) nfds = check_write.size(); fd_set error_fds; FD_ZERO(&error_fds); for (auto i = 0U; i < check_error.size() && i < FD_SETSIZE; i++) FD_SET(static_cast<SOCKET>(check_error[i]), &error_fds); if (check_error.size() > nfds) nfds = check_error.size(); timeval tv; if (microseconds != -1) { tv.tv_sec = microseconds / 1000000; tv.tv_usec = microseconds % 1000000; } int32_t result = ::select(static_cast<int32_t>(nfds + 1), &read_fds, &write_fds, &error_fds, &tv); for (auto i = 0U; i < check_read.size(); i++) { FD_CLR(static_cast<SOCKET>(check_read[i]), &read_fds); if (FD_ISSET(static_cast<SOCKET>(check_read[i]), &read_fds) == 0) check_read[i] = 0; } for (auto i = 0U; i < check_write.size(); i++) { FD_CLR(static_cast<SOCKET>(check_write[i]), &write_fds); if (FD_ISSET(static_cast<SOCKET>(check_write[i]), &write_fds) == 0) check_write[i] = 0; } for (auto i = 0U; i < check_error.size(); i++) { FD_CLR(static_cast<SOCKET>(check_error[i]), &error_fds); if (FD_ISSET(static_cast<SOCKET>(check_error[i]), &error_fds) == 0) check_error[i] = 0; } return result; } int32_t socket::send(intptr_t handle, const vector<uint8_t>& buffer, size_t offset, size_t size, int32_t flags) { return static_cast<int32_t>(::send(static_cast<SOCKET>(handle), reinterpret_cast<const char*>(&buffer.data()[offset]), static_cast<int32_t>(size), flags)); } int32_t socket::send_to(intptr_t handle, const vector<uint8_t>& buffer, size_t offset, size_t size, int32_t flags, const vector<uint8_t>& socket_address) { return static_cast<int32_t>(::sendto(static_cast<SOCKET>(handle), reinterpret_cast<const char*>(&buffer.data()[offset]), static_cast<int32_t>(size), flags, reinterpret_cast<const SOCKADDR*>(socket_address.data()), static_cast<int32_t>(socket_address.size()))); } int32_t socket::set_blocking(intptr_t handle, bool blocking) { u_long mode = blocking ? 0 : 1; return ioctlsocket(static_cast<SOCKET>(handle), FIONBIO, &mode); } int32_t socket::set_raw_socket_option(intptr_t handle, int32_t socket_option_level, int32_t socket_option_name, intptr_t option, size_t option_length) { return setsockopt(static_cast<SOCKET>(handle), socket_option_level, socket_option_name, reinterpret_cast<const char*>(option), static_cast<int32_t>(option_length)); } int32_t socket::set_socket_option(intptr_t handle, int32_t socket_option_level, int32_t socket_option_name, intptr_t option, size_t option_length) { return setsockopt(static_cast<SOCKET>(handle), socket_option_level_to_native(socket_option_level), socket_option_name_to_native(socket_option_name), reinterpret_cast<const char*>(option), static_cast<int32_t>(option_length)); } int32_t socket::set_socket_linger_option(intptr_t handle, bool enabled, uint32_t linger_time) { LINGER l {static_cast<u_short>(enabled), static_cast<u_short>(linger_time)}; return setsockopt(static_cast<SOCKET>(handle), SOL_SOCKET, SO_LINGER, reinterpret_cast<const char*>(&l), static_cast<int32_t>(sizeof(LINGER))); } int32_t socket::set_socket_multicast_option(intptr_t handle, int32_t socket_option_name, uint32_t multicast_address, uint32_t interface_index) { struct multicast { uint32_t multicast_address; uint32_t interface_index; } m {multicast_address, interface_index}; return setsockopt(static_cast<SOCKET>(handle), IPPROTO_TCP, socket_option_name_to_native(socket_option_name), reinterpret_cast<const char*>(&m), static_cast<int32_t>(sizeof(multicast))); } int32_t socket::set_socket_ip_v6_multicast_option(intptr_t handle, int32_t socket_option_name, const vector<uint8_t>& multicast_address, uint32_t interface_index) { struct multicast { uint8_t multicast_address[16]; uint32_t interface_index; } m; for (auto index = 0U; index < multicast_address.size(); ++index) m.multicast_address[index] = multicast_address[index]; m.interface_index = interface_index; return setsockopt(static_cast<SOCKET>(handle), IPPROTO_TCP, socket_option_name_to_native(socket_option_name), reinterpret_cast<const char*>(&m), static_cast<int32_t>(sizeof(multicast))); } int32_t socket::shutdown(intptr_t handle, int32_t how) { return ::shutdown(static_cast<SOCKET>(handle), how); } void socket::startup() { static WORD version_requested = MAKEWORD(2, 2); static WSADATA wsa_data = {0}; WSAStartup(version_requested, &wsa_data); }
60.498328
1,023
0.779535
gammasoft71
9889c6f9277040707bed82dfc5ce1110184f66d5
2,104
cpp
C++
GUICheckbox.cpp
Magtheridon96/Unfinished-RPG
f002a7e19684f31e6158ca78e24bdd514932d72c
[ "MIT" ]
1
2015-09-14T13:19:16.000Z
2015-09-14T13:19:16.000Z
GUICheckbox.cpp
Magtheridon96/Unfinished-RPG
f002a7e19684f31e6158ca78e24bdd514932d72c
[ "MIT" ]
null
null
null
GUICheckbox.cpp
Magtheridon96/Unfinished-RPG
f002a7e19684f31e6158ca78e24bdd514932d72c
[ "MIT" ]
null
null
null
#include "GUICheckbox.h" #include "Context.h" gui::check_box::check_box(const std::string& p_label, int p_x, int p_y, int p_size) : state(false) , label(p_label) , size(p_size) { set_callback([this] { state = !state; }); set_x(p_x); set_y(p_y); if (label != "") { const sf::Font& text_font = resource_cache::get_font(resource_directory::get("font")); auto text_dimensions = find_text_dimensions(label, text_font, size); set_width(size + static_cast<unsigned int>(text_dimensions.x) + 4); } else { set_width(size); } set_height(size); } gui::check_box::~check_box() { } bool gui::check_box::handle_event(context& context) { bool handled = gui::callbackable::handle_event(context); return handled; } void gui::check_box::draw(context& context) { const sf::Texture& button_texture = resource_cache::get_texture(resource_directory::get("editor_button")); sf::Texture& tick_texture = resource_cache::get_texture(resource_directory::get("tick")); const sf::Font& text_font = resource_cache::get_font(resource_directory::get("font")); tick_texture.setSmooth(true); // Draw checkbox sf::Sprite checkbox(button_texture); checkbox.scale(size / checkbox.getLocalBounds().width, size / checkbox.getLocalBounds().height); checkbox.setPosition(static_cast<float>(x), static_cast<float>(y)); context.window.draw(checkbox); if (state) { // Draw tick if its on. sf::Sprite tick(tick_texture); tick.setScale(size / 24.0f, size / 24.0f); tick.setPosition(math::floor(x + checkbox.getGlobalBounds().width/2 - tick.getGlobalBounds().width/2), math::floor(y + checkbox.getGlobalBounds().height/2 - tick.getGlobalBounds().height/2)); context.window.draw(tick); } if (label != "") { sf::Text text(label, text_font, height); text.setColor(colors::white); text.setPosition(static_cast<float>(x + size) + 4.0f, static_cast<float>(y)); context.window.draw(text); } }
33.935484
113
0.647814
Magtheridon96
988c4200da0ddfdd9902759e819c734fb996dee2
468
hpp
C++
src/chp13/employee.hpp
gianscarpe/cpp_primer
f09c645449d9b79e7c77dde13381513dee25519a
[ "MIT" ]
null
null
null
src/chp13/employee.hpp
gianscarpe/cpp_primer
f09c645449d9b79e7c77dde13381513dee25519a
[ "MIT" ]
null
null
null
src/chp13/employee.hpp
gianscarpe/cpp_primer
f09c645449d9b79e7c77dde13381513dee25519a
[ "MIT" ]
null
null
null
#ifndef EMPLOYEE_H #define EMPLOYEE_H #include <string> class Employee{ public: static int counter; Employee(std::string _name) : name(_name) { id = counter++; } Employee(const Employee& e){ name = e.name; id = counter++; } Employee& operator=(const Employee& e){ name = e.name; id = counter++; return *this; } friend void print(const Employee&); private: int id; std::string name; }; int Employee::counter = 0; #endif
16.137931
45
0.630342
gianscarpe
988c7809c5520bacc7fcffcab5196747afdde658
1,428
cpp
C++
BUPT 2021 Winter Training #10/k.cpp
rakty/2022-spring-training
db36ad3838945d2bb3a951f9ccd8dfa6f0916d0d
[ "MIT" ]
1
2022-03-04T15:11:33.000Z
2022-03-04T15:11:33.000Z
BUPT 2021 Winter Training #10/k.cpp
rakty/2022-spring-training
db36ad3838945d2bb3a951f9ccd8dfa6f0916d0d
[ "MIT" ]
null
null
null
BUPT 2021 Winter Training #10/k.cpp
rakty/2022-spring-training
db36ad3838945d2bb3a951f9ccd8dfa6f0916d0d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define endl "\n" #define ll long long //const int inf=0x7fffffff; const int inf = 0x3f3f3f3f; int t, n, a, b, k, f; void solve() { cin >> n >> a >> b >> k >> f; vector<pair<string, string>>s(n); map<pair<string, string>, int> mp; int ans = a, temp; for (int i = 0; i < n; i++) { cin >> s[i].first >> s[i].second; } vector<pair<string, string>>resss = s; if (resss[0].first > resss[0].second) swap(resss[0].first, resss[0].second); mp[resss[0]] += ans; for (int i = 1; i < n; i++) { temp = ans; if (s[i].first == s[i - 1].second) ans += b; else ans += a; if (resss[i].first > resss[i].second) swap(resss[i].first, resss[i].second); mp[resss[i]] += ans - temp; } int flag = 0; vector<int>ress; for (auto x : mp) { ress.push_back(x.second); //cout<<x.first.first<<" "<<x.first.second<<" "<<x.second<<endl; } sort(ress.begin(), ress.end()); for (int i = ress.size() - 1; i >= 0; i--) { if (flag == k) break; if (ress[i] <= f) break; ans -= ress[i]; ans += f; flag++; if (flag == k) break; } cout << ans << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); t = 1; while (t--) { solve(); } return 0; }
24.20339
84
0.487395
rakty
989aceb1a0cda59239ab2e4a6247f902a47535f3
1,975
hpp
C++
pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/global/GlobalSfM_rotation_averaging.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
90
2019-05-19T03:48:23.000Z
2022-02-02T15:20:49.000Z
pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/global/GlobalSfM_rotation_averaging.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
11
2019-05-22T07:45:46.000Z
2021-05-20T01:48:26.000Z
pose_refinement/SA-LMPE/ba/openMVG/sfm/pipelines/global/GlobalSfM_rotation_averaging.hpp
Aurelio93/satellite-pose-estimation
46957a9bc9f204d468f8fe3150593b3db0f0726a
[ "MIT" ]
18
2019-05-19T03:48:32.000Z
2021-05-29T18:19:16.000Z
// This file is part of OpenMVG, an Open Multiple View Geometry C++ library. // Copyright (c) 2015 Pierre MOULON. // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef OPENMVG_SFM_GLOBAL_ENGINE_PIPELINES_GLOBAL_ROTATION_AVERAGING_HPP #define OPENMVG_SFM_GLOBAL_ENGINE_PIPELINES_GLOBAL_ROTATION_AVERAGING_HPP #include <vector> namespace openMVG { namespace sfm { enum ERotationAveragingMethod { ROTATION_AVERAGING_L1 = 1, ROTATION_AVERAGING_L2 = 2 }; enum ERelativeRotationInferenceMethod { TRIPLET_ROTATION_INFERENCE_NONE = 0, TRIPLET_ROTATION_INFERENCE_COMPOSITION_ERROR = 1 }; } // namespace sfm } // namespace openMVG namespace openMVG { namespace graph { struct Triplet; } } #include "openMVG/types.hpp" #include "openMVG/multiview/rotation_averaging_common.hpp" namespace openMVG { namespace sfm { class GlobalSfM_Rotation_AveragingSolver { private: mutable Pair_Set used_pairs; // pair that are considered as valid by the rotation averaging solver public: bool Run( ERotationAveragingMethod eRotationAveragingMethod, ERelativeRotationInferenceMethod eRelativeRotationInferenceMethod, const rotation_averaging::RelativeRotations & relativeRot_In, Hash_Map<IndexT, Mat3> & map_globalR ) const; /// Reject edges of the view graph that do not produce triplets with tiny /// angular error once rotation composition have been computed. void TripletRotationRejection( const double max_angular_error, std::vector<graph::Triplet> & vec_triplets, rotation_averaging::RelativeRotations & relativeRotations) const; /// Return the pairs validated by the GlobalRotation routine (inference can remove some) Pair_Set GetUsedPairs() const; }; } // namespace sfm } // namespace openMVG #endif // OPENMVG_SFM_GLOBAL_ENGINE_PIPELINES_GLOBAL_ROTATION_AVERAGING_HPP
29.477612
100
0.787848
Aurelio93
989c6bf4799c7224060564ca1d073ddfbff46e0c
1,097
cpp
C++
pass/lnast_print/pass_lnast_print.cpp
realdavidpang/livehd
c0462922400d34c0327b4aabb450332bda50f174
[ "BSD-3-Clause" ]
46
2018-05-31T23:07:02.000Z
2019-09-16T20:21:03.000Z
pass/lnast_print/pass_lnast_print.cpp
realdavidpang/livehd
c0462922400d34c0327b4aabb450332bda50f174
[ "BSD-3-Clause" ]
120
2018-05-16T23:11:09.000Z
2019-09-25T18:52:49.000Z
pass/lnast_print/pass_lnast_print.cpp
realdavidpang/livehd
c0462922400d34c0327b4aabb450332bda50f174
[ "BSD-3-Clause" ]
8
2018-11-08T18:53:52.000Z
2019-09-05T20:04:20.000Z
// This file is distributed under the BSD 3-Clause License. See LICENSE for details. #include "pass_lnast_print.hpp" #include "lnast_writer.hpp" #include <fstream> #include <ostream> #include <iostream> static Pass_plugin sample("pass_lnast_print", Pass_lnast_print::setup); Pass_lnast_print::Pass_lnast_print(const Eprp_var& var) : Pass("pass.lnast_print", var) {} void Pass_lnast_print::setup() { Eprp_method m1("pass.lnast_print", "Print LNAST in textual form to the terminal or a specified file", &Pass_lnast_print::do_work); m1.add_label_optional("odir", "output directory"); register_pass(m1); } void Pass_lnast_print::do_work(const Eprp_var& var) { Pass_lnast_print pass(var); auto odir = pass.get_odir(var); bool has_file_output = (odir != "/INVALID"); for (const auto &lnast : var.lnasts) { std::fstream fs; if (has_file_output) { fs.open(absl::StrCat(odir, "/", lnast->get_top_module_name(), ".ln"), std::fstream::out); } std::ostream &os = (has_file_output) ? fs : std::cout; Lnast_writer writer(os, lnast); writer.write_all(); } }
31.342857
132
0.709207
realdavidpang
98a02a22ec0da77d3923487ae14f1a256fa57d08
704
cpp
C++
origin_code/d.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
origin_code/d.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
origin_code/d.cpp
vectordb-io/vstl
1cd35add1a28cc1bcac560629b4a49495fe2b065
[ "Apache-2.0" ]
null
null
null
// function for Chapter 2 exercise #include <iostream> #include <algorithm> using namespace std; void d(int x[], int n) { for (int i = 0; i < n; i += 2) x[i] += 2; i = 1; while (i <= n/2) { x[i] += x[i+1]; i++; } } int main() { int a[15] = {1,2,3,4,5,6,7,8,9,10,0,0,0,0,0}; int n = 10; // output the array elements cout << "a[0:9] = "; copy(a, a+10, ostream_iterator<int>(cout, " ")); cout << endl; d(a,n); cout << "Completed function d(y,10)" << endl; // output the array elements cout << "a[0:9] = "; copy(a, a+10, ostream_iterator<int>(cout, " ")); cout << endl; return 0; }
16.761905
52
0.46733
vectordb-io
f0f9ce7929d400f516c460bc7b3b284787cf5bf9
7,856
cc
C++
arccore/src/message_passing/arccore/message_passing/SerializeMessageList.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
16
2021-09-20T12:37:01.000Z
2022-03-18T09:19:14.000Z
arccore/src/message_passing/arccore/message_passing/SerializeMessageList.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
66
2021-09-17T13:49:39.000Z
2022-03-30T16:24:07.000Z
arccore/src/message_passing/arccore/message_passing/SerializeMessageList.cc
cedricga91/framework
143eeccb5bf375df4a3f11b888681f84f60380c6
[ "Apache-2.0" ]
11
2021-09-27T16:48:55.000Z
2022-03-23T19:06:56.000Z
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* SerializeMessageList.cc (C) 2000-2020 */ /* */ /* Liste de messages de sérialisation. */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #include "arccore/message_passing/SerializeMessageList.h" #include "arccore/message_passing/IRequestList.h" #include "arccore/message_passing/BasicSerializeMessage.h" #include "arccore/message_passing/Messages.h" #include "arccore/base/NotImplementedException.h" #include "arccore/base/FatalErrorException.h" #include <algorithm> /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace Arccore::MessagePassing::internal { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ SerializeMessageList:: SerializeMessageList(IMessagePassingMng* mpm) : m_message_passing_mng(mpm) , m_request_list(mpCreateRequestListRef(mpm)) , m_message_passing_phase(timeMetricPhaseMessagePassing(mpm->timeMetricCollector())) { } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void SerializeMessageList:: addMessage(ISerializeMessage* message) { BasicSerializeMessage* true_message = dynamic_cast<BasicSerializeMessage*>(message); if (!true_message) ARCCORE_FATAL("Can not convert 'ISerializeMessage' to 'BasicSerializeMessage'"); m_messages_to_process.add(true_message); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void SerializeMessageList:: processPendingMessages() { for( BasicSerializeMessage* sm : m_messages_to_process ){ PointToPointMessageInfo message_info(buildMessageInfo(sm)); if (sm->destination().isNull() && !m_allow_any_rank_receive){ // Il faudra faire un probe pour ce message m_messages_to_probe.add({sm,message_info}); } else _addMessage(sm,message_info); sm->setIsProcessed(true); } m_messages_to_process.clear(); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Integer SerializeMessageList:: waitMessages(eWaitType wait_type) { processPendingMessages(); // NOTE: il faudrait peut-être faire aussi faire des probe() dans l'appel // à _waitMessages() car il est possible que tous les messages n'aient pas // été posté. Dans ce cas, il faudrait passer en mode non bloquant tant // qu'il y a des probe à faire while(!m_messages_to_probe.empty()) _doProbe(); return _waitMessages(wait_type); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void SerializeMessageList:: _doProbe() { // Il faut tester avec probe() si des messages sont disponibles for( ProbeInfo& p : m_messages_to_probe ){ //tm->info() << "CHECK PROBE msg=" << p.m_message_info << " is_done?=" << p.m_is_probe_done; // Ne devrait pas être 'vrai' mais par sécurité on fait le test. if (p.m_is_probe_done) continue; MessageId message_id = mpProbe(m_message_passing_mng,p.m_message_info); if (message_id.isValid()){ //tm->info() << "FOUND PROBE message_id=" << message_id; PointToPointMessageInfo message_info(message_id,NonBlocking); _addMessage(p.m_serialize_message,message_info); p.m_is_probe_done = true; } } // Supprime les probes qui sont terminés. auto k = std::remove_if(m_messages_to_probe.begin(),m_messages_to_probe.end(), [](const ProbeInfo& p) { return p.m_is_probe_done; }); m_messages_to_probe.resize(k-m_messages_to_probe.begin()); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Integer SerializeMessageList:: _waitMessages(eWaitType wait_type) { TimeMetricSentry tphase(m_message_passing_phase); if (wait_type==WaitAll){ m_request_list->wait(WaitAll); // Indique que les messages sont bien terminés for( ISerializeMessage* sm : m_messages_serialize ) sm->setFinished(true); m_request_list->clear(); m_messages_serialize.clear(); return (-1); } if (wait_type==WaitSome || wait_type==TestSome){ Integer nb_request = m_request_list->size(); m_request_list->wait(wait_type); m_remaining_serialize_messages.clear(); Integer nb_done = 0; for( Integer i=0; i<nb_request; ++i ){ BasicSerializeMessage* sm = m_messages_serialize[i]; if (m_request_list->isRequestDone(i)){ ++nb_done; sm->setFinished(true); } else{ m_remaining_serialize_messages.add(sm); } } m_request_list->removeDoneRequests(); m_messages_serialize = m_remaining_serialize_messages; if (nb_done==nb_request) return (-1); return nb_done; } ARCCORE_THROW(NotImplementedException,"waitMessage with wait_type=={0}",(int)wait_type); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void SerializeMessageList:: _addMessage(BasicSerializeMessage* sm,const PointToPointMessageInfo& message_info) { Request r; ISerializer* s = sm->serializer(); if (sm->isSend()) r = mpSend(m_message_passing_mng,s,message_info); else r = mpReceive(m_message_passing_mng,s,message_info); m_request_list->add(r); m_messages_serialize.add(sm); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ PointToPointMessageInfo SerializeMessageList:: buildMessageInfo(ISerializeMessage* sm) { MessageId message_id(sm->_internalMessageId()); if (message_id.isValid()){ PointToPointMessageInfo message_info(message_id,NonBlocking); message_info.setSourceRank(sm->source()); return message_info; } return { sm->source(), sm->destination(), sm->internalTag(), NonBlocking }; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ Ref<ISerializeMessage> SerializeMessageList:: createAndAddMessage(MessageRank destination,ePointToPointMessageType type) { MessageRank source(m_message_passing_mng->commRank()); auto x = BasicSerializeMessage::create(source,destination,type); addMessage(x.get()); return x; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // End namespace Arcane::MessagePassing /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
37.588517
96
0.502037
cedricga91
0b0127cd0c6c2815889dde2d9e5e7755c47094d7
1,310
cc
C++
lib/ui/painting/image.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
null
null
null
lib/ui/painting/image.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
null
null
null
lib/ui/painting/image.cc
alibitek/engine
0f0b144b0320d00d837fb2af80cd542ab1359491
[ "BSD-3-Clause" ]
1
2020-03-05T02:44:12.000Z
2020-03-05T02:44:12.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/lib/ui/painting/image.h" #include "flutter/common/threads.h" #include "flutter/lib/ui/painting/utils.h" #include "lib/tonic/converter/dart_converter.h" #include "lib/tonic/dart_args.h" #include "lib/tonic/dart_binding_macros.h" #include "lib/tonic/dart_library_natives.h" namespace blink { typedef CanvasImage Image; IMPLEMENT_WRAPPERTYPEINFO(ui, Image); #define FOR_EACH_BINDING(V) \ V(Image, width) \ V(Image, height) \ V(Image, dispose) FOR_EACH_BINDING(DART_NATIVE_CALLBACK) void CanvasImage::RegisterNatives(tonic::DartLibraryNatives* natives) { natives->Register({FOR_EACH_BINDING(DART_REGISTER_NATIVE)}); } CanvasImage::CanvasImage() {} CanvasImage::~CanvasImage() { // Skia objects must be deleted on the IO thread so that any associated GL // objects will be cleaned up through the IO thread's GL context. SkiaUnrefOnIOThread(&image_); } void CanvasImage::dispose() { ClearDartWrapper(); } size_t CanvasImage::GetAllocationSize() { if (image_) { return image_->width() * image_->height() * 4; } else { return sizeof(CanvasImage); } } } // namespace blink
25.192308
76
0.730534
alibitek
0b035cdafea27f5861f8050bec3addbba883aa00
1,724
hpp
C++
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/socket/tcp_acceptor.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/socket/tcp_acceptor.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/rubetek/socket/tcp_acceptor.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
#pragma once #include <msw/noncopyable.hpp> #include <msw/asio/tcp_acceptor.hpp> #include <msw/lexical_cast/network/endpoint/to_string.hpp> #include <msw/lexical_cast/network/endpoint/from_string.hpp> namespace rubetek { struct tcp_acceptor : msw::noncopyable { typedef msw::tcp_acceptor::io_service io_service ; typedef msw::tcp_acceptor::endpoint endpoint ; typedef msw::tcp_acceptor::on_accept on_accept ; tcp_acceptor (boost::asio::io_service&, msw::wbyte port, on_accept) ; tcp_acceptor (boost::asio::io_service&, endpoint , on_accept) ; private: logger const logger_ ; msw::tcp_acceptor tcp_acceptor_ ; }; } namespace rubetek { inline tcp_acceptor::tcp_acceptor(boost::asio::io_service& io_service, endpoint endpoint, on_accept on_accept) : logger_ ( "tcp acceptor", msw::network_endpoint_to_string(endpoint), log::level::info) , tcp_acceptor_ ( io_service , endpoint , [this, on_accept](boost::asio::ip::tcp::socket socket) { logger_.debug("accepted new connection: ", msw::network_endpoint_to_string(socket.remote_endpoint())); on_accept(std::move(socket)); } , [this](boost::system::error_code ec) { logger_.error(ec.message()); throw boost::system::system_error(ec); } ) {} inline tcp_acceptor::tcp_acceptor(boost::asio::io_service& io_service, msw::wbyte port, on_accept on_accept) : tcp_acceptor (io_service, msw::tcp_endpoint_from_string("0.0.0.0", port), on_accept) {} }
32.528302
118
0.61949
yklishevich
0b077a221f8f1e994f8c9141b207ad6ad5078ef3
733
hh
C++
styler.hh
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
styler.hh
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
styler.hh
jdb19937/makemore
61297dd322b3a9bb6cdfdd15e8886383cb490534
[ "MIT" ]
null
null
null
#ifndef __MAKEMORE_STYLER_HH__ #define __MAKEMORE_STYLER_HH__ 1 #include <string.h> #include <stdlib.h> #include <string> #include <map> #include "project.hh" #include "cholo.hh" namespace makemore { struct Styler : Project { double *tmp; unsigned int dim; std::map<std::string, Cholo*> tag_cholo; double *msamp, *fsamp; unsigned int msampn, fsampn; Styler(const std::string &dir); ~Styler() { delete[] tmp; } void add_cholo(const std::string &tag, const std::string &fn) { assert(tag_cholo.find(tag) == tag_cholo.end()); tag_cholo[tag] = new Cholo(fn, dim); } void encode(const double *ctr, Parson *prs); void generate(const Parson &prs, double *ctr, unsigned int m = 1); }; } #endif
17.878049
68
0.673943
jdb19937
0b0bf34cddfcaaf99c2bee8de7bb780719217fed
2,689
cpp
C++
src/modules/keyboardmanager/KeyboardManagerEditorLibrary/KeyboardManagerEditorStrings.cpp
tameemzabalawi/PowerToys
5c6f7b1aea90ecd9ebe5cb8c7ddf82f8113fcb45
[ "MIT" ]
76,518
2019-05-06T22:50:10.000Z
2022-03-31T22:20:54.000Z
src/modules/keyboardmanager/KeyboardManagerEditorLibrary/KeyboardManagerEditorStrings.cpp
Nakatai-0322/PowerToys
1f64c1cf837ca958ad14dc3eb7887f36220a1ef9
[ "MIT" ]
15,530
2019-05-07T01:10:24.000Z
2022-03-31T23:48:46.000Z
src/modules/keyboardmanager/KeyboardManagerEditorLibrary/KeyboardManagerEditorStrings.cpp
Nakatai-0322/PowerToys
1f64c1cf837ca958ad14dc3eb7887f36220a1ef9
[ "MIT" ]
5,184
2019-05-06T23:32:32.000Z
2022-03-31T15:43:25.000Z
#include "pch.h" #include "KeyboardManagerEditorStrings.h" // Function to return the error message winrt::hstring KeyboardManagerEditorStrings::GetErrorMessage(ShortcutErrorType errorType) { switch (errorType) { case ShortcutErrorType::NoError: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_REMAPSUCCESSFUL).c_str(); case ShortcutErrorType::SameKeyPreviouslyMapped: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SAMEKEYPREVIOUSLYMAPPED).c_str(); case ShortcutErrorType::MapToSameKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_MAPPEDTOSAMEKEY).c_str(); case ShortcutErrorType::ConflictingModifierKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_CONFLICTINGMODIFIERKEY).c_str(); case ShortcutErrorType::SameShortcutPreviouslyMapped: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SAMESHORTCUTPREVIOUSLYMAPPED).c_str(); case ShortcutErrorType::MapToSameShortcut: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_MAPTOSAMESHORTCUT).c_str(); case ShortcutErrorType::ConflictingModifierShortcut: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_CONFLICTINGMODIFIERSHORTCUT).c_str(); case ShortcutErrorType::WinL: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_WINL).c_str(); case ShortcutErrorType::CtrlAltDel: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_CTRLALTDEL).c_str(); case ShortcutErrorType::RemapUnsuccessful: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_REMAPUNSUCCESSFUL).c_str(); case ShortcutErrorType::SaveFailed: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SAVEFAILED).c_str(); case ShortcutErrorType::ShortcutStartWithModifier: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SHORTCUTSTARTWITHMODIFIER).c_str(); case ShortcutErrorType::ShortcutCannotHaveRepeatedModifier: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SHORTCUTNOREPEATEDMODIFIER).c_str(); case ShortcutErrorType::ShortcutAtleast2Keys: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SHORTCUTATLEAST2KEYS).c_str(); case ShortcutErrorType::ShortcutOneActionKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SHORTCUTONEACTIONKEY).c_str(); case ShortcutErrorType::ShortcutNotMoreThanOneActionKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_SHORTCUTMAXONEACTIONKEY).c_str(); case ShortcutErrorType::ShortcutMaxShortcutSizeOneActionKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_MAXSHORTCUTSIZE).c_str(); case ShortcutErrorType::ShortcutDisableAsActionKey: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_DISABLEASACTIONKEY).c_str(); default: return GET_RESOURCE_STRING(IDS_ERRORMESSAGE_DEFAULT).c_str(); } }
54.877551
90
0.804016
tameemzabalawi