blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
f275b68c90f0f091dac880c763fd2fae0a172c89
69b32b79c7a62590b1e21ac98e3475be1e19a912
/contrib/autoboost/autoboost/preprocessor/list/reverse.hpp
a70debfe758d940d47f883d34450f089e0785fd4
[ "Apache-2.0" ]
permissive
codemercenary/autowiring
636596d1ece37ea75003cd5180299c4adc070869
b2775e86cd29fc3e9bc50f3f5f9e735efdbcff21
refs/heads/master
2020-12-25T00:29:08.143286
2016-08-19T23:49:16
2016-08-19T23:49:16
22,248,790
0
1
null
null
null
null
UTF-8
C++
false
false
1,551
hpp
reverse.hpp
# /* Copyright (C) 2001 # * Housemarque Oy # * http://www.housemarque.com # * # * 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) # */ # # /* Revised by Paul Mensonides (2002) */ # # /* See http://www.boost.org for most recent version. */ # # ifndef AUTOBOOST_PREPROCESSOR_LIST_REVERSE_HPP # define AUTOBOOST_PREPROCESSOR_LIST_REVERSE_HPP # # include <autoboost/preprocessor/config/config.hpp> # include <autoboost/preprocessor/list/fold_left.hpp> # # /* AUTOBOOST_PP_LIST_REVERSE */ # # if ~AUTOBOOST_PP_CONFIG_FLAGS() & AUTOBOOST_PP_CONFIG_EDG() # define AUTOBOOST_PP_LIST_REVERSE(list) AUTOBOOST_PP_LIST_FOLD_LEFT(AUTOBOOST_PP_LIST_REVERSE_O, AUTOBOOST_PP_NIL, list) # else # define AUTOBOOST_PP_LIST_REVERSE(list) AUTOBOOST_PP_LIST_REVERSE_I(list) # define AUTOBOOST_PP_LIST_REVERSE_I(list) AUTOBOOST_PP_LIST_FOLD_LEFT(AUTOBOOST_PP_LIST_REVERSE_O, AUTOBOOST_PP_NIL, list) # endif # # define AUTOBOOST_PP_LIST_REVERSE_O(d, s, x) (x, s) # # /* AUTOBOOST_PP_LIST_REVERSE_D */ # # if ~AUTOBOOST_PP_CONFIG_FLAGS() & AUTOBOOST_PP_CONFIG_EDG() # define AUTOBOOST_PP_LIST_REVERSE_D(d, list) AUTOBOOST_PP_LIST_FOLD_LEFT_ ## d(AUTOBOOST_PP_LIST_REVERSE_O, AUTOBOOST_PP_NIL, list) # else # define AUTOBOOST_PP_LIST_REVERSE_D(d, list) AUTOBOOST_PP_LIST_REVERSE_D_I(d, list) # define AUTOBOOST_PP_LIST_REVERSE_D_I(d, list) AUTOBOOST_PP_LIST_FOLD_LEFT_ ## d(AUTOBOOST_PP_LIST_REVERSE_O, AUTOBOOST_PP_NIL, list) # endif # # endif
6eb41a4bf5f12f0ad448f8827331593af7f90718
9d08f0ad9b6847045caf28978a697ad8abeeb63a
/esp32_WiFiManager_Basic.ino
72c9f6b49a5e600a9dab0a3910e41c8f7d0992ea
[]
no_license
alifainur/mtech
21b1bd9e4aee2552279e861e35761e4cc72c924f
630dabf5e605aeddcbbaca960f61a3ef0b84f108
refs/heads/master
2022-12-07T10:05:26.139838
2022-11-29T15:42:03
2022-11-29T15:42:03
225,377,072
0
0
null
null
null
null
UTF-8
C++
false
false
400
ino
esp32_WiFiManager_Basic.ino
#include <WiFiManager.h> void setup() { WiFi.mode(WIFI_STA); Serial.begin(115200); WiFiManager wm; wm.resetSettings(); bool res = wm.autoConnect("ESP32_Fainur","aaaaaaaa"); if(!res) { Serial.println("Failed to connect"); } else { Serial.println("connected to WiFi"); } } void loop() { // put your main code here, to run repeatedly: }
56c9e66f963842c7f78a3fb1ad04fd0105a1c8a3
b91488c44fc40559fa46182476fa10129ce2b0f8
/FootCommander.cpp
9e7f96cd88cdbe850557b95bdfd4ab968a40d87b
[ "MIT" ]
permissive
shanishalel/wargame
17b0608bb5276e3a4ca29d4255c417e7c3e1fcc5
7edb972be458dc57c0b1c59138e37a9508d8c2cc
refs/heads/master
2022-11-24T19:23:11.011009
2020-07-24T08:50:04
2020-07-24T08:50:04
274,949,067
0
0
MIT
2020-06-25T15:18:17
2020-06-25T15:18:16
null
UTF-8
C++
false
false
1,379
cpp
FootCommander.cpp
#include "FootCommander.hpp" using namespace std; /* the footcommander made all his footsoliders attack */ void FootCommander :: attack(vector<vector<Soldier *>> &board, pair<int, int> location){ Soldier *s = board[location.first][location.second]; int i=location.first; int j=location.second; for (int i = 0; i < board.size(); i++) { for (int j = 0; j < board[0].size(); j++){ Soldier *a=board[i][j]; if( a != nullptr){ if( FootSoldier *fs = dynamic_cast<FootSoldier*> (a)){ //check that it is a footsolider FootCommander *footcom = dynamic_cast<FootCommander*> (a); //if the solider is an footcommander solider //if it isn't a footcommander or it's the location we in if ( footcom == nullptr || ( i == location.first && j == location.second)) { if ( fs->getNum() == s->getNum()){ //the same player if ( fs != nullptr){//there is a footsoldier there fs->FootSoldier::attack(board , {i,j}); } } } } } } } }
0addc4e4f3e56814275d24d39324edc0d43bcdc1
57609e8e131f78abf07d8d94ed43f5e8a9686fe0
/GDBManipulator/src/ArgumentCallBackFunctions.h
a1b3144de82f999c228d80a18d56c0393132ef1a
[ "MIT" ]
permissive
intel/Dependency-Reduction-Unit-Framework
56fd45e15c1221263137e525383ac8afde8d7150
4e538d293dc738ee60462fe00ffacf0739ba720b
refs/heads/master
2023-05-27T15:28:27.066080
2022-09-07T06:24:00
2022-09-07T06:24:00
262,437,314
3
5
MIT
2020-07-08T09:16:25
2020-05-08T22:00:50
C++
UTF-8
C++
false
false
1,063
h
ArgumentCallBackFunctions.h
/** * Copyright (C) 2020 Intel Corporation * SPDX-License-Identifier: AGPL-3.0-or-later * @author: Sebastian Balz */ #ifndef GDBMANIPULATOR_ARGUMENTCALLBACKFUNCTIONS_H #define GDBMANIPULATOR_ARGUMENTCALLBACKFUNCTIONS_H #include "argvParser.h" #include "tester/TestAnalyser.h" extern string elfFile; extern string callServer; extern string callClient; extern string xmlFile; extern int gdbPort; extern bool flashTar; extern amountOfInfo testLevel; extern bool runOnTarget; extern bool cliHighlighting; extern string gdbScriptAfterExecution; extern string disabedTestGroups; extern string disabedTestGroups; extern string enabledTestGroups; enum runModeType{ testModeSetting, runModeSetting, flashModeSetting }; extern runModeType executionMode; extern bool failByFailedTests; /** * define all program arguments. */ argvParser *initProgramArguments(); /** * log the status of all arguments */ void logArgumentStatus(); std::ostream &operator<<(std::ostream &strm, const runModeType &a); #endif //GDBMANIPULATOR_ARGUMENTCALLBACKFUNCTIONS_H
3cbfb6c28afcbb13c61d8d9685b24a28250cb653
f012891a6066d01b4fc419bef97299f2df25e342
/Mathematics/MM40.cpp
e55582b2d070947f4507245510c72980e10bb33c
[]
no_license
wayne1116/ITSA-Online-programming
50bc0243f8a99079303801461a3b56be87b1620b
96789878f26b2af1983efdbb292c3e8614b3e456
refs/heads/master
2020-04-30T08:30:00.415952
2020-02-28T17:34:11
2020-02-28T17:34:11
176,717,738
0
0
null
null
null
null
UTF-8
C++
false
false
897
cpp
MM40.cpp
#include<stdio.h> #include<stdlib.h> int main() { int a, i, j, k, number, base, temp, number1; char result[1024]; while(scanf("%d", &a)!=EOF){ for(i=0; i<a; i++){ scanf("%d %d", &number, &base); for(j=0; j<1024; j++){ result[j]='0'; } j=0; number1=number; while(number>0){ temp=number%base; if(base>10 && temp>=10){ result[j++]=temp+55; } else{ result[j++]=temp+48; } number/=base; } for(k=j-1; k>0; k--){ printf("%c", result[k]); } printf("%c\n", result[0]); } } return 0; }
ab626f5f2f2963a99b8091135cc11abaeb4a5e16
37a7732ce1f30349aaa36955c892dd8c2626bae4
/pea/BB.cpp
c40b387d2b75e612c7a013bd7ee4cce4f34e10f2
[]
no_license
tomekflorczuk/TravellingSalesmanProblem
4a3f275ab772676ac337fefc3715ac82dcc836f8
6c3896426fd59bb9b4da651483b74a4ab4440030
refs/heads/master
2020-05-24T05:35:11.360123
2019-05-17T01:08:22
2019-05-17T01:08:22
187,119,896
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
2,457
cpp
BB.cpp
#include "BB.h" int* BB::visited; int BB::Size; int BB::it; int BB::startingpoint; int BB::currentpoint; int BB::cost; int BB::mincost; vector<int> BB::points; vector<int> BB::minpoints; //Konstruktor BB::BB() { Size = Data::GetSize(); visited = new int[Size]; for (int i = 0; i < Size; ++i) visited[i] = 0; startingpoint = 0; cost = 0; it = 0; currentpoint = startingpoint; mincost = INT_MAX; for (int i = 1; i < Size; i++) points.push_back(i); } //Destruktor BB::~BB() { } //Dostęp do wierzchołka startowego int BB::GetStartingPoint() { return startingpoint; } //Metoda podziału i ograniczeń void BB::BranchAndBound(int currentpoint) { if (it != Size - 1) { visited[currentpoint] = 1; for (int i = 1; i < Size; i++) { if (visited[i] == 1) continue; if (Boundary(i) > mincost) continue;; cost = cost + Data::GetCost(currentpoint, i); points[it] = i; it++; BranchAndBound(i); cost = cost - Data::GetCost(currentpoint, i); } } else { cost = cost + Data::GetCost(currentpoint, startingpoint); if (cost < mincost) { mincost = cost; minpoints = points; } cost = cost - Data::GetCost(currentpoint, startingpoint); } visited[currentpoint] = 0; it--; } //Obliczanie granicy int BB::Boundary(int currentpoint) { int mincost; int bound = 0; int result = cost; for (int i = 0; i < Size; i++) { if (visited[i] == true) continue; mincost = INT_MAX; for(int j = 1; j < Size; j++)//Koszty wyjścia z wierzchołka { if(visited[j] == 1 || i == j) continue; if (Data::GetCost(i, j) < mincost) mincost = Data::GetCost(i, j); } if (Data::GetCost(i, startingpoint) < mincost) mincost = Data::GetCost(i, startingpoint); bound = bound + mincost; mincost = INT_MAX; for (int j = 0; j < Size; j++)//Koszty wejścia do wierzchołka { if (visited[j] == 1 || i == j) continue; if (Data::GetCost(j, i) < mincost) mincost = Data::GetCost(j, i); } if (Data::GetCost(currentpoint, i) < mincost) mincost = Data::GetCost(currentpoint, i); bound = bound + mincost; } return result + bound / 2; } //Wyświetlenie wyniku void BB::ShowResult() { cout << "0->"; for (int i = 0; i < Size - 1; i++) { cout << minpoints[i] << "->"; } cout << "0"; cout << endl; cout << "$" << mincost << endl; } //Zwalnianie pamięci void BB::Clear() { delete[] visited; while (!points.empty()) points.pop_back(); while (!minpoints.empty()) minpoints.pop_back(); }
00b9b4770eb5e815b8b3e4249ea821f9bf0f3400
7ef33fe1a49ea76c1132235b864790d82f595014
/src/index.h
4961112feb733ed7dabd07cf9c7038e3d9cb3df0
[ "BSD-3-Clause" ]
permissive
gear-genomics/tracy
91ae9891b4fc4a1931279e913f46d04ce26b9c8c
970bb5b51e25f8f592a3dcd19dd38a4e9bdc0662
refs/heads/main
2023-04-14T02:16:09.872971
2023-04-12T07:13:28
2023-04-12T07:13:28
137,339,828
91
17
BSD-3-Clause
2023-04-07T11:38:13
2018-06-14T09:54:24
C++
UTF-8
C++
false
false
4,523
h
index.h
#ifndef INDEX_H #define INDEX_H #include <sdsl/suffix_arrays.hpp> #include <fstream> #include <iomanip> #include <boost/dynamic_bitset.hpp> #include <boost/program_options/cmdline.hpp> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/date_time/gregorian/gregorian.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/stream_buffer.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/filesystem.hpp> using namespace sdsl; namespace tracy { struct IndexConfig { boost::filesystem::path genome; boost::filesystem::path outfile; }; int index(int argc, char** argv) { IndexConfig c; // Parameter boost::program_options::options_description generic("Generic options"); generic.add_options() ("help,?", "show help message") ("output,o", boost::program_options::value<boost::filesystem::path>(&c.outfile)->default_value("genome.fm9"), "output file") ; boost::program_options::options_description hidden("Hidden options"); hidden.add_options() ("input-file", boost::program_options::value<boost::filesystem::path>(&c.genome), "bgzipped genome file") ; boost::program_options::positional_options_description pos_args; pos_args.add("input-file", -1); boost::program_options::options_description cmdline_options; cmdline_options.add(generic).add(hidden); boost::program_options::options_description visible_options; visible_options.add(generic); boost::program_options::variables_map vm; boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(pos_args).run(), vm); boost::program_options::notify(vm); // Check command line arguments if ((vm.count("help")) || (!vm.count("input-file"))) { std::cout << "Usage: tracy " << argv[0] << " [OPTIONS] genome.fa.gz" << std::endl; std::cout << visible_options << "\n"; return -1; } // Show cmd boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); std::cout << '[' << boost::posix_time::to_simple_string(now) << "] "; std::cout << "tracy "; for(int i=0; i<argc; ++i) { std::cout << argv[i] << ' '; } std::cout << std::endl; // Reference index csa_wt<> fm_index; // What kind of reference? std::ifstream ifile(c.genome.string().c_str(), std::ios::binary | std::ios::in); if (ifile.is_open()) { char fcode[4]; ifile.seekg(0); ifile.read(fcode, 4); if (((uint8_t)fcode[0] == (uint8_t)0x1f) && ((uint8_t)fcode[1] == (uint8_t)0x8b)) { boost::filesystem::path dumpfile(c.outfile.string() + ".dump"); std::string index_file = c.outfile.string(); // Load FM index now = boost::posix_time::second_clock::local_time(); if (!load_from_checked_file(fm_index, index_file)) { std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Prepare FM-Index" << std::endl; // Dump fasta bool firstSeq = true; std::ofstream tmpout(dumpfile.string().c_str()); std::ifstream file(c.genome.string().c_str(), std::ios_base::in | std::ios_base::binary); boost::iostreams::filtering_streambuf<boost::iostreams::input> dataIn; dataIn.push(boost::iostreams::gzip_decompressor()); dataIn.push(file); std::istream instream(&dataIn); std::string line; while(std::getline(instream, line)) { if ((!line.empty()) && (line[0] == '>')) { if (!firstSeq) tmpout << std::endl; else firstSeq = false; } else { tmpout << boost::to_upper_copy(line); } } tmpout << std::endl; file.close(); tmpout.close(); now = boost::posix_time::second_clock::local_time(); std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Create FM-Index" << std::endl; // Build index construct(fm_index, dumpfile.string().c_str(), 1); store_to_checked_file(fm_index, index_file); boost::filesystem::remove(dumpfile); } } ifile.close(); } now = boost::posix_time::second_clock::local_time(); std::cout << '[' << boost::posix_time::to_simple_string(now) << "] " << "Done." << std::endl; return 0; } } #endif
9983708af8defa196289f40569540a6209792a0f
e5f57aae37a480cf40180d0a5664aaab5a0c0341
/vaca/Application.cpp
c5b2ec888997f17150aa1f881a7ae9d76a654bc1
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
TheLightWay/vaca
6ddabf0cd12a46583b03cddc99d2b13da87a4e41
95728e6a5c41d9fe2c731f7767b7334b623f41ed
refs/heads/master
2023-06-10T09:47:28.085286
2023-04-12T02:52:15
2023-04-12T02:52:15
149,952,301
0
0
MIT
2018-09-23T05:56:48
2018-09-23T05:56:48
null
UTF-8
C++
false
false
4,866
cpp
Application.cpp
// Vaca - Visual Application Components Abstraction // Copyright (c) 2005-2010 David Capello // // This file is distributed under the terms of the MIT license, // please read LICENSE.txt for more information. #ifdef VACA_WINDOWS #include <windows.h> #endif #include "vaca/Application.h" #include "vaca/Debug.h" #include "vaca/Frame.h" #include "vaca/Timer.h" #include "vaca/Graphics.h" #include "vaca/Font.h" #ifndef NDEBUG #include "vaca/System.h" #endif using namespace vaca; HINSTANCE Application::m_HINSTANCE = NULL; Application* Application::m_instance = NULL; std::vector<String> Application::m_args; /** Initializes the variables of the Application class. @win32 It calls @msdn{CoInitialize} and @msdn{InitCommonControls}. @endwin32 @see run */ Application::Application() : Thread() { assert(Application::m_HINSTANCE == NULL); assert(Application::m_instance == NULL); CoInitialize(NULL); Application::m_HINSTANCE = ::GetModuleHandle(NULL); Application::m_instance = this; INITCOMMONCONTROLSEX icce; icce.dwSize = sizeof(INITCOMMONCONTROLSEX); icce.dwICC = 0 | ICC_WIN95_CLASSES | ICC_BAR_CLASSES | ICC_COOL_CLASSES ; InitCommonControlsEx(&icce); VACA_TRACE("Application started\n"); } /** Finishes the application. @win32 It calls @msdn{CoUninitialize}. @endwin32 */ Application::~Application() { assert(Application::m_HINSTANCE != NULL); assert(Application::m_instance == this); Timer::stop_timer_thread(); Application::m_HINSTANCE = NULL; Application::m_instance = NULL; #ifndef NDEBUG Referenceable::showLeaks(); #endif VACA_TRACE("Application finished\n"); // close the log file details::removeAllThreadData(); details::closeLogFile(); CoUninitialize(); #ifdef MEMORY_LEAK_DETECTOR atexit(check_leaks); #endif } size_t Application::getArgc() { return m_args.size(); } const String& Application::getArgv(size_t i) { return m_args[i]; } /** Returns the parameters in the command line. @c Application::getArgs()[0] is the name of the executable file. */ const std::vector<String>& Application::getArgs() { return m_args; } void Application::setArgs(const std::vector<String>& args) { m_args = args; } /** Returns the Application's singleton. A program using Vaca must have one instance of Applicaton or a class derived from it. */ Application* Application::getInstance() { return m_instance; } /** Returns the Win32's @c HINSTANCE. @win32 HINSTANCE handles are specific of Windows. @endwin32 @internal */ HINSTANCE Application::getHandle() { return Application::m_HINSTANCE; } /** Changes the priority of the process respecting to all other processes currently running on the operating system. @see Thread#setThreadPriority */ void Application::setProcessPriority(ProcessPriority priority) { int nPriority; switch (priority) { case ProcessPriority::Idle: nPriority = IDLE_PRIORITY_CLASS; break; case ProcessPriority::Normal: nPriority = NORMAL_PRIORITY_CLASS; break; case ProcessPriority::High: nPriority = HIGH_PRIORITY_CLASS; break; case ProcessPriority::RealTime: nPriority = REALTIME_PRIORITY_CLASS; break; default: assert(false); // TODO throw invalid argument exception return; } ::SetPriorityClass(::GetCurrentProcess(), nPriority); } /** The common way to start the application. You should call this member function from @e WinMain, using the Application instance. The work of this routine is really simple: it calls #main and then CurrentThread#doMessageLoop. You can make your own class derived from Application and override #main so you can customized the initialization (e.g. show a Frame). Example: @code int VACA_MAIN() { Application app; Frame frm("My frame"); frm.setVisible(true); app.run(); return 0; } @endcode The same example with a variation: @code class MyApp : public Application { Frame frm; public: MyApp() : frm("My frame") { } virtual void main() { frm.setVisible(true); } }; int VACA_MAIN() { MyApp app; app.run(); return 0; } @endcode @see CurrentThread#doMessageLoop */ void Application::run() { main(); CurrentThread::doMessageLoop(); } /** The application entry point. After calling #run, #main is executed and when it finishes, the CurrentThread#doMessageLoop is automatically invoked (to process messages for visible @link Frame frames@endlink). */ void Application::main() { // do nothing }
215d93cb88bcaaa3deb36b081aed644504496a84
7eb853a4c478c5d83d18152211e11c0a52110afc
/HC-06_Config.ino
517a19db9e549a2bf572d45e183001352b132da6
[]
no_license
kmcgerald/floppy-waffle
eb7437d89f7846997166d53946d7d162e5482f65
8ea754b73cee3e7b5418731bf00cb1d71d86aea3
refs/heads/master
2021-01-15T15:36:24.445331
2020-12-21T03:54:25
2020-12-21T03:54:25
43,971,078
1
0
null
null
null
null
UTF-8
C++
false
false
1,300
ino
HC-06_Config.ino
//This is a simple sketch to setup an HC-06 Bluetooth module via an Arduino and the IDE Serial Monitor //Connect to the arduino at 9600 with No line ending //Connect the power and ground of the HC-06 to the Arduino VCC and GND and connect the module's RX to pin 11 and TX to pin 10 //Try different baud rates for "mySerial" until sending an "AT" command produces an "OK" response. /* AT : check the connection AT+NAME: Change name. No space between name and command. AT+BAUD: change baud rate, x is baud rate code, no space between command and code. AT+PIN: change pin, xxxx is the pin, again, no space. AT+VERSION AT+NAMEPROTOTYPE will set the name to PROTOTYPE. To change baud rate, type AT+BAUDX, where X=1 to 9. 1 set to 1200bps 2 set to 2400bps 3 set to 4800bps 4 set to 9600bps (Default) 5 set to 19200bps 6 set to 38400bps 7 set to 57600bps 8 set to 115200bps so sending AT+BAUD4 will set the baud rate to 9600. */ #include <SoftwareSerial.h> SoftwareSerial mySerial(10, 11); // RX, TX void setup() { Serial.begin(9600); pinMode(9,OUTPUT); digitalWrite(9,HIGH); Serial.println("Enter AT commands:"); mySerial.begin(57600); } void loop() { if (mySerial.available()) Serial.write(mySerial.read()); if (Serial.available()) mySerial.write(Serial.read()); }
5b9ca510a831714d27fd977c6a2bed9f90c9c1ef
6efc15021bdb3d32fbdedba142e8e1f4747e6deb
/ECS/Defs.hpp
7985504a4402dff31bee45d83df9aeef279cfdf3
[]
no_license
MaxUAforever/ECS
f146dc0fa1b398f4afcda61449e0281c622d9141
e97e4244662cfb143f1cb7dca29cc7fe0f36dbcb
refs/heads/main
2023-07-28T11:50:08.312004
2021-09-07T08:47:27
2021-09-07T08:47:27
396,392,706
0
0
null
null
null
null
UTF-8
C++
false
false
353
hpp
Defs.hpp
#ifndef Defs_hpp #define Defs_hpp #include <boost/uuid/uuid.hpp> #include <time.h> namespace ECS { using ComponentID = boost::uuids::uuid; using EntityID = boost::uuids::uuid; using SystemID = boost::uuids::uuid; using EventID = boost::uuids::uuid; using TypeID = boost::uuids::uuid; using Time = time_t; } // namespace ECS #endif /* Defs_hpp */
ff5fe3fde299251f26cb29891f2c417add082736
b356e4cfc0888068f4bd2a99eeb82b45274e38e3
/AddMarkEdit.cpp
37b5b76c9d115a0a9355f8e47f9e7d83d1ca152a
[]
no_license
PeratX/StudentManagementSystem
735804caec4712ce482d7111c249c146ddd1f97d
47332a9ad4d5d5f87e24320da4c1c2a3c6b92bd7
refs/heads/master
2022-11-13T03:40:49.629258
2020-07-08T12:21:15
2020-07-08T12:21:15
276,601,711
0
0
null
null
null
null
UTF-8
C++
false
false
1,281
cpp
AddMarkEdit.cpp
// AddMarkEdit.cpp: 实现文件 // #include "pch.h" #include "StudentManagementSystem.h" #include "AddMarkEdit.h" #include "afxdialogex.h" // AddMarkEdit 对话框 IMPLEMENT_DYNAMIC(AddMarkEdit, CDialogEx) AddMarkEdit::AddMarkEdit(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG_ADD_SUB_INFO, pParent) { } AddMarkEdit::~AddMarkEdit() { } void AddMarkEdit::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_EDIT_MARK, EditMark); DDX_Control(pDX, IDC_COMBO_SUB, ComboSub); } BEGIN_MESSAGE_MAP(AddMarkEdit, CDialogEx) END_MESSAGE_MAP() // AddMarkEdit 消息处理程序 void AddMarkEdit::OnOK() { info.sub = subs[ComboSub.GetCurSel()]; CString buf; EditMark.GetWindowTextW(buf); info.mark = _ttoi(buf); CDialogEx::OnOK(); } BOOL AddMarkEdit::OnInitDialog() { CDialogEx::OnInitDialog(); int i = 0; auto it = subjects->begin(); while (it != subjects->end()) { subs[i] = &it->second; CString buf; buf.Format(_T("%d | %s"), it->second.num, it->second.name); ComboSub.AddString(buf); i++; ++it; } ComboSub.SetCurSel(0); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE }
2a2c798d9a3450e9a3c8f46a1b4594e3e5763ac7
a72ddfb8e5dda0ddee9ca933964baac7d5197dff
/Classes/HelloWorldScene.cpp
ade7c4d9736b6e80076efb1e8b1cb70ab38ac05f
[]
no_license
nphgiang/ShaderDemo
195f533aa9cda98ad02140f26681f8fcaa527dfa
e9abae0f2eece43882b50242a5fd24cb3c53eb48
refs/heads/master
2021-01-22T04:53:44.898584
2015-05-13T17:27:46
2015-05-13T17:27:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
952
cpp
HelloWorldScene.cpp
#include "HelloWorldScene.h" #include "proj.win32\BlurNode.h" #include "proj.win32\PostProcessingNode.h" #include "proj.win32\BlurNode2Pass.h" #include "proj.win32\BlurNodeSampling.h" USING_NS_CC; Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !Layer::init() ) { return false; } Size winSize = Director::getInstance()->getWinSize(); BlurNodeSampling* node = BlurNodeSampling::create(); node->setAnchorPoint(Point(0.5f, 0.5f)); node->setPosition(winSize.width / 2, winSize.height / 2); addChild(node); return true; }
60295b39eabd8e5f6fb6e1eab82d205fb678af31
b05e856dd558bdcd255e81dd6660050d33a968d9
/25_qvariant/QVariabt_88/dialog.cpp
65fb607aeedb8ed552480de9a1f4b5cd99987e19
[]
no_license
DawidMaciazek/qtTutorials
337c424da7f2b81fa2fa4e3e355014b71e1d3b37
df00dcfe02e82f5157065fa9dc5cc0f5f3be26d7
refs/heads/master
2020-12-25T14:23:57.587523
2016-10-17T13:56:24
2016-10-17T13:56:24
66,942,516
0
0
null
null
null
null
UTF-8
C++
false
false
584
cpp
dialog.cpp
#include "dialog.h" #include "ui_dialog.h" #include <QVariant> #include <QDebug> #include "myclass.h" Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); QVariant v = 1233.03; qDebug() << v.toInt(); qDebug() << v.toDouble(); if(v.canConvert<QString>()) { qDebug() << v.toString(); } MyClass myclass; myclass.number = 213123; QVariant z = QVariant::fromValue(myclass); MyClass zclass = z.value<MyClass>(); qDebug() << zclass.number; } Dialog::~Dialog() { delete ui; }
a9ed42fed68fd899182e47219b1f27f168149017
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/gse/include/tencentcloud/gse/v20191112/model/CreateGameServerSessionRequest.h
9507bab26d9a98d34fd7d2ffe2d5bcdba4c71b30
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
12,659
h
CreateGameServerSessionRequest.h
/* * Copyright (c) 2017-2019 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. */ #ifndef TENCENTCLOUD_GSE_V20191112_MODEL_CREATEGAMESERVERSESSIONREQUEST_H_ #define TENCENTCLOUD_GSE_V20191112_MODEL_CREATEGAMESERVERSESSIONREQUEST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/gse/v20191112/model/GameProperty.h> namespace TencentCloud { namespace Gse { namespace V20191112 { namespace Model { /** * CreateGameServerSession请求参数结构体 */ class CreateGameServerSessionRequest : public AbstractModel { public: CreateGameServerSessionRequest(); ~CreateGameServerSessionRequest() = default; std::string ToJsonString() const; /** * 获取最大玩家数量,最小值不小于0 * @return MaximumPlayerSessionCount 最大玩家数量,最小值不小于0 * */ uint64_t GetMaximumPlayerSessionCount() const; /** * 设置最大玩家数量,最小值不小于0 * @param _maximumPlayerSessionCount 最大玩家数量,最小值不小于0 * */ void SetMaximumPlayerSessionCount(const uint64_t& _maximumPlayerSessionCount); /** * 判断参数 MaximumPlayerSessionCount 是否已赋值 * @return MaximumPlayerSessionCount 是否已赋值 * */ bool MaximumPlayerSessionCountHasBeenSet() const; /** * 获取别名ID。每个请求需要指定别名ID 或者舰队 ID,如果两个同时指定时,优先选择舰队 ID * @return AliasId 别名ID。每个请求需要指定别名ID 或者舰队 ID,如果两个同时指定时,优先选择舰队 ID * */ std::string GetAliasId() const; /** * 设置别名ID。每个请求需要指定别名ID 或者舰队 ID,如果两个同时指定时,优先选择舰队 ID * @param _aliasId 别名ID。每个请求需要指定别名ID 或者舰队 ID,如果两个同时指定时,优先选择舰队 ID * */ void SetAliasId(const std::string& _aliasId); /** * 判断参数 AliasId 是否已赋值 * @return AliasId 是否已赋值 * */ bool AliasIdHasBeenSet() const; /** * 获取创建者ID,最大长度不超过1024个ASCII字符 * @return CreatorId 创建者ID,最大长度不超过1024个ASCII字符 * */ std::string GetCreatorId() const; /** * 设置创建者ID,最大长度不超过1024个ASCII字符 * @param _creatorId 创建者ID,最大长度不超过1024个ASCII字符 * */ void SetCreatorId(const std::string& _creatorId); /** * 判断参数 CreatorId 是否已赋值 * @return CreatorId 是否已赋值 * */ bool CreatorIdHasBeenSet() const; /** * 获取舰队ID。每个请求需要指定别名ID 或者舰队 ID,如果两个同时指定时,优先选择舰队 ID * @return FleetId 舰队ID。每个请求需要指定别名ID 或者舰队 ID,如果两个同时指定时,优先选择舰队 ID * */ std::string GetFleetId() const; /** * 设置舰队ID。每个请求需要指定别名ID 或者舰队 ID,如果两个同时指定时,优先选择舰队 ID * @param _fleetId 舰队ID。每个请求需要指定别名ID 或者舰队 ID,如果两个同时指定时,优先选择舰队 ID * */ void SetFleetId(const std::string& _fleetId); /** * 判断参数 FleetId 是否已赋值 * @return FleetId 是否已赋值 * */ bool FleetIdHasBeenSet() const; /** * 获取游戏属性,最大长度不超过16组 * @return GameProperties 游戏属性,最大长度不超过16组 * */ std::vector<GameProperty> GetGameProperties() const; /** * 设置游戏属性,最大长度不超过16组 * @param _gameProperties 游戏属性,最大长度不超过16组 * */ void SetGameProperties(const std::vector<GameProperty>& _gameProperties); /** * 判断参数 GameProperties 是否已赋值 * @return GameProperties 是否已赋值 * */ bool GamePropertiesHasBeenSet() const; /** * 获取游戏服务器会话属性详情,最大长度不超过4096个ASCII字符 * @return GameServerSessionData 游戏服务器会话属性详情,最大长度不超过4096个ASCII字符 * */ std::string GetGameServerSessionData() const; /** * 设置游戏服务器会话属性详情,最大长度不超过4096个ASCII字符 * @param _gameServerSessionData 游戏服务器会话属性详情,最大长度不超过4096个ASCII字符 * */ void SetGameServerSessionData(const std::string& _gameServerSessionData); /** * 判断参数 GameServerSessionData 是否已赋值 * @return GameServerSessionData 是否已赋值 * */ bool GameServerSessionDataHasBeenSet() const; /** * 获取游戏服务器会话自定义ID,最大长度不超过4096个ASCII字符 * @return GameServerSessionId 游戏服务器会话自定义ID,最大长度不超过4096个ASCII字符 * */ std::string GetGameServerSessionId() const; /** * 设置游戏服务器会话自定义ID,最大长度不超过4096个ASCII字符 * @param _gameServerSessionId 游戏服务器会话自定义ID,最大长度不超过4096个ASCII字符 * */ void SetGameServerSessionId(const std::string& _gameServerSessionId); /** * 判断参数 GameServerSessionId 是否已赋值 * @return GameServerSessionId 是否已赋值 * */ bool GameServerSessionIdHasBeenSet() const; /** * 获取幂等token,最大长度不超过48个ASCII字符 * @return IdempotencyToken 幂等token,最大长度不超过48个ASCII字符 * */ std::string GetIdempotencyToken() const; /** * 设置幂等token,最大长度不超过48个ASCII字符 * @param _idempotencyToken 幂等token,最大长度不超过48个ASCII字符 * */ void SetIdempotencyToken(const std::string& _idempotencyToken); /** * 判断参数 IdempotencyToken 是否已赋值 * @return IdempotencyToken 是否已赋值 * */ bool IdempotencyTokenHasBeenSet() const; /** * 获取游戏服务器会话名称,最大长度不超过1024个ASCII字符 * @return Name 游戏服务器会话名称,最大长度不超过1024个ASCII字符 * */ std::string GetName() const; /** * 设置游戏服务器会话名称,最大长度不超过1024个ASCII字符 * @param _name 游戏服务器会话名称,最大长度不超过1024个ASCII字符 * */ void SetName(const std::string& _name); /** * 判断参数 Name 是否已赋值 * @return Name 是否已赋值 * */ bool NameHasBeenSet() const; private: /** * 最大玩家数量,最小值不小于0 */ uint64_t m_maximumPlayerSessionCount; bool m_maximumPlayerSessionCountHasBeenSet; /** * 别名ID。每个请求需要指定别名ID 或者舰队 ID,如果两个同时指定时,优先选择舰队 ID */ std::string m_aliasId; bool m_aliasIdHasBeenSet; /** * 创建者ID,最大长度不超过1024个ASCII字符 */ std::string m_creatorId; bool m_creatorIdHasBeenSet; /** * 舰队ID。每个请求需要指定别名ID 或者舰队 ID,如果两个同时指定时,优先选择舰队 ID */ std::string m_fleetId; bool m_fleetIdHasBeenSet; /** * 游戏属性,最大长度不超过16组 */ std::vector<GameProperty> m_gameProperties; bool m_gamePropertiesHasBeenSet; /** * 游戏服务器会话属性详情,最大长度不超过4096个ASCII字符 */ std::string m_gameServerSessionData; bool m_gameServerSessionDataHasBeenSet; /** * 游戏服务器会话自定义ID,最大长度不超过4096个ASCII字符 */ std::string m_gameServerSessionId; bool m_gameServerSessionIdHasBeenSet; /** * 幂等token,最大长度不超过48个ASCII字符 */ std::string m_idempotencyToken; bool m_idempotencyTokenHasBeenSet; /** * 游戏服务器会话名称,最大长度不超过1024个ASCII字符 */ std::string m_name; bool m_nameHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_GSE_V20191112_MODEL_CREATEGAMESERVERSESSIONREQUEST_H_
c410a0141be31474a46868bc05f31ddda5161b26
a623bb4db329c8d63e03908d16dc2808bacbcdaa
/include/vRt/vRt_lib.cpp
ce2853d2a5848df950fd7ab8e8a9add10aea8980
[ "MIT" ]
permissive
gitter-badger/vRt
990358412ec885352d3893bf80fdc286e01d170c
a50b67d42a7d8eb0735016337ec7f482a2bde253
refs/heads/master
2020-03-19T12:14:12.155526
2018-06-07T12:54:32
2018-06-07T12:54:32
136,505,385
0
0
MIT
2018-06-07T16:41:44
2018-06-07T16:41:44
null
UTF-8
C++
false
false
87
cpp
vRt_lib.cpp
// implementator of vRt in static lib #include "vRt/vRt.h" #include "vRt/vRt_impl.inl"
0bc9d02582a0358b29f09351668def76647430c1
cdd954c874762b94828dac7c29f185804403b4b2
/RocketOpenNIPlugin/deps/OpenNI/include/XnNodeAllocator.h
757e4005e98a8467a3089ca2fdfd88278c7c5bea
[ "Apache-2.0" ]
permissive
Adminotech/meshmoon-plugins
cd2c898bcae0fbab796e9829c48754c81be4644a
32043ef783bdf137860d7d01eb22de564628e572
refs/heads/master
2021-01-13T00:44:55.012875
2016-03-07T14:58:03
2016-03-07T14:58:03
52,879,540
4
2
null
null
null
null
UTF-8
C++
false
false
2,147
h
XnNodeAllocator.h
/**************************************************************************** * * * OpenNI 1.x Alpha * * Copyright (C) 2011 PrimeSense Ltd. * * * * This file is part of OpenNI. * * * * OpenNI is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as published * * by the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * OpenNI 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 Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with OpenNI. If not, see <http://www.gnu.org/licenses/>. * * * ****************************************************************************/ #ifndef _NISIMPLENODEALLOCATOR_H #define _NISIMPLENODEALLOCATOR_H #include <IXnNodeAllocator.h> #include <XnNode.h> class XnNodeAllocator : public INiNodeAllocator { public: /** * Allocate a new XnNode * * @return NULL if allocating a new node failed */ virtual XnNode *Allocate() { return XnNode::Allocate(); } /** * Release an XnNode * * @param pNode [in] The node to deallocate */ virtual void Deallocate(XnNode *pNode) { XnNode::Deallocate(pNode); } }; #endif //_NISIMPLENODEALLOCATOR_H
5554a63feed39e456fda5a6dcc1d7f0bc45b85df
1e0145f29225cd5fac51d88e8053403cb6c47c50
/src/fsa/seq_io.cpp
7252279f5cef1315a3a974a51960a52f58744937
[]
no_license
TheLuoFengLab/NECAT
aa14b3092b0908c7c94531cc154887f0113aeb5c
0c5fc856aedc855c96efb78d8340372104cb5cfe
refs/heads/master
2022-09-15T01:08:16.652954
2021-03-18T06:17:58
2021-03-18T06:17:58
205,390,438
0
0
null
null
null
null
UTF-8
C++
false
false
2,308
cpp
seq_io.cpp
#include "seq_io.hpp" #include <cassert> #include <algorithm> #include <cassert> namespace fsa { bool FastaReader::Next(Item &item) { item.id = Tell(); item.quality = ""; return GetHead(item.head, item.sub_head) && GetSeq(item.seq); } bool FastaReader::GetHead(std::string &head, std::string &sub_head) { std::string line = in_.QueryStrippedLine(); in_.ConsumeStrippedLine(); //printf("xxx:%s\n", line.c_str()); fflush(stdout); if (!line.empty() && line[0] == '>') { std::string::size_type s = 1; while (s < line.size() && ::isspace(line[s])) s++; std::string::size_type e = std::min(s+1, line.size()); while (e < line.size() && !::isspace(line[e])) e++; if (e > s) { head = line.substr(s, e-s); while (e < line.size() && ::isspace(line[e])) e++; sub_head = line.substr(e); return true; } else { return false; } } else { return false; } } bool FastaReader::GetSeq(std::string &seq) { seq = ""; std::string line = in_.QueryStrippedLine(); while (!line.empty() && line[0] != '>') { seq += line; in_.ConsumeStrippedLine(); line = in_.QueryStrippedLine(); } return true;// !seq.empty(); allow empty sequence } bool FastqReader::Next(Item &item) { assert(IsValid()); item.id = Tell(); return GetHead(item.head, item.sub_head) && GetSeq(item.seq) && GetHead1() && GetQuality(item.quality); } bool FastqReader::GetHead(std::string &head, std::string &sub_head) { std::string line = in_.GetStrippedLine(); if (!line.empty() && line[0] == '@') { std::string::size_type s = 1; while (s < line.size() && ::isspace(line[s])) s++; std::string::size_type e = std::min(s+1, line.size()); while (e < line.size() && !::isspace(line[e])) e++; if (e > s) { head = line.substr(s, e-s); while (e < line.size() && ::isspace(line[e])) e++; sub_head = line.substr(e); return true; } else { return false; } } else { return false; } } } // namespace fsa {
04c7938b8954b6b515e261c5fba0644107a30618
04740a66d98730afca496eb0cf5e7b5edea5f6e6
/backend/CDataset/rotate/rotate_1.cpp
86f6754bdf636a5991c689205fd535716dfde7a9
[]
no_license
mehulthakral/logic_detector
0c06fbd12d77a02c888d0bbe3e6776a18f2f46e3
f7a07a6d229b250da9e02d3fac1a12fa51be97e8
refs/heads/master
2023-04-12T12:45:29.370502
2021-05-05T17:15:02
2021-05-05T17:15:02
323,953,099
2
0
null
2021-05-03T16:50:44
2020-12-23T16:39:28
null
UTF-8
C++
false
false
352
cpp
rotate_1.cpp
class Solution { public: #include<vector> void rotate(vector<int>& nums, int k) { reverse(nums.begin(),nums.end()); // reverse the array reverse(nums.begin(),nums.begin()+k%nums.size()); // reverse the first k ele reverse(nums.begin()+k%nums.size(),nums.end()); // reverse the last n-k ele } };
e793aba516dc35aa662f732493c5c497329f60b9
c51064f0e88a44339d3f4ea729bad3e2df4cd336
/cpp/libs/ssp21/src/crypto/Algorithms.cpp
ecde9f37fe4283f2f95792c4fe108d440b76676d
[]
no_license
ssp21/ssp21-cpp
219e0da72d5d9a8bf4a0cc4a25e22dcdb3a9ad81
90e111a8e369ce44276824e4abec66e6a83927e6
refs/heads/master
2021-07-17T03:47:50.888364
2020-10-09T18:14:02
2020-10-09T18:14:02
65,405,723
3
2
null
2021-04-26T18:58:41
2016-08-10T18:13:40
C++
UTF-8
C++
false
false
4,038
cpp
Algorithms.cpp
#include "crypto/Algorithms.h" #include "ssp21/util/Exception.h" namespace ssp21 { HandshakeError Algorithms::Session::configure(SessionNonceMode nonce_mode, SessionCryptoMode session_mode) { switch (nonce_mode) { case (SessionNonceMode::greater_than_last_rx): this->verify_nonce = &NonceFunctions::verify_greater_than_last; break; case (SessionNonceMode::strict_increment): this->verify_nonce = &NonceFunctions::verify_strict_increment; break; default: return HandshakeError::unsupported_nonce_mode; } switch (session_mode) { case (SessionCryptoMode::hmac_sha256_16): { if (!Crypto::supports_sha256()) { return HandshakeError::unsupported_session_mode; } this->session_mode = SessionModes::hmac_sha_256_trunc16(); break; } case (SessionCryptoMode::aes_256_gcm): if (!Crypto::supports_aes256_gcm()) { return HandshakeError::unsupported_session_mode; } this->session_mode = SessionModes::aes_256_gcm(); break; default: return HandshakeError::unsupported_session_mode; } return HandshakeError::none; } HandshakeError Algorithms::Handshake::configure( HandshakeKDF handshake_kdf, HandshakeHash handshake_hash) { switch (handshake_hash) { case (HandshakeHash::sha256): if (!Crypto::supports_sha256()) { return HandshakeError::unsupported_handshake_hash; } this->hash = &Crypto::hash_sha256; break; default: return HandshakeError::unsupported_handshake_hash; } switch (handshake_kdf) { case (HandshakeKDF::hkdf_sha256): if (!Crypto::supports_sha256()) { return HandshakeError::unsupported_handshake_kdf; } this->kdf = &Crypto::hkdf_sha256; break; default: return HandshakeError::unsupported_handshake_kdf; } return HandshakeError::none; } Algorithms::Common Algorithms::Common::get_or_throw(const CryptoSuite& suite) { Algorithms::Common ret; const auto err = ret.configure( suite.handshake_hash, suite.handshake_kdf, suite.session_nonce_mode, suite.session_crypto_mode); if (any(err)) { throw Exception("unable to configure algorithms: ", HandshakeErrorSpec::to_string(err)); } return ret; } HandshakeError Algorithms::Common::configure(HandshakeHash handshake_hash, HandshakeKDF handshake_kdf, SessionNonceMode session_nonce_mode, SessionCryptoMode session_crypto_mode) { { const auto err = this->handshake.configure(handshake_kdf, handshake_hash); if (any(err)) { return err; } } { const auto err = this->session.configure(session_nonce_mode, session_crypto_mode); if (any(err)) { return err; } } return HandshakeError::none; } HandshakeError Algorithms::Common::configure(const CryptoSpec& spec) { return this->configure( spec.handshake_hash, spec.handshake_kdf, spec.session_nonce_mode, spec.session_crypto_mode); } Algorithms::DH Algorithms::DH::get_or_throw(HandshakeEphemeral type) { Algorithms::DH ret; const auto err = ret.configure(type); if (any(err)) { throw Exception("Unable to configure DH algorithms: ", HandshakeErrorSpec::to_string(err)); } return ret; } HandshakeError Algorithms::DH::configure(HandshakeEphemeral type) { switch (type) { case (HandshakeEphemeral::x25519): if (!Crypto::supports_x25519()) { return HandshakeError::unsupported_handshake_ephemeral; } this->dh = &Crypto::dh_x25519; this->gen_key_pair = &Crypto::gen_keypair_x25519; return HandshakeError::none; default: return HandshakeError::unsupported_handshake_ephemeral; } } }
931952bff5d26f3d27714bfe50c839fadc5a2f91
db80b43f473d595fd5b8a540a0bf283828860c0e
/connected.cpp
1ad06dd648cd3b2c3dec472452ca21dc62f5624b
[]
no_license
hrunderla/VLN_1_UI
d9700f6c945321432cbd6ca6f0e4b7c35e921379
462e91c40fa631d350ce7a69e5e6a038d5a139fe
refs/heads/master
2021-01-10T10:09:34.401516
2015-12-14T14:02:00
2015-12-14T14:02:00
47,764,770
0
0
null
null
null
null
UTF-8
C++
false
false
752
cpp
connected.cpp
#include "connected.h" Connected::Connected() { nameOne = ""; nameTwo = ""; idOne = 0; idTwo = 0; } Connected::Connected(string name1, string name2) { nameOne = name1; nameTwo = name2; idOne = 0; idTwo = 0; } void Connected::putNameOne(int anId) { idOne = anId; } void Connected::putNameTwo(int anId) { idTwo = anId; } string Connected::getNameOne() const { return nameOne; } string Connected::getNameTwo() const { return nameTwo; } ostream& operator << (ostream& outs, const Connected& Connected) { outs << setw(40); outs.setf(ios::left); outs << Connected.nameOne; outs << setw(40); outs.setf(ios::left); outs << Connected.nameTwo; return outs; }
660e1facb685aa93a152faafbca96d17ca8aac56
a766ee23c2243f850ebdb83a69d0fb8a5359c07d
/2015/UVa/UVa536.cpp
346c4c2e3036756d88db2c9bffdb6da926bfe9e2
[ "MIT" ]
permissive
jasha64/jasha64
24e127e57dd8852e5a006ba98be6c17312733597
653881f0f79075a628f98857e77eac27aef1919d
refs/heads/master
2021-06-23T08:34:27.220649
2021-06-20T06:05:50
2021-06-20T06:05:50
218,268,953
1
1
null
null
null
null
UTF-8
C++
false
false
965
cpp
UVa536.cpp
#include <iostream> #include <string> using namespace std; struct Node { char Data; Node *Left, *Right; } *Root; string s1, s2; inline Node* newnode() {return new Node();} void Recover(int Left2, int Right2, int Left1, Node* Root) { Root -> Data = s1[Left1]; if (Left2 == Right2) return; int Pos = s2.find(s1[Left1]); if (Pos - 1 >= Left2) Recover(Left2, Pos - 1, Left1 + 1, Root -> Left = newnode()); if (Pos + 1 <= Right2) Recover(Pos + 1, Right2, Left1 + Pos - Left2 + 1, Root -> Right = newnode()); } void Post_Order(Node* Root) { if (Root == NULL) return; Post_Order(Root -> Left); Post_Order(Root -> Right); cout << Root -> Data; } void Remove_Tree(Node* Root) { if (Root == NULL) return; Remove_Tree(Root -> Left); Remove_Tree(Root -> Right); delete Root; } int main() { while (cin >> s1 >> s2) { Root = newnode(); Recover(0, s2.size() - 1, 0, Root); Post_Order(Root); cout << endl; Remove_Tree(Root); } return 0; }
2cef1c08ab30ddeb74e462c7421296cede32b56c
f7510a0f27b84c704d53de7d931c82229eb186bb
/WPFKeyboard.Native/ManageCpp/KeyboardLayoutHelper.cpp
aee8a33969aa37ddeb2a8441ed2cf36ba1bdf64d
[]
no_license
ZT-/WPFKeyboard
4be4436aa5dd7e4c16e68e7a0e1c6f40958f1405
b46fb70f65da7319df1019974f6128ff9abf4f65
refs/heads/master
2022-01-15T05:44:30.858397
2019-07-22T14:32:56
2019-07-22T14:32:56
198,239,983
0
0
null
null
null
null
UTF-8
C++
false
false
1,896
cpp
KeyboardLayoutHelper.cpp
#include "stdafx.h" #include "KeyboardLayoutHelper.h" #include "KLL.h" WPFKeyboardNative::KeyboardLayoutHelper::KeyboardLayoutHelper(void) { } WPFKeyboardNative::KeyboardLayout^ WPFKeyboardNative::KeyboardLayoutHelper::GetLayout(System::String^ keyboardLayoutDll) { CKLL *kll = nullptr; try{ kll = new CKLL(); System::IntPtr p = System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(keyboardLayoutDll); char *charKeyboardLayoutDll = static_cast<char*>(p.ToPointer()); bool result = kll->LoadDLL(charKeyboardLayoutDll); System::Runtime::InteropServices::Marshal::FreeHGlobal(p); if(!result) throw gcnew Exception(String::Format("Unabled to load keyboard layout dll {0}.", keyboardLayoutDll)); KeyboardLayout^ layout = gcnew KeyboardLayout(keyboardLayoutDll); for(int i=0;i < kll->GetModifiersCount(); i++) { layout->CharModifiers->Add(gcnew CharModifier(kll->GetModifierAtIndex(i)->VirtualKey, kll->GetModifierAtIndex(i)->ModifierBits)); } for(int i=0;i < kll->GetVKCount(); i++) { CKLL::VK_STRUCT *vk = kll->GetVKAtIndex(i); array<int>^ characters = gcnew array<int>(vk->Characters.size()); for(int y = 0; y <vk->Characters.size(); y++) { characters[y] = (int)vk->Characters[y]; } layout->VirtualKeys->Add(gcnew VirtualKey(vk->VirtualKey, vk->Attributes, characters)); } for(int i=0;i < kll->GetScanCodesCount(); i++) { layout->ScanCodes->Add(gcnew ScanCode(kll->GetScanCodeAtIndex(i)->VirtualKey, kll->GetScanCodeAtIndex(i)->ScanCode, kll->GetScanCodeAtIndex(i)->E0Set, kll->GetScanCodeAtIndex(i)->E1Set)); } for(int i=0;i < kll->GetScanCodeTextCount(); i++) { layout->CodeText->Add(gcnew ScanCodeText(kll->GetScanCodeTextAtIndex(i)->ScanCode, gcnew String(kll->GetScanCodeTextAtIndex(i)->Text))); } return layout; } finally { if(kll != nullptr) { delete kll; kll = nullptr; } } }
ce13562c90c8154c34776a93c54d165255d7f72d
a821bfe3f3cc066527118e3cc51e1e4cce08101e
/IARCS JUDGE/ENDCORR/End of Corruption.cpp
e40f11020313d2049d7ddf259810c28ffee381b7
[]
no_license
valalithak/Competitive-Programming
b7fa717d1f39325bf04247cdbdeb6d4d13e5f33c
493bc1ef5451d38fee03bb598f7e1382e886c949
refs/heads/master
2021-06-19T00:17:36.745551
2019-10-14T13:46:34
2019-10-14T13:46:34
154,393,189
0
1
null
2019-10-14T13:46:35
2018-10-23T20:34:05
C++
UTF-8
C++
false
false
281
cpp
End of Corruption.cpp
#include <bits/stdc++.h> using namespace std; int A,B,N,tmp; int main() { priority_queue <int , vector <int> > P; cin>>A>>B; N=A+B; while(N--) { cin>>tmp; if(tmp==-1){ cout<<P.top()<<endl; P.pop(); continue; } P.push(tmp); } return 0; }
4da0fafb6ed6d8a3e5bc4e944185ba5a416415b1
17353cfd2c984f2b57ab09dce5b793f34b051f19
/src/plugProjectKandoU/interactBattle.cpp
2763ab43de5eae3277555a4b68f3b849cf54a614
[]
no_license
mxygon/pikmin2
573df84b127b27f1c5db6be22680b63fd34565d5
fa16b706d562d3f276406d8a87e01ad541515737
refs/heads/main
2023-09-02T06:56:56.216154
2021-11-12T09:34:26
2021-11-12T09:34:26
427,367,127
1
0
null
2021-11-12T13:19:54
2021-11-12T13:19:53
null
UTF-8
C++
false
false
1,630
cpp
interactBattle.cpp
#include "types.h" #include "game/interactBattle.h" #include "game/Creature.h" /* * --INFO-- * Address: 8019FE78 * Size: 000044 */ namespace Game { bool InteractFlick::actCommon(Creature* param_1) { if (param_1->isStickTo()) { param_1->endStick(); } return true; }; ///* // * --INFO-- // * Address: 8019FEBC // * Size: 00006C // */ // void Game::InteractAttack::actCommon(Game::Creature*) //{ // /* // .loc_0x0: // stwu r1, -0x10(r1) // mflr r0 // stw r0, 0x14(r1) // stw r31, 0xC(r1) // mr r31, r4 // lwz r3, 0x4(r3) // lwz r12, 0x0(r3) // lwz r12, 0x1C(r12) // mtctr r12 // bctrl // rlwinm. r0,r3,0,24,31 // beq- .loc_0x54 // mr r3, r31 // lwz r12, 0x0(r31) // lwz r12, 0x7C(r12) // mtctr r12 // bctrl // rlwinm. r0,r3,0,24,31 // bne- .loc_0x54 // li r3, 0 // b .loc_0x58 // .loc_0x54: // li r3, 0x1 // .loc_0x58: // lwz r0, 0x14(r1) // lwz r31, 0xC(r1) // mtlr r0 // addi r1, r1, 0x10 // blr // */ //} ///* // * --INFO-- // * Address: 8019FF28 // * Size: 000008 // */ // void Game::InteractSwallow::actCommon(Game::Creature*) //{ // /* // .loc_0x0: // li r3, 0x1 // blr // */ //} ///* // * --INFO-- // * Address: 8019FF30 // * Size: 000008 // */ // void Game::InteractKill::actCommon(Game::Creature*) //{ // /* // .loc_0x0: // li r3, 0x1 // blr // */ //} }; // namespace Game
8e5f9a115c43474c97636e2f9888a2b3ce5df2e2
92bb51629d67f694c385a9c2d84f99fdd6b811a1
/Library/Library.prj/CSVRcdB.cpp
c523f73546d24952d377629f48a2f67a7e6032e4
[ "MIT" ]
permissive
rrvt/WixApp
0bb1e5a2e309725a240fc42f4f1f03e756b97b3c
80b03383e850fbc361f656dbacfc0bd4e42bd155
refs/heads/master
2023-07-24T09:41:56.652497
2023-07-08T06:11:54
2023-07-08T06:11:54
240,187,528
0
1
null
null
null
null
UTF-8
C++
false
false
1,039
cpp
CSVRcdB.cpp
// My CSV Records #include "pch.h" #include "CSVLex.h" #include "CSVOut.h" #include "CSVRcdB.h" // load csv data from file bool CSVRcdB::load(CSVLex& lex){ static TCchar* NullStg = _T(""); clear(); while (lex.get_token() != EolToken) { CSVtok& tok = lex.token; CSVtok& tok1 = lex.token1; if (tok.code == CommaToken) {put(NullStg); putI++; lex.accept_token(); continue;} if (tok1.code == CommaToken) {put(tok.name.trim()); putI++; lex.accept_two_tokens(); continue;} if (tok.code == EOFToken) return putI > 0; put(tok.name.trim()); putI++; lex.accept_token(); } lex.accept_token(); return true; } void CSVRcdB::store(Archive& ar) { CSVOut co(ar); String* s; String line; for (getI = 0, s = get(); s; getI++, s = get()) { if (getI > 0) co << _T(','); co << *s; } co << vCrlf; } int CSVRcdB::display(NotePad& np) { String* s; for (getI = 0, s = get(); s; getI++, s = get()) {if (getI > 0) np << _T(','); np << *s;} np << nCrlf; return 1; }
d7f323ab853db88268f67a67b170338b37139669
1f3b037857da5b9742c209b55f56f208252cc897
/include/Control/ControlMap.hpp
819bdf3d160393c96145cf093bb2cf2e7609ec6e
[]
no_license
Kraghan/Dead-Pixel-Society
cd4cd8178a8a411147bb84469afde8a010d51d6d
728958d2134b21cf20fe32d3a819d541dce73a69
refs/heads/master
2020-04-16T02:50:42.815122
2017-01-10T17:19:06
2017-01-10T17:19:06
68,087,857
3
1
null
null
null
null
UTF-8
C++
false
false
677
hpp
ControlMap.hpp
// // Created by Kraghan on 13/10/2016. // #ifndef PROJECT_CONTROLMAP_HPP #define PROJECT_CONTROLMAP_HPP #include "Control/EnumActions.hpp" #include "Control/GameContext.hpp" #include <iostream> #include <map> class ControlMap { private: std::map <int,Actions> m_map_game, m_map_menu, m_map_game_controller, m_map_menu_controller; public: ControlMap(); ControlMap(int up,int down,int left,int right,int attack,int jump,int activate,int validate,int exit,int pause, int c_attack,int c_jump,int c_activate,int c_validate,int c_exit,int c_pause); Actions getAction(int keyPressed) const; void debug(); }; #endif //PROJECT_CONTROLMAP_HPP
d83394aa51c0f0febe970a10969ba27a2a46b61c
b309c832dec3df54dd7893eed4919abe49905d76
/Resources.h
d97f532ee1130b0d335e311553d92f3b06175721
[]
no_license
gitter-badger/Hydround
fe1db32a2ca2a5a1f8e422cdf392b213956b87f5
a5346693abeb47755804d0e51c998f6dd8301556
refs/heads/master
2021-01-16T22:15:08.950065
2016-02-14T09:57:21
2016-02-14T09:57:21
51,689,303
0
0
null
2016-02-14T09:58:20
2016-02-14T09:58:19
null
UTF-8
C++
false
false
1,369
h
Resources.h
// ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ // ▒▒█▒▒█▒█▒▒█▒███▒▒███▒▒▒██▒▒█▒▒█▒█▒▒█▒███▒▒ // ▒▒█▒▒█▒█▒▒█▒█▒▒█▒█▒▒█▒█▒▒█▒█▒▒█▒██▒█▒█▒▒█▒ // ▒▒████▒▒███▒█▒▒█▒███▒▒█▒▒█▒█▒▒█▒█▒██▒█▒▒█▒ // ▒▒█▒▒█▒▒▒▒█▒█▒▒█▒█▒█▒▒█▒▒█▒█▒▒█▒█▒▒█▒█▒▒█▒ // ▒▒█▒▒█▒▒██▒▒███▒▒█▒▒█▒▒██▒▒▒██▒▒█▒▒█▒███▒▒ // ▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ #ifndef RECOURCES_H_ #define RECOURCES_H_ #include <iostream> #include <sstream> using namespace std; class Resources { public: static string getTranslationFile(){ return "/home/undrfined/Hydround/source/Translation.json"; } static string getDefaultLanguage(){ // TODO delete this method, read language from config return "en"; } static string getConfigFile(){ return "/home/undrfined/Hydround/source/Config.json"; } }; #endif /* RECOURCES_H_ */
d2b31fe0d51471d1688a4f7d520404f90afd48d6
e05936836a5b1c9a4c3731cd21e53b1a38457e4e
/Day 5/Class.cpp
04a9677f5d1e5fde93602e0baffc7d4b502e0d5b
[]
no_license
shivamgupta57121/GS-Coderantine-CPP
90c7c93318ebd1632c00683b4d55b9a6a50c8f67
d5cb146e2d176b74435ce72d553eea87f68432d0
refs/heads/master
2022-11-17T14:44:58.414284
2020-06-20T13:04:55
2020-06-20T13:04:55
272,037,927
0
0
null
null
null
null
UTF-8
C++
false
false
815
cpp
Class.cpp
#include<bits/stdc++.h> using namespace std; class student{ private: int roll; string name; float marks[3]; float total, per; void calculate(){ total=0; for(int i=0;i<3;i++) total+=marks[i]; per = total/3; } public: student(){ cout<<"enter roll: "; cin>>roll; cout<<"name: "; cin>>name; cout<<"marks in three subjects: \n"; for(int i=0;i<3;i++) cin>>marks[i]; calculate(); } void print(){ cout<<roll<<"\t"<<name<<"\t"<<per<<endl; } }; int main() { student s1; student s2; cout<<"Roll\t Name\t Per\n"; s1.print(); s2.print(); return 0; }
e9d16378ee7f15fd0242e0d792d5ce5ac1f4b485
05092fbc5d7b7a4641f902d96f3430ad5105c87c
/test.cpp
f372f5483b0f29d5ee1331530e8cd30bfaed3db8
[]
no_license
choxsword/LearningCpp
cc78676e2d540bc1eb76149ad3e1255fcb08ad0c
5f5ab9a535a828ca17011bdc5f400fcdaab5466b
refs/heads/master
2021-04-12T10:06:52.587193
2018-03-26T03:30:30
2018-03-26T03:30:30
126,772,237
0
0
null
null
null
null
UTF-8
C++
false
false
577
cpp
test.cpp
#include<iostream> #include "test.h" using namespace std; namespace test { TansCons& TansCons::operator =(const TansCons& obj) { cout<<"="<<endl; } TansCons::TansCons(const char* obj) { cout<<"trans cons"<<endl; } TansCons::TansCons(const TansCons& obj) { cout<<"copy cons"<<endl; } int test_size::mem; void* test_size::operator new(size_t memo_size) { cout<<"ohoh"<<endl; return ::operator new(memo_size); } int POD::mem=666; }
966032293acddb95b39e94996c740e9920d2ffd1
5687b2d67015cbf8f1119ff2421f5a3b112f0932
/login.cpp
e35ce9f1f6b8b2c327a0fbf3944813917503fc39
[]
no_license
sockerboy/MyChat
2799f3a4b7c150e5fb9645e4729704ece6f6b3df
3b48cddd18b19f816bb8f2792324a5c738b01f75
refs/heads/master
2023-03-17T09:15:03.989644
2018-03-16T06:32:29
2018-03-16T06:32:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,763
cpp
login.cpp
#include "login.h" #include "ui_login.h" #include<QMessageBox> #include<QSqlQuery> #include<QDebug> bool connectDb(){ QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("127.0.0.1"); db.setDatabaseName("luchat"); db.setPort(3306); db.setUserName("root"); db.setPassword("88"); if(db.open()){ qDebug()<<"connect database success!"<<endl; qDebug()<<QSqlDatabase::drivers()<<endl; return true; } else{ QMessageBox::warning(0,"警告","无法连接到数据库!",QMessageBox::Ok); qDebug()<<"connect database failure!"<<endl; return false; } } Login::Login(unsigned int*id,QWidget *parent) : QDialog(parent), ui(new Ui::Login) { ui->setupUi(this); this->id = id; } Login::~Login() { delete ui; } void Login::on_loginButton_clicked() { if(ui->idLineEdit->text().isEmpty()||ui->passwordLineEdit->text().isEmpty()){ QMessageBox::warning(this,tr("请输入账号密码!"),tr("请输入账号密码!"),QMessageBox::Ok); return; } bool check; QString idStr = ui->idLineEdit->text(); *id = idStr.toUInt(&check); QString password = ui->passwordLineEdit->text(); if(check){//监测账号是否为数字 connectDb(); QSqlQuery query; query.exec(QString("select * from Account where id=")+idStr+" and password="+password+";"); check = query.next(); if(check){ //数据库中存在该账号密码 登录成功 QDialog::accept(); } } if(!check){ QMessageBox::warning(this,tr("账号或密码错误!"),tr("账号或密码错误"),QMessageBox::Ok); } } void Login::on_cancelButton_clicked() { QDialog::reject(); }
0b2ecbc3ee3fbfa3aabf5e63ba8a0ca9d27fb5b0
b172c1ad3459efda447340537f4488356c882637
/src/widgets/utils/sliderwithvalues.hpp
441f35a3561b904149721412b99eb2df8010c655
[]
no_license
davafons/imagecpp
532e4131cdf70d62c37c199c496ffd2a764edbd6
a8026729ed5d50b058928a5d2ecb97599871c93c
refs/heads/master
2020-07-30T00:08:21.997323
2019-11-27T21:51:44
2019-11-27T21:51:44
210,011,406
0
0
null
null
null
null
UTF-8
C++
false
false
543
hpp
sliderwithvalues.hpp
#pragma once #include <QLabel> #include <QSlider> class SliderWithValues : public QWidget { Q_OBJECT public: SliderWithValues(Qt::Orientation orientation, QWidget *parent = nullptr); int minimum() const; int maximum() const; signals: void valueChanged(double value); public slots: void setMin(int min); void setMax(int max); void setRange(int min, int max); void setValue(double value); void setSubsteps(int substeps); private: QSlider *slider_{nullptr}; QLabel *value_label_{nullptr}; int substeps_ = 10; };
e35cafb6bbd720ab59c3f4e2ab4411fbac2d789e
db3809ad07d942ff837907e902c025d6a5e0bc64
/src/vetero-displayd/charset.cc
ee514def41d673ee4b7314b42a8d7d1ba7ca127c
[]
no_license
bwalle/vetero
3178cc33d30207b8382ee5aff380713f852b1edb
a2a20b2d445f04f4c311215934e2d872c189063a
refs/heads/master
2022-10-24T18:37:51.242361
2022-10-08T14:38:17
2022-10-08T14:38:17
163,579,380
0
0
null
null
null
null
UTF-8
C++
false
false
2,999
cc
charset.cc
/* {{{ * (c) 2011, Bernhard Walle <bernhard@bwalle.de> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. }}} */ #include <stdexcept> #include <clocale> #include <cstdlib> #include <cstring> #include <cerrno> #include <langinfo.h> #include <iconv.h> #include "hd44780-charmap.h" #include "charset.h" namespace vetero { namespace display { std::string queryNativeCharset() { static std::string charset; if (charset.empty()) { std::string old_locale = std::setlocale(LC_CTYPE, NULL); std::setlocale(LC_CTYPE, ""); charset = nl_langinfo(CODESET); std::setlocale(LC_CTYPE, old_locale.c_str()); } return charset; } std::string native2latin1(const std::string &native) { return toLatin1(native, ""); } std::string toLatin1(const std::string &stringToConvert, const std::string &charset) { std::string sourceCharset = charset; if (sourceCharset.empty()) sourceCharset = queryNativeCharset(); iconv_t iconv_handle = iconv_open("iso-8859-1", sourceCharset.c_str()); if (iconv_handle == reinterpret_cast<iconv_t>(-1)) throw CharsetError("Unable to obtain iconv handle for '"+ sourceCharset +"' -> 'iso-8859-1'"); // the result *must* be smaller or equal because we know that it's latin1. char *resultbuffer = new char[stringToConvert.size()+1]; // iconv doesn't write to the buffer, it just modifies the input pointer char *input = const_cast<char *>(stringToConvert.c_str()); size_t inbytesleft = stringToConvert.size(); char *output = resultbuffer; size_t outbytesleft = stringToConvert.size(); int ret = iconv(iconv_handle, &input, &inbytesleft, &output, &outbytesleft); iconv_close(iconv_handle); if (ret < 0) { delete[] resultbuffer; throw CharsetError("Error when converting '"+ stringToConvert +"' ("+ sourceCharset +") to latin1: " + std::string(std::strerror(errno)) ); } resultbuffer[stringToConvert.size() - outbytesleft] = '\0'; std::string result(resultbuffer); delete[] resultbuffer; return result; } std::string latin12hd44780(const std::string &latin1) { std::string result; for (size_t i = 0; i < latin1.size(); ++i) result += char(HD44780_charmap[ static_cast<unsigned char>(latin1[i]) ]); return result; } } // end namespace vetero } // end namespace display
b3e945610df9ba2c2aa870abbacaf6847482fe9a
883e53051c4579b32e85a0d8d35b814da0f26dfe
/Jacob/Lektion 10/OPG 11.1 - Shapes 1/Shapes_1/Rectangle.cpp
64b6b178d1a7914ea2aee7cd671f487cad25aca2
[]
no_license
Andreasgdp/Cpp-2.-semester
fa8b2b5b462d558cd88f6f75c04fca0fb8afc9cb
8180e6ea86bb933f8c0f16579c57eeeac8345eff
refs/heads/main
2023-06-10T00:20:44.345868
2021-06-23T15:00:12
2021-06-23T15:00:12
335,230,193
0
0
null
null
null
null
UTF-8
C++
false
false
148
cpp
Rectangle.cpp
#include "Rectangle.h" Rectangle::Rectangle() { } double Rectangle::calcArea(double height, double width) { return mArea = height * width; }
61b1d62a4a2db853371d91965ec4c83d1f0481da
e4c14e337dbea3118bb138b668437fd0ab020ad2
/hue-emulator/lib/service_hue_bridge/hue_light.cpp
dc3571656973cacc88e5f8522b67678e2e65798c
[ "MIT" ]
permissive
aenniw/ESP8266
69060792c9c8a2b380d5a763ebc7a5b85104f530
2642fba2e37be68343a4c19a286a813e5aab4cf1
refs/heads/master
2023-06-25T11:15:46.035427
2023-06-11T09:19:38
2023-06-11T09:51:32
73,233,861
5
0
MIT
2022-11-22T07:55:03
2016-11-08T22:45:23
C++
UTF-8
C++
false
false
2,412
cpp
hue_light.cpp
#include "hue_light.h" static const char *TEMPLATE_CONFIG_LIGHT = "/hue/l/cf-template.json"; LedLight::LedLight(LedStripService *l, const char *n, const uint8_t index) : HueLight(n, get_file_index_info(HUE_LIGHT, index, false), TEMPLATE_CONFIG_LIGHT) { ls = l; ls->set_animated_color_change(true); String unique_id = "AA:BB:CC:DD:EE:FF:00:11-"; unique_id += index; ConfigJSON::set<const char *>(cf->name, {"uniqueid"}, unique_id.c_str()); ConfigJSON::set<bool>(cf->name, {"state", "on"}, false); mark_for_reindex(); } uint8_t LedLight::get_brightness() const { return ls->get_brightness(); } void LedLight::set_color_cie(float x, float y) { HueLight::set_color_cie(x, y); ConfigJSON::clear_array(cf->name, {"state", "xy"}); ConfigJSON::add_to_array<float>(cf->name, {"state", "xy"}, x); ConfigJSON::add_to_array<float>(cf->name, {"state", "xy"}, y); ConfigJSON::set<const char *>(cf->name, {"state", "colormode"}, "xy"); mark_for_reindex(); } void LedLight::set_color_ct(const uint32_t ct) { HueLight::set_color_ct(ct); ConfigJSON::set<uint32_t>(cf->name, {"state", "ct"}, ct); ConfigJSON::set<const char *>(cf->name, {"state", "colormode"}, "ct"); mark_for_reindex(); } void LedLight::set_color_rgb(const uint8_t _r, const uint8_t _g, const uint8_t _b) { ls->set_rgb(_r, _g, _b); HueLight::set_color_rgb(_r, _g, _b); } void LedLight::set_state(const bool s) { if (s) { ls->set_rgb(r, g, b); } else ls->set_rgb(0, 0, 0); ConfigJSON::set<bool>(cf->name, {"state", "on"}, s); mark_for_reindex(); } void LedLight::set_hue(const uint16_t h) { ls->set_hue(h); ConfigJSON::set<uint16_t>(cf->name, {"state", "hue"}, h); ConfigJSON::set<const char *>(cf->name, {"state", "colormode"}, "hs"); mark_for_reindex(); } void LedLight::set_brightness(const uint8_t b) { ls->set_brightness(b); ConfigJSON::set<uint8_t>(cf->name, {"state", "bri"}, b); ConfigJSON::set<const char *>(cf->name, {"state", "colormode"}, "hs"); mark_for_reindex(); } void LedLight::set_saturation(const uint8_t s) { ls->set_saturation(s); ConfigJSON::set<uint8_t>(cf->name, {"state", "sat"}, s); ConfigJSON::set<const char *>(cf->name, {"state", "colormode"}, "hs"); mark_for_reindex(); } void LedLight::set_transition(const uint16_t t) { ls->set_delay(uint16_t(t * 0.25f)); }
7592d6b02095fc39167f897f89877eb92020b94e
35b2422a965fbe5a753c591c1130628453e61d9d
/MQTT_StrangerThingsWall/MQTT_StrangerThingsWall.ino
042f1e32c5e49cf4f376bbd7d283ff2e4c7b346b
[ "Apache-2.0" ]
permissive
Starius-Project/StrangerThings_LightWall
d728f127aa9153e9f2bc59badcf2be73758856d1
d3ef9e205d780721baeb26a4e106b1ca724db8b5
refs/heads/master
2020-04-16T20:05:25.656693
2019-07-22T14:26:00
2019-07-22T14:26:00
165,886,331
0
0
null
null
null
null
UTF-8
C++
false
false
11,702
ino
MQTT_StrangerThingsWall.ino
/*************************************************** Adafruit MQTT Library ESP8266 Example Must use ESP8266 Arduino from: https://github.com/esp8266/Arduino Works great with Adafruit's Huzzah ESP board & Feather ----> https://www.adafruit.com/product/2471 ----> https://www.adafruit.com/products/2821 Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Tony DiCola for Adafruit Industries. MIT license, all text above must be included in any redistribution ****************************************************/ #include <ESP8266WiFi.h> #include <Adafruit_NeoPixel.h> #include "Adafruit_MQTT.h" #include "Adafruit_MQTT_Client.h" /************************* WiFi Access Point *********************************/ #define WLAN_SSID "SFR_51F8" #define WLAN_PASS "43bzsu6hva92fhvr7uzr" /************************* Adafruit.io Setup *********************************/ #define AIO_SERVER "io.adafruit.com" #define AIO_SERVERPORT 1883 // use 8883 for SSL #define AIO_USERNAME "Electro_Guy" #define AIO_KEY "2e81c6d2c7d3a6cd22f49961de5ed0931665b620" /************ Global State (you don't need to change this!) ******************/ // Create an ESP8266 WiFiClient class to connect to the MQTT server. WiFiClient client; // or... use WiFiFlientSecure for SSL //WiFiClientSecure client; // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details. Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); /****************************** Feeds ***************************************/ // Setup a feed called 'photocell' for publishing. // Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname> Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/photocell"); // Setup a feed called 'onoff' for subscribing to changes. Adafruit_MQTT_Subscribe StrangerThings = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/strangerthings"); /*************************** Sketch Code ************************************/ // Bug workaround for Arduino 1.6.6, it seems to need a function declaration // for some reason (only affects ESP8266, likely an arduino-builder bug). void MQTT_connect(); //////////LED #define LED_PIN D2 // How many NeoPixels are attached to the Arduino? #define LED_COUNT 50 Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800); long randNumber; //Pixel random number variable long randNumberR; //RED random number variable long randNumberG; //GREEN random number variable long randNumberB; //BLUE random number variable int A = 48; int B = 46; int C = 44; int D = 43; int E = 41; int F = 40; int G = 38; int H = 36; int Q = 29; int P = 26; int O = 25; int N = 24; int M = 22; int L = 20; int K = 19; int J = 18; int I = 16; int R = 12; int S = 11; int T = 10; int U = 8; int V = 7; int W = 5; int X = 4; int Y = 2; int Z = 0; int LEDARRAY[26] = {A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z}; void setup() { strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED) strip.show(); // Turn OFF all pixels ASAP strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255) for (int i = 0; i < LED_COUNT; i++) { strip.setPixelColor(i,0, 0, 0); //turn random pixel off strip.show(); } randomSeed(analogRead(3)); Serial.begin(115200); delay(10); Serial.println(F("Adafruit MQTT demo")); // Connect to WiFi access point. Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(WLAN_SSID); WiFi.begin(WLAN_SSID, WLAN_PASS); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); // Setup MQTT subscription for onoff feed. mqtt.subscribe(&StrangerThings); strip.setBrightness(255); } uint32_t x=45; void loop() { // Ensure the connection to the MQTT server is alive (this will make the first // connection and automatically reconnect when disconnected). See the MQTT_connect // function definition further below. MQTT_connect(); // this is our 'wait for incoming subscription packets' busy subloop // try to spend your time here Adafruit_MQTT_Subscribe *subscription; while ((subscription = mqtt.readSubscription(5000))) { if (subscription == &StrangerThings) { Serial.print(F("Got: ")); Serial.println((char *)StrangerThings.lastread); if (strcmp((char *)StrangerThings.lastread, "ON") == 0){ randomPixel(S); delay(1000); randomPixel(K); delay(1000); randomPixel(U); delay(1000); randomPixel(L); delay(1000); randomPixel(L); delay(1000); rainbow(3); for (int i = 0; i < LED_COUNT; i++) { strip.setPixelColor(i,0, 0, 0); //turn random pixel off strip.show(); } Serial.println("Upside down"); /*if (! photocell.publish(x)) { Serial.println(F("Failed")); } else { Serial.println(F("OK!")); }*/ } if (strcmp((char *)StrangerThings.lastread, "RAINBOW") == 0){ rainbow(3); } if (strcmp((char *)StrangerThings.lastread, "DEATH") == 0){ randomPixel(D); delay(1000); randomPixel(E); delay(1000); randomPixel(A); delay(1000); randomPixel(T); delay(1000); randomPixel(H); delay(1000); } if (strcmp((char *)StrangerThings.lastread, "HELP") == 0){ randomPixel(H); delay(1000); randomPixel(E); delay(1000); randomPixel(L); delay(1000); randomPixel(P); delay(1000); } if (strcmp((char *)StrangerThings.lastread, "4JULY") == 0){ randomPixel(T); delay(1000); randomPixel(O); delay(1000); randomPixel(D); delay(1000); randomPixel(A); delay(1000); randomPixel(Y); delay(1000); } } // ping the server to keep the mqtt connection alive // NOT required if you are publishing once every KEEPALIVE seconds /* if(! mqtt.ping()) { mqtt.disconnect(); } */ } } // Function to connect and reconnect as necessary to the MQTT server. // Should be called in the loop function and it will take care if connecting. void MQTT_connect() { int8_t ret; // Stop if already connected. if (mqtt.connected()) { return; } Serial.print("Connecting to MQTT... "); uint8_t retries = 3; while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected Serial.println(mqtt.connectErrorString(ret)); Serial.println("Retrying MQTT connection in 5 seconds..."); mqtt.disconnect(); delay(5000); // wait 5 seconds retries--; if (retries == 0) { // basically die and wait for WDT to reset me while (1); } } Serial.println("MQTT Connected!"); randomPixel(C); delay(1000); for (int i = 0; i < LED_COUNT; i++) { strip.setPixelColor(i,0, 0, 0); //turn random pixel off strip.show(); } } //Random pixel with random color. void randomPixel(int c) { randNumberR = random(0, 255); //Random RED value randNumberG = random(0, 255); //Random GREEN value randNumberB = random(0, 255); //Random BLUE value for (int i = 0; i < LED_COUNT; i++) { strip.setPixelColor(i,0, 0, 0); //turn random pixel off strip.show(); } strip.setPixelColor(c,randNumberR, randNumberG, randNumberB); //turn pixel on strip.show(); } // Some functions of our own for creating animated effects ----------------- // Fill strip pixels one after another with a color. Strip is NOT cleared // first; anything there will be covered pixel by pixel. Pass in color // (as a single 'packed' 32-bit value, which you can get by calling // strip.Color(red, green, blue) as shown in the loop() function above), // and a delay time (in milliseconds) between pixels. void colorWipe(uint32_t color, int wait) { for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip... strip.setPixelColor(i, color); // Set pixel's color (in RAM) strip.show(); // Update strip to match delay(wait); // Pause for a moment } } // Theater-marquee-style chasing lights. Pass in a color (32-bit value, // a la strip.Color(r,g,b) as mentioned above), and a delay time (in ms) // between frames. void theaterChase(uint32_t color, int wait) { for(int a=0; a<10; a++) { // Repeat 10 times... for(int b=0; b<3; b++) { // 'b' counts from 0 to 2... strip.clear(); // Set all pixels in RAM to 0 (off) // 'c' counts up from 'b' to end of strip in steps of 3... for(int c=b; c<strip.numPixels(); c += 3) { strip.setPixelColor(c, color); // Set pixel 'c' to value 'color' } strip.show(); // Update strip with new contents delay(wait); // Pause for a moment } } } // Rainbow cycle along whole strip. Pass delay time (in ms) between frames. void rainbow(int wait) { // Hue of first pixel runs 5 complete loops through the color wheel. // Color wheel has a range of 65536 but it's OK if we roll over, so // just count from 0 to 5*65536. Adding 256 to firstPixelHue each time // means we'll make 5*65536/256 = 1280 passes through this outer loop: for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) { for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip... // Offset pixel hue by an amount to make one full revolution of the // color wheel (range of 65536) along the length of the strip // (strip.numPixels() steps): int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels()); // strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or // optionally add saturation and value (brightness) (each 0 to 255). // Here we're using just the single-argument hue variant. The result // is passed through strip.gamma32() to provide 'truer' colors // before assigning to each pixel: strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue))); } strip.show(); // Update strip with new contents delay(wait); // Pause for a moment } } // Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames. void theaterChaseRainbow(int wait) { int firstPixelHue = 0; // First pixel starts at red (hue 0) for(int a=0; a<30; a++) { // Repeat 30 times... for(int b=0; b<3; b++) { // 'b' counts from 0 to 2... strip.clear(); // Set all pixels in RAM to 0 (off) // 'c' counts up from 'b' to end of strip in increments of 3... for(int c=b; c<strip.numPixels(); c += 3) { // hue of pixel 'c' is offset by an amount to make one full // revolution of the color wheel (range 65536) along the length // of the strip (strip.numPixels() steps): int hue = firstPixelHue + c * 65536L / strip.numPixels(); uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB strip.setPixelColor(c, color); // Set pixel 'c' to value 'color' } strip.show(); // Update strip with new contents delay(wait); // Pause for a moment firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames } } }
db16792a253ed181959f85a0ea8904898a400582
d3bbc8fe573b0149d2d18546fa5311ab3b514f35
/src/engine/render/text/freetype_font.cpp
e4cf6ea79984226aa641f3fc567a459aa2a41723
[]
no_license
enlit3d/traps_sweeper
9ef857faa4bcd3427690211c42893b2dccaba907
e1a3349a9be456f45a6e1814ce521235a62046aa
refs/heads/master
2022-07-17T05:34:04.626110
2020-04-24T06:25:03
2020-04-24T06:25:03
198,321,048
1
1
null
null
null
null
UTF-8
C++
false
false
2,795
cpp
freetype_font.cpp
#include "freetype_font.h" #include "utf.h" #include "ft2build.h" #include "freetype/ftglyph.h" #include FT_FREETYPE_H #include <iostream> #include <cassert> namespace engine::render { struct FreeTypeFont::Impl { Impl(str_ref filePath, i32 pointSize) { if (FT_Init_FreeType(&library)) { throw; } auto error = FT_New_Face( library, filePath.c_str(), 0, &face ); if (error) { if (error == FT_Err_Unknown_File_Format) { std::cout << "Unknown file format."; } else { throw; } } if (FT_Set_Pixel_Sizes(face, 0, pointSize)) { throw; } auto& m = face->size->metrics; fontMetrics = FontMetrics{ m.height / 64, m.descender / 64, m.ascender / 64 }; } ~Impl() { FT_Done_Face(face); FT_Done_FreeType(library); } ImageData renderGlyph(u32 ch) { //if (FT_Load_Char(face, ch, FT_LOAD_DEFAULT)) { if (FT_Load_Char(face, ch, FT_LOAD_FORCE_AUTOHINT)) { throw; } if (FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL)) { throw; } //if (FT_Glyph_To_Bitmap(face->glyph, FT_RENDER_MODE_NORMAL, 0, false)) { // throw; //} auto& bitmap = face->glyph->bitmap; auto imageData = ImageData{ (i32)bitmap.width, (i32)bitmap.rows, 4 }; auto i = 0; for (u32 y = 0; y < bitmap.rows; ++y) { for (u32 x = 0; x < bitmap.width; ++x) { u8 v = static_cast<u8>(bitmap.buffer[y * bitmap.pitch + x]); imageData.data()[i++] = 255; // r imageData.data()[i++] = 255; // g imageData.data()[i++] = 255; // b imageData.data()[i++] = v; // a } } assert(imageData.data() + i == imageData.data() + imageData.bytes()); return imageData; } public: FT_Library library; FT_Face face; FontMetrics fontMetrics; }; FreeTypeFont::FreeTypeFont(FreeTypeFontSrc& src, i32 pointSize) : FreeTypeFont(src._filePath, pointSize) { } FreeTypeFont::FreeTypeFont(str_ref filePath, i32 pointSize) : _impl(std::make_unique<Impl>(filePath, pointSize)) { } FreeTypeFont::~FreeTypeFont() = default; FreeTypeFont::FreeTypeFont(FreeTypeFont&&) noexcept = default; FreeTypeFont& FreeTypeFont::operator=(FreeTypeFont&&) noexcept = default; ImageData FreeTypeFont::renderGlyph(u32 ch) { return _impl->renderGlyph(ch); } ImageData FreeTypeFont::renderGlyph(const char* ch) { return renderGlyph(ext::utf::utf8ToUtf32(ch)); } GlyphMetrics FreeTypeFont::getMetricsForPreviousRendered() { auto& slot = _impl->face->glyph; return { slot->bitmap_left, -((i32)slot->bitmap.rows - slot->bitmap_top), slot->advance.x / 64 }; } const FontMetrics& FreeTypeFont::getFontMetrics() const { return _impl->fontMetrics; } FreeTypeFontSrc::FreeTypeFontSrc(str_t filePath) : _filePath{filePath} { } }
a81c58599a0d3cb9b49cff72004917f4424a5f01
f1f9859230125fc7dd1aa5d0ab685c98d2f51444
/Dong/cpp/search_Binary/search_Binary/main.cpp
d94ebe7fd7878f998c617d7b09d6a04ee5b7ee81
[ "MIT" ]
permissive
dong199903/Data-and-Struct
4379a547e02e87a2c4867d779494856634ee322f
54ac178c83d2aaaaef6fb3bc8a138cc8d48b2a19
refs/heads/master
2022-08-25T16:48:06.287896
2022-07-23T17:49:23
2022-07-23T17:49:23
208,051,148
1
1
null
null
null
null
UTF-8
C++
false
false
560
cpp
main.cpp
/************************************************************************* > File Name: array_queue.c > Author: DongZePing > Mail: 1939485575@qq.com > Time: 2019-07-27 > > 1) > 2) > 3) ************************************************************************/ #include "Search.h" #include <iostream> using namespace std; void main() { Array a1; a1.print(); cout<< a1.Search_Binary1(1); cout << a1.Search_Binary2(1); cout << a1.Search_Binary3(1); cout << a1.Search_Binary4(1); cout << a1.Search_Binary5(1); system("pause"); }
ea0431322dc0e9c21616fdd80dda96039908f186
5e72ba60c16573312f2b74bebd91ebd31d758bf4
/NEO/filehelper.cpp
f67712b07f2040196aef930560439673ae6ded05
[]
no_license
Malakahh/NEOQt
ff0e288f906b985f27d823f2a73820ab324bfbe8
1368b41469501b9ab47d88b64ef28821328db83e
refs/heads/master
2020-07-22T07:50:16.560162
2017-09-19T16:53:17
2017-09-19T16:53:17
73,830,902
0
0
null
null
null
null
UTF-8
C++
false
false
2,961
cpp
filehelper.cpp
#include "filehelper.h" FileHelper::FileHelper(QObject* parent) : QObject(parent) { #ifdef Q_OS_ANDROID this->userStorageDir.setPath(QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation).last()); #endif #ifdef Q_OS_IOS this->userStorageDir.setPath(QStandardPaths::standardLocations(QStandardPaths::DocumentsLocation).last()); #endif qDebug() << "USER STORAGE DIR: " << this->userStorageDir.absolutePath(); QString dataPath = QStandardPaths::standardLocations(QStandardPaths::ConfigLocation).last() + "/powercharge"; this->dataStorageDir.mkpath(dataPath); this->dataStorageDir.setPath(dataPath); } FileHelper& FileHelper::getInstance() { static FileHelper instance; return instance; } QVariant FileHelper::getFiles(QString extensionFilter) { QList<QObject*> list; this->files = this->userStorageDir.entryInfoList(QDir::Files); for (QFileInfo& info : this->files) { qDebug() << info.fileName(); if (extensionFilter == "" || info.suffix().toLower() == extensionFilter.toLower()) { list.append(new FileBrowserData(info.fileName())); } } return QVariant::fromValue(list); } void FileHelper::save(QString path, std::vector<char> data) { QFile f(path); f.open(QIODevice::WriteOnly); QDataStream ds(&f); ds.writeRawData(data.data(), data.size()); f.flush(); f.close(); } void FileHelper::load(QString path, std::vector<char>& data) { QFile f(path); f.open(QIODevice::ReadOnly); char d[f.size()]; QDataStream ds(&f); ds.readRawData(d, f.size()); f.close(); data.assign(d, d + f.size()); } void FileHelper::saveLog(QString fileName) { if (fileName == "") { return; } std::vector<char> log = ChargerModel::getInstance().parseLog(); fileName.append(".csv"); QString path = this->userStorageDir.absolutePath() + "/" + fileName; this->save(path, log); } void FileHelper::loadProgram(QString fileName, std::vector<char>& data) { QString path = this->userStorageDir.absolutePath() + "/" + fileName; this->load(path, data); } void FileHelper::saveDataFile(std::vector<char> data) { QString path = this->dataStorageDir.absolutePath() + "/data.dat"; this->save(path, data); } void FileHelper::loadDataFile(std::vector<char>& data) { QString path = this->dataStorageDir.absolutePath() + "/data.dat"; this->load(path, data); } /* void FileHelper::test(QString fileName) { const char data[] = { 0x41, 0x42, 0x43, 0x31, 0x32, 0x33 }; //Save Test //this->save(fileName, data, 6); //Load test char* data2; unsigned int len; this->load(fileName, data2, len); bool correct = true; for (int i = 0; i < len; i++) { if (data[i] != data2[1]) correct = false; } qDebug() << "Arrays are equal: " << correct; } */
c980ec91aa7f341a83fce32442e7e598547df184
eebb79e0ffb9bf2c729e83e133ff61a4c2e36d49
/src/realm/sync/network/network.cpp
0090c4db3260b2e31f79b740ba21d324f47cbcf2
[ "Apache-2.0" ]
permissive
realm/realm-core
878349ddbf33353de26272d7b1e8f93690ba28d1
c258e2681bca5fb33bbd23c112493817b43bfa86
refs/heads/master
2023-08-31T21:14:19.625989
2023-08-31T20:29:06
2023-08-31T20:29:06
1,917,262
1,059
189
Apache-2.0
2023-09-14T18:11:10
2011-06-18T21:18:46
C++
UTF-8
C++
false
false
88,336
cpp
network.cpp
#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <algorithm> #include <cerrno> #include <condition_variable> #include <limits> #include <mutex> #include <stdexcept> #include <thread> #include <vector> #include <fcntl.h> #ifndef _WIN32 #include <netinet/tcp.h> #include <unistd.h> #include <poll.h> #include <realm/util/to_string.hpp> #endif #include <realm/util/features.h> #include <realm/util/optional.hpp> #include <realm/util/misc_errors.hpp> #include <realm/util/priority_queue.hpp> #include <realm/sync/network/network.hpp> #if defined _GNU_SOURCE && !REALM_ANDROID #define HAVE_LINUX_PIPE2 1 #else #define HAVE_LINUX_PIPE2 0 #endif // Note: Linux specific accept4() is not available on Android. #if defined _GNU_SOURCE && defined SOCK_NONBLOCK && defined SOCK_CLOEXEC && !REALM_ANDROID #define HAVE_LINUX_ACCEPT4 1 #else #define HAVE_LINUX_ACCEPT4 0 #endif #if defined _GNU_SOURCE && defined SOCK_CLOEXEC #define HAVE_LINUX_SOCK_CLOEXEC 1 #else #define HAVE_LINUX_SOCK_CLOEXEC 0 #endif #ifndef _WIN32 #if REALM_NETWORK_USE_EPOLL #include <linux/version.h> #include <sys/epoll.h> #elif REALM_HAVE_KQUEUE #include <sys/types.h> #include <sys/event.h> #include <sys/time.h> #else #include <poll.h> #endif #endif // On Linux kernels earlier than 2.6.37, epoll can't handle timeout values // bigger than (LONG_MAX - 999ULL)/HZ. HZ in the wild can be as big as 1000, // and LONG_MAX can be as small as (2**31)-1, so the largest number of // milliseconds we can be sure to support on those early kernels is 2147482. #if REALM_NETWORK_USE_EPOLL #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 37) #define EPOLL_LARGE_TIMEOUT_BUG 1 #endif #endif using namespace realm::util; using namespace realm::sync::network; namespace { using native_handle_type = SocketBase::native_handle_type; #ifdef _WIN32 // This Winsock initialization call is required prior to any other Winsock API call // made by the process. It is OK if a process calls it multiple times. struct ProcessInitialization { ProcessInitialization() { WSADATA wsaData; int i = WSAStartup(MAKEWORD(2, 2), &wsaData); if (i != 0) { throw std::system_error(i, std::system_category(), "WSAStartup() Winsock initialization failed"); } } ~ProcessInitialization() { // Must be called 1 time for each call to WSAStartup() that has taken place WSACleanup(); } }; ProcessInitialization g_process_initialization; std::error_code make_winsock_error_code(int error_code) { switch (error_code) { case WSAEAFNOSUPPORT: return make_basic_system_error_code(EAFNOSUPPORT); case WSAEINVAL: return make_basic_system_error_code(EINVAL); case WSAECANCELLED: return make_basic_system_error_code(ECANCELED); case WSAECONNABORTED: return make_basic_system_error_code(ECONNABORTED); case WSAECONNRESET: return make_basic_system_error_code(ECONNRESET); case WSAEWOULDBLOCK: return make_basic_system_error_code(EAGAIN); } // Microsoft's STL can map win32 (and winsock!) error codes to known (posix-compatible) errc ones. auto ec = std::system_category().default_error_condition(error_code); if (ec.category() == std::generic_category()) return make_basic_system_error_code(ec.value()); return std::error_code(ec.value(), ec.category()); } #endif // defined _WIN32 inline bool check_socket_error(int ret, std::error_code& ec) { #ifdef _WIN32 if (REALM_UNLIKELY(ret == SOCKET_ERROR)) { ec = make_winsock_error_code(WSAGetLastError()); return true; } #else if (REALM_UNLIKELY(ret == -1)) { ec = make_basic_system_error_code(errno); return true; } #endif return false; } // Set file status flag O_NONBLOCK if `value` is true, otherwise clear it. // // Note that these flags are set at the file description level, and are therfore // shared between duplicated descriptors (dup()). // // `ec` untouched on success. std::error_code set_nonblock_flag(native_handle_type fd, bool value, std::error_code& ec) noexcept { #ifdef _WIN32 u_long flags = value ? 1 : 0; int r = ioctlsocket(fd, FIONBIO, &flags); if (r == SOCKET_ERROR) { ec = make_winsock_error_code(WSAGetLastError()); return ec; } #else int flags = ::fcntl(fd, F_GETFL, 0); if (REALM_UNLIKELY(flags == -1)) { ec = make_basic_system_error_code(errno); return ec; } flags &= ~O_NONBLOCK; flags |= (value ? O_NONBLOCK : 0); int ret = ::fcntl(fd, F_SETFL, flags); if (REALM_UNLIKELY(ret == -1)) { ec = make_basic_system_error_code(errno); return ec; } #endif return std::error_code(); // Success } // Set file status flag O_NONBLOCK. See set_nonblock_flag(int, bool, // std::error_code&) for details. Throws std::system_error on failure. void set_nonblock_flag(native_handle_type fd, bool value = true) { std::error_code ec; if (set_nonblock_flag(fd, value, ec)) throw std::system_error(ec); } // Set file descriptor flag FD_CLOEXEC if `value` is true, otherwise clear it. // // Note that this method of setting FD_CLOEXEC is subject to a race condition if // another thread calls any of the exec functions concurrently. For that reason, // this function should only be used when there is no better alternative. For // example, Linux generally offers ways to set this flag atomically with the // creation of a new file descriptor. // // `ec` untouched on success. std::error_code set_cloexec_flag(native_handle_type fd, bool value, std::error_code& ec) noexcept { #ifndef _WIN32 int flags = ::fcntl(fd, F_GETFD, 0); if (REALM_UNLIKELY(flags == -1)) { ec = make_basic_system_error_code(errno); return ec; } flags &= ~FD_CLOEXEC; flags |= (value ? FD_CLOEXEC : 0); int ret = ::fcntl(fd, F_SETFD, flags); if (REALM_UNLIKELY(ret == -1)) { ec = make_basic_system_error_code(errno); return ec; } #endif return std::error_code(); // Success } // Set file descriptor flag FD_CLOEXEC. See set_cloexec_flag(int, bool, // std::error_code&) for details. Throws std::system_error on failure. REALM_UNUSED inline void set_cloexec_flag(native_handle_type fd, bool value = true) { std::error_code ec; if (set_cloexec_flag(fd, value, ec)) throw std::system_error(ec); } inline void checked_close(native_handle_type fd) noexcept { #ifdef _WIN32 int status = closesocket(fd); if (status == -1) { BOOL b = CloseHandle((HANDLE)fd); REALM_ASSERT(b || GetLastError() != ERROR_INVALID_HANDLE); } #else int ret = ::close(fd); // We can accept various errors from close(), but they must be ignored as // the file descriptor is closed in any case (not necessarily according to // POSIX, but we shall assume it anyway). `EBADF`, however, would indicate // an implementation bug, so we don't want to ignore that. REALM_ASSERT(ret != -1 || errno != EBADF); #endif } class CloseGuard { public: CloseGuard() noexcept {} explicit CloseGuard(native_handle_type fd) noexcept : m_fd{fd} { REALM_ASSERT(fd != -1); } CloseGuard(CloseGuard&& cg) noexcept : m_fd{cg.release()} { } ~CloseGuard() noexcept { if (m_fd != -1) checked_close(m_fd); } void reset(native_handle_type fd) noexcept { REALM_ASSERT(fd != -1); if (m_fd != -1) checked_close(m_fd); m_fd = fd; } operator native_handle_type() const noexcept { return m_fd; } native_handle_type release() noexcept { native_handle_type fd = m_fd; m_fd = -1; return fd; } private: native_handle_type m_fd = -1; }; #ifndef _WIN32 class WakeupPipe { public: WakeupPipe() { int fildes[2]; #if HAVE_LINUX_PIPE2 int flags = O_CLOEXEC; int ret = ::pipe2(fildes, flags); #else int ret = ::pipe(fildes); #endif if (REALM_UNLIKELY(ret == -1)) { std::error_code ec = make_basic_system_error_code(errno); throw std::system_error(ec); } m_read_fd.reset(fildes[0]); m_write_fd.reset(fildes[1]); #if !HAVE_LINUX_PIPE2 set_cloexec_flag(m_read_fd); // Throws set_cloexec_flag(m_write_fd); // Throws #endif } // Thread-safe. int wait_fd() const noexcept { return m_read_fd; } // Cause the wait descriptor (wait_fd()) to become readable within a short // amount of time. // // Thread-safe. void signal() noexcept { std::lock_guard lock{m_mutex}; if (!m_signaled) { char c = 0; ssize_t ret = ::write(m_write_fd, &c, 1); REALM_ASSERT_RELEASE(ret == 1); m_signaled = true; } } // Must be called after the wait descriptor (wait_fd()) becomes readable. // // Thread-safe. void acknowledge_signal() noexcept { std::lock_guard lock{m_mutex}; if (m_signaled) { char c; ssize_t ret = ::read(m_read_fd, &c, 1); REALM_ASSERT_RELEASE(ret == 1); m_signaled = false; } } private: CloseGuard m_read_fd, m_write_fd; std::mutex m_mutex; bool m_signaled = false; // Protected by `m_mutex`. }; #else // defined _WIN32 class WakeupPipe { public: SOCKET wait_fd() const noexcept { return INVALID_SOCKET; } void signal() noexcept { m_signal_count++; } bool is_signaled() const noexcept { return m_signal_count > 0; } void acknowledge_signal() noexcept { m_signal_count--; } private: std::atomic<uint32_t> m_signal_count = 0; }; #endif // defined _WIN32 std::error_code translate_addrinfo_error(int err) noexcept { switch (err) { case EAI_AGAIN: return ResolveErrors::host_not_found_try_again; case EAI_BADFLAGS: return error::invalid_argument; case EAI_FAIL: return ResolveErrors::no_recovery; case EAI_FAMILY: return error::address_family_not_supported; case EAI_MEMORY: return error::no_memory; case EAI_NONAME: #if defined(EAI_ADDRFAMILY) case EAI_ADDRFAMILY: #endif #if defined(EAI_NODATA) && (EAI_NODATA != EAI_NONAME) case EAI_NODATA: #endif return ResolveErrors::host_not_found; case EAI_SERVICE: return ResolveErrors::service_not_found; case EAI_SOCKTYPE: return ResolveErrors::socket_type_not_supported; default: return error::unknown; } } struct GetaddrinfoResultOwner { struct addrinfo* ptr; GetaddrinfoResultOwner(struct addrinfo* p) : ptr{p} { } ~GetaddrinfoResultOwner() noexcept { if (ptr) freeaddrinfo(ptr); } }; } // unnamed namespace class Service::IoReactor { public: IoReactor(); ~IoReactor() noexcept; // Add an initiated I/O operation that did not complete immediately. void add_oper(Descriptor&, LendersIoOperPtr, Want); void remove_canceled_ops(Descriptor&, OperQueue<AsyncOper>& completed_ops) noexcept; bool wait_and_advance(clock::time_point timeout, clock::time_point now, bool& interrupted, OperQueue<AsyncOper>& completed_ops); // The reactor is considered empty when no operations are currently managed // by it. An operation is managed by a reactor if it was added through // add_oper() and not yet passed out through `completed_ops` of // wait_and_advance(). bool empty() const noexcept; // Cause wait_and_advance() to return within a short amount of time. // // Thread-safe. void interrupt() noexcept; #if REALM_NETWORK_USE_EPOLL || REALM_HAVE_KQUEUE void register_desc(Descriptor&); void deregister_desc(Descriptor&) noexcept; #endif #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS clock::duration get_and_reset_sleep_time() noexcept; #endif private: #if REALM_NETWORK_USE_EPOLL static constexpr int s_epoll_event_buffer_size = 256; const std::unique_ptr<epoll_event[]> m_epoll_event_buffer; const CloseGuard m_epoll_fd; static std::unique_ptr<epoll_event[]> make_epoll_event_buffer(); static CloseGuard make_epoll_fd(); #elif REALM_HAVE_KQUEUE // !REALM_NETWORK_USE_EPOLL && REALM_HAVE_KQUEUE static constexpr int s_kevent_buffer_size = 256; const std::unique_ptr<struct kevent[]> m_kevent_buffer; const CloseGuard m_kqueue_fd; static std::unique_ptr<struct kevent[]> make_kevent_buffer(); static CloseGuard make_kqueue_fd(); #endif // !REALM_NETWORK_USE_EPOLL && REALM_HAVE_KQUEUE #if REALM_NETWORK_USE_EPOLL || REALM_HAVE_KQUEUE OperQueue<IoOper> m_active_ops; // If there are already active operations, just activate as many additional // operations as can be done without blocking. Otherwise, block until at // least one operation can be activated or the timeout is reached. Then, if // the timeout was not reached, activate as many additional operations as // can be done without any further blocking. // // May occasionally return with no active operations and before the timeout // has been reached, but this can be assumed to happen rarely enough that it // will never amount to a performance problem. // // Argument `now` is unused if `timeout.time_since_epoch() <= 0`. // // Returns true if, and only if a wakeup pipe signal was // received. Operations may already have been activated in this case. bool wait_and_activate(clock::time_point timeout, clock::time_point now); void advance_active_ops(OperQueue<AsyncOper>& completed_ops) noexcept; #else // !(REALM_NETWORK_USE_EPOLL || REALM_HAVE_KQUEUE) struct OperSlot { std::size_t pollfd_slot_ndx = 0; // Zero when slot is unused OperQueue<IoOper> read_ops, write_ops; }; std::vector<OperSlot> m_operations; // Indexed by file descriptor // First entry in `m_pollfd_slots` is always the read end of the wakeup // pipe. There is then an additional entry for each entry in `m_operations` // where `pollfd_slot_ndx` is nonzero. All entries always have `pollfd::fd` // >= 0. // // INVARIANT: m_pollfd_slots.size() == 1 + N, where N is the number of // entries in m_operations where pollfd_slot_ndx is nonzero. std::vector<pollfd> m_pollfd_slots; void discard_pollfd_slot_by_move_last_over(OperSlot&) noexcept; #endif // !(REALM_NETWORK_USE_EPOLL || REALM_HAVE_KQUEUE) std::size_t m_num_operations = 0; WakeupPipe m_wakeup_pipe; #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS clock::duration m_sleep_time = clock::duration::zero(); #endif }; inline bool Service::IoReactor::empty() const noexcept { return (m_num_operations == 0); } inline void Service::IoReactor::interrupt() noexcept { m_wakeup_pipe.signal(); } #if REALM_NETWORK_USE_EPOLL inline Service::IoReactor::IoReactor() : m_epoll_event_buffer{make_epoll_event_buffer()} // Throws , m_epoll_fd{make_epoll_fd()} // Throws , m_wakeup_pipe{} // Throws { epoll_event event = epoll_event(); // Clear event.events = EPOLLIN; event.data.ptr = nullptr; int ret = epoll_ctl(m_epoll_fd, EPOLL_CTL_ADD, m_wakeup_pipe.wait_fd(), &event); if (REALM_UNLIKELY(ret == -1)) { std::error_code ec = make_basic_system_error_code(errno); throw std::system_error(ec); } } inline Service::IoReactor::~IoReactor() noexcept {} inline void Service::IoReactor::register_desc(Descriptor& desc) { epoll_event event = epoll_event(); // Clear event.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP | EPOLLET; // Enable edge triggering event.data.ptr = &desc; int ret = epoll_ctl(m_epoll_fd, EPOLL_CTL_ADD, desc.m_fd, &event); if (REALM_UNLIKELY(ret == -1)) { std::error_code ec = make_basic_system_error_code(errno); throw std::system_error(ec); } } inline void Service::IoReactor::deregister_desc(Descriptor& desc) noexcept { epoll_event event = epoll_event(); // Clear int ret = epoll_ctl(m_epoll_fd, EPOLL_CTL_DEL, desc.m_fd, &event); REALM_ASSERT(ret != -1); } inline std::unique_ptr<epoll_event[]> Service::IoReactor::make_epoll_event_buffer() { return std::make_unique<epoll_event[]>(s_epoll_event_buffer_size); // Throws } inline CloseGuard Service::IoReactor::make_epoll_fd() { int flags = 0; flags |= EPOLL_CLOEXEC; int ret = epoll_create1(flags); if (REALM_UNLIKELY(ret == -1)) { std::error_code ec = make_basic_system_error_code(errno); throw std::system_error(ec); } int epoll_fd = ret; return CloseGuard{epoll_fd}; } bool Service::IoReactor::wait_and_activate(clock::time_point timeout, clock::time_point now) { int max_wait_millis = 0; bool allow_blocking_wait = m_active_ops.empty(); if (allow_blocking_wait) { if (timeout.time_since_epoch().count() <= 0) { max_wait_millis = -1; // Allow indefinite blocking } else if (now < timeout) { auto diff = timeout - now; int max_int_millis = std::numeric_limits<int>::max(); // 17592186044415 is the largest value (45-bit signed integer) // garanteed to be supported by std::chrono::milliseconds. In the // worst case, `int` is a 16-bit integer, meaning that we can only // wait about 30 seconds at a time. In the best case // (17592186044415) we can wait more than 500 years at a time. In // the typical case (`int` has 32 bits), we can wait 24 days at a // time. long long max_chrono_millis = 17592186044415; if (max_chrono_millis < max_int_millis) max_int_millis = int(max_chrono_millis); #if EPOLL_LARGE_TIMEOUT_BUG long max_safe_millis = 2147482; // Circa 35 minutes if (max_safe_millis < max_int_millis) max_int_millis = int(max_safe_millis); #endif if (diff > std::chrono::milliseconds(max_int_millis)) { max_wait_millis = max_int_millis; } else { // Overflow is impossible here, due to the preceding check auto diff_millis = std::chrono::duration_cast<std::chrono::milliseconds>(diff); // The conversion to milliseconds will round down if the tick // period of `diff` is less than a millisecond, which it usually // is. This is a problem, because it can lead to premature // wakeups, which in turn could cause extranous iterations in // the event loop. This is especially problematic when a small // `diff` is rounded down to zero milliseconds, becuase that can // easily produce a "busy wait" condition for up to a // millisecond every time this happens. Obviously, the solution // is to round up, instead of down. if (diff_millis < diff) { // Note that the following increment cannot overflow, // because diff_millis < diff <= max_int_millis <= // std::numeric_limits<int>::max(). ++diff_millis; } max_wait_millis = int(diff_millis.count()); } } } for (int i = 0; i < 2; ++i) { #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS clock::time_point sleep_start_time = clock::now(); #endif int ret = epoll_wait(m_epoll_fd, m_epoll_event_buffer.get(), s_epoll_event_buffer_size, max_wait_millis); if (REALM_UNLIKELY(ret == -1)) { int err = errno; if (err == EINTR) return false; // Infrequent premature return is ok std::error_code ec = make_basic_system_error_code(err); throw std::system_error(ec); } REALM_ASSERT(ret >= 0); #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS m_sleep_time += clock::now() - sleep_start_time; #endif int n = ret; bool got_wakeup_pipe_signal = false; for (int j = 0; j < n; ++j) { const epoll_event& event = m_epoll_event_buffer[j]; bool is_wakeup_pipe_signal = !event.data.ptr; if (REALM_UNLIKELY(is_wakeup_pipe_signal)) { m_wakeup_pipe.acknowledge_signal(); got_wakeup_pipe_signal = true; continue; } Descriptor& desc = *static_cast<Descriptor*>(event.data.ptr); if ((event.events & (EPOLLIN | EPOLLHUP | EPOLLERR)) != 0) { if (!desc.m_read_ready) { desc.m_read_ready = true; m_active_ops.push_back(desc.m_suspended_read_ops); } } if ((event.events & (EPOLLOUT | EPOLLHUP | EPOLLERR)) != 0) { if (!desc.m_write_ready) { desc.m_write_ready = true; m_active_ops.push_back(desc.m_suspended_write_ops); } } if ((event.events & EPOLLRDHUP) != 0) desc.m_imminent_end_of_input = true; } if (got_wakeup_pipe_signal) return true; if (n < s_epoll_event_buffer_size) break; max_wait_millis = 0; } return false; } #elif REALM_HAVE_KQUEUE // !REALM_NETWORK_USE_EPOLL && REALM_HAVE_KQUEUE inline Service::IoReactor::IoReactor() : m_kevent_buffer{make_kevent_buffer()} // Throws , m_kqueue_fd{make_kqueue_fd()} // Throws , m_wakeup_pipe{} // Throws { struct kevent event; EV_SET(&event, m_wakeup_pipe.wait_fd(), EVFILT_READ, EV_ADD, 0, 0, nullptr); int ret = ::kevent(m_kqueue_fd, &event, 1, nullptr, 0, nullptr); if (REALM_UNLIKELY(ret == -1)) { std::error_code ec = make_basic_system_error_code(errno); throw std::system_error(ec); } } inline Service::IoReactor::~IoReactor() noexcept {} inline void Service::IoReactor::register_desc(Descriptor& desc) { struct kevent events[2]; // EV_CLEAR enables edge-triggered behavior EV_SET(&events[0], desc.m_fd, EVFILT_READ, EV_ADD | EV_CLEAR, 0, 0, &desc); EV_SET(&events[1], desc.m_fd, EVFILT_WRITE, EV_ADD | EV_CLEAR, 0, 0, &desc); int ret = ::kevent(m_kqueue_fd, events, 2, nullptr, 0, nullptr); if (REALM_UNLIKELY(ret == -1)) { std::error_code ec = make_basic_system_error_code(errno); throw std::system_error(ec); } } inline void Service::IoReactor::deregister_desc(Descriptor& desc) noexcept { struct kevent events[2]; EV_SET(&events[0], desc.m_fd, EVFILT_READ, EV_DELETE, 0, 0, nullptr); EV_SET(&events[1], desc.m_fd, EVFILT_WRITE, EV_DELETE, 0, 0, nullptr); int ret = ::kevent(m_kqueue_fd, events, 2, nullptr, 0, nullptr); REALM_ASSERT(ret != -1); } inline std::unique_ptr<struct kevent[]> Service::IoReactor::make_kevent_buffer() { return std::make_unique<struct kevent[]>(s_kevent_buffer_size); // Throws } inline CloseGuard Service::IoReactor::make_kqueue_fd() { int ret = ::kqueue(); if (REALM_UNLIKELY(ret == -1)) { std::error_code ec = make_basic_system_error_code(errno); throw std::system_error(ec); } int epoll_fd = ret; return CloseGuard{epoll_fd}; } bool Service::IoReactor::wait_and_activate(clock::time_point timeout, clock::time_point now) { timespec max_wait_time{}; // Clear to zero bool allow_blocking_wait = m_active_ops.empty(); if (allow_blocking_wait) { // Note that ::kevent() will silently clamp `max_wait_time` to 24 hours // (86400 seconds), but that is ok, because the caller is prepared for // premature return as long as it happens infrequently enough to not // pose a performance problem. constexpr std::time_t max_wait_seconds = 86400; if (timeout.time_since_epoch().count() <= 0) { max_wait_time.tv_sec = max_wait_seconds; } else if (now < timeout) { auto diff = timeout - now; auto secs = std::chrono::duration_cast<std::chrono::seconds>(diff); auto nsecs = std::chrono::duration_cast<std::chrono::nanoseconds>(diff - secs); auto secs_2 = std::min(secs.count(), std::chrono::seconds::rep(max_wait_seconds)); max_wait_time.tv_sec = std::time_t(secs_2); max_wait_time.tv_nsec = long(nsecs.count()); } } for (int i = 0; i < 4; ++i) { #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS clock::time_point sleep_start_time = clock::now(); #endif int ret = ::kevent(m_kqueue_fd, nullptr, 0, m_kevent_buffer.get(), s_kevent_buffer_size, &max_wait_time); if (REALM_UNLIKELY(ret == -1)) { int err = errno; if (err == EINTR) return false; // Infrequent premature return is ok std::error_code ec = make_basic_system_error_code(err); throw std::system_error(ec); } REALM_ASSERT(ret >= 0); #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS m_sleep_time += clock::now() - sleep_start_time; #endif int n = ret; bool got_wakeup_pipe_signal = false; for (int j = 0; j < n; ++j) { const struct kevent& event = m_kevent_buffer[j]; bool is_wakeup_pipe_signal = !event.udata; if (REALM_UNLIKELY(is_wakeup_pipe_signal)) { REALM_ASSERT(m_wakeup_pipe.wait_fd() == int(event.ident)); m_wakeup_pipe.acknowledge_signal(); got_wakeup_pipe_signal = true; continue; } Descriptor& desc = *static_cast<Descriptor*>(event.udata); REALM_ASSERT(desc.m_fd == int(event.ident)); if (event.filter == EVFILT_READ) { if (!desc.m_read_ready) { desc.m_read_ready = true; m_active_ops.push_back(desc.m_suspended_read_ops); } if ((event.flags & EV_EOF) != 0) desc.m_imminent_end_of_input = true; } if (event.filter == EVFILT_WRITE) { if (!desc.m_write_ready) { desc.m_write_ready = true; m_active_ops.push_back(desc.m_suspended_write_ops); } } } if (got_wakeup_pipe_signal) return true; if (n < s_kevent_buffer_size) break; // Clear to zero to disable blocking for any additional opportunistic // event extractions. max_wait_time = timespec{}; } return false; } #endif // !REALM_NETWORK_USE_EPOLL && REALM_HAVE_KQUEUE #if REALM_NETWORK_USE_EPOLL || REALM_HAVE_KQUEUE void Service::IoReactor::add_oper(Descriptor& desc, LendersIoOperPtr op, Want want) { if (REALM_UNLIKELY(!desc.m_is_registered)) { register_desc(desc); // Throws desc.m_is_registered = true; } switch (want) { case Want::read: if (REALM_UNLIKELY(desc.m_read_ready)) goto active; desc.m_suspended_read_ops.push_back(std::move(op)); goto proceed; case Want::write: if (REALM_UNLIKELY(desc.m_write_ready)) goto active; desc.m_suspended_write_ops.push_back(std::move(op)); goto proceed; case Want::nothing: break; } REALM_ASSERT(false); active: m_active_ops.push_back(std::move(op)); proceed: ++m_num_operations; } void Service::IoReactor::remove_canceled_ops(Descriptor& desc, OperQueue<AsyncOper>& completed_ops) noexcept { // Note: Canceled operations that are currently active (in m_active_ops) // will be removed later by advance_active_ops(). while (LendersIoOperPtr op = desc.m_suspended_read_ops.pop_front()) { completed_ops.push_back(std::move(op)); --m_num_operations; } while (LendersIoOperPtr op = desc.m_suspended_write_ops.pop_front()) { completed_ops.push_back(std::move(op)); --m_num_operations; } } bool Service::IoReactor::wait_and_advance(clock::time_point timeout, clock::time_point now, bool& interrupted, OperQueue<AsyncOper>& completed_ops) { clock::time_point now_2 = now; for (;;) { bool wakeup_pipe_signal = wait_and_activate(timeout, now_2); // Throws if (REALM_UNLIKELY(wakeup_pipe_signal)) { interrupted = true; return false; } advance_active_ops(completed_ops); if (!completed_ops.empty()) return true; if (timeout.time_since_epoch().count() > 0) { now_2 = clock::now(); bool timed_out = (now_2 >= timeout); if (timed_out) return false; } } } void Service::IoReactor::advance_active_ops(OperQueue<AsyncOper>& completed_ops) noexcept { OperQueue<IoOper> new_active_ops; while (LendersIoOperPtr op = m_active_ops.pop_front()) { if (op->is_canceled()) { completed_ops.push_back(std::move(op)); --m_num_operations; continue; } Want want = op->advance(); switch (want) { case Want::nothing: REALM_ASSERT(op->is_complete()); completed_ops.push_back(std::move(op)); --m_num_operations; continue; case Want::read: { Descriptor& desc = op->descriptor(); if (REALM_UNLIKELY(desc.m_read_ready)) goto still_active; desc.m_suspended_read_ops.push_back(std::move(op)); continue; } case Want::write: { Descriptor& desc = op->descriptor(); if (REALM_UNLIKELY(desc.m_write_ready)) goto still_active; desc.m_suspended_write_ops.push_back(std::move(op)); continue; } } REALM_ASSERT(false); still_active: new_active_ops.push_back(std::move(op)); } m_active_ops.push_back(new_active_ops); } #else // !(REALM_NETWORK_USE_EPOLL || REALM_HAVE_KQUEUE) inline Service::IoReactor::IoReactor() : m_wakeup_pipe{} // Throws { pollfd slot = pollfd(); // Cleared slot slot.fd = m_wakeup_pipe.wait_fd(); slot.events = POLLRDNORM; m_pollfd_slots.emplace_back(slot); // Throws } inline Service::IoReactor::~IoReactor() noexcept { #if REALM_ASSERTIONS_ENABLED std::size_t n = 0; for (std::size_t i = 0; i < m_operations.size(); ++i) { OperSlot& oper_slot = m_operations[i]; while (oper_slot.read_ops.pop_front()) ++n; while (oper_slot.write_ops.pop_front()) ++n; } REALM_ASSERT(n == m_num_operations); #endif } void Service::IoReactor::add_oper(Descriptor& desc, LendersIoOperPtr op, Want want) { native_handle_type fd = desc.m_fd; // Make sure there are enough slots in m_operations { std::size_t n = std::size_t(fd) + 1; // FIXME: Check for arithmetic overflow if (m_operations.size() < n) m_operations.resize(n); // Throws } // Allocate a pollfd_slot unless we already have one OperSlot& oper_slot = m_operations[fd]; if (oper_slot.pollfd_slot_ndx == 0) { pollfd pollfd_slot = pollfd(); // Cleared slot pollfd_slot.fd = fd; std::size_t pollfd_slot_ndx = m_pollfd_slots.size(); REALM_ASSERT(pollfd_slot_ndx > 0); m_pollfd_slots.emplace_back(pollfd_slot); // Throws oper_slot.pollfd_slot_ndx = pollfd_slot_ndx; } pollfd& pollfd_slot = m_pollfd_slots[oper_slot.pollfd_slot_ndx]; REALM_ASSERT(pollfd_slot.fd == fd); REALM_ASSERT(((pollfd_slot.events & POLLRDNORM) != 0) == !oper_slot.read_ops.empty()); REALM_ASSERT(((pollfd_slot.events & POLLWRNORM) != 0) == !oper_slot.write_ops.empty()); REALM_ASSERT((pollfd_slot.events & ~(POLLRDNORM | POLLWRNORM)) == 0); switch (want) { case Want::nothing: break; case Want::read: pollfd_slot.events |= POLLRDNORM; oper_slot.read_ops.push_back(std::move(op)); goto finish; case Want::write: pollfd_slot.events |= POLLWRNORM; oper_slot.write_ops.push_back(std::move(op)); goto finish; } REALM_ASSERT(false); return; finish: ++m_num_operations; } void Service::IoReactor::remove_canceled_ops(Descriptor& desc, OperQueue<AsyncOper>& completed_ops) noexcept { native_handle_type fd = desc.m_fd; REALM_ASSERT(fd >= 0); REALM_ASSERT(std::size_t(fd) < m_operations.size()); OperSlot& oper_slot = m_operations[fd]; REALM_ASSERT(oper_slot.pollfd_slot_ndx > 0); REALM_ASSERT(!oper_slot.read_ops.empty() || !oper_slot.write_ops.empty()); pollfd& pollfd_slot = m_pollfd_slots[oper_slot.pollfd_slot_ndx]; REALM_ASSERT(pollfd_slot.fd == fd); while (LendersIoOperPtr op = oper_slot.read_ops.pop_front()) { completed_ops.push_back(std::move(op)); --m_num_operations; } while (LendersIoOperPtr op = oper_slot.write_ops.pop_front()) { completed_ops.push_back(std::move(op)); --m_num_operations; } discard_pollfd_slot_by_move_last_over(oper_slot); } bool Service::IoReactor::wait_and_advance(clock::time_point timeout, clock::time_point now, bool& interrupted, OperQueue<AsyncOper>& completed_ops) { #ifdef _WIN32 using nfds_type = std::size_t; #else using nfds_type = nfds_t; #endif clock::time_point now_2 = now; std::size_t num_ready_descriptors = 0; { // std::vector guarantees contiguous storage pollfd* fds = &m_pollfd_slots.front(); nfds_type nfds = nfds_type(m_pollfd_slots.size()); for (;;) { int max_wait_millis = -1; // Wait indefinitely if (timeout.time_since_epoch().count() > 0) { if (now_2 >= timeout) return false; // No operations completed auto diff = timeout - now_2; int max_int_millis = std::numeric_limits<int>::max(); // 17592186044415 is the largest value (45-bit signed integer) // garanteed to be supported by std::chrono::milliseconds. In // the worst case, `int` is a 16-bit integer, meaning that we // can only wait about 30 seconds at a time. In the best case // (17592186044415) we can wait more than 500 years at a // time. In the typical case (`int` has 32 bits), we can wait 24 // days at a time. long long max_chrono_millis = 17592186044415; if (max_int_millis > max_chrono_millis) max_int_millis = int(max_chrono_millis); if (diff > std::chrono::milliseconds(max_int_millis)) { max_wait_millis = max_int_millis; } else { // Overflow is impossible here, due to the preceeding check auto diff_millis = std::chrono::duration_cast<std::chrono::milliseconds>(diff); // The conversion to milliseconds will round down if the // tick period of `diff` is less than a millisecond, which // it usually is. This is a problem, because it can lead to // premature wakeups, which in turn could cause extranous // iterations in the event loop. This is especially // problematic when a small `diff` is rounded down to zero // milliseconds, becuase that can easily produce a "busy // wait" condition for up to a millisecond every time this // happens. Obviously, the solution is to round up, instead // of down. if (diff_millis < diff) { // Note that the following increment cannot overflow, // because diff_millis < diff <= max_int_millis <= // std::numeric_limits<int>::max(). ++diff_millis; } max_wait_millis = int(diff_millis.count()); } } #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS clock::time_point sleep_start_time = clock::now(); #endif #ifdef _WIN32 max_wait_millis = 1000; // Windows does not have a single API call to wait for pipes and // sockets with a timeout. So we repeatedly poll them individually // in a loop until max_wait_millis has elapsed or an event happend. // // FIXME: Maybe switch to Windows IOCP instead. // Following variable is the poll time for the sockets in // miliseconds. Adjust it to find a balance between CPU usage and // response time: constexpr INT socket_poll_timeout = 10; for (size_t t = 0; t < m_pollfd_slots.size(); t++) m_pollfd_slots[t].revents = 0; using namespace std::chrono; auto started = steady_clock::now(); int ret = 0; for (;;) { if (m_pollfd_slots.size() > 1) { // Poll all network sockets ret = WSAPoll(LPWSAPOLLFD(&m_pollfd_slots[1]), ULONG(m_pollfd_slots.size() - 1), socket_poll_timeout); REALM_ASSERT(ret != SOCKET_ERROR); } if (m_wakeup_pipe.is_signaled()) { m_pollfd_slots[0].revents = POLLIN; ret++; } if (ret != 0 || (duration_cast<milliseconds>(steady_clock::now() - started).count() >= max_wait_millis)) { break; } // If we don't have any sockets to poll for (m_pollfd_slots is less than 2) and no one signals // the wakeup pipe, we'd be stuck busy waiting for either condition to become true. std::this_thread::sleep_for(std::chrono::milliseconds(socket_poll_timeout)); } #else // !defined _WIN32 int ret = ::poll(fds, nfds, max_wait_millis); #endif bool interrupted_2 = false; if (REALM_UNLIKELY(ret == -1)) { #ifndef _WIN32 int err = errno; if (REALM_UNLIKELY(err != EINTR)) { std::error_code ec = make_basic_system_error_code(err); throw std::system_error(ec); } #endif interrupted_2 = true; } #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS m_sleep_time += clock::now() - sleep_start_time; #endif if (REALM_LIKELY(!interrupted_2)) { REALM_ASSERT(ret >= 0); num_ready_descriptors = ret; break; } // Retry on interruption by system signal if (timeout.time_since_epoch().count() > 0) now_2 = clock::now(); } } if (num_ready_descriptors == 0) return false; // No operations completed // Check wake-up descriptor if (m_pollfd_slots[0].revents != 0) { REALM_ASSERT((m_pollfd_slots[0].revents & POLLNVAL) == 0); m_wakeup_pipe.acknowledge_signal(); interrupted = true; return false; } std::size_t orig_num_operations = m_num_operations; std::size_t num_pollfd_slots = m_pollfd_slots.size(); std::size_t pollfd_slot_ndx = 1; while (pollfd_slot_ndx < num_pollfd_slots && num_ready_descriptors > 0) { pollfd& pollfd_slot = m_pollfd_slots[pollfd_slot_ndx]; REALM_ASSERT(pollfd_slot.fd >= 0); if (REALM_LIKELY(pollfd_slot.revents == 0)) { ++pollfd_slot_ndx; continue; } --num_ready_descriptors; REALM_ASSERT((pollfd_slot.revents & POLLNVAL) == 0); // Treat errors like read and/or write-readiness if ((pollfd_slot.revents & (POLLHUP | POLLERR)) != 0) { REALM_ASSERT((pollfd_slot.events & (POLLRDNORM | POLLWRNORM)) != 0); if ((pollfd_slot.events & POLLRDNORM) != 0) pollfd_slot.revents |= POLLRDNORM; if ((pollfd_slot.events & POLLWRNORM) != 0) pollfd_slot.revents |= POLLWRNORM; } OperSlot& oper_slot = m_operations[pollfd_slot.fd]; REALM_ASSERT(oper_slot.pollfd_slot_ndx == pollfd_slot_ndx); OperQueue<IoOper> new_read_ops, new_write_ops; auto advance_ops = [&](OperQueue<IoOper>& ops) noexcept { while (LendersIoOperPtr op = ops.pop_front()) { Want want = op->advance(); switch (want) { case Want::nothing: REALM_ASSERT(op->is_complete()); completed_ops.push_back(std::move(op)); --m_num_operations; continue; case Want::read: new_read_ops.push_back(std::move(op)); continue; case Want::write: new_write_ops.push_back(std::move(op)); continue; } REALM_ASSERT(false); } }; // Check read-readiness if ((pollfd_slot.revents & POLLRDNORM) != 0) { REALM_ASSERT(!oper_slot.read_ops.empty()); advance_ops(oper_slot.read_ops); pollfd_slot.events &= ~POLLRDNORM; } // Check write-readiness if ((pollfd_slot.revents & POLLWRNORM) != 0) { REALM_ASSERT(!oper_slot.write_ops.empty()); advance_ops(oper_slot.write_ops); pollfd_slot.events &= ~POLLWRNORM; } if (!new_read_ops.empty()) { oper_slot.read_ops.push_back(new_read_ops); pollfd_slot.events |= POLLRDNORM; } if (!new_write_ops.empty()) { oper_slot.write_ops.push_back(new_write_ops); pollfd_slot.events |= POLLWRNORM; } if (pollfd_slot.events == 0) { discard_pollfd_slot_by_move_last_over(oper_slot); --num_pollfd_slots; } else { ++pollfd_slot_ndx; } } REALM_ASSERT(num_ready_descriptors == 0); bool any_operations_completed = (m_num_operations < orig_num_operations); return any_operations_completed; } void Service::IoReactor::discard_pollfd_slot_by_move_last_over(OperSlot& oper_slot) noexcept { std::size_t pollfd_slot_ndx = oper_slot.pollfd_slot_ndx; oper_slot.pollfd_slot_ndx = 0; // Mark unused if (pollfd_slot_ndx < m_pollfd_slots.size() - 1) { pollfd& last_pollfd_slot = m_pollfd_slots.back(); m_operations[last_pollfd_slot.fd].pollfd_slot_ndx = pollfd_slot_ndx; m_pollfd_slots[pollfd_slot_ndx] = last_pollfd_slot; } m_pollfd_slots.pop_back(); } #endif // !(REALM_NETWORK_USE_EPOLL || REALM_HAVE_KQUEUE) #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS auto Service::IoReactor::get_and_reset_sleep_time() noexcept -> clock::duration { clock::duration sleep_time = m_sleep_time; m_sleep_time = clock::duration::zero(); return sleep_time; } #endif // REALM_UTIL_NETWORK_EVENT_LOOP_METRICS class Service::Impl { public: Service& service; IoReactor io_reactor; Impl(Service& s) : service{s} , io_reactor{} // Throws { } ~Impl() { bool resolver_thread_started = m_resolver_thread.joinable(); if (resolver_thread_started) { { std::lock_guard lock{m_mutex}; m_stop_resolver_thread = true; m_resolver_cond.notify_all(); } m_resolver_thread.join(); } // Avoid calls to recycle_post_oper() after destruction has begun. m_completed_operations.clear(); } void report_event_loop_metrics(util::UniqueFunction<EventLoopMetricsHandler> handler) { #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS m_event_loop_metrics_timer.emplace(service); m_event_loop_metrics_timer->async_wait( std::chrono::seconds{30}, [this, handler = std::move(handler)](Status status) { REALM_ASSERT(status.is_ok()); clock::time_point now = clock::now(); clock::duration elapsed_time = now - m_event_loop_metrics_start_time; clock::duration sleep_time = io_reactor.get_and_reset_sleep_time(); clock::duration nonsleep_time = elapsed_time - sleep_time; double saturation = double(nonsleep_time.count()) / double(elapsed_time.count()); clock::duration internal_exec_time = nonsleep_time - m_handler_exec_time; internal_exec_time += now - m_handler_exec_start_time; double inefficiency = double(internal_exec_time.count()) / double(elapsed_time.count()); m_event_loop_metrics_start_time = now; m_handler_exec_start_time = now; m_handler_exec_time = clock::duration::zero(); handler(saturation, inefficiency); // Throws report_event_loop_metrics(std::move(handler)); // Throws }); // Throws #else static_cast<void>(handler); #endif } void run() { run_impl(true); } void run_until_stopped() { run_impl(false); } void stop() noexcept { { std::lock_guard lock{m_mutex}; if (m_stopped) return; m_stopped = true; } io_reactor.interrupt(); } void reset() noexcept { std::lock_guard lock{m_mutex}; m_stopped = false; } static Endpoint::List resolve(const Resolver::Query&, std::error_code&); void add_resolve_oper(LendersResolveOperPtr op) { { std::lock_guard lock{m_mutex}; m_resolve_operations.push_back(std::move(op)); // Throws m_resolver_cond.notify_all(); } bool resolver_thread_started = m_resolver_thread.joinable(); if (resolver_thread_started) return; auto func = [this]() noexcept { resolver_thread(); }; m_resolver_thread = std::thread{std::move(func)}; } void add_wait_oper(LendersWaitOperPtr op) { m_wait_operations.push(std::move(op)); // Throws } void post(PostOperConstr constr, std::size_t size, void* cookie) { { std::lock_guard lock{m_mutex}; std::unique_ptr<char[]> mem; if (m_post_oper && m_post_oper->m_size >= size) { // Reuse old memory AsyncOper* op = m_post_oper.release(); REALM_ASSERT(dynamic_cast<UnusedOper*>(op)); static_cast<UnusedOper*>(op)->UnusedOper::~UnusedOper(); // Static dispatch mem.reset(static_cast<char*>(static_cast<void*>(op))); } else { // Allocate new memory mem.reset(new char[size]); // Throws } std::unique_ptr<PostOperBase, LendersOperDeleter> op; op.reset((*constr)(mem.get(), size, *this, cookie)); // Throws mem.release(); m_completed_operations_2.push_back(std::move(op)); } io_reactor.interrupt(); } void recycle_post_oper(PostOperBase* op) noexcept { std::size_t size = op->m_size; op->~PostOperBase(); // Dynamic dispatch OwnersOperPtr op_2(new (op) UnusedOper(size)); // Does not throw // Keep the larger memory chunk (`op_2` or m_post_oper) { std::lock_guard lock{m_mutex}; if (!m_post_oper || m_post_oper->m_size < size) swap(op_2, m_post_oper); } } void trigger_exec(TriggerExecOperBase& op) noexcept { { std::lock_guard lock{m_mutex}; if (op.m_in_use) return; op.m_in_use = true; bind_ptr<TriggerExecOperBase> op_2{&op}; // Increment use count LendersOperPtr op_3{op_2.release()}; m_completed_operations_2.push_back(std::move(op_3)); } io_reactor.interrupt(); } void reset_trigger_exec(TriggerExecOperBase& op) noexcept { std::lock_guard lock{m_mutex}; op.m_in_use = false; } void add_completed_oper(LendersOperPtr op) noexcept { m_completed_operations.push_back(std::move(op)); } void remove_canceled_ops(Descriptor& desc) noexcept { io_reactor.remove_canceled_ops(desc, m_completed_operations); } void cancel_resolve_oper(ResolveOperBase& op) noexcept { std::lock_guard lock{m_mutex}; op.cancel(); } void cancel_incomplete_wait_oper(WaitOperBase& op) noexcept { auto p = std::equal_range(m_wait_operations.begin(), m_wait_operations.end(), op.m_expiration_time, WaitOperCompare{}); auto pred = [&op](const LendersWaitOperPtr& op_2) { return &*op_2 == &op; }; auto i = std::find_if(p.first, p.second, pred); REALM_ASSERT(i != p.second); m_completed_operations.push_back(m_wait_operations.erase(i)); } private: OperQueue<AsyncOper> m_completed_operations; // Completed, canceled, and post operations struct WaitOperCompare { bool operator()(const LendersWaitOperPtr& a, clock::time_point b) { return a->m_expiration_time > b; } bool operator()(clock::time_point a, const LendersWaitOperPtr& b) { return a > b->m_expiration_time; } bool operator()(const LendersWaitOperPtr& a, const LendersWaitOperPtr& b) { return a->m_expiration_time > b->m_expiration_time; } }; using WaitQueue = util::PriorityQueue<LendersWaitOperPtr, std::vector<LendersWaitOperPtr>, WaitOperCompare>; WaitQueue m_wait_operations; std::mutex m_mutex; OwnersOperPtr m_post_oper; // Protected by `m_mutex` OperQueue<ResolveOperBase> m_resolve_operations; // Protected by `m_mutex` OperQueue<AsyncOper> m_completed_operations_2; // Protected by `m_mutex` bool m_stopped = false; // Protected by `m_mutex` bool m_stop_resolver_thread = false; // Protected by `m_mutex` bool m_resolve_in_progress = false; // Protected by `m_mutex` std::condition_variable m_resolver_cond; // Protected by `m_mutex` std::thread m_resolver_thread; #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS util::Optional<DeadlineTimer> m_event_loop_metrics_timer; clock::time_point m_event_loop_metrics_start_time = clock::now(); clock::time_point m_handler_exec_start_time; clock::duration m_handler_exec_time = clock::duration::zero(); #endif void run_impl(bool return_when_idle) { bool no_incomplete_resolve_operations; on_handlers_executed_or_interrupted : { std::lock_guard lock{m_mutex}; if (m_stopped) return; // Note: Order of post operations must be preserved. m_completed_operations.push_back(m_completed_operations_2); no_incomplete_resolve_operations = (!m_resolve_in_progress && m_resolve_operations.empty()); if (m_completed_operations.empty()) goto on_time_progressed; } on_operations_completed : { #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS m_handler_exec_start_time = clock::now(); #endif while (LendersOperPtr op = m_completed_operations.pop_front()) execute(op); // Throws #ifdef REALM_UTIL_NETWORK_EVENT_LOOP_METRICS m_handler_exec_time += clock::now() - m_handler_exec_start_time; #endif goto on_handlers_executed_or_interrupted; } on_time_progressed : { clock::time_point now = clock::now(); if (process_timers(now)) goto on_operations_completed; bool no_incomplete_operations = (io_reactor.empty() && m_wait_operations.empty() && no_incomplete_resolve_operations); if (no_incomplete_operations && return_when_idle) { // We can only get to this point when there are no completion // handlers ready to execute. It happens either because of a // fall-through from on_operations_completed, or because of a // jump to on_time_progressed, but that only happens if no // completions handlers became ready during // wait_and_process_io(). // // We can also only get to this point when there are no // asynchronous operations in progress (due to the preceeding // if-condition. // // It is possible that an other thread has added new post // operations since we checked, but there is really no point in // rechecking that, as it is always possible, even after a // recheck, that new post handlers get added after we decide to // return, but before we actually do return. Also, if would // offer no additional guarantees to the application. return; // Out of work } // Blocking wait for I/O bool interrupted = false; if (wait_and_process_io(now, interrupted)) // Throws goto on_operations_completed; if (interrupted) goto on_handlers_executed_or_interrupted; goto on_time_progressed; } } bool process_timers(clock::time_point now) { bool any_operations_completed = false; for (;;) { if (m_wait_operations.empty()) break; auto& op = m_wait_operations.top(); if (now < op->m_expiration_time) break; op->complete(); m_completed_operations.push_back(m_wait_operations.pop_top()); any_operations_completed = true; } return any_operations_completed; } bool wait_and_process_io(clock::time_point now, bool& interrupted) { clock::time_point timeout; if (!m_wait_operations.empty()) timeout = m_wait_operations.top()->m_expiration_time; bool operations_completed = io_reactor.wait_and_advance(timeout, now, interrupted, m_completed_operations); // Throws return operations_completed; } static void execute(LendersOperPtr& lenders_ptr) { lenders_ptr.release()->recycle_and_execute(); // Throws } void resolver_thread() noexcept { LendersResolveOperPtr op; for (;;) { { std::unique_lock lock{m_mutex}; if (op) { m_completed_operations_2.push_back(std::move(op)); io_reactor.interrupt(); } m_resolve_in_progress = false; while (m_resolve_operations.empty() && !m_stop_resolver_thread) m_resolver_cond.wait(lock); if (m_stop_resolver_thread) return; op = m_resolve_operations.pop_front(); m_resolve_in_progress = true; if (op->is_canceled()) continue; } try { op->m_endpoints = resolve(op->m_query, op->m_error_code); // Throws only std::bad_alloc } catch (std::bad_alloc&) { op->m_error_code = make_basic_system_error_code(ENOMEM); } op->complete(); } } }; // This function promises to only ever throw std::bad_alloc. Endpoint::List Service::Impl::resolve(const Resolver::Query& query, std::error_code& ec) { Endpoint::List list; using addrinfo_type = struct addrinfo; addrinfo_type hints = addrinfo_type(); // Clear hints.ai_flags = query.m_flags; hints.ai_family = query.m_protocol.m_family; hints.ai_socktype = query.m_protocol.m_socktype; hints.ai_protocol = query.m_protocol.m_protocol; const char* query_host = query.m_host.empty() ? 0 : query.m_host.c_str(); const char* query_service = query.m_service.empty() ? 0 : query.m_service.c_str(); struct addrinfo* first = nullptr; int ret = ::getaddrinfo(query_host, query_service, &hints, &first); if (REALM_UNLIKELY(ret != 0)) { #ifdef EAI_SYSTEM if (ret == EAI_SYSTEM) { if (errno != 0) { ec = make_basic_system_error_code(errno); } else { ec = error::unknown; } return list; } #endif ec = translate_addrinfo_error(ret); return list; } GetaddrinfoResultOwner gro(first); // Count number of IPv4/IPv6 endpoints std::size_t num_endpoints = 0; { struct addrinfo* curr = first; while (curr) { bool ip_v4 = curr->ai_family == AF_INET; bool ip_v6 = curr->ai_family == AF_INET6; if (ip_v4 || ip_v6) ++num_endpoints; curr = curr->ai_next; } } REALM_ASSERT(num_endpoints >= 1); // Copy the IPv4/IPv6 endpoints list.m_endpoints.set_size(num_endpoints); // Throws struct addrinfo* curr = first; std::size_t endpoint_ndx = 0; while (curr) { bool ip_v4 = curr->ai_family == AF_INET; bool ip_v6 = curr->ai_family == AF_INET6; if (ip_v4 || ip_v6) { REALM_ASSERT((ip_v4 && curr->ai_addrlen == sizeof(Endpoint::sockaddr_ip_v4_type)) || (ip_v6 && curr->ai_addrlen == sizeof(Endpoint::sockaddr_ip_v6_type))); Endpoint& ep = list.m_endpoints[endpoint_ndx]; ep.m_protocol.m_family = curr->ai_family; ep.m_protocol.m_socktype = curr->ai_socktype; ep.m_protocol.m_protocol = curr->ai_protocol; if (ip_v4) { ep.m_sockaddr_union.m_ip_v4 = reinterpret_cast<Endpoint::sockaddr_ip_v4_type&>(*curr->ai_addr); } else { ep.m_sockaddr_union.m_ip_v6 = reinterpret_cast<Endpoint::sockaddr_ip_v6_type&>(*curr->ai_addr); } ++endpoint_ndx; } curr = curr->ai_next; } ec = std::error_code(); // Success return list; } Service::Service() : m_impl{std::make_unique<Impl>(*this)} // Throws { } Service::~Service() noexcept {} void Service::run() { m_impl->run(); // Throws } void Service::run_until_stopped() { m_impl->run_until_stopped(); } void Service::stop() noexcept { m_impl->stop(); } void Service::reset() noexcept { m_impl->reset(); } void Service::report_event_loop_metrics(util::UniqueFunction<EventLoopMetricsHandler> handler) { m_impl->report_event_loop_metrics(std::move(handler)); // Throws } void Service::do_post(PostOperConstr constr, std::size_t size, void* cookie) { m_impl->post(constr, size, cookie); // Throws } void Service::recycle_post_oper(Impl& impl, PostOperBase* op) noexcept { impl.recycle_post_oper(op); } void Service::trigger_exec(Impl& impl, TriggerExecOperBase& op) noexcept { impl.trigger_exec(op); } void Service::reset_trigger_exec(Impl& impl, TriggerExecOperBase& op) noexcept { impl.reset_trigger_exec(op); } void Service::Descriptor::accept(Descriptor& desc, StreamProtocol protocol, Endpoint* ep, std::error_code& ec) noexcept { REALM_ASSERT(is_open()); union union_type { Endpoint::sockaddr_union_type m_sockaddr_union; char m_extra_byte[sizeof(Endpoint::sockaddr_union_type) + 1]; }; union_type buffer; struct sockaddr* addr = &buffer.m_sockaddr_union.m_base; socklen_t addr_len = sizeof buffer; CloseGuard new_sock_fd; for (;;) { #if HAVE_LINUX_ACCEPT4 // On Linux (HAVE_LINUX_ACCEPT4), make the accepted socket inherit the // O_NONBLOCK status flag from the accepting socket to avoid an extra // call to fcntl(). Note, it is deemed most likely that the accepted // socket is going to be used in nonblocking when, and only when the // accepting socket is used in nonblocking mode. Other platforms are // handled below. int flags = SOCK_CLOEXEC; if (!in_blocking_mode()) flags |= SOCK_NONBLOCK; native_handle_type ret = ::accept4(m_fd, addr, &addr_len, flags); #else native_handle_type ret = ::accept(m_fd, addr, &addr_len); #endif #ifdef _WIN32 if (ret == INVALID_SOCKET) { int err = WSAGetLastError(); if (err == WSAEINTR) continue; // Retry on interruption by system signal set_read_ready(err != WSAEWOULDBLOCK); ec = make_winsock_error_code(err); // Failure return; } #else if (REALM_UNLIKELY(ret == -1)) { int err = errno; if (err == EINTR) continue; // Retry on interruption by system signal if (err == EWOULDBLOCK) err = EAGAIN; set_read_ready(err != EAGAIN); ec = make_basic_system_error_code(err); // Failure return; } #endif new_sock_fd.reset(ret); #if REALM_PLATFORM_APPLE int optval = 1; ret = ::setsockopt(new_sock_fd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof optval); if (REALM_UNLIKELY(ret == -1)) { // setsockopt() reports EINVAL if the other side disconnected while // the connection was waiting in the listen queue. int err = errno; if (err == EINVAL) { continue; } ec = make_basic_system_error_code(err); return; } #endif set_read_ready(true); break; } socklen_t expected_addr_len = protocol.is_ip_v4() ? sizeof(Endpoint::sockaddr_ip_v4_type) : sizeof(Endpoint::sockaddr_ip_v6_type); if (REALM_UNLIKELY(addr_len != expected_addr_len)) REALM_TERMINATE("Unexpected peer address length"); #if !HAVE_LINUX_ACCEPT4 { bool value = true; if (REALM_UNLIKELY(set_cloexec_flag(new_sock_fd, value, ec))) return; } #endif // On some platforms (such as Mac OS X), the accepted socket automatically // inherits file status flags from the accepting socket, but on other // systems, this is not the case. In the case of Linux (HAVE_LINUX_ACCEPT4), // the inheriting behaviour is obtained by using the Linux specific // accept4() system call. // // For other platforms, we need to be sure that m_in_blocking_mode for the // new socket is initialized to reflect the actual state of O_NONBLOCK on // the new socket. // // Note: This implementation currently never modifies status flags other // than O_NONBLOCK, so we only need to consider that flag. #if !REALM_PLATFORM_APPLE && !HAVE_LINUX_ACCEPT4 // Make the accepted socket inherit the state of O_NONBLOCK from the // accepting socket. { bool value = !m_in_blocking_mode; if (::set_nonblock_flag(new_sock_fd, value, ec)) return; } #endif desc.assign(new_sock_fd.release(), m_in_blocking_mode); desc.set_write_ready(true); if (ep) { ep->m_protocol = protocol; ep->m_sockaddr_union = buffer.m_sockaddr_union; } ec = std::error_code(); // Success } std::size_t Service::Descriptor::read_some(char* buffer, std::size_t size, std::error_code& ec) noexcept { if (REALM_UNLIKELY(assume_read_would_block())) { ec = error::resource_unavailable_try_again; // Failure return 0; } for (;;) { int flags = 0; #ifdef _WIN32 ssize_t ret = ::recv(m_fd, buffer, int(size), flags); if (ret == SOCKET_ERROR) { int err = WSAGetLastError(); // Retry on interruption by system signal if (err == WSAEINTR) continue; set_read_ready(err != WSAEWOULDBLOCK); ec = make_winsock_error_code(err); // Failure return 0; } #else ssize_t ret = ::recv(m_fd, buffer, size, flags); if (ret == -1) { int err = errno; // Retry on interruption by system signal if (err == EINTR) continue; if (err == EWOULDBLOCK) err = EAGAIN; set_read_ready(err != EAGAIN); ec = make_basic_system_error_code(err); // Failure return 0; } #endif if (REALM_UNLIKELY(ret == 0)) { set_read_ready(true); ec = MiscExtErrors::end_of_input; return 0; } REALM_ASSERT(ret > 0); std::size_t n = std::size_t(ret); REALM_ASSERT(n <= size); #if REALM_NETWORK_USE_EPOLL // On Linux a partial read (n < size) on a nonblocking stream-mode // socket is guaranteed to only ever happen if a complete read would // have been impossible without blocking (i.e., without failing with // EAGAIN/EWOULDBLOCK), or if the end of input from the remote peer was // detected by the Linux kernel. // // Further more, after a partial read, and when working with Linux epoll // in edge-triggered mode (EPOLLET), it is safe to suspend further // reading until a new read-readiness notification is received, provided // that we registered interest in EPOLLRDHUP events, and an EPOLLRDHUP // event was not received prior to the partial read. This is safe in the // sense that reading is guaranteed to be resumed in a timely fashion // (without unnessesary blocking), and in a manner that is free of race // conditions. Note in particular that if a read was partial because the // kernel had detected the end of input prior to that read, but the // EPOLLRDHUP event was not received prior the that read, then reading // will still be resumed immediately by the pending EPOLLRDHUP event. // // Note that without this extra "loss of read-readiness" trigger, it // would have been necessary for the caller to immediately follow up // with an (otherwise redundant) additional invocation of read_some() // just to detect the loss of read-readiness. // // FIXME: Will this scheme also work with Kqueue on FreeBSD and macOS? // In particular, do we know that a partial read (n < size) on a // nonblocking stream-mode socket is guaranteed to only ever happen if a // complete read would have been impossible without blocking, or if the // end of input from the remote peer was detected by the FreeBSD and/or // macOS kernel? See http://stackoverflow.com/q/40123626/1698548. set_read_ready(n == size || m_imminent_end_of_input); #else set_read_ready(true); #endif ec = std::error_code(); // Success return n; } } std::size_t Service::Descriptor::write_some(const char* data, std::size_t size, std::error_code& ec) noexcept { if (REALM_UNLIKELY(assume_write_would_block())) { ec = error::resource_unavailable_try_again; // Failure return 0; } for (;;) { int flags = 0; #ifdef __linux__ // Prevent SIGPIPE when remote peer has closed the connection. flags |= MSG_NOSIGNAL; #endif #ifdef _WIN32 ssize_t ret = ::send(m_fd, data, int(size), flags); if (ret == SOCKET_ERROR) { int err = WSAGetLastError(); // Retry on interruption by system signal if (err == WSAEINTR) continue; set_write_ready(err != WSAEWOULDBLOCK); ec = make_winsock_error_code(err); // Failure return 0; } #else ssize_t ret = ::send(m_fd, data, size, flags); if (ret == -1) { int err = errno; // Retry on interruption by system signal if (err == EINTR) continue; #if REALM_PLATFORM_APPLE // The macOS kernel can generate an undocumented EPROTOTYPE in // certain cases where the peer has closed the connection (in // tcp_usr_send() in bsd/netinet/tcp_usrreq.c) See also // http://erickt.github.io/blog/2014/11/19/adventures-in-debugging-a-potential-osx-kernel-bug/. if (REALM_UNLIKELY(err == EPROTOTYPE)) err = EPIPE; #endif if (err == EWOULDBLOCK) err = EAGAIN; set_write_ready(err != EAGAIN); ec = make_basic_system_error_code(err); // Failure return 0; } #endif REALM_ASSERT(ret >= 0); std::size_t n = std::size_t(ret); REALM_ASSERT(n <= size); #if REALM_NETWORK_USE_EPOLL // On Linux a partial write (n < size) on a nonblocking stream-mode // socket is guaranteed to only ever happen if a complete write would // have been impossible without blocking (i.e., without failing with // EAGAIN/EWOULDBLOCK). // // Further more, after a partial write, and when working with Linux // epoll in edge-triggered mode (EPOLLET), it is safe to suspend further // writing until a new write-readiness notification is received. This is // safe in the sense that writing is guaranteed to be resumed in a // timely fashion (without unnessesary blocking), and in a manner that // is free of race conditions. // // Note that without this extra "loss of write-readiness" trigger, it // would have been necessary for the caller to immediately follow up // with an (otherwise redundant) additional invocation of write_some() // just to detect the loss of write-readiness. // // FIXME: Will this scheme also work with Kqueue on FreeBSD and macOS? // In particular, do we know that a partial write (n < size) on a // nonblocking stream-mode socket is guaranteed to only ever happen if a // complete write would have been impossible without blocking? See // http://stackoverflow.com/q/40123626/1698548. set_write_ready(n == size); #else set_write_ready(true); #endif ec = std::error_code(); // Success return n; } } #if REALM_NETWORK_USE_EPOLL || REALM_HAVE_KQUEUE void Service::Descriptor::deregister_for_async() noexcept { service_impl.io_reactor.deregister_desc(*this); } #endif // REALM_NETWORK_USE_EPOLL || REALM_HAVE_KQUEUE void Service::Descriptor::set_nonblock_flag(bool value) { ::set_nonblock_flag(m_fd, value); // Throws } void Service::Descriptor::add_initiated_oper(LendersIoOperPtr op, Want want) { if (REALM_UNLIKELY(want == Want::nothing)) { REALM_ASSERT(op->is_complete()); service_impl.add_completed_oper(std::move(op)); return; } REALM_ASSERT(!op->is_complete()); service_impl.io_reactor.add_oper(*this, std::move(op), want); // Throws } void Service::Descriptor::do_close() noexcept { checked_close(m_fd); m_fd = -1; } auto Service::Descriptor::do_release() noexcept -> native_handle_type { native_handle_type fd = m_fd; m_fd = -1; return fd; } Service& Resolver::get_service() noexcept { return m_service_impl.service; } Endpoint::List Resolver::resolve(const Query& query, std::error_code& ec) { return Service::Impl::resolve(query, ec); // Throws } void Resolver::cancel() noexcept { if (m_resolve_oper && m_resolve_oper->in_use() && !m_resolve_oper->is_canceled()) { Service::ResolveOperBase& op = static_cast<Service::ResolveOperBase&>(*m_resolve_oper); m_service_impl.cancel_resolve_oper(op); } } void Resolver::initiate_oper(Service::LendersResolveOperPtr op) { m_service_impl.add_resolve_oper(std::move(op)); // Throws } Service& SocketBase::get_service() noexcept { return m_desc.service_impl.service; } void SocketBase::cancel() noexcept { bool any_incomplete = false; if (m_read_oper && m_read_oper->in_use() && !m_read_oper->is_canceled()) { m_read_oper->cancel(); if (!m_read_oper->is_complete()) any_incomplete = true; } if (m_write_oper && m_write_oper->in_use() && !m_write_oper->is_canceled()) { m_write_oper->cancel(); if (!m_write_oper->is_complete()) any_incomplete = true; } if (any_incomplete) m_desc.service_impl.remove_canceled_ops(m_desc); } std::error_code SocketBase::bind(const Endpoint& ep, std::error_code& ec) { if (!is_open()) { if (REALM_UNLIKELY(open(ep.protocol(), ec))) return ec; } native_handle_type sock_fd = m_desc.native_handle(); socklen_t addr_len = ep.m_protocol.is_ip_v4() ? sizeof(Endpoint::sockaddr_ip_v4_type) : sizeof(Endpoint::sockaddr_ip_v6_type); int ret = ::bind(sock_fd, &ep.m_sockaddr_union.m_base, addr_len); if (REALM_UNLIKELY(check_socket_error(ret, ec))) return ec; ec = std::error_code(); // Success return ec; } Endpoint SocketBase::local_endpoint(std::error_code& ec) const { Endpoint ep; union union_type { Endpoint::sockaddr_union_type m_sockaddr_union; char m_extra_byte[sizeof(Endpoint::sockaddr_union_type) + 1]; }; native_handle_type sock_fd = m_desc.native_handle(); union_type buffer; struct sockaddr* addr = &buffer.m_sockaddr_union.m_base; socklen_t addr_len = sizeof buffer; int ret = ::getsockname(sock_fd, addr, &addr_len); if (REALM_UNLIKELY(check_socket_error(ret, ec))) return ep; socklen_t expected_addr_len = m_protocol.is_ip_v4() ? sizeof(Endpoint::sockaddr_ip_v4_type) : sizeof(Endpoint::sockaddr_ip_v6_type); if (addr_len != expected_addr_len) throw util::runtime_error("Unexpected local address length"); ep.m_protocol = m_protocol; ep.m_sockaddr_union = buffer.m_sockaddr_union; ec = std::error_code(); // Success #ifdef _WIN32 ep.m_sockaddr_union.m_ip_v4.sin_addr.s_addr = inet_addr("127.0.0.1"); #endif return ep; } std::error_code SocketBase::open(const StreamProtocol& prot, std::error_code& ec) { if (REALM_UNLIKELY(is_open())) throw util::runtime_error("Socket is already open"); int type = prot.m_socktype; #if HAVE_LINUX_SOCK_CLOEXEC type |= SOCK_CLOEXEC; #endif native_handle_type ret = ::socket(prot.m_family, type, prot.m_protocol); #ifdef _WIN32 if (REALM_UNLIKELY(ret == INVALID_SOCKET)) { ec = make_winsock_error_code(WSAGetLastError()); return ec; } #else if (REALM_UNLIKELY(ret == -1)) { ec = make_basic_system_error_code(errno); return ec; } #endif CloseGuard sock_fd{ret}; #if !HAVE_LINUX_SOCK_CLOEXEC { bool value = true; if (REALM_UNLIKELY(set_cloexec_flag(sock_fd, value, ec))) return ec; } #endif #if REALM_PLATFORM_APPLE { int optval = 1; int ret = setsockopt(sock_fd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof optval); if (REALM_UNLIKELY(ret == -1)) { ec = make_basic_system_error_code(errno); return ec; } } #endif bool in_blocking_mode = true; // New sockets are in blocking mode by default m_desc.assign(sock_fd.release(), in_blocking_mode); m_protocol = prot; ec = std::error_code(); // Success return ec; } std::error_code SocketBase::do_assign(const StreamProtocol& prot, native_handle_type sock_fd, std::error_code& ec) { if (REALM_UNLIKELY(is_open())) throw util::runtime_error("Socket is already open"); // We need to know whether the specified socket is in blocking or in // nonblocking mode. Rather than reading the current mode, we set it to // blocking mode (disable nonblocking mode), and initialize // `m_in_blocking_mode` to true. { bool value = false; if (::set_nonblock_flag(sock_fd, value, ec)) return ec; } bool in_blocking_mode = true; // New sockets are in blocking mode by default m_desc.assign(sock_fd, in_blocking_mode); m_protocol = prot; ec = std::error_code(); // Success return ec; } void SocketBase::get_option(opt_enum opt, void* value_data, std::size_t& value_size, std::error_code& ec) const { int level = 0; int option_name = 0; map_option(opt, level, option_name); native_handle_type sock_fd = m_desc.native_handle(); socklen_t option_len = socklen_t(value_size); int ret = ::getsockopt(sock_fd, level, option_name, static_cast<char*>(value_data), &option_len); if (REALM_UNLIKELY(check_socket_error(ret, ec))) return; value_size = std::size_t(option_len); ec = std::error_code(); // Success } void SocketBase::set_option(opt_enum opt, const void* value_data, std::size_t value_size, std::error_code& ec) { int level = 0; int option_name = 0; map_option(opt, level, option_name); native_handle_type sock_fd = m_desc.native_handle(); int ret = ::setsockopt(sock_fd, level, option_name, static_cast<const char*>(value_data), socklen_t(value_size)); if (REALM_UNLIKELY(check_socket_error(ret, ec))) return; ec = std::error_code(); // Success } void SocketBase::map_option(opt_enum opt, int& level, int& option_name) const { switch (opt) { case opt_ReuseAddr: level = SOL_SOCKET; option_name = SO_REUSEADDR; return; case opt_Linger: level = SOL_SOCKET; #if REALM_PLATFORM_APPLE // By default, SO_LINGER on Darwin uses "ticks" instead of // seconds for better accuracy, but we want to be cross-platform. option_name = SO_LINGER_SEC; #else option_name = SO_LINGER; #endif // REALM_PLATFORM_APPLE return; case opt_NoDelay: level = IPPROTO_TCP; option_name = TCP_NODELAY; // Specified by POSIX.1-2001 return; } REALM_ASSERT(false); } std::error_code Socket::connect(const Endpoint& ep, std::error_code& ec) { REALM_ASSERT(!m_write_oper || !m_write_oper->in_use()); if (!is_open()) { if (REALM_UNLIKELY(open(ep.protocol(), ec))) return ec; } m_desc.ensure_blocking_mode(); // Throws native_handle_type sock_fd = m_desc.native_handle(); socklen_t addr_len = (ep.m_protocol.is_ip_v4() ? sizeof(Endpoint::sockaddr_ip_v4_type) : sizeof(Endpoint::sockaddr_ip_v6_type)); int ret = ::connect(sock_fd, &ep.m_sockaddr_union.m_base, addr_len); if (REALM_UNLIKELY(check_socket_error(ret, ec))) return ec; ec = std::error_code(); // Success return ec; } std::error_code Socket::shutdown(shutdown_type what, std::error_code& ec) { native_handle_type sock_fd = m_desc.native_handle(); int how = what; int ret = ::shutdown(sock_fd, how); if (REALM_UNLIKELY(check_socket_error(ret, ec))) return ec; ec = std::error_code(); // Success return ec; } bool Socket::initiate_async_connect(const Endpoint& ep, std::error_code& ec) { if (!is_open()) { if (REALM_UNLIKELY(open(ep.protocol(), ec))) return true; // Failure } m_desc.ensure_nonblocking_mode(); // Throws // Initiate connect operation. native_handle_type sock_fd = m_desc.native_handle(); socklen_t addr_len = ep.m_protocol.is_ip_v4() ? sizeof(Endpoint::sockaddr_ip_v4_type) : sizeof(Endpoint::sockaddr_ip_v6_type); int ret = ::connect(sock_fd, &ep.m_sockaddr_union.m_base, addr_len); if (ret != -1) { ec = std::error_code(); // Success return true; // Immediate completion. } // EINPROGRESS (and on Windows, also WSAEWOULDBLOCK) indicates that the // underlying connect operation was successfully initiated, but not // immediately completed, and EALREADY indicates that an underlying connect // operation was already initiated, and still not completed, presumably // because a previous call to connect() or async_connect() failed, or was // canceled. #ifdef _WIN32 int err = WSAGetLastError(); if (err != WSAEWOULDBLOCK) { ec = make_winsock_error_code(err); return true; // Failure } #else int err = errno; if (REALM_UNLIKELY(err != EINPROGRESS && err != EALREADY)) { ec = make_basic_system_error_code(err); return true; // Failure } #endif return false; // Successful initiation, but no immediate completion. } std::error_code Socket::finalize_async_connect(std::error_code& ec) noexcept { native_handle_type sock_fd = m_desc.native_handle(); int connect_errno = 0; socklen_t connect_errno_size = sizeof connect_errno; int ret = ::getsockopt(sock_fd, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&connect_errno), &connect_errno_size); if (REALM_UNLIKELY(check_socket_error(ret, ec))) return ec; // getsockopt() failed if (REALM_UNLIKELY(connect_errno)) { ec = make_basic_system_error_code(connect_errno); return ec; // connect failed } return std::error_code(); // Success } std::error_code Acceptor::listen(int backlog, std::error_code& ec) { native_handle_type sock_fd = m_desc.native_handle(); int ret = ::listen(sock_fd, backlog); if (REALM_UNLIKELY(check_socket_error(ret, ec))) return ec; ec = std::error_code(); // Success return ec; } Service& DeadlineTimer::get_service() noexcept { return m_service_impl.service; } void DeadlineTimer::cancel() noexcept { if (m_wait_oper && m_wait_oper->in_use() && !m_wait_oper->is_canceled()) { m_wait_oper->cancel(); if (!m_wait_oper->is_complete()) { using WaitOperBase = Service::WaitOperBase; WaitOperBase& wait_operation = static_cast<WaitOperBase&>(*m_wait_oper); m_service_impl.cancel_incomplete_wait_oper(wait_operation); } } } void DeadlineTimer::initiate_oper(Service::LendersWaitOperPtr op) { m_service_impl.add_wait_oper(std::move(op)); // Throws } bool ReadAheadBuffer::read(char*& begin, char* end, int delim, std::error_code& ec) noexcept { std::size_t in_avail = m_end - m_begin; std::size_t out_avail = end - begin; std::size_t n = std::min(in_avail, out_avail); // If n is 0, return whether or not the read expects 0 bytes for the completed response if (n == 0) return out_avail == 0; bool delim_mode = (delim != std::char_traits<char>::eof()); char* i = (!delim_mode ? m_begin + n : std::find(m_begin, m_begin + n, std::char_traits<char>::to_char_type(delim))); begin = std::copy(m_begin, i, begin); m_begin = i; if (begin == end) { if (delim_mode) ec = MiscExtErrors::delim_not_found; } else { if (m_begin == m_end) return false; REALM_ASSERT(delim_mode); *begin++ = *m_begin++; // Transfer delimiter } return true; } namespace realm::sync::network { std::string host_name() { // POSIX allows for gethostname() to report success even if the buffer is // too small to hold the name, and in that case POSIX requires that the // buffer is filled, but not that it contains a final null-termination. char small_stack_buffer[256]; int ret = ::gethostname(small_stack_buffer, sizeof small_stack_buffer); if (ret != -1) { // Check that a null-termination was included char* end = small_stack_buffer + sizeof small_stack_buffer; char* i = std::find(small_stack_buffer, end, 0); if (i != end) return std::string(small_stack_buffer, i); } constexpr std::size_t large_heap_buffer_size = 4096; std::unique_ptr<char[]> large_heap_buffer(new char[large_heap_buffer_size]); // Throws ret = ::gethostname(large_heap_buffer.get(), large_heap_buffer_size); if (REALM_LIKELY(ret != -1)) { // Check that a null-termination was included char* end = large_heap_buffer.get() + large_heap_buffer_size; char* i = std::find(large_heap_buffer.get(), end, 0); if (i != end) return std::string(large_heap_buffer.get(), i); } throw std::system_error(errno, std::system_category(), "gethostname() failed"); } Address make_address(const char* c_str, std::error_code& ec) noexcept { Address addr; int ret = ::inet_pton(AF_INET6, c_str, &addr.m_union); REALM_ASSERT(ret == 0 || ret == 1); if (ret == 1) { addr.m_is_ip_v6 = true; ec = std::error_code(); // Success (IPv6) return addr; } ret = ::inet_pton(AF_INET, c_str, &addr.m_union); REALM_ASSERT(ret == 0 || ret == 1); if (ret == 1) { ec = std::error_code(); // Success (IPv4) return addr; } ec = error::invalid_argument; return Address(); // FIXME: Currently. `addr.m_ip_v6_scope_id` is always set to zero. It nees // to be set based on a combined inspection of the original string // representation, and the parsed address. The following code is "borrowed" // from ASIO: /* *scope_id = 0; if (const char* if_name = strchr(src, '%')) { in6_addr_type* ipv6_address = static_cast<in6_addr_type*>(dest); bool is_link_local = ((ipv6_address->s6_addr[0] == 0xfe) && ((ipv6_address->s6_addr[1] & 0xc0) == 0x80)); bool is_multicast_link_local = ((ipv6_address->s6_addr[0] == 0xff) && ((ipv6_address->s6_addr[1] & 0x0f) == 0x02)); if (is_link_local || is_multicast_link_local) *scope_id = if_nametoindex(if_name + 1); if (*scope_id == 0) *scope_id = atoi(if_name + 1); } */ } class ResolveErrorCategory : public std::error_category { public: const char* name() const noexcept final { return "realm.sync.network.resolve"; } std::string message(int value) const final { switch (ResolveErrors(value)) { case ResolveErrors::host_not_found: return "Host not found (authoritative)"; case ResolveErrors::host_not_found_try_again: return "Host not found (non-authoritative)"; case ResolveErrors::no_data: return "The query is valid but does not have associated address data"; case ResolveErrors::no_recovery: return "A non-recoverable error occurred"; case ResolveErrors::service_not_found: return "The service is not supported for the given socket type"; case ResolveErrors::socket_type_not_supported: return "The socket type is not supported"; } REALM_ASSERT(false); return {}; } }; const std::error_category& resolve_error_category() noexcept { static const ResolveErrorCategory resolve_error_category; return resolve_error_category; } std::error_code make_error_code(ResolveErrors err) { return std::error_code(int(err), resolve_error_category()); } } // namespace realm::sync::network
6483123fe70e496ea42102f1d5da3d4e77d98a88
683b2336df14be15c5c4b40ebc6006986ecc8f1b
/sparkplug-bridge/SPARKPLUG-BRIDGE/Test/Src/Common_ut.cpp
ab82aec9c3ea1978f7a095424fd2b2cfa50ffc2c
[ "MIT" ]
permissive
dspshivaji/uwc
30f943fdfb8e4ac19a546679957cca0c4b36b378
637b3888bb617b4f44c4818d4d62d5c822cd683d
refs/heads/master
2023-07-08T20:01:50.612426
2021-07-23T15:52:18
2021-07-23T15:52:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,185
cpp
Common_ut.cpp
/******************************************************************************** * Copyright (c) 2021 Intel Corporation. * 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 "../Inc/Common_ut.hpp" void Common_ut::SetUp() { // Setup code } void Common_ut::TearDown() { // TearDown code } /** * Test case to check if getTopicParts() splits the topic successfully * @param :[in] None * @param :[out] None * @return None */ TEST_F(Common_ut, getTopicParts_Test01) { std::vector<std::string> TopicParts; CCommon::getInstance().getTopicParts("PartA_UT/PartB_UT/PartC_UT", TopicParts, "/"); EXPECT_EQ("PartC_UT",TopicParts[2]); } /** * Test case to check if function getDatapointsQ() executes successfully * @param :[in] None * @param :[out] None * @return None */ TEST_F(Common_ut, getDataPointInQ) { QMgr::getDatapointsQ(); EXPECT_EQ(true, true); } /** * Test case to check if function getScadaSubQ() executes successfully * @param :[in] None * @param :[out] None * @return None */ TEST_F(Common_ut, ScadaSubQ) { QMgr::getScadaSubQ(); EXPECT_EQ(true, true); }
7b7d6168b56bd4286bab082ed0d499ea95212c97
aea7799cdf8ecb7b9304c8898767e91949f71d4b
/round1/construct-binary-tree-from-inorder-postorder.cpp
89a148ccf1798e9fbf49471c182d14f3e55566b8
[]
no_license
elsucai/LC
e2baab13168761519ae537176e42fa04607de88a
d5915a4efb6e16e2cea5f8d448ca72c2f8edcc9b
refs/heads/master
2016-09-08T02:05:30.401990
2014-04-01T22:50:23
2014-04-01T22:50:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,163
cpp
construct-binary-tree-from-inorder-postorder.cpp
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void helper(TreeNode* &root, vector<int> &inorder, int is, int ie, vector<int> &postorder, int ps, int pe){ if(is > ie || ps > pe) return; int i, val, size; if(!root){ val = postorder[pe]; root = new TreeNode(val); } for(i = is; i <= ie; i++){ if(inorder[i] == val) break; } // i is the root in inorder size = i - is; helper(root->left, inorder, is, i-1, postorder, ps, ps + size - 1); helper(root->right, inorder, i+1, ie, postorder, ps + size, pe-1); } TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // Start typing your C/C++ solution below // DO NOT write int main() function TreeNode* root = NULL; if(inorder.empty()) return NULL; if(inorder.size() != postorder.size()) return NULL; int is, ie, ps, pe; is = ps = 0; ie = pe = inorder.size()-1; helper(root, inorder, is, ie, postorder, ps, pe); return root; } };
51ad171070a2f35b731d14c8088f7844d3066067
97564ea3ed8611b79b57504406207de7bdd2a152
/application.cpp
ef46fedf554269bcbf487cd4e597930a3c16d729
[]
no_license
sy-long/AVL-tree
0e91ae23e0f95f0f8a84b41f5ed0e2a2bff26366
54947b7b1c234f417823a4ea95f77adba12aded2
refs/heads/master
2020-04-16T19:41:59.770896
2019-01-15T15:02:33
2019-01-15T15:02:33
165,870,553
2
0
null
null
null
null
GB18030
C++
false
false
686
cpp
application.cpp
#include "avltree_h.h" #include <stdio.h> #include <stdlib.h> int main() { pnode node = NULL; int chiose; int key; while (1) { printf("1.插入节点\n"); printf("2.删除节点\n"); printf("3.退出"); printf("\n\n"); printf("请输入:"); scanf("%d", &chiose); switch (chiose) { case 1: { printf("请输入要插入的数据:"); scanf("%d", &key); node = insert(node, key); printf("\n"); show_tree(node); } break; case 2: printf("请输入要删除的数据:"); scanf("%d", &key); node = delete_node(node, key); printf("\n"); show_tree(node); break; case 3:exit(0); break; default: break; } } return 0; }
dc50c00e98beef65395120d8a17cbeabc6793f7f
0381e635c0faf699b41f3e7bc78c29ca10eda074
/SocketLib/SocketLibSocket.cpp
3be51c69d07423e1e60024c8914dad7a8ca1dabf
[]
no_license
ysbbswork/Chatroom
884b83704b579de8aa0215b4836057d6054a13a6
ebb97378c646aead31c9167dee0199fc3c6e65da
refs/heads/master
2020-03-20T09:58:03.401148
2018-06-15T14:41:33
2018-06-15T14:41:33
137,354,538
4
0
null
null
null
null
GB18030
C++
false
false
6,188
cpp
SocketLibSocket.cpp
// socket classes: Basic, Data, and Listening. #include "SocketLibSocket.h" namespace SocketLib { void Socket::Close() { #ifdef WIN32 closesocket( m_sock ); #else close( m_sock ); #endif // invalidate the socket m_sock = -1; } void Socket::SetBlocking( bool p_blockmode ) { int err; #ifdef WIN32 unsigned long mode = !p_blockmode; err = ioctlsocket( m_sock, FIONBIO, &mode ); #else // get the flags int flags = fcntl( m_sock, F_GETFL, 0 ); // set or clear the non-blocking flag if( p_blockmode == false ) { flags |= O_NONBLOCK; } else { flags &= ~O_NONBLOCK; } err = fcntl( m_sock, F_SETFL, flags ); #endif if( err == -1 ) { throw( Exception( GetError() ) ); } m_isblocking = p_blockmode; } Socket::Socket( sock p_socket ): m_sock( p_socket ) { if( p_socket != -1 ) { socklen_t s = sizeof(m_localinfo); getsockname( p_socket, (sockaddr*)(&m_localinfo), &s ); } // the socket is blocking by default m_isblocking = true; } DataSocket::DataSocket( sock p_socket ) : Socket( p_socket ),m_connected( false ) { if( p_socket != -1 ) { socklen_t s = sizeof(m_remoteinfo); getpeername( p_socket, (sockaddr*)(&m_remoteinfo), &s ); m_connected = true; } } void DataSocket::Connect( ipaddress p_addr, port p_port ) { int err; // if the socket is already connected... if( m_connected == true ) { throw Exception( EAlreadyConnected ); } // first try to obtain a socket descriptor from the OS, if // there isn't already one. if( m_sock == -1 ) { m_sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); // throw an exception if the socket could not be created if( m_sock == -1 ) { throw Exception( GetError() ); } } // set up the socket address structure m_remoteinfo.sin_family = AF_INET; m_remoteinfo.sin_port = htons( p_port ); m_remoteinfo.sin_addr.s_addr = p_addr; memset( &(m_remoteinfo.sin_zero), 0, 8 ); // now the socket is created, so connect it. socklen_t s = sizeof(struct sockaddr); err = connect( m_sock, (struct sockaddr*)(&m_remoteinfo), s ); if( err == -1 ) { throw Exception( GetError() ); } m_connected = true; // to get the local port, you need to do a little more work err = getsockname( m_sock, (struct sockaddr*)(&m_localinfo), &s ); if( err != 0 ) { throw Exception( GetError() ); } } int DataSocket::Send( const char* p_buffer, int p_size ) { int err; // make sure the socket is connected first. if( m_connected == false ) { throw Exception( ENotConnected ); } // attempt to send the data err = send( m_sock, p_buffer, p_size, 0 ); if( err == -1 ) { Error e = GetError(); if( e != EOperationWouldBlock ) { throw Exception( e ); } err = 0; } return err; } int DataSocket::Receive( char* p_buffer, int p_size ) { int err; if( m_connected == false ) { throw Exception( ENotConnected ); } err = recv( m_sock, p_buffer, p_size, 0 ); if( err == 0 ) { throw Exception( EConnectionClosed ); } if( err == -1 ) { throw Exception( GetError() ); } return err; } void DataSocket::Close() { if( m_connected == true ) { shutdown( m_sock, 2 ); } // close the socket Socket::Close(); m_connected = false; } ListeningSocket::ListeningSocket() { m_listening = false; } void ListeningSocket::Listen( port p_port ) { int err; if( m_sock == -1 ) { m_sock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); // throw an exception if the socket could not be created if( m_sock == -1 ) { throw Exception( GetError() ); } } int reuse = 1; err = setsockopt( m_sock, SOL_SOCKET, SO_REUSEADDR, (char*)(&reuse), sizeof( reuse ) ); if( err != 0 ) { throw Exception( GetError() ); } m_localinfo.sin_family = AF_INET; m_localinfo.sin_port = htons( p_port );//整个socket address structure需要动态定义的是端口号 m_localinfo.sin_addr.s_addr = htonl( INADDR_ANY );//绑定到任何地址,= inet_addr("127.0.0.1");时是绑定到具体的IP地址 memset( &(m_localinfo.sin_zero), 0, 8 ); err = bind( m_sock, (struct sockaddr*)&m_localinfo, sizeof(struct sockaddr)); if( err == -1 ) { throw Exception( GetError() ); } err = listen( m_sock, 8 ); if( err == -1 ) { throw Exception( GetError() ); } m_listening = true; } DataSocket ListeningSocket::Accept() { sock s; struct sockaddr_in socketaddress; // try to accept a connection socklen_t size = sizeof(struct sockaddr); s = accept( m_sock, (struct sockaddr*)&socketaddress, &size ); if( s == -1 ) { throw Exception( GetError() ); } // return the newly created socket. return DataSocket( s ); } void ListeningSocket::Close() { Socket::Close(); m_listening = false; } }
1d8eedf12c0aca9a00f51cc5327607a7a7013af9
691ff4baa6fd2643a5b5d969d74c80941a83f1bd
/include/indigo-bondorder/python/interface.hpp
0616de17daf93d279a7aa9b89cd13fb700e81e0c
[ "MIT" ]
permissive
Cuboxylate/indigo-bondorder
f82b1142b6e46578cd1cf0a34acca2d1b9ee4ec4
a7d4543b4245c5b987c45c1440cc5764f862fce5
refs/heads/master
2020-09-22T14:56:59.873452
2019-12-02T03:18:58
2019-12-02T03:18:58
225,249,004
0
0
MIT
2019-12-01T23:52:06
2019-12-01T23:52:05
null
UTF-8
C++
false
false
777
hpp
interface.hpp
// // interface.hpp // indigo-bondorder // // Created by Welsh, Ivan on 8/01/18. // Copyright © 2018 Allison Group. All rights reserved. // #include "../api.hpp" #include <pybind11/pybind11.h> #ifndef INDIGO_BONDORDER_PYTHON_INTERFACE_HPP #define INDIGO_BONDORDER_PYTHON_INTERFACE_HPP /// @todo add opaque set<string> stuff so can add to string // PYBIND11_MAKE_OPAQUE(std::set<indigo-bondorder::String>) namespace indigo_bondorder { void GenerateOptions(pybind11::module& m); void GeneratePyAtom(pybind11::module& m); void GeneratePyBond(pybind11::module& m); void GeneratePyMolecule(pybind11::module& m); void GeneratePyPeriodicTable(pybind11::module& m); void GeneratePyElement(pybind11::module& m); } #endif /* INDIGO_BONDORDER_PYTHON_INTERFACE_HPP */
12f76122c23930cd7ebf9ae74bbf7d344f92d76c
b14d85e2f1ed77d51e897965b3e443334f19ee6c
/main.cpp
4c69d16b879c2f9ba6f0aecd2bd0ba3009790f2c
[]
no_license
jeffrey-wro/qrfinaldemo
cd899d2d8ff34c7cb8a883296f794e07e948ce00
7250a5d76b0ea26610d34251a4bdea88a57d0656
refs/heads/master
2020-05-06T13:27:48.443862
2019-04-10T14:11:30
2019-04-10T14:11:30
180,138,256
0
0
null
null
null
null
UTF-8
C++
false
false
2,671
cpp
main.cpp
#include <vector> #include <iostream> #include <stdio.h> #include "MyRio.h" #include "I2C.h" #include "Motor_Controller.h" #include "Utils.h" #include "opencv2/core.hpp" #include "opencv2/opencv.hpp" #include "opencv2/objdetect.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/core/operations.hpp" #include "ImageSender.h" using namespace std; using namespace cv; #define ENABLE_SERVER 1 extern NiFpga_Session myrio_session; NiFpga_Status status; int main(int argc, char **argv) { int speed = 200; VideoCapture cam(0); // open the default camera if (!cam.isOpened()) // check if we succeeded return -1; status = MyRio_Open(); if (MyRio_IsNotSuccess(status)) { return status; } MyRio_I2c i2c; status = Utils::setupI2CB(&myrio_session, &i2c); Motor_Controller mc = Motor_Controller(&i2c); mc.controllerEnable(DC); int volt = mc.readBatteryVoltage(1); printf("%d\n\n", volt); string data; Mat display, frame, pts; QRCodeDetector qrDecoder = QRCodeDetector(); while(1) { cam >> frame; //get new frame cvtColor(frame, display, COLOR_BGR2GRAY); if(qrDecoder.detect(display, pts)) { while(1) { data = qrDecoder.detectAndDecode(display, pts); if(data == "Ver1") { //move backwards leftCount = -360; rightCount = 360; mc.setMotorDegrees(DC, speed, leftCount, speed, rightCount); //wait for 3 seconds Utils::waitFor(3); //turn 90 degrees left rightCount = -485; mc.setMotorDegrees(DC, 0, leftCount, speed, rightCount); //wait for 3 seconds Utils::waitFor(3); //move forwards leftCount = 360; rightCount = -360; mc.setMotorDegrees(DC, speed, leftCount, speed, rightCount); //turn 90 degrees right rightCount = 485; //fix mc.setMotorDegrees(DC, 0, leftCount, speed, rightCount); //cleanup Utils::waitFor(3); mc.controllerReset(DC); status = MyRio_Close(); return status; } if(data == "right") { //add relevant code here //move backwards leftCount += 360; rightCount -= 360; mc.setMotorDegrees(DC, speed, leftCount, speed, rightCount); //wait for 3 seconds Utils::waitFor(3); //turn 90 degrees rightCount -= 465; mc.setMotorDegrees(DC, 0, leftCount, speed, rightCount); Utils::waitFor(3); Utils::waitFor(2); mc.controllerReset(DC); status = MyRio_Close(); return status; } } } } Utils::waitFor(2); mc.controllerReset(DC); status = MyRio_Close(); return status; }
f04256c76dde705a3d9a394b71bd3a8887ec6cc4
623815a3f9e0805bc29925c8782c972a29e8bf3e
/Stock_Market/player.cpp
cf8a93ff9113e2e6dcafd321081ef7326fefacd7
[]
no_license
Conbot2/CSE-232
7d5f1f422c835624f24d48c23162b4f1960300e1
faa24d3ac93d643ab1048bb2bf28fd57f7da5746
refs/heads/master
2021-01-18T07:19:49.403121
2014-07-04T19:43:15
2014-07-04T19:43:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,116
cpp
player.cpp
#include "player.h" using std::to_string; Player::Player(double amount) { cash = amount; } bool Player::buy(Market &m, string stock, long date, long quantity) { bool valid; double price = m.get_price(stock,date) * quantity; if (price <= cash && price > -1.0) valid = true; else valid = false; if (valid) { cash -= price; stocks[stock] += quantity; } return valid; } bool Player::sell(Market &m, string stock, long date, long quantity) { bool has_stock, has_enough; if (stocks[stock] > 0) has_stock = true; else has_stock = false; if (stocks[stock] >= quantity) has_enough = true; else has_enough = false; if (has_stock && has_enough) { double profit = m.get_price(stock,date) * quantity; cash += profit; stocks[stock] -= quantity; } return (has_stock && has_enough); } string Player::to_str() { string output = "Player has:" + to_string(cash) + " dollars, stocks are:\n"; string line; for (auto elem : stocks) { line = elem.first + ", quantity " + to_string(elem.second) + "\n"; output += line; } return output; }
f93cb76c002deb48b77228245c9ed0eca8526a76
c0e240b822fc185b3542143e7b4c87c45f4655fb
/Compiler/include/Symbol.h
1d0e05bfd57e523bf87c8b252101d0afcd39eb98
[ "MIT" ]
permissive
SilenceX12138/MIPS-Microsystems
615bf01c26beb4586c114d708f17587c7bbd9952
d389b706b0930151a710b544db436c2883af958b
refs/heads/master
2023-07-29T12:13:33.938266
2021-09-09T02:57:32
2021-09-09T02:57:32
403,604,431
57
1
null
null
null
null
UTF-8
C++
false
false
3,211
h
Symbol.h
#ifndef _SYMBOL_H_ #define _SYMBOL_H_ #include <string> #include <vector> #include "Token.h" using namespace std; enum SymbolKind { UndefSymKind, ConstSym, VarSym, ArrSym, FuncSym, }; enum SymbolType { UndefSymType, IntSym, CharSym, StrSym, }; enum FunctionRetType { UndefRetType, VoidRet, IntRet, CharRet, }; class Symbol { private: // basic attr int id; int validRegionId; Token symbolToken; SymbolKind symbolKind; SymbolType symbolType; // const int constIntValue; char constCharValue; string constStrValue; // array vector<int> arrayDim; // default to be {0, 0} // function FunctionRetType retType; vector<SymbolType> argType; int stackframeSize; // memory to alloc for a function call // active record int addr; // temp const&var's offset to current region's $sp static string showName(const Symbol &s); static string showKind(const Symbol &s); static string showType(const Symbol &s); static string showConst(const Symbol &s); static string showDim(const Symbol &s); static string showRet(const Symbol &s); static string showArg(const Symbol &s); public: static int symbolCnt; Symbol(); Symbol(const Symbol &s); // 整型常量 Symbol(int validRegionId, Token symbolToken, SymbolKind symbolKind, SymbolType symbolType, int constIntValue); // 字符型常量 Symbol(int validRegionId, Token symbolToken, SymbolKind symbolKind, SymbolType symbolType, char constCharValue); // 字符串型常量 Symbol(int validRegionId, Token symbolToken, SymbolKind symbolKind, SymbolType symbolType, string constStrValue); // 简单变量 Symbol(int validRegionId, Token symbolToken, SymbolKind symbolKind, SymbolType symbolType); // 数组变量 Symbol(int validRegionId, Token symbolToken, SymbolKind symbolKind, SymbolType symbolType, vector<int> arrayDim); // 函数 Symbol(int validRegionId, Token symbolToken, SymbolKind symbolKind, FunctionRetType retType, vector<SymbolType> argType); friend ostream &operator<<(ostream &output, const Symbol &t); // 从1开始的Symbol主码=符号表索引+1 int getId(); int getValidRegionId(); // 获取符号对应的token的原始text 在符号为标识符和字符串常量时返回的是名字 string getName(); // 获取符号对应的token的小写text 在符号为标识符和字符串常量时返回的是小写名字 string getLowerName(); SymbolKind getKind(); SymbolType getType(); FunctionRetType getRetType(); int getConstIntValue(); char getConstCharValue(); string getConstStrValue(); // 获取指定维度大小 int getArrDim(int dim); // 获取数组元素个数 int getArrCnt(); // 获取参数类型列表 vector<SymbolType> getArgType(); // 变量获取栈地址 int getAddr(); // 函数获取栈大小 int getStackFrameSize(); // 是否是全局符号 bool isGlobal(); void setArgType(vector<SymbolType> argType); void setAddr(int addr); void setStackFrameSize(int size); }; extern Symbol nullSym; #endif
c123e9b064297978e2730f412d6dd817c1a57e3e
2dfa3c811556fbedf94f1af1a4b0567c9374d566
/week1/Digit palindrome.cpp
3586f57c4abb002953d6fa87f1fb718e7f365544
[]
no_license
nnonnoon/AbstractDataType
697b95d699c1f5c0bbb119479ecb833c59b79a59
f224be42faea768e818c3992699ff0dc365513e4
refs/heads/master
2020-08-27T02:05:10.140286
2019-10-24T05:02:23
2019-10-24T05:02:23
217,214,092
0
0
null
null
null
null
UTF-8
C++
false
false
357
cpp
Digit palindrome.cpp
#include <iostream> using namespace std; int main() { int n ,num,digit, count = 0; cin >> num; n=num; do{ int digit = num%10; count = (count * 10 ) + digit ; num/=10; } while (num!=0); if (n==count){ cout<<"yes\n"; } else { cout<<"no\n"; } return 0 ; }
6a0c8c15fa18ea20ed02c87f07d86ce8167c5c01
72e9c8bdb8bb7f2834a49604c73f7bf192d6e0d7
/tests/src/main.cpp
fca26ded9efea3895ab31f91627fd3b98dbcdb73
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
IntegraSources/ISML
005b36e8d3471f76d7cd222366246ace627a3061
e8c2fe0bc0480064b53f2eb6bbc36c5bbea9670c
refs/heads/master
2023-06-12T10:21:05.386158
2021-07-02T07:37:55
2021-07-02T07:37:55
382,255,914
0
0
null
null
null
null
UTF-8
C++
false
false
315
cpp
main.cpp
/** * @file main.cpp * @author Oleg E. Vorobiov <o.vorobiov(at)integrasources.com> * @date 26.02.2020 */ ISML_DISABLE_WARNINGS_PUSH # include <gtest/gtest.h> ISML_DISABLE_WARNINGS_POP auto main(int argc, char** argv) -> int { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
c8c05c875356f0a97ec212449a8ee210f4d554ab
2a1b10c8145c67ae8087ccf2f14b34d1b837a3cb
/old/Minion/src/Regression/CLogistic.h
634ad0010275beba44ca2e9237741712529923fe
[]
no_license
strikles-zz/poker
88c99903eacc2cd3572ed2135dde9d2d85024626
bfdac5742c2605bc76d56707c7c59f11c3761423
refs/heads/master
2021-06-05T20:15:18.740933
2015-10-14T15:14:53
2015-10-14T15:14:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
913
h
CLogistic.h
#pragma once //#include <unsupported/Eigen/NonLinearOptimization> #include "DB/CData.h" class CLogistic { public: CLogistic() {}; CLogistic(int br_ndx, int nacted, eBetType action); CLogistic(Matrix<double, Dynamic, Dynamic, RowMajor>& X, VectorXd& y, VectorXd& theta) {}; public: VectorXd J_history; Matrix<double, Dynamic, Dynamic, RowMajor> classifier; public: double sigmoid(const double& x); void TrainOnevsAll(const Matrix<double, Dynamic, Dynamic, RowMajor>& X, const VectorXd& y, int num_labels, double lambda); int PredictOnevsAll(const VectorXd& point); double Cost(const Matrix<double, Dynamic, Dynamic, RowMajor>& X, const VectorXd& y, VectorXd& theta, double lambda); void GradientDescent(const Matrix<double, Dynamic, Dynamic, RowMajor>& X, const VectorXd& y_class, VectorXd& theta, double alpha); private: int m_npoints, m_ndims; CDataObject* m_data; private: bool init(); };
713da2c56f2ce0d5f5a20d92668c048296823ccb
14cd82ceb0ed01235ac8c7208219fc4df7a7b1d2
/Introduction to Progamming/Lab Projects/lab4/metric_translator.cpp
7c6910db71c4df8357bbdcabfc5bbd2c54b52304
[]
no_license
OliverAkhtar/Projects
947000000e1ce1d653c58b705143b6cbe1cf4a3b
c2bcfa51886de155843aa79a4d6968d6ad0bf641
refs/heads/master
2021-01-10T15:55:45.933009
2017-11-15T21:12:22
2017-11-15T21:12:22
49,913,736
0
0
null
null
null
null
UTF-8
C++
false
false
603
cpp
metric_translator.cpp
/*This program converts kilograms, centimeters, and kilometers to pounds, inches, and miles respectively.*/ #include <iostream> using namespace std; int main() { double kilos, pounds, centimeters, inches, kilometers, miles; cout << "Enter kilograms:"; cin >> kilos; pounds = (kilos * 2.20462); cout << "Pounds:" << pounds << endl; cout << "Enter centimeters:"; cin >> centimeters; inches = (centimeters * 0.393701); cout << "Inches:" << inches << endl; cout << "Enter kilometers:"; cin >> kilometers; miles = (kilometers * 0.621371); cout << "Miles:" << miles << endl; return 0; }
b84f205db80fd2c6f66ba60e30e8cad065c61e9e
ad15b756efe01065429a5f3085a04948f99912fb
/codeblocks-file.cpp
0146e37f1dfa240fb5fa4b9003775601b4d5ab05
[]
no_license
sayedmushahid/Digital-clock-and-stopwatch
f81462fa9a0ecbf4231064ea8d96464f3b79073b
1b1e89742c6cfa23be9d338c851d59d50dd0f921
refs/heads/master
2020-09-22T12:58:28.172664
2019-12-01T18:09:28
2019-12-01T18:09:28
225,206,275
0
0
null
null
null
null
UTF-8
C++
false
false
3,267
cpp
codeblocks-file.cpp
#include <stdio.h> #include <conio.h> #include <iostream> #include <graphics.h> #include <time.h> #include <dos.h> #include <string.h> #include <windows.h> using namespace std; void digital(); void stopwatch(); void watch(); int main() { /* request auto detection */ int gdriver = DETECT, gmode, err; /* initialize graphic mode */ initgraph(&gdriver, &gmode, "C:/TURBOC3/BGI"); err = graphresult(); if (err != 0) { /* error occurred */ cout<<"Graphics Error: %s\n"<< grapherrormsg(err); return 0; } {cout<<"\n\n\t\t\t\t ENTER YOUR CHOICE"<<endl; cout<<"\n\n\t\t\t\t 1 FOR DIGITAL CLOCK"<<endl; cout<<"\n\n\t\t\t\t 2 FOR STOPWATCH"<<endl; int x; cin>>x; switch (x) { case 1: digital(); break; case 2: stopwatch(); break; default: cout<<"Invalid Input"; } getche(); /* deallocate memory allocated for graphic screen */ closegraph(); return 0; } } void digital () { int midx, midy; long mytime; char date[256]; /* mid positions in x and y axis */ midx = getmaxx() / 2; midy = getmaxy() / 2; /* mid positions in x and y axis */ midx = getmaxx() / 2; midy = getmaxy() / 2; while (!kbhit()) { /* clears graphic screen */ delay(1000); cleardevice(); /* get time in seconds */ mytime = time(NULL); /* store the date and time in the given string */ strcpy(date, ctime(&mytime)); setcolor(10); settextjustify(CENTER_TEXT, CENTER_TEXT); settextstyle(TRIPLEX_FONT, HORIZ_DIR, 4); /* locate the postion to write */ moveto(midx, midy); /* print the date and time */ outtext(date); } } int h=0,m=0,s=0,ms=0; char ch = 'p'; void stopwatch() { watch(); while(1) { ch=getche(); if(ch=='s'||ch=='S') break; if(ch=='e'||ch=='E') exit(0); } while(1) { watch(); delay(35); if(_kbhit()) ch=getche(); if(ch=='r'||ch=='R') { h=m=s=ms=0; watch(); while(1) { if(_kbhit()) ch = getche(); if(ch=='s'||ch=='S') break; if(ch=='e'||ch=='E') exit(0); } } else if(ch=='p'||ch=='P') while(1) { if(_kbhit()) ch=getche(); if(ch=='s'||ch=='S') break; if(ch=='e'||ch=='E') exit(0); if(ch=='r'||ch=='R') { ch='c'; h=m=s=ms=0; watch(); } } else if(ch=='e'||ch=='E') exit(0); if(ms!=9) ms++; else { ms=0; if(s!=59) s++; else { s=0; if(m!=59) m++; else { m=0; h++; } } } } } void watch() { system("cls"); cout<<"#***********************#"; cout<<"\n#\t The A.R.T\t#"; cout<<"\n#\t Stopwatch\t#"; cout<<"\n#***********************#"; cout<<"\n#\t "<<h<<":"<<m<<":"<<s<<":"<<ms<<" \t#"; cout<<"\n#***********************#"; cout<<"\n\n#***********************#"; cout<<"\n#\tPress Key\t#"; cout<<"\n#\tS -> Start\t#"; cout<<"\n#\tP -> Pause\t#"; cout<<"\n#\tR -> Reset\t#"; cout<<"\n#\tE -> Exit\t#"; cout<<"\n#***********************#"; }
979714b454ddea8aaba07809949d7cb0a97b0a7f
aecfb99ab56c0a12dca0e3a965a0be44c2a56494
/src/logger.cpp
de26204d7fcf9d70a72d27f472b8a4979fb25e6f
[ "MIT" ]
permissive
shwangdev/SoundPatty
760471e73710a43fe16845dfa5ed87fd9704e433
29280f7545897fd6a77c6b376b0752dedf9903f5
refs/heads/master
2021-05-27T08:56:38.430494
2012-09-11T22:26:22
2012-09-11T22:26:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,355
cpp
logger.cpp
#include "logger.h" int LogLevel = 3; const char *LogLevels[] = {"FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"}; extern void log_mo (const int log_level, const char *file, const int line, const char *pretty_fn, const char *format, ...) { if (log_level > LogLevel) return; va_list arg; va_start (arg, format); struct timeval tv; struct timezone tz; struct tm *tm; time_t rawtime; gettimeofday(&tv, &tz); tm = localtime(&tv.tv_sec); /* Now we have tv.tv_usec printf(" %d:%02d:%02d %d \n", tm->tm_hour, tm->tm_min, tm->tm_sec, tv.tv_usec); */ char datetime [40]; time ( &rawtime ); tm = localtime ( &rawtime ); strftime (datetime,40,"%Y-%m-%d %H:%M:%S",tm); sprintf (datetime, "%s,%d", datetime, (int)tv.tv_usec); datetime[24] = '\0'; // Cut to seconds^-4 char *prefix, *fileline; fileline = (char*)malloc(strlen(file)+27); sprintf(fileline, "%s(%d)", file, line); // &fileline[7] due to skipping first 7 characters (with default waf build it's '../src/' if ( -1 == asprintf (&prefix, "%s [%x] %-19s %-5s - %s\n", datetime, (unsigned int)pthread_self(), &fileline[7], LogLevels[log_level], format)) { printf ("FATAL: Memory allocation failed!"); } delete fileline; vfprintf (stderr, prefix, arg); va_end (arg); }
2d029e5bf5302dd51b915e85be0a04657ab036a3
b22517f050296795a40845168e270e113ac8f5c5
/AllSources/AnimatioTest2/AnimatioTest2/Mesh.cpp
907045cbba1ccc68530f0a12b735b3a5290cee7c
[]
no_license
movinglinguini/GraphicsProgrammingStuff
b35502cc117c7cce3af2c4739af06e4b8577889a
8fbb7ce7938c0fa8b162faed13e626417a0ebbef
refs/heads/master
2021-06-16T07:36:04.294299
2017-05-03T15:54:04
2017-05-03T15:54:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,341
cpp
Mesh.cpp
#include "Mesh.h" #include "Model.h" void Mesh::_SetUpMesh() { glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, ListVertices.size() * sizeof(Vertex), &ListVertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(GLuint), &indices[0], GL_STATIC_DRAW); //Vertex Positions glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)0); glEnableVertexAttribArray(0); //Vertex Normals glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, Normal)); glEnableVertexAttribArray(1); //Texture Coordinates glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, TexCoords)); glEnableVertexAttribArray(2); //Vector IDs glVertexAttribIPointer(3, 1, GL_INT, sizeof(Vertex), (GLvoid*)offsetof(Vertex, id)); glEnableVertexAttribArray(3); //Vector Weights glVertexAttribPointer(4, 4, GL_FLOAT, GL_TRUE, sizeof(Vertex), (GLvoid*)offsetof(Vertex, Weights)); glEnableVertexAttribArray(4); glBindVertexArray(0); } void Mesh::Draw(Shader shader, glm::vec3 Color, float shininess) { GLuint diffuse_Num = 1; GLuint specular_Num = 1; if (this->ListTextures.size() == 0) { glUniform1i(glGetUniformLocation(shader.Program, "accessTextures"), 0); glUniform3f(glGetUniformLocation(shader.Program, "material.defaultDiffuse"), 0.3f, 0.3f, 0.3f); } else { glUniform1i(glGetUniformLocation(shader.Program, "accessTextures"), 1); for (int i = 0; i < this->ListTextures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); std::stringstream ss; std::string number; std::string name = ListTextures[i].type; if (this->ListTextures[i].type == "texture_diffuse") { ss << diffuse_Num++; } if (this->ListTextures[i].type == "texture_specular") { ss << specular_Num++; } number = ss.str(); glUniform1i(glGetUniformLocation(shader.Program, ("material." + name + number).c_str()), i); glBindTexture(GL_TEXTURE_2D, this->ListTextures[i].id); //Bind the texture } } glActiveTexture(GL_TEXTURE0); glUniform1f(glGetUniformLocation(shader.Program, "material.shininess"), shininess); glUniform3f(glGetUniformLocation(shader.Program, "material.ambient"), Color.x, Color.y, Color.z); //Load the bone matrices if the model is rigged if (Model_I_Belong_To->is_rigged) { for (int i = 0; i < Model_I_Belong_To->GetSkeleton()->List_Bones.size(); i++) { std::cout << "[\n " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[0][0] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[0][1] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[0][2] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[0][3] << std::endl << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[1][0] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[1][1] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[1][2] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[1][3] << std::endl << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[2][0] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[2][1] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[2][2] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[2][3] << std::endl << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[3][0] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[3][1] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[3][2] << ", " << Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(i)[3][3] << std::endl << "]" << std::endl; } glUniformMatrix4fv(glGetUniformLocation(shader.Program, "mBones"), Model_I_Belong_To->GetSkeleton()->BoneMatrices.size(), GL_FALSE, glm::value_ptr(Model_I_Belong_To->GetSkeleton()->BoneMatrices.at(0))); } //Draw the mesh with textures and shading and all that beautiful glory glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); for (GLuint i = 0; i < this->ListTextures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } }
e70da2ab4b4f89dc15bcd28727dfbac517a72c6f
19f202902bd92fa4667f1ebccccdd96eab62f007
/src/EscapeCancelFilter.h
cbf2ac10394bcd708126ef2074251a3b9535ce99
[ "MIT" ]
permissive
HaikuArchives/CapitalBe
3fcfb80eb1e6e25afa9a54e7abae6e821a71d666
3952438722cb3d2e8d2d00f078c2a867f6817cd8
refs/heads/master
2022-04-30T19:16:26.738165
2022-03-29T15:13:49
2022-03-29T15:13:49
14,126,200
3
13
MIT
2022-03-29T15:13:50
2013-11-04T22:58:36
C++
UTF-8
C++
false
false
731
h
EscapeCancelFilter.h
#ifndef ESCAPE_CANCEL_FILTER_H #define ESCAPE_CANCEL_FILTER_H // This is for any window which doesn't already have an AutoTextControl in it. #include <MessageFilter.h> #include <Handler.h> class EscapeCancelFilter : public BMessageFilter { public: EscapeCancelFilter(void) : BMessageFilter(B_PROGRAMMED_DELIVERY, B_ANY_SOURCE,B_KEY_DOWN) {} ~EscapeCancelFilter(void) {} filter_result Filter(BMessage *msg, BHandler **target) { int32 rawchar; msg->FindInt32("raw_char",&rawchar); if(rawchar == B_ESCAPE) { BLooper *loop = (*target)->Looper(); if(loop) { BMessenger msgr(loop); msgr.SendMessage(B_QUIT_REQUESTED); return B_SKIP_MESSAGE; } } return B_DISPATCH_MESSAGE; } }; #endif
2bfaded2b09a97412643b9879042b8d5262fe043
5fc8c13eed9f3d0e3c3f0786dc6dd6818738b517
/training-OpenGL/PaOpenGLTest02MFC/PaOpenGLTest02MFCView.h
85829074f4e3e870fbd3a3595a2c41da2f34d82c
[]
no_license
asm32cn/VC
3348a6c74b1c3c8671fab40aa8a953b062435fdf
08f6cd3e03a64cc5601c4b807dbd435f26979543
refs/heads/master
2020-03-15T16:23:26.939288
2018-05-13T17:42:26
2018-05-13T17:42:26
132,233,454
0
0
null
null
null
null
UTF-8
C++
false
false
1,958
h
PaOpenGLTest02MFCView.h
// PaOpenGLTest02MFCView.h : interface of the CPaOpenGLTest02MFCView class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_PAOPENGLTEST02MFCVIEW_H__1E228C24_719E_460C_8D34_5E412274CBB9__INCLUDED_) #define AFX_PAOPENGLTEST02MFCVIEW_H__1E228C24_719E_460C_8D34_5E412274CBB9__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CPaOpenGLTest02MFCView : public CView { protected: // create from serialization only CPaOpenGLTest02MFCView(); DECLARE_DYNCREATE(CPaOpenGLTest02MFCView) // Attributes public: CPaOpenGLTest02MFCDoc* GetDocument(); // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CPaOpenGLTest02MFCView) public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); //}}AFX_VIRTUAL // Implementation public: virtual ~CPaOpenGLTest02MFCView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: HGLRC m_hGLContext; BOOL CreateViewGLContext(HDC hDC); //{{AFX_MSG(CPaOpenGLTest02MFCView) afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg void OnDestroy(); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnPaint(); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: int m_GLPixelIndex; BOOL SetWindowPixelFormat(HDC hDC); }; #ifndef _DEBUG // debug version in PaOpenGLTest02MFCView.cpp inline CPaOpenGLTest02MFCDoc* CPaOpenGLTest02MFCView::GetDocument() { return (CPaOpenGLTest02MFCDoc*)m_pDocument; } #endif ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_PAOPENGLTEST02MFCVIEW_H__1E228C24_719E_460C_8D34_5E412274CBB9__INCLUDED_)
df3fd87cb49073085371c43a789dd8f9cb3c86e7
56cc596fee14b9228d7f7ede13ad0ad19032663a
/ch14_VirtualRoomServer/VRConnectFourFallingSphereSimulation.cpp
838797515612e1a175150f12dbe33088b4f6b2d1
[]
no_license
yangmaoer/VirtualRoom
289453b932c4fa3f05cf77954220e0fa6c4cdc74
56caa4fae8b6551c6bab2444c7c12ef5f22e90bf
refs/heads/master
2020-03-30T00:29:37.001765
2014-10-30T12:50:14
2014-10-30T12:50:14
null
0
0
null
null
null
null
ISO-8859-3
C++
false
false
1,556
cpp
VRConnectFourFallingSphereSimulation.cpp
//############################################################################# // File: VRConnectFourFallingSphereSimulation.cpp // Author: Cedric Renggli, Marc Wacker, Roman Kühne // Date: Mai 2014 //############################################################################# #include "VRConnectFourFallingSphereSimulation.h" using namespace VirtualRoom::Game; //----------------------------------------------------------------------------- ConnectFourFallingSphereSimulation::ConnectFourFallingSphereSimulation(BoardPlayField* boardPlayField, SLint zIndex) : BoardGameSimulation() , _boardPlayField(boardPlayField), _actualStep(0) { this->_boardPlayField->_actualPosition = this->_boardPlayField->_simulationStartPosition; this->_effectiveNumberOfSteps = NUMBER_OF_STEPS_PER_SPHERE * (CONNECTFOUR_NUMBER_OF_ROWS_COLUMNS_LEVELS - zIndex); this->_deltaVector = (this->_boardPlayField->_simulationEndPosition - this->_boardPlayField->_simulationStartPosition) / (this->_effectiveNumberOfSteps); } //----------------------------------------------------------------------------- /*! simulates the sphere */ void ConnectFourFallingSphereSimulation::doSimulationStep () { if(this->_actualStep < this->_effectiveNumberOfSteps) { this->_boardPlayField->_actualPosition += this->_deltaVector; this->_actualStep++; } else { this->_boardPlayField->_actualPosition = this->_boardPlayField->_simulationEndPosition; this->_isFinished = true; } } //-----------------------------------------------------------------------------
d7b75e3eae201a8d0c8a50544e91c78d33953553
6c71d7e1a86c15ccd1d901073449c6e41d093183
/RegionBasedColorTransfer.h
c28805678bc1aba272188a430ca238450bb9fe69
[]
no_license
anthony123/StyleTransfer
9bac3a3a6eaf1e317f956dfa92febe943301c9dd
54b263021be25195631fe28ea007c76b3d806342
refs/heads/master
2021-01-18T22:52:29.594789
2016-06-26T13:37:58
2016-06-26T13:37:58
61,990,243
0
0
null
null
null
null
UTF-8
C++
false
false
1,339
h
RegionBasedColorTransfer.h
#ifndef REGION_BASED_COLOR_TRANSFER_H #define REGION_BASED_COLOR_TRANSFER_H #include "cv.h" #include "highgui.h" #include "Segmentation.h" #include <vector> using namespace std; using namespace cv; class RegionBasedColorTransfer { private: //constant values const int number_of_color_type = 9; vector<Vec3f> colorValues; Mat source, target; vector<vector<Pixel> > sourceBuffer; vector<vector<Pixel> > targetBuffer; // vector<vector<Pixel> > sourceClassification(number_of_color_type); //vector<vector<Pixel> > targetClassification(number_of_color_type); vector<vector<Pixel> > sourceClassification; vector<vector<Pixel> > targetClassification; //helper function //classify color into different category int classifyColor(const Mat &image, Pixel position) const; //find the min color Eclidean basic color int minColorDistance(const Vec3f & value) const; public: RegionBasedColorTransfer(char* sourceFile, char* targetFile); void segmentImages(vector<vector<Pixel> >&sourceBuffer, vector<vector<Pixel> >&targetBuffer)const; void classifyColor(); void globallyTransferColor(); //void correlateSourceAndTargetRegions(); //void colorTransferCorrespondently(); //void textureTransferCorrespondently(); void process(); void showTarget() const; void showSource() const; }; #endif
c7d458d3efde333239ae66534fcc70dce4e649ec
c69aa6543b2fd2a1b0818767f718839adf478e6e
/knapsack.cpp
35b3e36878a63cbf00f180586b351f572e8362d9
[]
no_license
StuartSpiegel/0-1-Knapsack
3273d235711a4caaacc7010b012377c286250daa
7a8ccf78df3b8b365a52dc6f8e925f07236d6f5d
refs/heads/master
2020-07-25T01:59:43.578877
2019-09-12T19:57:40
2019-09-12T19:57:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,249
cpp
knapsack.cpp
/* Author: Stuart Spiegel Date: 9/12/2019 *********************************************************************************************************************************************************** Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to W. -->You cannot break an item, either pick the complete item, or don’t pick it (0-1 property). *********************************************************************************************************************************************************** */ //The item to be picked is either in the optimal set or it is not. //Maximum value obtained by n-1 items and W weight (excluding nth item). //Value of nth item plus maximum value obtained by n-1 items and W minus weight of the nth item (including nth item). /* A Naive recursive implementation of 0-1 Knapsack problem */ #include <bits/stdc++.h> using namespace std; //using the standard output // A utility function that returns maximum of two integers int max(int a, int b) { return (a > b)? a : b; } // Base Case, their are no items left to be picked if (n == 0 || W == 0) return 0; // If weight of the nth item is more // than Knapsack capacity W, then // this item cannot be included // in the optimal solution if (wt[n-1] > W) return knapSack(W, wt, val, n-1); // Return the maximum of two cases: // (1) nth item included // (2) not included else return max( val[n-1] + knapSack(W-wt[n-1], wt, val, n-1), knapSack(W, wt, val, n-1) ); } // Main Driver Code int main() { int val[] = {80, 10, 50}; //the values of the respective items in the knapsack int wt[] = {10, 25, 40}; //the weights of the items int W = 100; //weight limit of knapSack int n = sizeof(val)/sizeof(val[0]); //number of items cout<<knapSack(W, wt, val, n); //print the output to the console return 0; //dummy return }
32f478ce3ffa72f312fa04e75f141cba2cde77e1
40749684a15dd49a1d7103e706057ac41a802916
/visualization/src/addBoundingBox.cpp
b9adcf5cd48bd8e280123dbe8f58a2048ea2ea44
[]
no_license
gywhitel/PCL_learning
e02b4bbcc865ab73d5e140f7d79b47607a25e0de
baa848155647b3af2d4b369932420dd743b44537
refs/heads/master
2023-06-12T10:51:36.108304
2021-07-05T13:02:03
2021-07-05T13:02:03
383,131,584
0
0
null
null
null
null
UTF-8
C++
false
false
3,591
cpp
addBoundingBox.cpp
#include "addBoundingBox.h" // Given centroid and a vector, return the end of the vector starting from the centroid // \param vector a translation vector // \param center a pointT type point, the centroid of the pointcloud pointT eigenvector_to_pointT(Eigen::Vector3f vector, pointT center) { pointT point; point.x = vector(0) + center.x; point.y = vector(1) + center.y; point.z = vector(2) + center.z; return point; } // \brief add a bounding box on given input cloud // \param[in] cloud a pointcloud pointer // \param[out] BB a BB_Parameter struct BB_Parameter pointcloud_Boundingbox(pcl::PointCloud<pointT>::ConstPtr cloud) { Eigen::Vector4f centroid; pcl::compute3DCentroid(*cloud, centroid); pointT center; center.x = centroid(0); center.y = centroid(1); center.z = centroid(2); // Principal Component Analysis pcl::PCA<pointT> pca; pcl::PointCloud<pcl::PointXYZ>::Ptr project_cloud (new pcl::PointCloud<pcl::PointXYZ>); pca.setInputCloud(cloud); // the project here is demean, subtract the mean from the pointcloud pca.project(*cloud, *project_cloud); // Column ordered eigenvectors, representing the eigenspace cartesian basis (right-handed coordinate system). auto eigenVectors = pca.getEigenVectors(); // NOTE: This line is necessary, which makes the frame right-hand. Otherwise the bounding box's orientation would be wrong. eigenVectors.col(2) = eigenVectors.col(0).cross(eigenVectors.col(1)); std::cout<<"PCA, Eigenvectors:\n"<<eigenVectors<<std::endl; auto ev1 = eigenvector_to_pointT(eigenVectors.col(0), center); auto ev2 = eigenvector_to_pointT(eigenVectors.col(1), center); auto ev3 = eigenvector_to_pointT(eigenVectors.col(2), center); pointT minPoint, maxPoint; pcl::getMinMax3D(*project_cloud, minPoint, maxPoint); // Get translation vector and rotation matrix const Eigen::Vector3f meanDiagonal = 0.5f*(maxPoint.getVector3fMap() + minPoint.getVector3fMap()); const Eigen::Vector3f BB_transform = eigenVectors * meanDiagonal + centroid.head<3>(); const Eigen::Quaternionf BB_quaternion(eigenVectors); BB_Parameter BB; BB.BB_quaternion = BB_quaternion; BB.BB_transform = BB_transform; BB.width = maxPoint.x - minPoint.x; BB.height = maxPoint.y - minPoint.y; BB.depth = maxPoint.z - minPoint.z; BB.center = center; BB.eigenvector_point1 = ev1; BB.eigenvector_point2 = ev2; BB.eigenvector_point3 = ev3; return BB; } void pointcloud_Boundingbox(pcl::PointCloud<pointT>::ConstPtr cloud, pcl::visualization::PCLVisualizer& viewer) { addBoundingBox(viewer, pointcloud_Boundingbox(cloud)); } // \brief Add a bounding box and orientation in a given PCL_Visualizer // \param[in] viewer the viewer to which the bounding box is added // \param[in] BB a BB_Parameter struct, containing all the parameters needed to render a bounding box void addBoundingBox(pcl::visualization::PCLVisualizer& viewer, BB_Parameter BB) { using namespace pcl::visualization; viewer.addCube(BB.BB_transform, BB.BB_quaternion,BB.width, BB.height, BB.depth, "bb"); viewer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, pcl::visualization::PCL_VISUALIZER_REPRESENTATION_WIREFRAME, "bb"); viewer.setShapeRenderingProperties(PCL_VISUALIZER_COLOR, 1,1,0,"bb"); viewer.addArrow(BB.eigenvector_point1, BB.center, 1,0,0,false, "x"); viewer.addArrow(BB.eigenvector_point2, BB.center, 0,1,0,false, "y"); viewer.addArrow(BB.eigenvector_point3, BB.center, 0,0,1,false, "z"); }
e37251d5d2ad4a0a1bfa9225435d36e360fc57b1
e90e4398cb2236991061a212ffbf39736f4ecf18
/source/materials/src/physicalstate.cpp
a06aed373bdcc20e177c8a3223eb894a7a181875
[]
no_license
KirillKomarov1993/OpenTuCo
f385881591665db7cb0642050779fa07058380d9
e6b8fe78fd3afed935537a45ee3fda7a272789f9
refs/heads/main
2022-12-19T20:10:54.269830
2020-10-15T21:19:45
2020-10-15T21:19:45
304,383,219
0
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
physicalstate.cpp
#include "physicalstate.h" namespace tuco { PhysicalState::PhysicalState(double _temperature) : temperature(_temperature) { } PhysicalState::PhysicalState(double _density, double _temperature) : density(_density), temperature(_temperature) { } }
b744e0aa2b82fad3d10456f5e1c879615735c58f
388bbd69059cdac4a7388bb9443f1d41bf0c3d8b
/plugins/filters/fidealfilterwidget.h
f69a86b2201f5a7389df38a602fb2a039eb866c1
[]
no_license
MADTeacher/VideoModeling
772d36cc97a663da246fabefc33e2dd50967b190
c8d17ad273fe32d2d2f103106e1851a86d56b369
refs/heads/master
2021-10-11T02:08:29.030420
2019-01-21T10:40:15
2019-01-21T10:40:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
459
h
fidealfilterwidget.h
#ifndef FIDEALFILTERWIDGET_H #define FIDEALFILTERWIDGET_H #include "baseprocessingwidget.h" namespace Ui { class FGaussianSettings; } class FIdealFilter; class FIdealFilterWidget : public BaseProcessingWidget { Q_OBJECT public: FIdealFilterWidget(FIdealFilter* processing, QWidget *parent = 0); ~FIdealFilterWidget(){} private: Ui::FGaussianSettings* m_settingWidget; FIdealFilter* m_processing; }; #endif // FIDEALFILTERWIDGET_H
ebd87a7c810720f4aa4c4c73cac547c86984e383
2c012a4d96ac17a92d225fe1811b68914302c943
/re/RouterActions.re
15b16b2bb09948c2132dc80fae6bf004b2cb13b5
[ "MIT" ]
permissive
Astrocoders/bs-react-native-router-flux
d9b4bd3a35708ef228bc79b4200dd24177ad9bc4
23293fd7c4219fb808b09ab0e920044c2b6d9d8a
refs/heads/develop
2021-09-01T02:58:42.497647
2017-10-16T17:38:28
2017-10-16T17:38:28
103,068,209
5
1
MIT
2018-03-17T10:46:00
2017-09-10T23:06:48
OCaml
UTF-8
C++
false
false
154
re
RouterActions.re
module RouterActions = { type params; external actions : string => params => bool = "default" [@@bs.module "../../../../src/rnrf/RouterActions"]; }
d1f2ce13f87fe693388021f4b269fc3cafd40340
703068b6ad1717ddeca70190b8ef2767b4b91ccf
/include/eth_trajectory_generation/misc.h
f001b6957d8ad51e7ad69d01c5e4bc5262f2c1d2
[ "Apache-2.0" ]
permissive
hoijo/mrs_uav_trajectory_generation
d51bcd68fbb24a20fcc1b9b5ad9f29c2643a3215
4d63a7937dbb7205cbdfbc6fffa29e77ddc7d63d
refs/heads/master
2023-01-20T11:16:05.979788
2020-11-30T13:43:55
2020-11-30T13:43:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,167
h
misc.h
#ifndef TRAJECTORY_GENERATION_MISC_H #define TRAJECTORY_GENERATION_MISC_H #include <iostream> #define CHECK_LT(v1, v2) \ if (!(v1 < v2)) \ std::cout << __FILE__ << ":" << __LINE__ << " Error: " << v1 << " >= " << v2 << std::endl; #define CHECK_GT(v1, v2) \ if (!(v1 > v2)) \ std::cout << __FILE__ << ":" << __LINE__ << " Error: " << v1 << " <= " << v2 #define CHECK_GE(v1, v2) \ if (!(v1 >= v2)) \ std::cout << __FILE__ << ":" << __LINE__ << " Error: " << v1 << " < " << v2 #define CHECK_LE(v1, v2) \ if (!(v1 <= v2)) \ std::cout << __FILE__ << ":" << __LINE__ << " Error: " << v1 << " > " << v2 << std::endl; #define CHECK_EQ(v1, v2) \ if (!(v1 == v2)) \ std::cout << __FILE__ << ":" << __LINE__ << " Error: " << v1 << " != " << v2 #define CHECK_NOTNULL(v) \ if ((v == NULL)) \ std::cout << __FILE__ << ":" << __LINE__ << " Error: " << v << " == NULL" << std::endl; #define CHECK(v) \ if (!(v)) \ std::cout << __FILE__ << ":" << __LINE__ << " Error: << !(v) " #define LOG(v) std::cout #define DLOG(v) std::cout #define VLOG(v) std::cout #endif // TRAJECTORY_GENERATION_MISC_H
cb3e572ffc11342fa9f593ac427100a652d22458
d3293df2e9ba7c01bc31e5dd40589b5327fbfcbb
/src/scene/TextureScene.cpp
2c077195f0a2968be16ad27021bedc4a2c971bbc
[]
no_license
trbabb/gltoy
7b742795d890a0205589c2dc7e12f9e15a348c69
05b9db17fc6b65046ded315ca63919e197cf1339
refs/heads/master
2021-01-15T16:28:55.162556
2019-02-17T04:25:12
2019-02-17T04:25:12
17,894,060
0
0
null
null
null
null
UTF-8
C++
false
false
2,346
cpp
TextureScene.cpp
#include <iostream> #include "glHeaders.h" #include <algorithm> #include <geomc/function/PerlinNoise.h> #include <geomc/random/RandomTools.h> #include "GLWindow.h" #include "Manipulator.h" #include "AnimTimer.h" #include "RenderPass.h" #include "Shader.h" #include "Image.h" #include "Texture.h" #include "visible/VisAxis.h" #include "visible/VisTextureCard.h" #include "visible/VisBall.h" #include "visible/VisCallback.h" #define RESOLUTION 1024 void enableAlpha(int dummy){ glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } void setColor(Vec4d c){ glColor4d(c.x, c.y, c.z, c.w); } void splat(Image<float,1> img){ Vec2f ctr = Vec2f(img.w()/2.0, img.h()/2.0); for (int y = 0; y < img.h(); y++){ for (int x = 0; x < img.w(); x++){ Vec2f pt = Vec2f(x,y) - ctr; float mag = pt.mag() / (img.w()*0.5); mag = M_CLAMP(1-mag, 0.0f, 1.0f); img.set(x,y,mag*mag); } } } int main(int argc, char** argv){ GLWindow win("OpenGL Toy Program", RESOLUTION, RESOLUTION); win.cam.setPosition(X_AXIS3d * 10); win.cam.setCenterOfInterest(ZERO_VEC3d); win.cam.setNear(0.1); win.cam.setFar(200); win.cam.setUp(Z_AXIS3d); Manipulator manip(&win, &win.cam); AnimTimer timer(&win); //gen texture ExprPtr(Vec2f,float) perlin = ExprPtr(Vec2f,float)(new PerlinNoiseExpr<float,2>()) * 0.5 + 0.5; Image<float,1> img = Image<float,1>(512,512); std::cout << "building texture..." << std::endl; img.fill(perlin, Rect2d(Vec2d(-15), Vec2d(15)), 1); std::cout << "done." << std::endl; Image<float,1> blob = Image<float,1>(128,128); splat(blob); //scene objects Texture tex = Texture(blob, GL_ALPHA, true); VisTextureCard tcard = VisTextureCard(tex); //build scene win.scene.push_back(new VisCallback<int>(&enableAlpha)); win.scene.push_back(new VisCallback<Vec4d>(&setColor, Vec4d(0.09,1))); Sampler<double> smp; for (int i = 0; i < 100; i++){ VisBall *b = new VisBall(smp.box(-ONE_VEC3d * 100, ONE_VEC3d * 100), smp.rng->rand<double>(0.01,10), 48, 24); win.scene.push_back(b); } win.scene.push_back(&tcard); win.setClearColor(Vec4d(0.11,0.11,0.11,1)); timer.begin(); win.showAll(); return 0; }
138e57bbbb0cf9d19f892a40307364defef27436
4d4822b29e666cea6b2d99d5b9d9c41916b455a9
/Example/Pods/Headers/Private/GeoFeatures/boost/parameter/aux_/result_of0.hpp
04f3b002599895d48ddb2bc944743616e1be0660
[ "BSL-1.0", "Apache-2.0" ]
permissive
eswiss/geofeatures
7346210128358cca5001a04b0e380afc9d19663b
1ffd5fdc49d859b829bdb8a9147ba6543d8d46c4
refs/heads/master
2020-04-05T19:45:33.653377
2016-01-28T20:11:44
2016-01-28T20:11:44
50,859,811
0
0
null
2016-02-01T18:12:28
2016-02-01T18:12:28
null
UTF-8
C++
false
false
71
hpp
result_of0.hpp
../../../../../../../../GeoFeatures/boost/parameter/aux_/result_of0.hpp
20da94f4c3f9657e92f4547aa07d0ea73a977d01
b0227e01d70a479a15433f0ea5054e3b8b855ee4
/LAR.h
a8ceb0e2439c7dee616976cd9755b85190d7f05a
[]
no_license
ITpC/lar
57dd6263975a2bdd3990ba6f804b4925479ccf25
c5320bb6520649ac2372eaeaad2133dd544b6f72
refs/heads/master
2021-06-19T00:03:57.225592
2021-01-01T00:27:42
2021-01-01T00:27:42
138,001,015
0
0
null
null
null
null
UTF-8
C++
false
false
10,711
h
LAR.h
/* * Copyright Pavel Kraynyukhov 2018. * * 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) * * $Id: lar:LAR.h Jun 16, 2018 1:04:08 PM $ * * EMail: pavel.kraynyukhov@gmail.com */ #ifndef __LAR_H__ #define __LAR_H__ #include <fstream> #include <cassert> #include <vector> #include <wolfCryptHaCW.h> #include <TOC.h> namespace lar { struct LARHeader { const char magic[3]; const uint8_t version; uint32_t TOCSize; uint32_t TOCCompressedSize; uint32_t TOCItems; wolf::SHA256SUM hashsum; LARHeader() : magic{'L','A','R'},version{1}, TOCSize{0},TOCCompressedSize{0},TOCItems{0},hashsum{0}{}; const bool valid() const { if((magic[0] == 'L')&&(magic[1]=='A')&&(magic[2]=='R')&&(version == 1)) return true; return false; } }; struct LAR { LARHeader header; std::vector<std::shared_ptr<TOCItem>> items; explicit LAR():header(),items(){} LAR(const LAR&)=delete; LAR(LAR&)=delete; void add(const std::string& dir_name) { for(auto dentry: fs::recursive_directory_iterator(dir_name)) { if(dentry.status().type() == fs::file_type::regular) { items.push_back(std::make_shared<TOCItem>(dentry.path())); std::cout << "New archive entry: " << dentry.path() << std::endl; } } } const bool read_toc(const std::string& archname) { items.clear(); std::ifstream archive(archname,std::ios_base::in|std::ios_base::binary); if(archive&&archive.is_open()) { archive.read((char*)(&header),sizeof(header)); assert(archive.gcount() == sizeof(header)); assert(header.valid()); auto compressedTOC=std::make_shared<itc::ByteArray>(header.TOCCompressedSize); archive.read((char*)(compressedTOC->data()),header.TOCCompressedSize); auto tocUnCompressed=std::make_shared<itc::ByteArray>(); itc::bz2::decompress(compressedTOC,tocUnCompressed); size_t offset=0; do{ items.push_back(std::make_shared<TOCItem>(*tocUnCompressed,offset)); offset+=items[items.size()-1]->path_size+56; }while(offset < tocUnCompressed->size()); archive.close(); return true; } return false; } void list() { for(auto item : items) { std::cout << item->relativePath << std::endl; } } void unpack(const std::string& archname, const fs::path& p=fs::current_path()) { if(read_toc(archname)) { size_t archive_offset=sizeof(header)+header.TOCCompressedSize; std::ifstream archive(archname,std::ios_base::in|std::ios_base::binary); if(archive&&archive.is_open()) { archive.seekg(archive_offset); for(auto& item : items) { itc::CompressionBuffer arhived_file=std::make_shared<itc::ByteArray>(item->compressedSize); archive.read((char*)(arhived_file->data()),item->compressedSize); itc::CompressionBuffer unpacked_file=std::make_shared<itc::ByteArray>(item->fsize); itc::bz2::decompress(arhived_file,unpacked_file); wolf::SHA256SUM hashsum; wolf::sha256sum(*unpacked_file,hashsum); if(memcmp(hashsum,item->hashsum,32) == 0) { fs::path file_path=p / item->relativePath; fs::path subdir_path=file_path.parent_path(); std::error_code ec; fs::create_directories(subdir_path,ec); if(ec.value() != 0) { throw std::system_error(ec.value(),ec.category(),"Can not create directory: "+subdir_path.u8string()+". Error: "+ec.message()); } std::ofstream thefile(file_path,std::ios_base::out|std::ios_base::binary); if(thefile&&thefile.is_open()) { thefile.write((const char*)(unpacked_file->data()),unpacked_file->size()); if(thefile.bad()) { throw std::system_error(EACCES,std::system_category(),"Can not unpack file: "+file_path.u8string()); } thefile.close(); }else{ throw std::system_error(EACCES,std::system_category(),"Can not unpack file: "+file_path.u8string()); } } else{ throw std::system_error(EILSEQ,std::system_category(),"Corrupt archive, hashsum is incorrect"); } } } }else{ throw std::system_error(EINVAL,std::system_category(),"Can't read TOC"); } } void pack(const std::string& archname) { std::vector<uint8_t> checksums; itc::CompressionBuffer prepin=std::make_shared<itc::ByteArray>(); header.TOCItems=items.size(); std::string tempname("TMP_LAR_XXXXXX"); int ffd=mkstemp((char*)(tempname.data())); if(ffd == -1) throw std::system_error(errno,std::system_category(),"Can't create temporary file"); std::string tempname1="TMP_LAR_XXXXXX"; int fd=mkstemp((char*)(tempname1.data())); if(fd == -1) throw std::system_error(errno,std::system_category(),"Can't create temporary file"); for(auto item : items) { std::ifstream file(item->relativePath,std::ios_base::in|std::ios_base::binary); // file.open(item->relativePath,std::ios_base::in|std::ios_base::binary); if(file&&file.is_open()) { if(item->fsize > memavail()/3) { throw std::system_error( ENOMEM, std::system_category(), std::string("File [")+ item->relativePath.u8string()+ std::string("] size is too large (larger then the third of available memory)") ); } itc::CompressionBuffer filebuff=std::make_shared<itc::ByteArray>(item->fsize); file.read((char*)filebuff->data(),item->fsize); item->calcHashSum(*filebuff); checksums.resize(checksums.size()+32); memcpy(checksums.data()+(checksums.size()-32),item->hashsum,32); itc::CompressionBuffer compressedContent=std::make_shared<itc::ByteArray>(); itc::bz2::compress(filebuff,compressedContent); item->compressedSize=compressedContent->size(); auto ret=::write(fd,compressedContent->data(),compressedContent->size()); if(ret == -1) { throw std::system_error( errno, std::system_category(), std::string("File [")+ item->relativePath.u8string()+ std::string("] error on writing to archive ")+archname ); } } else{ throw std::system_error( EACCES, std::system_category(), std::string("Can't open file: ")+item->relativePath.u8string() ); } file.close(); } wolf::sha256sum(checksums,header.hashsum); itc::CompressionBuffer TOC=std::make_shared<itc::ByteArray>(); for(auto& item : items) { std::vector<uint8_t> toc_item; item->dump(toc_item); TOC->reserve(TOC->size()+toc_item.size()); TOC->insert(TOC->end(),toc_item.begin(),toc_item.end()); } header.TOCSize=TOC->size(); itc::CompressionBuffer compressedTOC=std::make_shared<itc::ByteArray>(); itc::bz2::compress(TOC,compressedTOC); header.TOCCompressedSize=compressedTOC->size(); auto ret=::write(ffd,compressedTOC->data(),compressedTOC->size()); if(ret == -1) { throw std::system_error( errno, std::system_category(), std::string("error on writing TOC to archive ")+archname ); } std::ofstream archive(fs::current_path() / archname, std::ios_base::out|std::ios_base::binary); if(archive&&archive.is_open()) { archive.write((char*)(&header),sizeof(header)); // determine TOC size lseek(ffd,0,SEEK_SET); off_t buff_len=lseek(ffd,0,SEEK_END); // read TOC from temp file lseek(ffd,0,SEEK_SET); char buff[buff_len]; auto ret=::read(ffd,buff,buff_len); if(ret == -1) { throw std::system_error( errno, std::system_category(), std::string("error on reading from archive ")+archname ); } // write TOC into archive. archive.write(buff,buff_len); // determine content size: lseek(fd,SEEK_SET,0); off_t content_buff_len=lseek(fd,0,SEEK_END); // read content and write it into archive. lseek(fd,0,SEEK_SET); if(content_buff_len < 4096) { char nbuff[content_buff_len]; auto ret=::read(fd,nbuff,content_buff_len); if(ret == -1) { throw std::system_error( errno, std::system_category(), std::string("error on reading from archive ")+archname ); } archive.write(nbuff,content_buff_len); }else{ char nbuff[4096]; for(size_t i=0;i<static_cast<size_t>(content_buff_len/4096);++i) { auto ret=::read(fd,nbuff,4096); if(ret == -1) { throw std::system_error( errno, std::system_category(), std::string("error on reading from archive ")+archname ); } archive.write(nbuff,4096); } size_t last_chunk=(content_buff_len-static_cast<size_t>(content_buff_len/4096)*4096); auto ret=::read(fd,nbuff,last_chunk); if(ret == -1) { throw std::system_error( errno, std::system_category(), std::string("error on reading from archive ")+archname ); } archive.write(nbuff,last_chunk); } close(fd); close(ffd); unlink(tempname.c_str()); unlink(tempname1.c_str()); archive.close(); } } }; } #endif /* __LAR_H__ */
098a761a4c856a6ed8809bf84dadcf9974686247
180492f944459ac416476603f601407e9c4c6988
/NeoLoader/FileTransfer/ed2kMule/MuleSocket.h
3fdac9646c701a345fe3ac7e82fd578b20a566e9
[]
no_license
bratao/NeoLoader
3a05068f104fa82c853a3ccf8bcc079c5a61a527
7885abdb71dc98ef1b45273faaad699eda82c57b
refs/heads/master
2021-01-15T08:48:06.483422
2015-04-02T18:04:54
2015-04-02T18:04:54
35,004,681
0
1
null
2015-05-03T23:33:38
2015-05-03T23:33:38
null
UTF-8
C++
false
false
1,122
h
MuleSocket.h
#pragma once #include "../../Networking/StreamSocket.h" #include "../../../Framework/Buffer.h" class CSymmetricKey; class CMuleServer; class CSimpleDH; class CMuleSocket: public CStreamSocket { Q_OBJECT public: CMuleSocket(CSocketThread* pSocketThread); virtual ~CMuleSocket(); virtual void SendPacket(const QByteArray& Packet, uint8 Prot); virtual void QueuePacket(uint64 ID, const QByteArray& Packet, uint8 Prot); virtual void InitCrypto(const QByteArray& UserHash); virtual void InitCrypto(); virtual void ProcessCrypto(); virtual bool IsEncrypted(); signals: void ReceivedPacket(QByteArray Packet, quint8 Prot); private slots: virtual void OnConnected(); protected: friend class CMuleServer; virtual void StreamOut(byte* Data, size_t Length); virtual void StreamIn(byte* Data, size_t Length); virtual void ProcessStream(); uint8 m_NextPacketProt; quint32 m_NextPacketLength; CSymmetricKey* m_CryptoKey; CSimpleDH* m_KeyExchange; enum ECrypto { eInit, ePending, ePadding, eDone } m_CryptoState; };
98a8df4a804070707b9df9756cf6841e5c61ed2e
60c06d4ba5234b7bee572137d9d4f2c627b405ab
/FLOW007/flow007.cpp
f5b595f5ca224fc37184e16f3cae36911fd14a69
[]
no_license
adarsh-k-tiwari/CodeChef-Practice
1a33fe89de79baa2f2d075667ca43c1219b083b5
8e25099deaf9b5b4f14dbe0f519b0dcf02c29ddd
refs/heads/master
2022-12-19T18:56:30.646639
2020-10-04T18:34:04
2020-10-04T18:34:04
299,215,826
1
1
null
2020-10-02T06:51:48
2020-09-28T06:52:24
C++
UTF-8
C++
false
false
399
cpp
flow007.cpp
#include<bits/stdc++.h> using namespace std; int main() { // #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); // #endif int test_cases; cin >> test_cases; while(test_cases--) { int num; cin >> num; int ans=0; int rem=0; while(num) { rem = num % 10; ans=ans*10 + rem; num = num /10; } cout<< ans << endl; } return 0; }
9dbf49f5be68ecb45c471b8c43dd214d9d55f586
7a5f7ea7211e1636ff69c56d1f9eaeb3a13bef53
/Bilibili/event/event_dmmsg.cpp
a1512817981eb9994f3e0c45c32bb4463c014fb6
[ "MIT" ]
permissive
yang123vc/BilibiliTool
034ba175e177b7e80a80f8f29fe19e62108e1439
c19cfa1d40252d5994d34ab9f9ecbbced6ba3d84
refs/heads/master
2020-08-03T04:50:31.716062
2019-09-14T16:16:02
2019-09-14T16:16:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,776
cpp
event_dmmsg.cpp
#include "event_dmmsg.h" #include "logger/log.h" #include "utility/platform.h" #include "utility/strconvert.h" enum { DM_NONE = 0, DM_ACTIVITY_MATCH_GIFT, DM_CHANGE_ROOM_INFO, DM_COMBO_SEND, DM_CUT_OFF, DM_DANMU_LOTTERY_START, DM_DANMU_LOTTERY_END, // DM_DANMU_LOTTERY_AWARD, DM_WARNING, DM_DANMU_MSG, DM_GUARD_BUY, DM_LIVE, // DM_LUCK_GIFT_AWARD_USER, // DM_MESSAGEBOX_USER_GAIN_MEDAL, DM_NOTICE_MSG, DM_NOTICE_MSG_H5, DM_GUARD_LOTTERY_START, DM_PK_MATCH, DM_PK_PRE, DM_PK_START, DM_PK_PROCESS, DM_PK_END, DM_PK_SETTLE, DM_PK_AGAIN, DM_PK_MIC_END, DM_PK_BATTLE_PRE, DM_PK_BATTLE_START, DM_PK_BATTLE_PROCESS, DM_PK_BATTLE_PRO_TYPE, DM_PK_BATTLE_GIFT, DM_PK_BATTLE_VOTES_ADD, DM_PK_BATTLE_END, DM_PK_BATTLE_SETTLE_USER, DM_PK_LOTTERY_START, DM_PREPARING, DM_RAFFLE_START, DM_RAFFLE_END, // DM_ROOM_REFRESH, DM_ROOM_SKIN_MSG, DM_SCORE_CARD, DM_TV_START, DM_TV_END, // DM_ROOM_BLOCK_INTO, DM_ROOM_BLOCK_MSG, // DM_ROOM_KICKOUT, DM_ROOM_LOCK, DM_ROOM_LIMIT, DM_ROOM_SILENT_ON, DM_ROOM_SILENT_OFF, DM_SEND_GIFT, // DM_SEND_TOP, DM_SPECIAL_GIFT, DM_WEEK_STAR_CLOCK, DM_WELCOME, DM_WELCOME_GUARD, DM_ENTRY_EFFECT, DM_WIN_ACTIVITY, DM_WISH_BOTTLE, DM_ROOM_RANK, DM_HOUR_RANK_AWARDS, DM_LOL_ACTIVITY, DM_ROOM_REAL_TIME_MESSAGE_UPDATE, DM_ROOM_SHIELD, DM_ROOM_ADMINS, DM_PK_INVITE_INIT, DM_PK_INVITE_FAIL, DM_PK_INVITE_CANCEL, DM_PK_INVITE_SWITCH_OPEN, DM_PK_INVITE_SWITCH_CLOSE, DM_PK_INVITE_REFUSE, DM_PK_CLICK_AGAIN, DM_PK_BATTLE_ENTRANCE, DM_PK_BATTLE_MATCH_TIMEOUT, DM_PK_BATTLE_RANK_CHANGE, DM_PK_BATTLE_SETTLE, DM_ACTIVITY_BANNER_UPDATE, DM_ACTIVITY_BANNER_RED_NOTICE_CLOSE, DM_ACTIVITY_BANNER_CLOSE, DM_ANIMATION, DM_BOSS_INFO, DM_BOSS_INJURY, DM_BOSS_BATTLE, DM_BOSS_ENERGY, DM_USER_TOAST_MSG, DM_room_admin_entrance, DM_new_anchor_reward, DM_DANMU_MSG_402220, DM_BOX_ACTIVITY_START, DM_ROOM_CHANGE, DM_DAILY_QUEST_NEWDAY, DM_GUIARD_MSG, DM_ROOM_BOX_MASTER, DM_ROOM_BOX_USER, DM_GUARD_ACHIEVEMENT_ROOM, DM_VOICE_JOIN_LIST, DM_VOICE_JOIN_ROOM_COUNT_INFO, DM_VOICE_JOIN_STATUS, DM_VOICE_JOIN_SWITCH, DM_ACTIVITY_BANNER_UPDATE_V2, DM_SUPER_CHAT_ENTRANCE, DM_ACTIVITY_EVENT, DM_COMBO_END, DM_GUARD_MSG, DM_LOTTERY_START, DM_SYS_GIFT, DM_SYS_MSG, DM_WELCOME_ACTIVITY }; struct tagDANMUMSGSYS { int itype; time_t time; int iuid, iround; int iroomid, igiftid;//SYSGIFT std::string msg; std::wstring wmsg; std::string url; }; void event_dmmsg::InitCMD() { // 15 3 m_cmdid["CHANGE_ROOM_INFO"] = DM_CHANGE_ROOM_INFO; m_cmdid["CUT_OFF"] = DM_CUT_OFF; m_cmdid["LIVE"] = DM_LIVE; m_cmdid["PREPARING"] = DM_PREPARING; m_cmdid["WARNING"] = DM_WARNING; m_cmdid["ROOM_SKIN_MSG"] = DM_ROOM_SKIN_MSG; m_cmdid["ROOM_BLOCK_MSG"] = DM_ROOM_BLOCK_MSG; m_cmdid["ROOM_LOCK"] = DM_ROOM_LOCK; m_cmdid["ROOM_LIMIT"] = DM_ROOM_LIMIT; m_cmdid["ROOM_RANK"] = DM_ROOM_RANK; m_cmdid["ROOM_SILENT_ON"] = DM_ROOM_SILENT_ON; m_cmdid["ROOM_SILENT_OFF"] = DM_ROOM_SILENT_OFF; m_cmdid["ROOM_REAL_TIME_MESSAGE_UPDATE"] = DM_ROOM_REAL_TIME_MESSAGE_UPDATE; m_cmdid["ROOM_SHIELD"] = DM_ROOM_SHIELD; m_cmdid["ROOM_ADMINS"] = DM_ROOM_ADMINS; // 9 3 m_cmdid["COMBO_SEND"] = DM_COMBO_SEND; m_cmdid["DANMU_MSG"] = DM_DANMU_MSG; m_cmdid["GUARD_BUY"] = DM_GUARD_BUY; m_cmdid["NOTICE_MSG"] = DM_NOTICE_MSG; m_cmdid["NOTICE_MSG_H5"] = DM_NOTICE_MSG_H5; m_cmdid["SEND_GIFT"] = DM_SEND_GIFT; m_cmdid["WELCOME"] = DM_WELCOME; m_cmdid["WELCOME_GUARD"] = DM_WELCOME_GUARD; m_cmdid["ENTRY_EFFECT"] = DM_ENTRY_EFFECT; // 15 m_cmdid["PK_INVITE_INIT"] = DM_PK_INVITE_INIT; m_cmdid["PK_INVITE_FAIL"] = DM_PK_INVITE_FAIL; m_cmdid["PK_INVITE_CANCEL"] = DM_PK_INVITE_CANCEL; m_cmdid["PK_INVITE_SWITCH_OPEN"] = DM_PK_INVITE_SWITCH_OPEN; m_cmdid["PK_INVITE_SWITCH_CLOSE"] = DM_PK_INVITE_SWITCH_CLOSE; m_cmdid["PK_INVITE_REFUSE"] = DM_PK_INVITE_REFUSE; m_cmdid["PK_MATCH"] = DM_PK_MATCH; m_cmdid["PK_PRE"] = DM_PK_PRE; m_cmdid["PK_START"] = DM_PK_START; m_cmdid["PK_PROCESS"] = DM_PK_PROCESS; m_cmdid["PK_END"] = DM_PK_END; m_cmdid["PK_SETTLE"] = DM_PK_SETTLE; m_cmdid["PK_AGAIN"] = DM_PK_AGAIN; m_cmdid["PK_MIC_END"] = DM_PK_MIC_END; m_cmdid["PK_CLICK_AGAIN"] = DM_PK_CLICK_AGAIN; // 13 m_cmdid["PK_BATTLE_ENTRANCE"] = DM_PK_BATTLE_ENTRANCE; m_cmdid["PK_BATTLE_MATCH_TIMEOUT"] = DM_PK_BATTLE_MATCH_TIMEOUT; m_cmdid["PK_BATTLE_PRE"] = DM_PK_BATTLE_PRE; m_cmdid["PK_BATTLE_START"] = DM_PK_BATTLE_START; m_cmdid["PK_BATTLE_PROCESS"] = DM_PK_BATTLE_PROCESS; m_cmdid["PK_BATTLE_PRO_TYPE"] = DM_PK_BATTLE_PRO_TYPE; m_cmdid["PK_BATTLE_GIFT"] = DM_PK_BATTLE_GIFT; m_cmdid["PK_BATTLE_VOTES_ADD"] = DM_PK_BATTLE_VOTES_ADD; m_cmdid["PK_BATTLE_END"] = DM_PK_BATTLE_END; m_cmdid["PK_BATTLE_RANK_CHANGE"] = DM_PK_BATTLE_RANK_CHANGE; m_cmdid["PK_BATTLE_SETTLE_USER"] = DM_PK_BATTLE_SETTLE_USER; m_cmdid["PK_BATTLE_SETTLE"] = DM_PK_BATTLE_SETTLE; m_cmdid["PK_LOTTERY_START"] = DM_PK_LOTTERY_START; // 15 1 m_cmdid["DANMU_LOTTERY_START"] = DM_DANMU_LOTTERY_START; m_cmdid["DANMU_LOTTERY_END"] = DM_DANMU_LOTTERY_END; m_cmdid["GUARD_LOTTERY_START"] = DM_GUARD_LOTTERY_START; m_cmdid["RAFFLE_START"] = DM_RAFFLE_START; m_cmdid["RAFFLE_END"] = DM_RAFFLE_END; m_cmdid["SCORE_CARD"] = DM_SCORE_CARD; m_cmdid["TV_START"] = DM_TV_START; m_cmdid["TV_END"] = DM_TV_END; m_cmdid["SPECIAL_GIFT"] = DM_SPECIAL_GIFT; m_cmdid["WEEK_STAR_CLOCK"] = DM_WEEK_STAR_CLOCK; m_cmdid["WIN_ACTIVITY"] = DM_WIN_ACTIVITY; m_cmdid["WISH_BOTTLE"] = DM_WISH_BOTTLE; m_cmdid["LOL_ACTIVITY"] = DM_LOL_ACTIVITY; m_cmdid["HOUR_RANK_AWARDS"] = DM_HOUR_RANK_AWARDS; m_cmdid["ACTIVITY_MATCH_GIFT"] = DM_ACTIVITY_MATCH_GIFT; // 3 m_cmdid["ACTIVITY_BANNER_UPDATE"] = DM_ACTIVITY_BANNER_UPDATE; m_cmdid["ACTIVITY_BANNER_RED_NOTICE_CLOSE"] = DM_ACTIVITY_BANNER_RED_NOTICE_CLOSE; m_cmdid["ACTIVITY_BANNER_CLOSE"] = DM_ACTIVITY_BANNER_CLOSE; // 5 m_cmdid["ANIMATION"] = DM_ANIMATION; m_cmdid["BOSS_INFO"] = DM_BOSS_INFO; m_cmdid["BOSS_INJURY"] = DM_BOSS_INJURY; m_cmdid["BOSS_BATTLE"] = DM_BOSS_BATTLE; m_cmdid["BOSS_ENERGY"] = DM_BOSS_ENERGY; // 17 m_cmdid["USER_TOAST_MSG"] = DM_USER_TOAST_MSG; m_cmdid["room_admin_entrance"] = DM_room_admin_entrance; m_cmdid["new_anchor_reward"] = DM_new_anchor_reward; m_cmdid["DANMU_MSG:4:0:2:2:2:0"] = DM_DANMU_MSG_402220; m_cmdid["BOX_ACTIVITY_START"] = DM_BOX_ACTIVITY_START; m_cmdid["ROOM_CHANGE"] = DM_ROOM_CHANGE; m_cmdid["DAILY_QUEST_NEWDAY"] = DM_DAILY_QUEST_NEWDAY; m_cmdid["GUIARD_MSG"] = DM_GUIARD_MSG; m_cmdid["ROOM_BOX_MASTER"] = DM_ROOM_BOX_MASTER; m_cmdid["ROOM_BOX_USER"] = DM_ROOM_BOX_USER; m_cmdid["GUARD_ACHIEVEMENT_ROOM"] = DM_GUARD_ACHIEVEMENT_ROOM; m_cmdid["VOICE_JOIN_LIST"] = DM_VOICE_JOIN_LIST; m_cmdid["VOICE_JOIN_ROOM_COUNT_INFO"] = DM_VOICE_JOIN_ROOM_COUNT_INFO; m_cmdid["VOICE_JOIN_STATUS"] = DM_VOICE_JOIN_STATUS; m_cmdid["VOICE_JOIN_SWITCH"] = DM_VOICE_JOIN_SWITCH; m_cmdid["ACTIVITY_BANNER_UPDATE_V2"] = DM_ACTIVITY_BANNER_UPDATE_V2; m_cmdid["SUPER_CHAT_ENTRANCE"] = DM_SUPER_CHAT_ENTRANCE; // 7 m_cmdid["ACTIVITY_EVENT"] = DM_ACTIVITY_EVENT; m_cmdid["COMBO_END"] = DM_COMBO_END; m_cmdid["GUARD_MSG"] = DM_GUARD_MSG; m_cmdid["LOTTERY_START"] = DM_LOTTERY_START; m_cmdid["SYS_GIFT"] = DM_SYS_GIFT; m_cmdid["SYS_MSG"] = DM_SYS_MSG; m_cmdid["WELCOME_ACTIVITY"] = DM_WELCOME_ACTIVITY; } void event_dmmsg::process_data(MSG_INFO *data) { int ret; switch (data->type) { case 0x03: { // int value = str[1] << 16 | str[2] << 8 | str[3]; // BOOST_LOG_SEV(g_logger::get(), trace) << "[DMMSG] " << room << " Popular:" << value; break; } case 0x05: { ret = ParseJSON(data); if (ret) { BOOST_LOG_SEV(g_logger::get(), debug) << "[DMMSG] " << data->id << " DMNEW: " << data->buff.get(); } break; } case 0x08: { BOOST_LOG_SEV(g_logger::get(), info) << "[DMMSG] " << data->id << " Link start..."; break; } default: { BOOST_LOG_SEV(g_logger::get(), error) << "[DMMSG] " << data->id << " Unknown msg type: " << data->type; break; } } } int event_dmmsg::ParseJSON(MSG_INFO *data) { rapidjson::Document doc; doc.Parse(data->buff.get()); if (!doc.IsObject() || !doc.HasMember("cmd") || !doc["cmd"].IsString()) { BOOST_LOG_SEV(g_logger::get(), error) << "[DMMSG] " << data->id << " JSON Wrong."; return -1; } std::string strtype = doc["cmd"].GetString(); if (!m_cmdid.count(strtype)) { // 新指令 return -1; } int cmdid = m_cmdid[strtype]; switch (cmdid) { case DM_DANMU_MSG: { return 0; } case DM_SPECIAL_GIFT: { if (data->opt & DM_HIDDENEVENT) { return this->ParseSTORMMSG(doc, data->id); } return 0; } case DM_NOTICE_MSG: { if (data->opt & DM_PUBEVENT) { return this->ParseNOTICEMSG(doc, data->id, DM_ROOM_AREA(data->opt)); } return 0; } case DM_GUARD_LOTTERY_START: { if (data->opt & DM_HIDDENEVENT) { return this->ParseGUARDLO(doc, data->id); } return 0; } case DM_PK_LOTTERY_START: { if (data->opt & DM_HIDDENEVENT) { return this->ParsePKLOTTERY(doc, data->id); } return 0; } case DM_PREPARING: case DM_CUT_OFF: { event_base::post_close_msg(data->id, data->opt); return 0; } case DM_LIVE: { event_base::post_open_msg(data->id, data->opt); return 0; } case DM_ROOM_CHANGE: { if (data->opt & DM_PUBEVENT) { return ParseROOMMSG(doc, data->id, data->opt); } return 0; } } return 0; } int event_dmmsg::ParseSTORMMSG(rapidjson::Document &doc, const unsigned room) { if (!doc.HasMember("data") || !doc["data"].IsObject() || !doc["data"].HasMember("39") || !doc["data"]["39"].IsObject() || !doc["data"]["39"].HasMember("action")) { return -1; } std::string tstr; tstr = doc["data"]["39"]["action"].GetString(); if (tstr == "start") { if (!doc["data"]["39"].HasMember("id")) { return -1; } long long id = 0; if (doc["data"]["39"]["id"].IsString()) { id = _atoi64(doc["data"]["39"]["id"].GetString()); } if (doc["data"]["39"]["id"].IsInt64()) { id = doc["data"]["39"]["id"].GetInt64(); } if (!id) { return -1; } std::shared_ptr<BILI_LOTTERYDATA> data(new BILI_LOTTERYDATA()); data->srid = room; data->rrid = room; data->loid = id; data->time_start = toollib::GetTimeStamp(); data->time_end = data->time_start + 90; data->type = "storm"; int num = 0; std::string content; if (doc["data"]["39"].HasMember("num") && doc["data"]["39"]["num"].IsInt()) { num = doc["data"]["39"]["num"].GetInt(); } if (doc["data"]["39"].HasMember("content") && doc["data"]["39"]["content"].IsString()) { content = doc["data"]["39"]["content"].GetString(); } BOOST_LOG_SEV(g_logger::get(), trace) << "[DMMSG] storm " << room << " num:" << num << " content:" << content; event_base::post_storm_msg(data); return 0; } if (tstr == "end") { return 0; } return -1; } int event_dmmsg::ParseNOTICEMSG(rapidjson::Document &doc, const unsigned room, const unsigned area) { // 如果消息不含有房间ID 则说明不是抽奖信息 if (!doc.HasMember("msg_type") || !doc["msg_type"].IsInt()) { return -1; } int type = doc["msg_type"].GetInt(); switch (type) { case 2: case 8: { return ParseSYSMSG(doc, room, area); } case 3: { return ParseGUARDMSG(doc, room, area); } case 1: case 4: case 5: case 6: case 9: case 10: { return 0; } } return -1; } int event_dmmsg::ParseSYSMSG(rapidjson::Document &doc, const unsigned room, const unsigned area) { // 如果消息不含有房间ID 则说明不是抽奖信息 if (!doc.HasMember("real_roomid") || !doc["real_roomid"].IsInt()) { return -1; } int rrid = doc["real_roomid"].GetInt(); // 如果是全区广播需要过滤重复消息 std::string tstr = doc["msg_common"].GetString(); std::wstring wmsg; toollib::UTF8ToUTF16(tstr, wmsg); if (wmsg.find(L"全区广播") != -1) { if (area != 1) { return 0; } } // 有房间号就进行抽奖 event_base::post_lottery_msg(rrid); return 0; } // 处理广播事件总督上船消息 int event_dmmsg::ParseGUARDMSG(rapidjson::Document &doc, const unsigned room, const unsigned area) { // 过滤当前房间的开通信息 std::string tstr = doc["msg_common"].GetString(); std::wstring wmsg; toollib::UTF8ToUTF16(tstr, wmsg); if (wmsg.find(L"在本房间") != -1) { return 0; } // 全区广播只需通知一次 if (area != 1) { return 0; } int rid = doc["real_roomid"].GetInt(); event_base::post_guard1_msg(rid); return 0; } // 处理房间事件非总督上船消息 int event_dmmsg::ParseGUARDLO(rapidjson::Document &doc, const unsigned room) { int btype = doc["data"]["privilege_type"].GetInt(); if (btype != 1) { std::shared_ptr<BILI_LOTTERYDATA> data(new BILI_LOTTERYDATA()); data->srid = room; data->rrid = room; data->loid = doc["data"]["id"].GetInt(); data->time_start = toollib::GetTimeStamp(); // data->time_end = data->time_start; data->type = doc["data"]["lottery"]["keyword"].GetString(); data->exinfo = btype; event_base::post_guard23_msg(data); } return 0; } int event_dmmsg::ParsePKLOTTERY(rapidjson::Document & doc, const unsigned room) { std::shared_ptr<BILI_LOTTERYDATA> data(new BILI_LOTTERYDATA()); data->srid = doc["data"]["room_id"].GetInt(); data->rrid = room; data->loid = doc["data"]["pk_id"].GetInt(); data->time_start = toollib::GetTimeStamp(); data->time_end = data->time_start + doc["data"]["time"].GetInt(); data->type = "pk"; event_base::post_pk_msg(data); return 0; } int event_dmmsg::ParseROOMMSG(rapidjson::Document & doc, const unsigned room, const unsigned opt) { unsigned area_cur = DM_ROOM_AREA(opt); unsigned area_new = doc["data"]["parent_area_id"].GetUint(); if (area_cur != area_new) { // 主分区发生更改 BOOST_LOG_SEV(g_logger::get(), trace) << "[DMMSG] room area change " << room << " from:" << area_cur << " to:" << area_new; event_base::post_close_msg(room, opt); } return 0; }
762512522748f1367fb22d81c084badeeb51c8cf
2bef6f6a1a6e3fe27d4f0158ecad5e13b6c6e205
/abcg/abcg_application.cpp
88e00cf1acdaf3e3d07beb8484e21ec377392497
[ "MIT" ]
permissive
mancinigabriel/abcg
8b8456ffe0cf4155a8bfe5b771c3c418ec45a5dc
33addcb6a937208f8f869482ba90f32f0586fc1e
refs/heads/main
2023-04-08T05:45:39.141410
2021-04-25T22:08:06
2021-04-25T22:08:06
338,852,997
1
1
MIT
2021-03-20T23:13:34
2021-02-14T16:50:52
C++
UTF-8
C++
false
false
3,215
cpp
abcg_application.cpp
/** * @file abcg_application.cpp * @brief Definition of abcg::Application class members. * * This project is released under the MIT License. */ #define TINYOBJLOADER_IMPLEMENTATION #include "abcg_application.hpp" #include <fmt/core.h> #include <gsl/gsl> #include "SDL_image.h" #include "abcg_exception.hpp" #include "abcg_openglwindow.hpp" #include "tiny_obj_loader.h" #if defined(__EMSCRIPTEN__) void abcg::mainLoopCallback(void *userData) { abcg::Application &app = *(static_cast<abcg::Application *>(userData)); bool done{}; app.mainLoopIterator(done); } #endif /** * @brief Constructs an abcg::Application object. * * Constructs an abcg::Application object and initializes the SDL library and * SDL subsystems. * * @throw abcg::Exception if SDL failed to initialize the subsystems. */ abcg::Application::Application([[maybe_unused]] int argc, char **argv) { Uint32 subsystemMask{SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER | SDL_INIT_EVENTS}; if (SDL_Init(subsystemMask) != 0) { throw abcg::Exception{abcg::Exception::SDL("SDL_Init failed")}; } #if !defined(__EMSCRIPTEN__) // Load support for the PNG image format auto imageFlags{IMG_INIT_PNG}; if (auto initialized{IMG_Init(imageFlags)}; (initialized & imageFlags) != imageFlags) { throw abcg::Exception{abcg::Exception::SDLImage("IMG_Init failed")}; } #endif // Get executable relative path std::string argv_str(*gsl::span{&argv, 1}[0]); #if defined(WIN32) if (auto n{argv_str.find_last_of('\\')}; n == std::string::npos) { // Called from the same directory of the executable m_basePath = "."; } else { m_basePath = argv_str.substr(0, n); } #else m_basePath = argv_str.substr(0, argv_str.find_last_of('/')); #endif } /** * @brief Destroys the abcg::Application object. * * Destroys the abcg::Application object and cleans up the SDL initialized * subsystems. */ abcg::Application::~Application() { #if !defined(__EMSCRIPTEN__) IMG_Quit(); #endif SDL_Quit(); } /** * @brief Runs the application for a set of windows. * * @param window Vector of pointers to windows. * * @throw abcg::Exception if the vector contains a null pointer. */ void abcg::Application::run( std::vector<std::unique_ptr<OpenGLWindow>> &windows) { for (auto &it : windows) { if (it == nullptr) { throw abcg::Exception{abcg::Exception::Runtime("Invalid pointer")}; } m_windows.push_back(std::move(it)); } run(); } void abcg::Application::mainLoopIterator([[maybe_unused]] bool &done) { SDL_Event event{}; while (SDL_PollEvent(&event) != 0) { #if !defined(__EMSCRIPTEN__) if (event.type == SDL_QUIT) done = true; #endif for (const auto &window : m_windows) { window->handleEvent(event, done); } } for (const auto &window : m_windows) { window->paint(); } } void abcg::Application::run() { for (const auto &w : m_windows) { w->initialize(m_basePath); } #if defined(__EMSCRIPTEN__) emscripten_set_main_loop_arg(mainLoopCallback, this, 0, true); #else bool done{}; while (!done) { mainLoopIterator(done); }; #endif }
824e83778e2d3ad70f95fb32aac0afcb5320e7b9
6d1d67f605e0695cfe6dfd13b4e30adab855c7f8
/RobotArm/Arm.cpp
0a2036848aea296cc5fbe6dabdac3e6bb689f3ee
[]
no_license
LauHoiYanGladys/RobotArm
f4a57dddeea692489319044c9ba132f20c3f2e53
dbd69b54fe83d526bab4b88b8378cf03c1e3b188
refs/heads/main
2023-07-13T22:09:46.776338
2021-08-19T04:38:49
2021-08-19T04:38:49
324,020,728
1
0
null
null
null
null
UTF-8
C++
false
false
15,324
cpp
Arm.cpp
#include <assert.h> /* assert */ #include "Arm.h" #include "DHframe.h" #include "Joint.h" #include "Link.h" #include "fssimplewindow.h" const double Arm::PI = 3.1415927; class Joint; using namespace Eigen; void Arm::draw() { for (auto& frame : theFrames) { // store current matrix state glPushMatrix(); //Note that the coordinate system is made right-handed in fssimplewindow, with z-axis pointing out of the screen // rotate frame 90 degrees counterclockwise about the x-axis // because openGL has y-axis up, while homogeneous transformation has z-axis up glRotatef(90, -1, 0, 0); // translate into the local frame Vector3d worldCenter = frame->getWorldCenter(false); glTranslatef(worldCenter(0), worldCenter(1), worldCenter(2)); // rotate into the local frame // get rotation matrix in world coordinates Matrix3d worldRotation = frame->getWorldRotationMat(false); // get angle-axis representation from rotation matrix Eigen::AngleAxisd theAngleAxis(worldRotation); double angleRotate = theAngleAxis.angle(); // convert from radian to degree angleRotate = angleRotate / PI * 180; Vector3d axisRotate = theAngleAxis.axis(); glRotatef(angleRotate, axisRotate(0), axisRotate(1), axisRotate(2)); //drawing of the frame frame->draw(); // restore original matrix state glPopMatrix(); } } void Arm::buildArm_Stanford() { alpha = 0.00001; // learning rate for revolute joint alphaPris = 0.5; // learning rate for prismatic joint costChangeStopThreshold = NULL; // slow response at certain goal positions if cost change is an IK stop criterion for this arm workspaceThreshold = 1.5; // define the 0th DH frame DHframe* zerothFrame = new DHframe(); // create first link and assign to 0th DH frame Link* firstLink = new Link(25); zerothFrame->assignLink(firstLink, Link::linkDirection::alongZ); // create the first (revolute) joint, assign to 0th DH frame Joint* firstJoint = new Joint(); zerothFrame->assignJoint(firstJoint); jointFrameMap.insert({ firstJoint, zerothFrame }); frameWithEndPoints.push_back(0); // add the joint to the joint collection theJoints.push_back(firstJoint); // add DH frame to frame collection theFrames.push_back(zerothFrame); // define the first DH frame DHframe* firstFrame = new DHframe(0., PI/2, 25., 0.); firstFrame->assignParentDHframe(zerothFrame); // create the second (revolute) joint, assign it to 1st DH frame Joint* secondJoint = new Joint(); firstFrame->assignJoint(secondJoint); jointFrameMap.insert({ secondJoint, firstFrame }); frameWithEndPoints.push_back(1); // record the frame index 1 in the collection of indices of frames containing jointVariables frameWithJointVariable.push_back(1); // add DH frame to frame collection theFrames.push_back(firstFrame); // add the joint to the joint collection theJoints.push_back(secondJoint); // define the second DH frame DHframe* secondFrame = new DHframe(0., PI / 2, 0., PI / 2); secondFrame->assignParentDHframe(firstFrame); // record the frame index 2 in the collection of indices of frames containing jointVariables frameWithJointVariable.push_back(2); // create the second link and assign it to the second DH frame Link* secondLink = new Link(25); secondFrame->assignLink(secondLink, Link::linkDirection::alongZ); // add DH frame to frame collection theFrames.push_back(secondFrame); // define the third DH frame, note that it has no associated joint DHframe* thirdFrame = new DHframe(0., 0., 25., 0); thirdFrame->assignParentDHframe(secondFrame); // create the third link and assign it to the third DH frame Link* thirdLink = new Link(25); thirdFrame->assignLink(thirdLink, Link::linkDirection::alongZ); // create the third (prismatic) joint // note that it corresponds to the third DH frame instead of second DH frame Joint* thirdJoint = new Joint(); thirdJoint->setJointTypePrismatic(); thirdFrame->assignJoint(thirdJoint); jointFrameMap.insert({ thirdJoint, thirdFrame }); frameWithEndPoints.push_back(3); // add DH frame to frame collection theFrames.push_back(thirdFrame); // add the joint to the joint collection theJoints.push_back(thirdJoint); // define the fourth DH frame (end-effector frame) DHframe* fourthFrame = new DHframe(0., 0., 25., -PI/2); fourthFrame->assignParentDHframe(thirdFrame); frameWithEndPoints.push_back(4); // add DH frame to frame collection theFrames.push_back(fourthFrame); // record the frame index 4 in the collection of indices of frames containing jointVariables frameWithJointVariable.push_back(4); } void Arm::buildArm_PUMA560() { alpha = 0.001; // learning rate costChangeStopThreshold = 0.02; workspaceThreshold = 1.5; // some link parameters double secondLinkOffset = 5.; double firstLinkLength = 25.; double secondLinkLength = 25.; double thirdLinkLength = 15.; // define the 0th DH frame DHframe* zerothFrame = new DHframe(); // create first link and assign to 0th DH frame Link* firstLink = new Link(firstLinkLength); zerothFrame->assignLink(firstLink, Link::linkDirection::alongZ); // create the first (revolute) joint, assign to 0th DH frame Joint* firstJoint = new Joint(); zerothFrame->assignJoint(firstJoint); jointFrameMap.insert({ firstJoint, zerothFrame }); frameWithEndPoints.push_back(0); // add the joint to the joint collection theJoints.push_back(firstJoint); // add DH frame to frame collection theFrames.push_back(zerothFrame); // define the first DH frame, note that it has no associated joint DHframe* firstFrame = new DHframe(0., 0., firstLinkLength, 0.); firstFrame->assignParentDHframe(zerothFrame); // record the frame index 1 in the collection of indices of frames containing jointVariables frameWithJointVariable.push_back(1); // add DH frame to frame collection theFrames.push_back(firstFrame); // define the second DH frame DHframe* secondFrame = new DHframe(0., -PI/2, 0., 0.); secondFrame->assignParentDHframe(firstFrame); // create the second (revolute) joint, assign it to 2nd DH frame Joint* secondJoint = new Joint(); secondFrame->assignJoint(secondJoint); jointFrameMap.insert({ secondJoint, secondFrame }); frameWithEndPoints.push_back(2); // add the second joint to the joint collection theJoints.push_back(secondJoint); // add DH frame to frame collection theFrames.push_back(secondFrame); // define the third DH frame (defined to make it easy finding the positions of end points when secondLinkOffset is not zero) DHframe* thirdFrame = new DHframe(0., 0., secondLinkOffset, 0.); thirdFrame->assignParentDHframe(secondFrame); frameWithEndPoints.push_back(3); // record the frame index 3 in the collection of indices of frames containing jointVariables frameWithJointVariable.push_back(3); // create the second link and assign it to the third DH frame Link* secondLink = new Link(secondLinkLength); thirdFrame->assignLink(secondLink, Link::linkDirection::alongX); // add DH frame to frame collection theFrames.push_back(thirdFrame); // define the fourth DH frame DHframe* fourthFrame = new DHframe(secondLinkLength, 0., 0., 0.); fourthFrame->assignParentDHframe(thirdFrame); // create the third (revolute) joint // note that it corresponds to the fourth DH frame Joint* thirdJoint = new Joint(); fourthFrame->assignJoint(thirdJoint); jointFrameMap.insert({ thirdJoint, fourthFrame }); frameWithEndPoints.push_back(4); // add the joint to the joint collection theJoints.push_back(thirdJoint); // add DH frame to frame collection theFrames.push_back(fourthFrame); // define the fifth DH frame (no associated joint, just defined to conform to the DH convention) DHframe* fifthFrame = new DHframe(0., -PI/2, 0., 0.); fifthFrame->assignParentDHframe(fourthFrame); // create the third link and assign it to the fifth DH frame Link* thirdLink = new Link(thirdLinkLength); fifthFrame->assignLink(thirdLink, Link::linkDirection::alongZ); // add DH frame to frame collection theFrames.push_back(fifthFrame); // record the frame index 5 in the collection of indices of frames containing jointVariables frameWithJointVariable.push_back(5); // define the sixth DH frame (end-effector frame) DHframe* sixthFrame = new DHframe(0., 0., thirdLinkLength, 0.); sixthFrame->assignParentDHframe(fifthFrame); frameWithEndPoints.push_back(6); // add DH frame to frame collection theFrames.push_back(sixthFrame); } void Arm::buildArm_SCARA() { alpha = 0.001; // learning rate for revolute joint alphaPris = 0.6; // learning rate for prismatic joint costChangeStopThreshold = 0.02; workspaceThreshold = 1.5; double zerothLinkLength = 25.; double firstLinkOffset = 5.; double firstLinkLength = 15.; double secondLinkLength = 15.; // define the 0th DH frame, note it is BEFORE the first joint (0th frame defined like this to make it easy to make a zeroth link to "elevate" the SCARA arm above ground); DHframe* zerothFrame = new DHframe(); // create zeroth link and assign to 0th DH frame Link* zerothLink = new Link(zerothLinkLength); zerothFrame->assignLink(zerothLink, Link::linkDirection::alongZ); frameWithEndPoints.push_back(0); // add zeroth DH frame to frame collection theFrames.push_back(zerothFrame); // define the first DH frame DHframe* firstFrame = new DHframe(0., 0., zerothLinkLength, 0.); firstFrame->assignParentDHframe(zerothFrame); frameWithEndPoints.push_back(1); // although this end point is not necessary for the skeleton, it's defined so that each joint consistently coincide with endpoints // create the first (revolute) joint, assign to 1st DH frame Joint* firstJoint = new Joint(); firstFrame->assignJoint(firstJoint); jointFrameMap.insert({ firstJoint, firstFrame }); // add the joint to the joint collection theJoints.push_back(firstJoint); // add first frame to frame collection theFrames.push_back(firstFrame); // define the second DH frame (defined to make it easy finding the positions of end points when firstLinkOffset is not zero) DHframe* secondFrame = new DHframe(0., 0., firstLinkOffset, 0.); secondFrame->assignParentDHframe(firstFrame); frameWithEndPoints.push_back(2); // record the frame index 2 in the collection of indices of frames containing jointVariables frameWithJointVariable.push_back(2); // create the first link and assign it to the second DH frame Link* firstLink = new Link(firstLinkLength); secondFrame->assignLink(firstLink, Link::linkDirection::alongX); // add DH frame to frame collection theFrames.push_back(secondFrame); // define the third DH frame DHframe* thirdFrame = new DHframe(firstLinkLength, 0., 0., 0.); thirdFrame->assignParentDHframe(secondFrame); frameWithEndPoints.push_back(3); // create the second (revolute) joint // note that it corresponds to the third DH frame Joint* secondJoint = new Joint(); thirdFrame->assignJoint(secondJoint); jointFrameMap.insert({ secondJoint, thirdFrame }); // add the joint to the joint collection theJoints.push_back(secondJoint); // add third DH frame to frame collection theFrames.push_back(thirdFrame); // define the fourth DH frame DHframe* fourthFrame = new DHframe(0., 0., 0., 0.); fourthFrame->assignParentDHframe(thirdFrame); // record the frame index 4 in the collection of indices of frames containing jointVariables frameWithJointVariable.push_back(4); // create second link and assign to fourth DH frame Link* secondLink = new Link(secondLinkLength); fourthFrame->assignLink(secondLink, Link::linkDirection::alongX); // add fourth DH frame to frame collection theFrames.push_back(fourthFrame); // define the fifth DH frame DHframe* fifthFrame = new DHframe(secondLinkLength, PI, 0., 0.); fifthFrame->assignParentDHframe(fourthFrame); frameWithEndPoints.push_back(5); // note that "third link length" is not defined and effectively set to zero // create the third (prismatic) joint // note that it corresponds to the fifth DH frame Joint* thirdJoint = new Joint(); thirdJoint->setJointTypePrismatic(); fifthFrame->assignJoint(thirdJoint); jointFrameMap.insert({ thirdJoint, fifthFrame }); // add the joint to the joint collection theJoints.push_back(thirdJoint); // add fifth DH frame to frame collection theFrames.push_back(fifthFrame); // define the sixth DH frame (end-effector frame), note that the last revolute joint in a typical SCARA arm is skipped as we currently only model end-effector's position but not orientation DHframe* sixthFrame = new DHframe(0., 0., 0., 0.); sixthFrame->assignParentDHframe(fifthFrame); frameWithEndPoints.push_back(6); // record the frame index 6 in the collection of indices of frames containing jointVariables frameWithJointVariable.push_back(6); // add DH frame to frame collection theFrames.push_back(sixthFrame); } void Arm::moveArm(std::vector<double> jointVariables) { assert(jointVariables.size() == frameWithJointVariable.size()); for (int i = 0; i < frameWithJointVariable.size(); i++) { int currFrameIndex = frameWithJointVariable[i]; if (theJoints[i]->type == Joint::revolute) { theFrames[currFrameIndex]->update_theta(jointVariables[i]); } else if (theJoints[i]->type == Joint::prismatic) { theFrames[currFrameIndex]->update_d(jointVariables[i]); } theJoints[i]->updateJointVariable(jointVariables[i]); } // also updates test frames to ensure next test frame computation is based on actual joint variables updateTestFrames(jointVariables); } void Arm::updateTestFrames(std::vector<double> jointVariables) { assert(jointVariables.size() == frameWithJointVariable.size()); for (int i = 0; i < frameWithJointVariable.size(); i++) { int currFrameIndex = frameWithJointVariable[i]; if (theJoints[i]->type == Joint::revolute) theFrames[currFrameIndex]->update_test_theta(jointVariables[i]); else if (theJoints[i]->type == Joint::prismatic) theFrames[currFrameIndex]->update_test_d(jointVariables[i]); } } Vector3d Arm::getTestJointVariable() { Vector3d testJointVariables; assert(testJointVariables.size() == frameWithJointVariable.size()); assert(frameWithJointVariable.back() < theFrames.size()); for (int i = 0; i < frameWithJointVariable.size(); i++) { int currFrameIndex = frameWithJointVariable[i]; if (theJoints[i]->type == Joint::revolute) testJointVariables(i) = theFrames[currFrameIndex]->test_theta; else if (theJoints[i]->type == Joint::prismatic) testJointVariables(i) = theFrames[currFrameIndex]->test_d; } return testJointVariables; } Vector3d Arm::compute_test_FK(int frameIndex) { Vector3d theFK; DHframe* theFrame; if (!theFrames.empty() && frameIndex <= theFrames.size() - 1) { theFrame = theFrames[frameIndex]; theFK = theFrame->getWorldCenter(true); } return theFK; } Vector3d Arm::compute_test_FK(DHframe* theFrame) { Vector3d theFK; theFK = theFrame->getWorldCenter(true); return theFK; } std::vector<DrawingUtilNG::vertexF> Arm::compute_test_FK_all() { std::vector<DrawingUtilNG::vertexF>res; for (int i = 0; i < frameWithEndPoints.size(); i++) { int currFrameIndex = frameWithEndPoints[i]; Vector3d tempVector3d = compute_test_FK(currFrameIndex); DrawingUtilNG::vertexF tempVertexF = { (float)tempVector3d(0), (float)tempVector3d(1),(float)tempVector3d(2) }; res.push_back(tempVertexF); } return res; }
196de621d713403caa02036622392f56aa606a50
c948d95c8ca8d0480488c317fe51aea06863fd20
/src/msg_service/AbstractMsgService.h
f4b8a7bf462451e3de5e763baab346262c9f1c77
[]
no_license
YifengWong/msg-service-client
c9c3fa4edea4aaba13f032393444ccca8531f1af
8fd6bd92e9fef70c873ab0dc01e99f5b537c4c64
refs/heads/master
2021-01-19T08:30:46.753885
2017-04-12T04:06:21
2017-04-12T04:06:21
87,641,077
0
0
null
null
null
null
UTF-8
C++
false
false
1,053
h
AbstractMsgService.h
/* * AbstractMsgService.h * * Created on: 2017年4月8日 * Author: wyf */ #ifndef MSG_SERVICE_ABSTRACTMSGSERVICE_H_ #define MSG_SERVICE_ABSTRACTMSGSERVICE_H_ #include "Message.h" #include "MsgManager.h" /* * As an interface for Message Service. * */ class AbstractMsgService { public: AbstractMsgService(MsgManager* msgMgr); virtual ~AbstractMsgService(); /* * Start the message service * */ virtual void startService() = 0; /* * Get next request's uuid, to tag a request * */ const std::string* getNextRequestUuid(); /* * Get next message with a image file. * */ Message* getNextMsg(const std::string userUuid); /* * Send a message to server. * */ void sendMsg(Message* msg);// include result /* * Send a result to server. * */ void sendResult(std::string userUuid, std::string result); protected: pthread_t recvThreadId; pthread_t sendThreadId; MsgManager* msgMgr; }; #endif /* MSG_SERVICE_ABSTRACTMSGSERVICE_H_ */
8edb26ec433241eeca00affc54befe9ea4a7f6cc
c7e7dfe4ac47ed253554ae01e325d495524b10a6
/Arduino_Motion_Capture_Glove_code.ino
1dfb1718934fc64fa615a7a2487a007c3f088501
[]
no_license
fred45/Frederick-F.-Motion-Capture-Glove-Code
63b535e1b559f2736036dbca19908b051f4072f4
c1bea2dc91da82aa3c8c3a902485aa239cd1529d
refs/heads/master
2021-01-02T22:36:17.788242
2017-08-04T15:05:16
2017-08-04T15:05:16
99,351,961
1
0
null
null
null
null
UTF-8
C++
false
false
31,009
ino
Arduino_Motion_Capture_Glove_code.ino
/*-----Arduino Code for Motion Capture Glove-----*/ #include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_LSM303_U.h> #include <Adafruit_L3GD20_U.h> #include <MahonyAHRS.h> #include <MadgwickAHRS.h> #define TCAADDR 0x70 Adafruit_LSM303_Mag_Unified mag1 = Adafruit_LSM303_Mag_Unified(1); Adafruit_LSM303_Mag_Unified mag2 = Adafruit_LSM303_Mag_Unified(2); Adafruit_LSM303_Mag_Unified mag3 = Adafruit_LSM303_Mag_Unified(3); Adafruit_LSM303_Mag_Unified mag4 = Adafruit_LSM303_Mag_Unified(4); Adafruit_LSM303_Accel_Unified accel1 = Adafruit_LSM303_Accel_Unified(1); Adafruit_LSM303_Accel_Unified accel2 = Adafruit_LSM303_Accel_Unified(2); Adafruit_LSM303_Accel_Unified accel3 = Adafruit_LSM303_Accel_Unified(3); Adafruit_LSM303_Accel_Unified accel4 = Adafruit_LSM303_Accel_Unified(4); Adafruit_L3GD20_Unified gyro1 = Adafruit_L3GD20_Unified(1); Adafruit_L3GD20_Unified gyro2 = Adafruit_L3GD20_Unified(2); Adafruit_L3GD20_Unified gyro3 = Adafruit_L3GD20_Unified(3); Adafruit_L3GD20_Unified gyro4 = Adafruit_L3GD20_Unified(4); const int flex1 = A0; const int flex2 = A1; const int flex3 = A2; const int flex4 = A3; const int flex5 = A4; const int flex6 = A5; const int flex7 = A6; const int flex8 = A7; const int flex9 = A8; const int flex10 = A9; const int flex11 = A10; const int flex12 = A11; const int flex13 = A12; const int buttonPin = 2; // the number of the pushbutton pin int sensorValue1 = 0; // the sensor value int sensorMin1 = 1023; // minimum sensor value int sensorMax1 = 0; // maximum sensor value int sensorValue2 = 0; int sensorMin2 = 1023; int sensorMax2 = 0; int sensorValue3 = 0; int sensorMin3 = 1023; int sensorMax3 = 0; int sensorValue4 = 0; int sensorMin4 = 1023; int sensorMax4 = 0; int sensorValue5 = 0; // the sensor value int sensorMin5 = 1023; // minimum sensor value int sensorMax5 = 0; // maximum sensor value int sensorValue6 = 0; int sensorMin6 = 1023; int sensorMax6 = 0; int sensorValue7 = 0; int sensorMin7 = 1023; int sensorMax7 = 0; int sensorValue8 = 0; int sensorMin8 = 1023; int sensorMax8 = 0; int sensorValue9 = 0; int sensorMin9 = 1023; int sensorMax9 = 0; int sensorValue10 = 0; int sensorMin10 = 1023; int sensorMax10 = 0; int sensorValue11 = 0; int sensorMin11 = 1023; int sensorMax11 = 0; int sensorValue12 = 0; int sensorMin12 = 1023; int sensorMax12 = 0; int sensorValue13 = 0; int sensorMin13 = 1023; int sensorMax13 = 0; const int numReadings = 4; int readIndex = 0; // the index of the current reading int readings1[numReadings]; // the readings from the analog input int total1 = 0; // the running total int average1 = 0; // the average int readings2[numReadings]; int total2 = 0; int average2 = 0; int readings3[numReadings]; int total3 = 0; int average3 = 0; int readings4[numReadings]; int total4 = 0; int average4 = 0; int readings5[numReadings]; int total5 = 0; int average5 = 0; int readings6[numReadings]; int total6 = 0; int average6 = 0; int readings7[numReadings]; int total7 = 0; int average7 = 0; int readings8[numReadings]; int total8 = 0; int average8 = 0; int readings9[numReadings]; int total9 = 0; int average9 = 0; int readings10[numReadings]; int total10 = 0; int average10 = 0; int readings11[numReadings]; int total11 = 0; int average11 = 0; int readings12[numReadings]; int total12 = 0; int average12 = 0; int readings13[numReadings]; int total13 = 0; int average13 = 0; int i = 0; float yawValue1 = 0; float yawMin1 = 360; float yawMax1 = -360; int pitchValue1 = 0; int pitchMin1 = -360; int pitchMax1 = 360; int rollValue1 = 0; int rollMin1 = 360; int rollMax1 = -360; int buttonState = 0; float prevYaw; float baseYaw; float roll1; float pitch1; float heading1; float prevHeading1; float prevPitch1; float prevRoll1; float ogHeading1; float ogPitch1; float ogRoll1; float deltaH1; float deltaP1; float deltaR1; int prevAccelx1 = 0; int prevMagx1 = 0; int prevAccely1 = 0; int prevMagy1 = 0; int prevAccelz1 = 0; int prevMagz1 = 0; float roll2; float pitch2; float heading2; float prevHeading2; float prevPitch2; float prevRoll2; float ogHeading2; float ogPitch2; float ogRoll2; float deltaH2; float deltaP2; float deltaR2; int prevAccelx2 = 0; int prevMagx2 = 0; int prevAccely2 = 0; int prevMagy2 = 0; int prevAccelz2 = 0; int prevMagz2 = 0; float roll3; float pitch3; float heading3; float prevHeading3; float prevPitch3; float prevRoll3; float ogHeading3; float ogPitch3; float ogRoll3; float deltaH3; float deltaP3; float deltaR3; int prevAccelx3 = 0; int prevMagx3 = 0; int prevAccely3 = 0; int prevMagy3 = 0; int prevAccelz3 = 0; int prevMagz3 = 0; float roll4; float pitch4; float heading4; float prevHeading4; float prevPitch4; float prevRoll4; float ogHeading4; float ogPitch4; float ogRoll4; float deltaH4; float deltaP4; float deltaR4; int prevAccelx4 = 0; int prevMagx4 = 0; int prevAccely4 = 0; int prevMagy4 = 0; int prevAccelz4 = 0; int prevMagz4 = 0; int index = 0; double totalYaw= 0; double deltaYaw = 0; boolean lastState = false; boolean buttonActive = false; boolean longPressActive = false; long buttonTimer = 0; long longPressTime1 = 250; long longPressTime2 = 700; float actualHeading=0; //const int numReadings = 50; float yawCal[numReadings]; const int pot1 = A0; const int pot2 = A1; float mag_offsets[3] = { 6.77F, -7.75F,36.94F }; float mag_softiron_matrix[3][3] = { { 0.977, 0.013, 0.002 }, { 0.314, 0.999, 0.004 }, { 0.002, 0.004, 1.025 } }; float mag_field_strength = 25.08F; Madgwick filter1; Madgwick filter2; Madgwick filter3; Madgwick filter4; void tcaselect(uint8_t i) { if (i > 7) return; Wire.beginTransmission(TCAADDR); Wire.write(1 << i); Wire.endTransmission(); } void setup(void) { Serial.begin(250000); Serial.println("I2C Test"); Serial.println(""); pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT); pinMode(flex1, INPUT); pinMode(flex2, INPUT); pinMode(flex3, INPUT); pinMode(flex4, INPUT); pinMode(flex5, INPUT); pinMode(flex6, INPUT); pinMode(flex7, INPUT); pinMode(flex8, INPUT); pinMode(flex9, INPUT); pinMode(flex10, INPUT); pinMode(41,OUTPUT); digitalWrite(41, HIGH); pinMode(42,OUTPUT); digitalWrite(42, HIGH); pinMode(43,OUTPUT); digitalWrite(43, HIGH); pinMode(44,OUTPUT); digitalWrite(44, HIGH); pinMode(45,OUTPUT); digitalWrite(45, HIGH); pinMode(46,OUTPUT); digitalWrite(46, HIGH); pinMode(47,OUTPUT); digitalWrite(47, HIGH); pinMode(48,OUTPUT); digitalWrite(48, HIGH); pinMode(49,OUTPUT); digitalWrite(49, HIGH); pinMode(50,OUTPUT); digitalWrite(50, HIGH); pinMode(51,OUTPUT); digitalWrite(51, HIGH); pinMode(52,OUTPUT); digitalWrite(52, HIGH); pinMode(53,OUTPUT); digitalWrite(53, HIGH); for (int i = 0; i < numReadings; i++) { readings1[i] = 0; readings2[i] = 0; readings3[i] = 0; readings4[i] = 0; readings5[i] = 0; readings6[i] = 0; readings7[i] = 0; readings8[i] = 0; readings9[i] = 0; readings10[i] = 0; readings11[i] = 0; readings12[i] = 0; readings13[i] = 0; } /* Initialise the 1st sensor */ tcaselect(1); if(!mag1.begin()) { //There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no mag1 detected ... Check your wiring!"); // while(1); } if(!accel1.begin()) { //There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no accel1 detected ... Check your wiring!"); // while(1); } Serial.println("oo"); if(!gyro1.begin()) { //There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no gyro1 detected ... Check your wiring!"); //while(1); } // Initialise the 2nd sensor tcaselect(5); if(!mag2.begin()) { // There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no mag2 detected ... Check your wiring!"); //while(1); } //Serial.println("oo2"); if(!gyro2.begin()) { //There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no gyro2 detected ... Check your wiring!"); //while(1); } //Serial.println("oo3"); if(!accel2.begin()) { //There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no accel2 detected ... Check your wiring!"); //while(1); } tcaselect(3); if(!mag3.begin()) { // There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no mag2 detected ... Check your wiring!"); //while(1); } //Serial.println("oo2"); if(!gyro3.begin()) { //There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no gyro2 detected ... Check your wiring!"); //while(1); } //Serial.println("oo3"); if(!accel3.begin()) { //There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no accel2 detected ... Check your wiring!"); //while(1); } tcaselect(6); if(!mag4.begin()) { // There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no mag2 detected ... Check your wiring!"); //while(1); } //Serial.println("oo2"); if(!gyro4.begin()) { //There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no gyro2 detected ... Check your wiring!"); //while(1); } //Serial.println("oo3"); if(!accel4.begin()) { //There was a problem detecting the HMC5883 ... check your connections //Serial.println("Ooops, no accel2 detected ... Check your wiring!"); //while(1); } filter1.begin(40); filter2.begin(40); filter3.begin(40); filter4.begin(40); filterFunction1(); ogHeading1 = filter1.getYaw(); heading1 = filter1.getYaw(); filterFunction2(); ogHeading2 = filter2.getYaw(); heading2 = filter2.getYaw(); filterFunction3(); ogHeading3 = filter3.getYaw(); heading3 = filter3.getYaw(); filterFunction4(); ogHeading4 = filter4.getYaw(); heading4 = filter4.getYaw(); while(millis()<5000){ sensorValue1 = analogRead(flex1); if (sensorValue1 > sensorMax1) { sensorMax1 = sensorValue1;} if (sensorValue1 < sensorMin1) { sensorMin1 = sensorValue1;} sensorValue2 = analogRead(flex2); if (sensorValue2 > sensorMax2) { sensorMax2 = sensorValue2;} if (sensorValue2 < sensorMin2) { sensorMin2 = sensorValue2;} sensorValue3 = analogRead(flex3); if (sensorValue3 > sensorMax3) { sensorMax3 = sensorValue3;} if (sensorValue3 < sensorMin3) { sensorMin3 = sensorValue3;} sensorValue4 = analogRead(flex4); if (sensorValue4 > sensorMax4) { sensorMax4 = sensorValue4;} if (sensorValue4 < sensorMin4) { sensorMin4 = sensorValue4;} sensorValue5 = analogRead(flex5); if (sensorValue5 > sensorMax5) { sensorMax5 = sensorValue5;} if (sensorValue5 < sensorMin5) { sensorMin5 = sensorValue5;} sensorValue6 = analogRead(flex6); if (sensorValue6 > sensorMax6) { sensorMax6 = sensorValue6;} if (sensorValue6 < sensorMin6) { sensorMin6 = sensorValue6;} sensorValue7 = analogRead(flex7); if (sensorValue7 > sensorMax7) { sensorMax7 = sensorValue7;} if (sensorValue7 < sensorMin7) { sensorMin7 = sensorValue7;} sensorValue8 = analogRead(flex8); if (sensorValue8 > sensorMax8) { sensorMax8 = sensorValue8;} if (sensorValue8 < sensorMin8) { sensorMin8 = sensorValue8;} sensorValue9 = analogRead(flex9); if (sensorValue9 > sensorMax9) { sensorMax9 = sensorValue9;} if (sensorValue9 < sensorMin9) { sensorMin9 = sensorValue9;} sensorValue10 = analogRead(flex10); if (sensorValue10 > sensorMax10) { sensorMax10 = sensorValue10;} if (sensorValue10 < sensorMin10) { sensorMin10 = sensorValue10;} sensorValue11 = analogRead(flex11); if (sensorValue11 > sensorMax11) { sensorMax11 = sensorValue11;} if (sensorValue11 < sensorMin11) { sensorMin11 = sensorValue11;} sensorValue12 = analogRead(flex12); if (sensorValue12 > sensorMax12) { sensorMax12 = sensorValue12;} if (sensorValue12 < sensorMin12) { sensorMin12 = sensorValue12;} sensorValue13 = analogRead(flex13); if (sensorValue13 > sensorMax13) { sensorMax13 = sensorValue13;} if (sensorValue13 < sensorMin13) { sensorMin13 = sensorValue13;} filterFunction1(); yawValue1= actualHeading; if (yawValue1 > yawMax1) { yawMax1 = yawValue1;} if (yawValue1 < yawMin1) { yawMin1 = yawValue1;} Serial.print(yawMax1); Serial.print(" "); Serial.println(actualHeading); pitchValue1= pitch1; if (pitchValue1 > pitchMax1) { pitchMax1 = pitchValue1;} if (pitchValue1 < pitchMin1) { pitchMin1 = pitchValue1;} rollValue1= roll1; if (rollValue1 > rollMax1) { rollMax1 = rollValue1;} if (rollValue1 < rollMin1) { rollMin1 = rollValue1;} } ogHeading1 = 0; ogPitch1 = 0; ogRoll1 = 0; ogHeading2 = 0; ogPitch2 = 0; ogRoll2 = 0; ogHeading3 = 0; ogPitch3 = 0; ogRoll3 = 0; ogHeading4 = 0; ogPitch4 = 0; ogRoll4 = 0; Serial.println(" "); Serial.print(yawMin1); Serial.print(" "); Serial.println(yawMax1); } void loop(void) { filterFunction1(); //Serial.print(micros()); Serial.print(heading1); Serial.print(" "); Serial.print(pitch1); Serial.print(" "); Serial.print(roll1); Serial.print(" "); filterFunction2(); filterFunction3(); flexFunction(); filterFunction4(); buttonState = digitalRead(buttonPin); if (buttonState == HIGH) { if (buttonActive == false) { buttonActive = true; buttonTimer = millis(); } if ((millis() - buttonTimer > longPressTime1) && (longPressActive == false)) { longPressActive = true; ogHeading1 = 0; ogPitch1 = 0; ogRoll1=0; ogHeading4 = 0; ogPitch4 = 0; ogRoll4 =0; //Serial.println("working"); } } else { if (buttonActive == true) { if (longPressActive == true) { longPressActive = false; } buttonActive = false; } } i++; serialFlush(); delay(20); } void filterFunction1(){ sensors_event_t gyro_event; sensors_event_t mag_event; sensors_event_t accel_event; tcaselect(1); mag1.getEvent(&mag_event); accel1.getEvent(&accel_event); gyro1.getEvent(&gyro_event); float x = mag_event.magnetic.x - mag_offsets[0]; float y = mag_event.magnetic.y - mag_offsets[1]; float z = mag_event.magnetic.z - mag_offsets[2]; float mx = x * mag_softiron_matrix[0][0] + y * mag_softiron_matrix[0][1] + z * mag_softiron_matrix[0][2]; float my = x * mag_softiron_matrix[1][0] + y * mag_softiron_matrix[1][1] + z * mag_softiron_matrix[1][2]; float mz = x * mag_softiron_matrix[2][0] + y * mag_softiron_matrix[2][1] + z * mag_softiron_matrix[2][2]; float gx = gyro_event.gyro.x * 57.2958F; float gy = gyro_event.gyro.y * 57.2958F; float gz = gyro_event.gyro.z * 57.2958F; filter1.update(gx, gy, gz, accel_event.acceleration.x, accel_event.acceleration.y, accel_event.acceleration.z, mx, my, mz); roll1 = filter1.getRoll(); //if(roll<0){roll*=-2;} pitch1 = filter1.getPitch(); //if(pitch<0){pitch*=-2;} heading1 = filter1.getYaw(); if(abs(accel1.raw.z-prevAccelz1)<20 && abs(mag1.raw.z-prevMagz1)<30){ heading1 = ogHeading1; } else{ deltaH1 = heading1-prevHeading1; ogHeading1 = ogHeading1 + 2*deltaH1; heading1 = ogHeading1; } if(abs(accel1.raw.x-prevAccelx1)<20 && abs(mag1.raw.x-prevMagx1)<10){ pitch1 = ogPitch1; } else{ deltaP1 = pitch1-prevPitch1; ogPitch1 = ogPitch1 + 2*deltaP1; pitch1 = ogPitch1; } if(abs(accel1.raw.y-prevAccely1)<20 && abs(mag1.raw.y-prevMagy1)<10){ roll1 = ogRoll1; //Serial.print("true"); } else{ deltaR1 = roll1-prevRoll1; ogRoll1 = ogRoll1 + 2*deltaR1; roll1 = ogRoll1; } //Serial.print(" "); Serial.print(accel1.raw.y); Serial.print(" "); prevHeading1 = filter1.getYaw(); prevPitch1 = filter1.getPitch(); prevRoll1 = filter1.getRoll(); //Serial.println(mag.raw.z-prevMag); prevAccelz1 = accel1.raw.z; prevMagz1 = mag1.raw.z; prevAccelx1 = accel1.raw.x; prevMagx1 = mag1.raw.x; prevAccely1 = accel1.raw.y; prevMagy1 = mag1.raw.y; actualHeading= heading1; } void filterFunction2(){ sensors_event_t gyro_event; sensors_event_t mag_event; sensors_event_t accel_event; tcaselect(5); gyro2.getEvent(&gyro_event); mag2.getEvent(&mag_event); accel2.getEvent(&accel_event); float x = mag_event.magnetic.x - mag_offsets[0]; float y = mag_event.magnetic.y - mag_offsets[1]; float z = mag_event.magnetic.z - mag_offsets[2]; float mx = x * mag_softiron_matrix[0][0] + y * mag_softiron_matrix[0][1] + z * mag_softiron_matrix[0][2]; float my = x * mag_softiron_matrix[1][0] + y * mag_softiron_matrix[1][1] + z * mag_softiron_matrix[1][2]; float mz = x * mag_softiron_matrix[2][0] + y * mag_softiron_matrix[2][1] + z * mag_softiron_matrix[2][2]; float gx = gyro_event.gyro.x * 57.2958F; float gy = gyro_event.gyro.y * 57.2958F; float gz = gyro_event.gyro.z * 57.2958F; filter2.update(gx, gy, gz, accel_event.acceleration.x, accel_event.acceleration.y, accel_event.acceleration.z, mx, my, mz); roll2 = filter2.getRoll(); //if(roll<0){roll*=-2;} pitch2 = filter2.getPitch(); //if(pitch<0){pitch*=-2;} heading2 = filter2.getYaw(); buttonState = digitalRead(buttonPin); if(buttonState == HIGH){ ogHeading2 = ogHeading1; ogPitch2 = ogPitch1; ogRoll2 = ogRoll1; } if(abs(accel2.raw.z-prevAccelz2)<20 && abs(mag2.raw.z-prevMagz2)<30){ heading2 = ogHeading2; //Serial.println("yea"); } else{ deltaH2 = heading2-prevHeading2; ogHeading2 = ogHeading2 + 2*deltaH2; heading2 = ogHeading2; } if(abs(accel2.raw.x-prevAccelx2)<20 && abs(mag2.raw.x-prevMagx2)<10){ pitch2 = ogPitch2; } else{ deltaP2 = pitch2-prevPitch2; ogPitch2 = ogPitch2 + 2*deltaP2; pitch2 = ogPitch2; } if(abs(accel2.raw.y-prevAccely2)<20 && abs(mag2.raw.y-prevMagy2)<10){ roll2 = ogRoll2; //Serial.print("true"); } else{ deltaR2 = roll2-prevRoll2; ogRoll2 = ogRoll2 + 2*deltaR2; roll2 = ogRoll2; } //Serial.print(" "); Serial.print(accel1.raw.y); Serial.print(" "); prevHeading2 = filter2.getYaw(); prevPitch2 = filter2.getPitch(); prevRoll2 = filter2.getRoll(); prevAccelz2 = accel2.raw.z; prevMagz2 = mag2.raw.z; prevAccelx2 = accel2.raw.x; prevMagx2 = mag2.raw.x; prevAccely2 = accel2.raw.y; prevMagy2 = mag2.raw.y; Serial.print(heading2); Serial.print(" "); Serial.print(pitch2); Serial.print(" "); Serial.print(roll2); Serial.print(" "); } void filterFunction3(){ sensors_event_t gyro_event; sensors_event_t mag_event; sensors_event_t accel_event; tcaselect(3); gyro3.getEvent(&gyro_event); mag3.getEvent(&mag_event); accel3.getEvent(&accel_event); float x = mag_event.magnetic.x - mag_offsets[0]; float y = mag_event.magnetic.y - mag_offsets[1]; float z = mag_event.magnetic.z - mag_offsets[2]; float mx = x * mag_softiron_matrix[0][0] + y * mag_softiron_matrix[0][1] + z * mag_softiron_matrix[0][2]; float my = x * mag_softiron_matrix[1][0] + y * mag_softiron_matrix[1][1] + z * mag_softiron_matrix[1][2]; float mz = x * mag_softiron_matrix[2][0] + y * mag_softiron_matrix[2][1] + z * mag_softiron_matrix[2][2]; float gx = gyro_event.gyro.x * 57.2958F; float gy = gyro_event.gyro.y * 57.2958F; float gz = gyro_event.gyro.z * 57.2958F; filter3.update(gx, gy, gz, accel_event.acceleration.x, accel_event.acceleration.y, accel_event.acceleration.z, mx, my, mz); roll3 = filter3.getRoll(); //if(roll<0){roll*=-2;} pitch3 = filter3.getPitch(); //if(pitch<0){pitch*=-2;} heading3 = filter3.getYaw(); buttonState = digitalRead(buttonPin); if(buttonState == HIGH){ ogHeading3 = ogHeading1; ogPitch3 = ogPitch1; ogRoll3 = ogRoll1; //Serial.println("button Pressed"); } if(abs(accel3.raw.z-prevAccelz3)<20 && abs(mag3.raw.z-prevMagz3)<30){ heading3 = ogHeading3; //Serial.println("yea"); } else{ deltaH3 = heading3-prevHeading3; ogHeading3 = ogHeading3 + 2*deltaH3; heading3 = ogHeading3; } if(abs(accel3.raw.x-prevAccelx3)<20 && abs(mag3.raw.x-prevMagx3)<10){ pitch3 = ogPitch3; } else{ deltaP3 = pitch3-prevPitch3; ogPitch3 = ogPitch3 + 2*deltaP3; pitch3 = ogPitch3; } if(abs(accel3.raw.y-prevAccely3)<20 && abs(mag3.raw.y-prevMagy3)<10){ roll3 = ogRoll3; //Serial.print("true"); } else{ deltaR3 = roll3-prevRoll3; ogRoll3 = ogRoll3 + 2*deltaR3; roll3 = ogRoll3; } //Serial.print(" "); Serial.print(accel1.raw.y); Serial.print(" "); prevHeading3 = filter3.getYaw(); prevPitch3 = filter3.getPitch(); prevRoll3 = filter3.getRoll(); prevAccelz3 = accel3.raw.z; prevMagz3 = mag3.raw.z; prevAccelx3 = accel3.raw.x; prevMagx3 = mag3.raw.x; prevAccely3 = accel3.raw.y; prevMagy3 = mag3.raw.y; Serial.print(heading3); Serial.print(" "); Serial.print(pitch3); Serial.print(" "); Serial.print(roll3); Serial.print(" "); } void filterFunction4(){ sensors_event_t gyro_event; sensors_event_t mag_event; sensors_event_t accel_event; tcaselect(6); gyro4.getEvent(&gyro_event); mag4.getEvent(&mag_event); accel4.getEvent(&accel_event); float x = mag_event.magnetic.x - mag_offsets[0]; float y = mag_event.magnetic.y - mag_offsets[1]; float z = mag_event.magnetic.z - mag_offsets[2]; float mx = x * mag_softiron_matrix[0][0] + y * mag_softiron_matrix[0][1] + z * mag_softiron_matrix[0][2]; float my = x * mag_softiron_matrix[1][0] + y * mag_softiron_matrix[1][1] + z * mag_softiron_matrix[1][2]; float mz = x * mag_softiron_matrix[2][0] + y * mag_softiron_matrix[2][1] + z * mag_softiron_matrix[2][2]; float gx = gyro_event.gyro.x * 57.2958F; float gy = gyro_event.gyro.y * 57.2958F; float gz = gyro_event.gyro.z * 57.2958F; filter4.update(gx, gy, gz, accel_event.acceleration.x, accel_event.acceleration.y, accel_event.acceleration.z, mx, my, mz); roll4 = filter4.getRoll(); //if(roll<0){roll*=-2;} pitch4 = filter4.getPitch(); //if(pitch<0){pitch*=-2;} heading4 = filter4.getYaw(); if(abs(accel4.raw.z-prevAccelz4)<20 && abs(mag4.raw.z-prevMagz4)<30){ heading4 = ogHeading4; //Serial.println("yea"); } else{ deltaH4 = heading4-prevHeading4; ogHeading4 = ogHeading4 + 2*deltaH4; heading4 = ogHeading4; } if(abs(accel4.raw.x-prevAccelx4)<20 && abs(mag4.raw.x-prevMagx4)<10){ pitch4 = ogPitch4; } else{ deltaP4 = pitch4-prevPitch4; ogPitch4 = ogPitch4 + 2*deltaP4; pitch4 = ogPitch4; } if(abs(accel4.raw.y-prevAccely4)<20 && abs(mag4.raw.y-prevMagy4)<10){ roll4 = ogRoll4; //Serial.print("true"); } else{ deltaR4 = roll4-prevRoll4; ogRoll4 = ogRoll4 + 2*deltaR4; roll4 = ogRoll4; } //Serial.print(" "); Serial.print(accel1.raw.y); Serial.print(" "); prevHeading4 = filter4.getYaw(); prevPitch4 = filter4.getPitch(); prevRoll4 = filter4.getRoll(); prevAccelz4 = accel4.raw.z; prevMagz4 = mag4.raw.z; prevAccelx4 = accel4.raw.x; prevMagx4 = mag4.raw.x; prevAccely4 = accel4.raw.y; prevMagy4 = mag4.raw.y; Serial.print(heading4); Serial.print(" "); Serial.print(pitch4); Serial.print(" "); Serial.print(roll4); Serial.println(" "); } void flexFunction(){ sensorValue1 = analogRead(flex1); sensorValue1 = map(sensorValue1, sensorMin1, sensorMax1, 0, 90); //sensorValue1 = constrain(sensorValue1, 0, 255); sensorValue1 = -(sensorValue1-90); sensorValue2 = analogRead(flex2); sensorValue2 = map(sensorValue2, sensorMin2, sensorMax2, 0, 90); //sensorValue2 = constrain(sensorValue2, 0, 255); sensorValue2 = -(sensorValue2-90); sensorValue3 = analogRead(flex3); sensorValue3 = map(sensorValue3, sensorMin3, sensorMax3, 0, 90); //sensorValue3 = constrain(sensorValue3, 0, 255); sensorValue3 = -(sensorValue3-90); sensorValue4 = analogRead(flex4); sensorValue4 = map(sensorValue4, sensorMin4, sensorMax4, 0, 90); //sensorValue4 = constrain(sensorValue4, 0, 255); sensorValue4 = -(sensorValue4-90); sensorValue5 = analogRead(flex5); sensorValue5 = map(sensorValue5, sensorMin5, sensorMax5, 0, 110); // sensorValue1 = constrain(sensorValue1, 0, 255); sensorValue5 = -(sensorValue5-110); sensorValue6 = analogRead(flex6); sensorValue6 = map(sensorValue6, sensorMin6, sensorMax6, 0, 110); //sensorValue2 = constrain(sensorValue2, 0, 255); sensorValue6 = -(sensorValue6-110); sensorValue7 = analogRead(flex7); sensorValue7 = map(sensorValue7, sensorMin7, sensorMax7, 0, 110); //sensorValue3 = constrain(sensorValue3, 0, 255); sensorValue7 = -(sensorValue7-110); sensorValue8 = analogRead(flex8); sensorValue8 = map(sensorValue8, sensorMin8, sensorMax8, 0, 110); //sensorValue4 = constrain(sensorValue4, 0, 255); sensorValue8 = -(sensorValue8-110); //sensor 9 is not used sensorValue9 = analogRead(flex9); sensorValue9 = map(sensorValue9, sensorMin9, sensorMax9, 0, 90); //sensorValue4 = constrain(sensorValue4, 0, 255); //sensorValue9 = -(sensorValue9-60); sensorValue10 = analogRead(flex10); sensorValue10 = map(sensorValue10, sensorMin10, sensorMax10, 0, 90); //sensorValue4 = constrain(sensorValue4, 0, 255); sensorValue10 = -(sensorValue10-90); sensorValue11 = analogRead(flex11); sensorValue11 = map(sensorValue11, sensorMin11, sensorMax11, 0, 90); //sensorValue4 = constrain(sensorValue4, 0, 255); sensorValue11 = -(sensorValue11-90); sensorValue11 = sensorValue11-sensorValue5/4; //sensorValue11 = map(sensorValue11, -110, 90, 0, 80); sensorValue12 = analogRead(flex12); sensorValue12 = map(sensorValue12, sensorMin12, sensorMax12, 0, 90); //sensorValue4 = constrain(sensorValue4, 0, 255); //sensorValue12 = -(sensorValue12-90); sensorValue12 = sensorValue12-sensorValue6/4; //sensorValue12 = map(sensorValue12, -110, 90, 0, 80); sensorValue13 = analogRead(flex13); sensorValue13 = map(sensorValue13, sensorMin13, sensorMax13, 0, 90); //sensorValue4 = constrain(sensorValue4, 0, 255); sensorValue13 = -(sensorValue13-90); sensorValue13 = sensorValue13-sensorValue7/4; //sensorValue13 = map(sensorValue13, -110, 90, 0, 80); total1 = total1 - readings1[readIndex]; readings1[readIndex] = sensorValue1; total1 = total1 + readings1[readIndex]; average1 = total1 / numReadings; total2 = total2 - readings2[readIndex]; readings2[readIndex] = sensorValue2; total2 = total2 + readings2[readIndex]; average2 = total2 / numReadings; total3 = total3 - readings3[readIndex]; readings3[readIndex] = sensorValue3; total3 = total3 + readings3[readIndex]; average3 = total3 / numReadings; total4 = total4 - readings4[readIndex]; readings4[readIndex] = sensorValue4; total4 = total4 + readings4[readIndex]; average4 = total4 / numReadings; total5 = total5 - readings5[readIndex]; readings5[readIndex] = sensorValue5; total5 = total5 + readings5[readIndex]; average5 = total5 / numReadings; total6 = total6 - readings6[readIndex]; readings6[readIndex] = sensorValue6; total6 = total6 + readings6[readIndex]; average6 = total6 / numReadings; total7 = total7 - readings7[readIndex]; readings7[readIndex] = sensorValue7; total7 = total7 + readings7[readIndex]; average7 = total7 / numReadings; total8 = total8 - readings8[readIndex]; readings8[readIndex] = sensorValue8; total8 = total8 + readings8[readIndex]; average8 = total8 / numReadings; total9 = total9 - readings9[readIndex]; readings9[readIndex] = sensorValue9; total9 = total9 + readings9[readIndex]; average9 = total9 / numReadings; total10 = total10 - readings10[readIndex]; readings10[readIndex] = sensorValue10; total10 = total10 + readings10[readIndex]; average10 = total10 / numReadings; total11 = total11 - readings11[readIndex]; readings11[readIndex] = sensorValue11; total11 = total11 + readings11[readIndex]; average11 = total11 / numReadings; total12 = total12 - readings12[readIndex]; readings12[readIndex] = sensorValue12; total12 = total12 + readings12[readIndex]; average12 = total12 / numReadings; total13 = total13 - readings13[readIndex]; readings13[readIndex] = sensorValue13; total13 = total13 + readings13[readIndex]; average13 = total13 / numReadings; readIndex++; if (readIndex >= numReadings) { readIndex = 0; } Serial.print(average1); Serial.print(" "); Serial.print(average2); Serial.print(" "); Serial.print(average3); Serial.print(" "); Serial.print(average4); Serial.print(" "); Serial.print(sensorValue5); Serial.print(" "); Serial.print(sensorValue6); Serial.print(" "); Serial.print(sensorValue7); Serial.print(" "); Serial.print(sensorValue8); Serial.print(" "); Serial.print(sensorValue9); Serial.print(" "); Serial.print(sensorValue10); Serial.print(" "); Serial.print(sensorValue11); Serial.print(" "); Serial.print(sensorValue12); Serial.print(" "); Serial.print(sensorValue13); Serial.print(" "); } void serialFlush(){ byte w = 0; for (int i = 0; i < 10; i++) { if (Serial.available()) { char val=""; while(Serial.available()) { char t= Serial.read(); val=val+t; } Serial.println(val); Serial.end(); // Ends the serial communication once all data is received Serial.begin(250000);\ } } Serial.flush(); }
9279301fed8a103aa8ab454a19b332140acdcb44
883887c3c84bd3ac4a11ac76414129137a1b643b
/Cscl3DWS/rmml/XML/mlRMMLXMLElement.cpp
47fa83f585db7772015378b69d8d00ca5eee2927
[]
no_license
15831944/vAcademia
4dbb36d9d772041e2716506602a602d516e77c1f
447f9a93defb493ab3b6f6c83cbceb623a770c5c
refs/heads/master
2022-03-01T05:28:24.639195
2016-08-18T12:32:22
2016-08-18T12:32:22
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
11,265
cpp
mlRMMLXMLElement.cpp
#include "mlRMML.h" namespace rmml { mlXMLElement::mlXMLElement(void) { nodeType=ELEMENT_NODE; } mlXMLElement::~mlXMLElement(void){ } /*************************** * реализация mlXMLElement */ /* interface Element : Node { readonly attribute DOMString tagName; DOMString getAttribute(in DOMString name); void setAttribute(in DOMString name, in DOMString value) raises(DOMException); void removeAttribute(in DOMString name) raises(DOMException); Attr getAttributeNode(in DOMString name); Attr setAttributeNode(in Attr newAttr) raises(DOMException); Attr removeAttributeNode(in Attr oldAttr) raises(DOMException); NodeList getElementsByTagName(in DOMString name); void normalize(); Element findElement(String tagName, String attrName, String attrValue) }; normalize() - если есть несколько идущих подряд текстовых child'ов, то объединяет их в один */ ///// JavaScript Variable Table JSPropertySpec mlXMLElement::_JSPropertySpec[] = { JSPROP_RO(tagName) { 0, 0, 0, 0, 0 } }; ///// JavaScript Function Table JSFunctionSpec mlXMLElement::_JSFunctionSpec[] = { JSFUNC(getAttribute,1) JSFUNC(setAttribute,2) JSFUNC(removeAttribute,1) JSFUNC(getAttributeNode,1) JSFUNC(setAttributeNode,1) JSFUNC(removeAttributeNode,1) JSFUNC(getElementsByTagName,1) // JSFUNC(normalize,0) JSFUNC(findElement,3) { 0, 0, 0, 0, 0 } }; MLJSCLASS_IMPL_BEGIN(XMLElement,mlXMLElement,2) MLJSCLASS_ADDPROTO(mlIXMLNode) MLJSCLASS_ADDPROPFUNC MLJSCLASS_IMPL_END(mlXMLElement) ///// JavaScript Set Property Wrapper JSBool mlXMLElement::JSSetProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp) { SET_PROPS_BEGIN(mlXMLElement); SET_PROTO_PROP(mlIXMLNode); default:; SET_PROPS_END; return JS_TRUE; } ///// JavaScript Get Property Wrapper JSBool mlXMLElement::JSGetProperty(JSContext *cx, JSObject *obj, jsval id, jsval *vp) { GET_PROPS_BEGIN(mlXMLElement); GET_PROTO_PROP(mlIXMLNode); default: switch(iID){ case JSPROP_tagName: *vp=STRING_TO_JSVAL(priv->nodeName); break; } GET_PROPS_END; return JS_TRUE; } JSBool mlXMLElement::JSFUNC_getAttribute(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { *rval = JSVAL_NULL; if (argc != 1 || (!JSVAL_IS_STRING(argv[0]))){ JS_ReportError(cx, "getAttribute method must get a string argument"); return JS_TRUE; } mlXMLElement* pXMLElem=(mlXMLElement*)JS_GetPrivate(cx, obj); JSString* jssName=JSVAL_TO_STRING(argv[0]); JSString* jssAttrValue=pXMLElem->getAttribute(jssName); if(jssAttrValue==NULL) *rval=JS_GetEmptyStringValue(cx); else *rval=STRING_TO_JSVAL(jssAttrValue); return JS_TRUE; } JSString* mlXMLElement::getAttribute(JSString* ajssName){ JSObject* jsoXMLAttr=getAttributeNode(ajssName); if(jsoXMLAttr==NULL) return NULL; mlXMLAttr* pXMLAttr=(mlXMLAttr*)JS_GetPrivate(mcx,jsoXMLAttr); ML_ASSERTION(mcx, pXMLAttr!=NULL,"mlXMLElement::getAttribute"); return pXMLAttr->nodeValue; } JSString* mlXMLElement::getID(){ mlXMLNamedNodeMap* pAttributes=GetAttributes(); if(pAttributes==NULL) return NULL; return pAttributes->getID(); } JSBool mlXMLElement::JSFUNC_setAttribute(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { *rval = JSVAL_FALSE; if (argc != 2 || (!JSVAL_IS_STRING(argv[0])) || (!JSVAL_IS_STRING(argv[1]))){ JS_ReportError(cx, "setAttribute method must get two string arguments"); return JS_TRUE; } mlXMLElement* pXMLElem=(mlXMLElement*)JS_GetPrivate(cx, obj); JSString* jssName=JSVAL_TO_STRING(argv[0]); JSString* jssValue=JSVAL_TO_STRING(argv[1]); pXMLElem->setAttribute(jssName,jssValue); *rval = JSVAL_TRUE; return JS_TRUE; } void mlXMLElement::setAttribute(JSString* ajssName, JSString* ajssValue){ JSObject* jsoXMLAttr=getAttributeNode(ajssName); if(jsoXMLAttr==NULL) return; mlXMLAttr* pXMLAttr=(mlXMLAttr*)JS_GetPrivate(mcx,jsoXMLAttr); ML_ASSERTION(mcx, pXMLAttr!=NULL,"mlXMLElement::getAttribute"); // если это ID, // то удалить его из mapID2XMLEl // UpdateIDMap(,NULL); // ?? // и вставить с новым ID-ом // ?? pXMLAttr->SetValue(ajssValue); } JSBool mlXMLElement::JSFUNC_removeAttribute(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { *rval = JSVAL_NULL; if (argc != 1 || (!JSVAL_IS_STRING(argv[0]))){ JS_ReportError(cx, "removeAttribute method must get a string argument"); return JS_TRUE; } mlXMLElement* pXMLElem=(mlXMLElement*)JS_GetPrivate(cx, obj); JSString* jssName=JSVAL_TO_STRING(argv[0]); pXMLElem->removeAttribute(jssName); return JS_TRUE; } void mlXMLElement::removeAttribute(JSString* ajssName){ mlXMLNamedNodeMap* pAttributes=GetAttributes(); if(pAttributes==NULL) return; pAttributes->removeNamedItem(ajssName); } JSBool mlXMLElement::JSFUNC_getAttributeNode(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { *rval = JSVAL_NULL; if (argc != 1 || (!JSVAL_IS_STRING(argv[0]))){ JS_ReportError(cx, "getAttributeNode method must get a string argument"); return JS_TRUE; } mlXMLElement* pXMLElem=(mlXMLElement*)JS_GetPrivate(cx, obj); JSString* jssName=JSVAL_TO_STRING(argv[0]); JSObject* jsoXMLAttr=pXMLElem->getAttributeNode(jssName); if(jsoXMLAttr==NULL) return JS_TRUE; *rval=OBJECT_TO_JSVAL(jsoXMLAttr); return JS_TRUE; } JSObject* mlXMLElement::getAttributeNode(JSString* ajssName){ if(ajssName==NULL) return NULL; mlXMLNamedNodeMap* pAttributes=GetAttributes(); if(pAttributes==NULL) return NULL; return pAttributes->getNamedItem(ajssName); } JSBool mlXMLElement::JSFUNC_setAttributeNode(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { *rval = JSVAL_FALSE; if (argc != 1 || (!JSVAL_IS_REAL_OBJECT(argv[0]))){ JS_ReportError(cx, "setAttributeNode method must get a XML attribute object"); return JS_TRUE; } JSObject* jsoXMLAttr=JSVAL_TO_OBJECT(argv[0]); if(!mlXMLAttr::IsInstance(cx, jsoXMLAttr)){ JS_ReportError(cx, "setAttributeNode method must get a XML attribute object"); return JS_TRUE; } mlXMLElement* pXMLElem=(mlXMLElement*)JS_GetPrivate(cx, obj); if(pXMLElem->setAttributeNode(jsoXMLAttr)==NULL){ JS_ReportError(cx, "unknown internal error in getAttributeNode method implementation"); return JS_TRUE; } *rval = JSVAL_TRUE; return JS_TRUE; } JSObject* mlXMLElement::setAttributeNode(JSObject* ajsoAttr){ if(!mlXMLAttr::IsInstance(mcx, ajsoAttr)) return NULL; mlXMLNamedNodeMap* pAttributes=GetAttributes(); if(pAttributes==NULL) return NULL; return pAttributes->setNamedItem(ajsoAttr); } JSBool mlXMLElement::JSFUNC_removeAttributeNode(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { *rval = JSVAL_FALSE; if (argc != 1 || (!JSVAL_IS_REAL_OBJECT(argv[0]))){ JS_ReportError(cx, "removeAttributeNode method must get a XML attribute object"); return JS_TRUE; } JSObject* jsoXMLAttr=JSVAL_TO_OBJECT(argv[0]); if(!mlXMLAttr::IsInstance(cx, jsoXMLAttr)){ JS_ReportError(cx, "removeAttributeNode method must get a XML attribute object"); return JS_TRUE; } mlXMLElement* pXMLElem=(mlXMLElement*)JS_GetPrivate(cx, obj); if(pXMLElem->removeAttributeNode(jsoXMLAttr)==NULL){ JS_ReportError(cx, "unknown internal error in removeAttributeNode method implementation"); return JS_TRUE; } *rval = JSVAL_TRUE; return JS_TRUE; } JSObject* mlXMLElement::removeAttributeNode(JSObject* ajsoAttr){ if(!mlXMLAttr::IsInstance(mcx, ajsoAttr)) return NULL; mlXMLNamedNodeMap* pAttributes=GetAttributes(); if(pAttributes==NULL) return NULL; return pAttributes->removeItem(ajsoAttr); } JSBool mlXMLElement::JSFUNC_getElementsByTagName(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { *rval = JSVAL_NULL; if (argc != 1 || (!JSVAL_IS_STRING(argv[0]))){ JS_ReportError(cx, "getElementsByTagName method must get a string argument"); return JS_TRUE; } mlXMLElement* pXMLElem=(mlXMLElement*)JS_GetPrivate(cx, obj); JSString* jssTagName=JSVAL_TO_STRING(argv[0]); JSObject* jsoNodeList=pXMLElem->getElementsByTagName(jssTagName); *rval=OBJECT_TO_JSVAL(jsoNodeList); return JS_TRUE; } JSObject* mlXMLElement::cloneNode(bool abDeep){ JSObject* jsoCloned=mlXMLElement::newJSObject(mcx); mlIXMLNode::CloneNode(jsoCloned); mlXMLElement* pCloned=(mlXMLElement*)JS_GetPrivate(mcx,jsoCloned); // clone attributes if(attributes!=NULL){ int iCount=attributes->mvNodeMap.size(); for(int iIdx=0; iIdx<iCount; iIdx++){ JSObject* jsoAttr=attributes->mvNodeMap[iIdx]; mlXMLAttr* pAttr=(mlXMLAttr*)JS_GetPrivate(mcx,jsoAttr); pCloned->attributes->setNamedItem(pAttr->cloneNode(0)); } } if(abDeep && childNodes!=NULL){ // clone children int iCount=childNodes->mvNodeList.size(); for(int iIdx=0; iIdx<iCount; iIdx++){ JSObject* jsoChild=childNodes->mvNodeList[iIdx]; mlIXMLNode* pChildNode=(mlIXMLNode*)JS_GetPrivate(mcx,jsoChild); pCloned->childNodes->AppendChild(pChildNode->cloneNode(true)); } } return jsoCloned; } JSBool mlXMLElement::JSFUNC_findElement(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval) { *rval=JSVAL_NULL; if (argc < 1 || argc > 3){ JS_ReportError(cx, "findElement method must get one, two or three string arguments"); return JS_TRUE; } if(!JSVAL_IS_STRING(argv[0])){ JS_ReportError(cx, "findElement method must get string arguments"); return JS_TRUE; } mlXMLElement* pXMLElem=(mlXMLElement*)JS_GetPrivate(cx, obj); JSString* jssTagName=JSVAL_TO_STRING(argv[0]); JSString* jssAttrName=NULL; JSString* jssAttrValue=NULL; if(argc >= 2){ if(!JSVAL_IS_STRING(argv[1])){ JS_ReportError(cx, "findElement method must get string arguments"); return JS_TRUE; } jssAttrName=JSVAL_TO_STRING(argv[1]); } if(argc == 3){ if(!JSVAL_IS_STRING(argv[2])){ JS_ReportError(cx, "findElement method must get string arguments"); return JS_TRUE; } jssAttrValue=JSVAL_TO_STRING(argv[2]); } JSObject* jsoElement=pXMLElem->findElement(jssTagName,jssAttrName,jssAttrValue); if(jsoElement!=NULL) *rval=OBJECT_TO_JSVAL(jsoElement); return JS_TRUE; } JSObject* mlXMLElement::findElement(JSString* ajssTagName, JSString* ajssAttrName, JSString* ajssAttrValue){ if(isEqual(nodeName,ajssTagName)){ if(ajssAttrName==NULL) return mjso; JSString* jssVal=getAttribute(ajssAttrName); if(jssVal!=NULL){ if(ajssAttrValue==NULL) return mjso; if(isEqual(jssVal,ajssAttrValue)) return mjso; } } if(childNodes==NULL) return NULL; // ищем среди дочерних элементов 1-го уровня int iCount=childNodes->mvNodeList.size(); for(int iIdx=0; iIdx<iCount; iIdx++){ JSObject* jsoChild=childNodes->mvNodeList[iIdx]; mlIXMLNode* pChildNode=(mlIXMLNode*)JS_GetPrivate(mcx,jsoChild); if(pChildNode->nodeType==ELEMENT_NODE){ mlXMLElement* pElem=(mlXMLElement*)pChildNode; JSObject* jsoFoundElem=pElem->findElement(ajssTagName, ajssAttrName, ajssAttrValue); if(jsoFoundElem!=NULL) return jsoFoundElem; } } return NULL; } }
e60712df773ddfddbbb04a77bc3475ed4f623375
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/components/content_settings/core/browser/cookie_settings.cc
3adbd6441eaf833f95fa2ef42cec24c7fe152e08
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
11,671
cc
cookie_settings.cc
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/content_settings/core/browser/cookie_settings.h" #include "base/check.h" #include "base/feature_list.h" #include "base/functional/bind.h" #include "build/blink_buildflags.h" #include "build/build_config.h" #include "components/content_settings/core/browser/content_settings_utils.h" #include "components/content_settings/core/browser/host_content_settings_map.h" #include "components/content_settings/core/common/content_settings.h" #include "components/content_settings/core/common/content_settings_pattern.h" #include "components/content_settings/core/common/content_settings_types.h" #include "components/content_settings/core/common/content_settings_utils.h" #include "components/content_settings/core/common/cookie_settings_base.h" #include "components/content_settings/core/common/features.h" #include "components/content_settings/core/common/pref_names.h" #include "components/permissions/features.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "extensions/buildflags/buildflags.h" #include "net/cookies/cookie_setting_override.h" #include "net/cookies/cookie_util.h" #include "net/cookies/site_for_cookies.h" #include "url/gurl.h" #include "url/origin.h" #if BUILDFLAG(USE_BLINK) #include "third_party/blink/public/common/features_generated.h" #endif namespace content_settings { CookieSettings::CookieSettings( HostContentSettingsMap* host_content_settings_map, PrefService* prefs, bool is_incognito, const char* extension_scheme) : host_content_settings_map_(host_content_settings_map), is_incognito_(is_incognito), extension_scheme_(extension_scheme), block_third_party_cookies_( net::cookie_util::IsForceThirdPartyCookieBlockingEnabled()) { content_settings_observation_.Observe(host_content_settings_map_.get()); pref_change_registrar_.Init(prefs); pref_change_registrar_.Add( prefs::kCookieControlsMode, base::BindRepeating(&CookieSettings::OnCookiePreferencesChanged, base::Unretained(this))); OnCookiePreferencesChanged(); } ContentSetting CookieSettings::GetDefaultCookieSetting( std::string* provider_id) const { return host_content_settings_map_->GetDefaultContentSetting( ContentSettingsType::COOKIES, provider_id); } ContentSettingsForOneType CookieSettings::GetCookieSettings() const { return host_content_settings_map_->GetSettingsForOneType( ContentSettingsType::COOKIES); } void CookieSettings::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { registry->RegisterIntegerPref( prefs::kCookieControlsMode, static_cast<int>(CookieControlsMode::kIncognitoOnly), user_prefs::PrefRegistrySyncable::SYNCABLE_PREF); } void CookieSettings::SetDefaultCookieSetting(ContentSetting setting) { DCHECK(IsValidSetting(setting)); host_content_settings_map_->SetDefaultContentSetting( ContentSettingsType::COOKIES, setting); } void CookieSettings::SetCookieSetting(const GURL& primary_url, ContentSetting setting) { DCHECK(IsValidSetting(setting)); host_content_settings_map_->SetContentSettingDefaultScope( primary_url, GURL(), ContentSettingsType::COOKIES, setting); } void CookieSettings::SetCookieSettingForUserBypass( const GURL& first_party_url) { ContentSettingConstraints constraints; // Only apply a lifetime outside incognito. In incognito, the duration is // inherintly limited. if (!is_incognito_) { constraints.set_lifetime( content_settings::features::kUserBypassUIExceptionExpiration.Get()); } constraints.set_session_model(SessionModel::Durable); host_content_settings_map_->SetContentSettingCustomScope( ContentSettingsPattern::Wildcard(), content_settings::URLToSchemefulSitePattern(first_party_url), ContentSettingsType::COOKIES, ContentSetting::CONTENT_SETTING_ALLOW, constraints); } bool CookieSettings::IsStoragePartitioningBypassEnabled( const GURL& first_party_url) { SettingInfo info; ContentSetting setting = host_content_settings_map_->GetContentSetting( GURL(), first_party_url, ContentSettingsType::COOKIES, &info); bool is_default = info.primary_pattern.MatchesAllHosts() && info.secondary_pattern.MatchesAllHosts(); return is_default ? false : IsAllowed(setting); } void CookieSettings::ResetCookieSetting(const GURL& primary_url) { host_content_settings_map_->SetNarrowestContentSetting( primary_url, GURL(), ContentSettingsType::COOKIES, CONTENT_SETTING_DEFAULT); } // TODO(crbug.com/1386190): Update to take in CookieSettingOverrides. bool CookieSettings::IsThirdPartyAccessAllowed( const GURL& first_party_url, content_settings::SettingInfo* info) const { // Use GURL() as an opaque primary url to check if any site // could access cookies in a 3p context on |first_party_url|. return IsAllowed(GetCookieSetting(GURL(), first_party_url, net::CookieSettingOverrides(), info)); } void CookieSettings::SetThirdPartyCookieSetting(const GURL& first_party_url, ContentSetting setting) { DCHECK(IsValidSetting(setting)); host_content_settings_map_->SetContentSettingCustomScope( ContentSettingsPattern::Wildcard(), ContentSettingsPattern::FromURLNoWildcard(first_party_url), ContentSettingsType::COOKIES, setting); } void CookieSettings::ResetThirdPartyCookieSetting(const GURL& first_party_url) { // Standard third party cookie settings are, with the introduction of User // Bypass, site scoped. There also may be an origin scoped exception either // created manually, or through the previous UI. Resetting should support // both of these. // TODO(crbug.com/1446230): Log metrics when there is pattern that has domain // as wildcard. auto pattern = content_settings::URLToSchemefulSitePattern(first_party_url); SettingInfo info; host_content_settings_map_->GetContentSetting( GURL(), first_party_url, ContentSettingsType::COOKIES, &info); if (!info.secondary_pattern.HasDomainWildcard()) { pattern = info.secondary_pattern; } host_content_settings_map_->SetContentSettingCustomScope( ContentSettingsPattern::Wildcard(), pattern, ContentSettingsType::COOKIES, CONTENT_SETTING_DEFAULT); } bool CookieSettings::IsStorageDurable(const GURL& origin) const { // TODO(dgrogan): Don't use host_content_settings_map_ directly. // https://crbug.com/539538 ContentSetting setting = host_content_settings_map_->GetContentSetting( origin /*primary*/, origin /*secondary*/, ContentSettingsType::DURABLE_STORAGE); return setting == CONTENT_SETTING_ALLOW; } bool CookieSettings::HasAnyFrameRequestedStorageAccess( const GURL& first_party_url) const { ContentSettingsForOneType settings = host_content_settings_map_->GetSettingsForOneType( ContentSettingsType::STORAGE_ACCESS); for (ContentSettingPatternSource source : settings) { // Skip default exceptions. if (source.primary_pattern.MatchesAllHosts() || source.secondary_pattern.MatchesAllHosts()) { continue; } // Skip exceptions that doesn't match the secondary pattern. if (!source.secondary_pattern.Matches(first_party_url)) { continue; } // There is an active SAA exception created in the context of // |first_party_url|. return true; } return false; } bool CookieSettings::ShouldIgnoreSameSiteRestrictions( const GURL& url, const net::SiteForCookies& site_for_cookies) const { return site_for_cookies.RepresentativeUrl().SchemeIs(kChromeUIScheme) && url.SchemeIsCryptographic(); } void CookieSettings::ShutdownOnUIThread() { DCHECK(thread_checker_.CalledOnValidThread()); pref_change_registrar_.RemoveAll(); } // Returns whether third-party cookie blocking should be bypassed (i.e. always // allow the cookie regardless of cookie content settings and third-party // cookie blocking settings. // This just checks the scheme of the |url| and |site_for_cookies|: // - Allow cookies if the |site_for_cookies| is a chrome:// scheme URL, and // the |url| has a secure scheme. // - Allow cookies if the |site_for_cookies| and the |url| match in scheme // and both have the Chrome extensions scheme. bool CookieSettings::ShouldAlwaysAllowCookies( const GURL& url, const GURL& first_party_url) const { if (first_party_url.SchemeIs(kChromeUIScheme) && url.SchemeIsCryptographic()) { return true; } #if BUILDFLAG(ENABLE_EXTENSIONS) if (url.SchemeIs(extension_scheme_) && first_party_url.SchemeIs(extension_scheme_)) { return true; } #endif // BUILDFLAG(ENABLE_EXTENSIONS) return false; } ContentSetting CookieSettings::GetContentSetting( const GURL& primary_url, const GURL& secondary_url, ContentSettingsType content_type, content_settings::SettingInfo* info) const { return host_content_settings_map_->GetContentSetting( primary_url, secondary_url, content_type, info); } bool CookieSettings::IsThirdPartyCookiesAllowedScheme( const std::string& scheme) const { return scheme == extension_scheme_; } bool CookieSettings::IsStorageAccessApiEnabled() const { // TODO(https://crbug.com/1411765): instead of using a BUILDFLAG and checking // the feature here, we should rely on CookieSettingsFactory to plumb in this // boolean instead. #if BUILDFLAG(USE_BLINK) return base::FeatureList::IsEnabled(blink::features::kStorageAccessAPI) || base::FeatureList::IsEnabled( permissions::features::kPermissionStorageAccessAPI); #else return false; #endif } CookieSettings::~CookieSettings() = default; bool CookieSettings::ShouldBlockThirdPartyCookiesInternal() { DCHECK(thread_checker_.CalledOnValidThread()); #if BUILDFLAG(IS_IOS) if (!base::FeatureList::IsEnabled(kImprovedCookieControls)) { return false; } #endif if (net::cookie_util::IsForceThirdPartyCookieBlockingEnabled()) { return true; } CookieControlsMode mode = static_cast<CookieControlsMode>( pref_change_registrar_.prefs()->GetInteger(prefs::kCookieControlsMode)); switch (mode) { case CookieControlsMode::kBlockThirdParty: return true; case CookieControlsMode::kIncognitoOnly: return is_incognito_; case CookieControlsMode::kOff: return false; } return false; } void CookieSettings::OnContentSettingChanged( const ContentSettingsPattern& primary_pattern, const ContentSettingsPattern& secondary_pattern, ContentSettingsTypeSet content_type_set) { if (content_type_set.Contains(ContentSettingsType::COOKIES)) { for (auto& observer : observers_) { observer.OnCookieSettingChanged(); } } } void CookieSettings::OnCookiePreferencesChanged() { DCHECK(thread_checker_.CalledOnValidThread()); bool new_block_third_party_cookies = ShouldBlockThirdPartyCookiesInternal(); { base::AutoLock auto_lock(lock_); if (block_third_party_cookies_ == new_block_third_party_cookies) { return; } block_third_party_cookies_ = new_block_third_party_cookies; } for (Observer& obs : observers_) { obs.OnThirdPartyCookieBlockingChanged(new_block_third_party_cookies); } } bool CookieSettings::ShouldBlockThirdPartyCookies() const { base::AutoLock auto_lock(lock_); return block_third_party_cookies_; } } // namespace content_settings
3ea89fc0d8903186c85a5e7b3f43ec2fcc8ca10a
e7209a5cb12250ae052ca882a3570c874b4c7dcf
/src/EditorRuntime/Widgets/wxImageComboBox.cpp
4e133982e9b453f976daf90df009c3d770c661d3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
akumetsuv/flood
3af52fc3934c289f72b4ca7828b90ce3a054dcda
e0d6647df9b7fac72443a0f65c0003b0ead7ed3a
refs/heads/master
2020-12-25T10:50:21.301224
2013-03-24T06:05:56
2013-03-24T06:05:56
8,084,980
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,209
cpp
wxImageComboBox.cpp
/************************************************************************ * * Flood Project © (2008-201x) * Licensed under the simplified BSD license. All rights reserved. * ************************************************************************/ #pragma once #include "Editor/API.h" #include "wxImageComboBox.h" NAMESPACE_EDITOR_BEGIN //-----------------------------------// wxImageComboBox::wxImageComboBox( wxWindow* parent, wxWindowID id ) : wxOwnerDrawnComboBox( parent, id, wxEmptyString, wxDefaultPosition, wxSize(-1, -1), 0, nullptr, wxCC_STD_BUTTON/*|wxCB_READONLY*/ ) { SetCustomPaintWidth( 150 ); GetTextCtrl()->Disable(); } //-----------------------------------// void wxImageComboBox::addImage( const ImageHandle& handle ) { Image* image = handle.Resolve(); Append( image->getPath() ); images.push_back(handle); } //-----------------------------------// wxBitmap* ConvertImageToBitmap( Image* image, const Path& fullPath ) { if( !image || !image->isLoaded() ) return nullptr; PixelFormat pf = image->getPixelFormat(); if( pf != PixelFormat::R8G8B8A8 ) { LogDebug("Invalid image format: %s", EnumGetValueName(ReflectionGetType(PixelFormat), (int32)pf)); return nullptr; } //wxBitmap* bmp = new wxBitmap; //bmp->Create(&image->getBuffer(), wxBITMAP_TYPE_ANY, image->getWidth(), image->getHeight(), 4); Stream* stream = StreamCreateFromFile(AllocatorGetHeap(), fullPath, StreamOpenMode::Read); if( !stream ) return nullptr; std::vector<byte> data; StreamRead(stream, data); wxMemoryInputStream mem(&data[0], data.size()); wxImage img(mem); img.Rescale(32, 32); StreamDestroy(stream); #if 0 const wxSize& size = GetSize(); if( img.GetWidth() > size.GetWidth() || img.GetHeight() > size.GetHeight() ) { img.Rescale( size.GetWidth(), size.GetHeight() ); } #endif wxBitmap* bmp = new wxBitmap(img); return bmp; } //-----------------------------------// void wxImageComboBox::OnDrawBackground (wxDC &dc, const wxRect &rect, int item, int flags) const { if ( item == wxNOT_FOUND ) return; const ImageHandle& image = images[item]; wxBitmap* bmp = ConvertImageToBitmap( image.Resolve(), "" ); if( !bmp ) return; dc.DrawBitmap( *bmp, rect.GetTopLeft() ); if( flags & wxODCB_PAINTING_SELECTED ) dc.DrawRectangle( rect ); delete bmp; } //-----------------------------------// void wxImageComboBox::OnDrawItem (wxDC &dc, const wxRect &rect, int item, int flags) const { if ( item == wxNOT_FOUND ) return; const ImageHandle& image = images[item]; wxBitmap* bmp = ConvertImageToBitmap( image.Resolve(), "" ); if( !bmp ) return; dc.DrawBitmap( *bmp, rect.GetTopLeft() ); delete bmp; } //-----------------------------------// wxCoord wxImageComboBox::OnMeasureItem (size_t item) const { Image* image = images[item].Resolve(); return image->getHeight(); } //-----------------------------------// wxCoord wxImageComboBox::OnMeasureItemWidth (size_t item) const { Image* image = images[item].Resolve(); return image->getWidth(); } //-----------------------------------// NAMESPACE_EDITOR_END
3241454990ed4a64859cb279a0ca70bfe7c30653
d018ba8b7983516583908129237a8a8cd8de7e11
/ultimo.ino
3c4ed960e8961b84b7dec10028ae430c0e87a51d
[]
no_license
drkside08/WALL-E
bafc5eff060faf1485ed3f5c30c3ffeb7228333c
0f1e36208d03f1201ba0ae9fe03b5873527c6fbe
refs/heads/master
2022-04-25T13:23:32.103355
2020-04-20T00:56:22
2020-04-20T00:56:22
257,103,366
0
0
null
null
null
null
UTF-8
C++
false
false
2,726
ino
ultimo.ino
boolean dato_anterior = 0; boolean dato_actual = 0; int Contador = 0; //<--Variable Digital int avancemotor1 = 2; int avancemotor2 = 3; int retromotor1 = 4; int retromotor2 = 5; int SenialEncoder = 6; int BArranque = 11; int BParo = 12; int BDistancia = 10; double Distancia = 0;//Varible digital void setup() //<-Aqui inicia la funcion SETUP------------------------------------- { Serial.begin(9600); ///Auxiliar para ver varibles internas o electricas pinMode(SenialEncoder,INPUT); //<-Renombrar pinMode(BArranque,INPUT); pinMode(BParo,INPUT); pinMode(BDistancia,INPUT); pinMode(avancemotor1,OUTPUT); pinMode(avancemotor2,OUTPUT); pinMode(retromotor1,OUTPUT); pinMode(retromotor2,OUTPUT); }//<--Aqui acaba la funcion SETUP-------------------------- /****************************************************************************************/ /* las variavles se declaran como entradas y salidas en la funcion "SETUP" por que */ /* son las primeras instruciones que se ejecutan cuando el arduino es alimentado */ /****************************************************************************************/ int Pulso(int ContadorAux) //<--- Inicio de la Funcion "PULSO" que es la que cuenta los pulsos en el encoder { dato_actual = digitalRead(SenialEncoder); if (dato_anterior != dato_actual) { delay(10); dato_actual = digitalRead(SenialEncoder); } if ( dato_anterior == 0 && dato_actual == 1) { ContadorAux++; Serial.println(ContadorAux); delay(100); } dato_anterior = dato_actual; return ContadorAux; /***********************************************************************************************************/ /* Si declaras las salidas y entradas aqui, el compilador no te dara errores pero internamente */ /* se estran redeclarando continuamente por lo que llevara al programa a bugerase o dañar la memoria */ /* del arduino, mas aparte es una mala practica declarar "ENTRADAS Y SALIDAS GLOBALES EN FUNCION QUE ESTAN */ /* EN CONSTANTE INTERACION" */ /***********************************************************************************************************/ } //<-----Fin de la funcion "PULSO" void loop() { while(Contador<15){ // se le da el numro de vueltas (125)..... digitalWrite (avancemotor1, HIGH); digitalWrite (avancemotor2, HIGH); Contador=Pulso(Contador); } digitalWrite (avancemotor1,LOW); digitalWrite (avancemotor2, LOW); delay (1000); //Contador=0; }
40a47d8d94dd23f64e1a72e15fb8fa99be8522d1
31d1a7fc130797fc6eb27d4b780259e168a9d53f
/apiwt/ApiServerWt.h
0af887be806cb41501e8dcffe94e551e07d2bf80
[]
no_license
RetroShare/rssocialnet
89b63bddc904753dda288d240ad45f2f31eae6b5
e1fe9a04d762e2cf2751dd609ea1d1d6060f5f00
refs/heads/master
2021-01-13T01:54:24.199700
2015-12-15T19:00:14
2015-12-15T19:00:14
31,284,034
5
4
null
2015-12-14T18:06:12
2015-02-24T21:56:36
C++
UTF-8
C++
false
false
417
h
ApiServerWt.h
#pragma once #include <Wt/WResource> #include "../api/ApiServer.h" namespace resource_api{ // main entry point of the http api class ApiServerWt: public Wt::WResource { public: ApiServerWt(const RsPlugInInterfaces& ifaces); ~ApiServerWt(){ beingDeleted(); } // Wt wants this void handleRequest(const Wt::Http::Request &request, Wt::Http::Response &response); private: ApiServer mApiServer; }; }
10cd3843e2e25f98c4f1ed69dbe1c13434202cb5
336dd1bc668e9f8e60487cdf4504de5f98c09d53
/servers/FrameWork.cpp
4c53b1131a92081f5e629f361f13cede645e7c2c
[]
no_license
Bobhu1995/epoll-learn
c5a1729b4a5f0e078eeb794319ece0a5b59b2a8d
d3f4fa830eeef0c4895c767d3a5d798dbfaa51af
refs/heads/main
2023-03-26T11:57:56.612552
2021-03-30T02:25:51
2021-03-30T02:25:51
317,156,382
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
8,192
cpp
FrameWork.cpp
#include <string.h> #include <malloc.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/stat.h> #include <netinet/tcp.h> #include <fcntl.h> #include <time.h> #include <sys/ioctl.h> #include <unistd.h> #include <errno.h> #include <poll.h> #include <execinfo.h> #include "FrameWork.h" namespace Server { ConnectFrame::ConnectFrame():epoll_fd(-1), epoll_ptr(nullptr){ } int32_t ConnectFrame::init() { if (FAIL == load_config()) { return FAIL; } for (size_t i = 0; i < sizeof(socket_info) / sizeof(SockInfo); ++i) { memset(&socket_info[i], 0, sizeof(SockInfo)); socket_info[i].sockfd = socket_fd_invalid; } epoll_ptr = nullptr; for (int32_t i = 0; i < server_config.open_port_count; ++i) { open_epoll_socket(server_config.open_prots[i], &server_config.local_ip[0]); } return SUCCESS; } int32_t ConnectFrame::load_config() { char tmp[] = "127.0.0.1"; for (size_t i = 0; i < strlen(tmp); ++i) { server_config.local_ip[i] = tmp[i]; } server_config.open_port_count = 1; server_config.open_prots[0] = 8888; server_config.socket_buffer_size = 131072; return SUCCESS; } int32_t ConnectFrame::working() { while (true){ recv_messages(); } } int32_t ConnectFrame::epoll_init(){ if (nullptr != epoll_ptr) { return FAIL; } memset(&epoll_events, 0, sizeof(epoll_events)); epoll_events.events = EPOLLIN | EPOLLERR | EPOLLHUP; epoll_events.data.ptr = nullptr; epoll_events.data.fd = -1; epoll_ptr = static_cast<epoll_event*> (malloc(MAX_SOCKET_COUNT * sizeof(epoll_event*))); if (nullptr == epoll_ptr) { return FAIL; } epoll_fd = epoll_create(MAX_SOCKET_COUNT); if(epoll_fd < 0){ return FAIL; } return SUCCESS; } int32_t ConnectFrame::epoll_socket(int32_t domain, int32_t type, int32_t protocol) { int32_t fd = socket(domain, type, protocol); if (fd < 0) { return FAIL; } int flags = -1; if(ioctl(fd, FIONBIO, &flags) && ((flags = fcntl(fd, F_GETFL, 0)) < 0 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)){ close(fd); return FAIL; } return fd; } int32_t ConnectFrame::open_epoll_socket(uint16_t port, char *local_ip) { if (epoll_init() != SUCCESS) { return FAIL; } int32_t socket_fd = epoll_socket(AF_INET, SOCK_STREAM, 0); if (socket_fd < 0 || socket_fd > MAX_SOCKET_COUNT) { epoll_destroy(); return FAIL; } int flags = 1; struct linger ling = { 0, 0 }; setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags)); setsockopt(socket_fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags)); setsockopt(socket_fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)); setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, &flags, sizeof(flags)); //set TCP_CORK struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); if (strlen(local_ip) < 0 || 0 >= inet_pton(AF_INET, local_ip, &(addr.sin_addr))) { addr.sin_addr.s_addr = htonl(INADDR_ANY); } int ret = 0; ret = bind(socket_fd, (struct sockaddr*) &addr, sizeof(addr)); if (ret < 0) { epoll_close(socket_fd); epoll_destroy(); return FAIL; } int32_t opt_value = 0; socklen_t opt_len = 0; opt_len = (socklen_t)sizeof(opt_value); opt_value = 128 * 1024; if (0 != setsockopt(socket_fd, SOL_SOCKET, SO_SNDBUF, (const void*)&opt_value, opt_len)) { return FAIL; } if (0 != setsockopt(socket_fd, SOL_SOCKET, SO_RCVBUF, (const void*)&opt_value, opt_len)) { return FAIL; } ret = listen(socket_fd, 128); if (ret < 0) { return FAIL; } if (epoll_new_socket(socket_fd) < 0) { epoll_close(socket_fd); epoll_destroy(); return FAIL; } socket_info[socket_fd].sockfd = socket_fd; socket_info[socket_fd].create_time = time(NULL); socket_info[socket_fd].socket_type = SOCKET_LISTEN; return SUCCESS; } int32_t ConnectFrame::epoll_new_socket(int32_t fd) { epoll_events.data.fd = fd; if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &epoll_events) < 0) { return FAIL; } return SUCCESS; } void ConnectFrame::epoll_close(int32_t fd) { close(fd); } void ConnectFrame::epoll_destroy() { free(epoll_ptr); close(epoll_fd); } void ConnectFrame::clear_socket(int32_t fd, const char* function /* = "NULL" */, int line /* = 0 */) { SockInfo* current_sock_ptr = &socket_info[fd]; int fd1 = current_sock_ptr->sockfd; if (fd != fd1) { return; } close(fd1); epoll_events.data.fd = fd1; if (epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd1, &epoll_events) < 0) { } current_sock_ptr->is_sent_message = false; current_sock_ptr->create_time = 0; current_sock_ptr->recvd_bytes = 0; current_sock_ptr->sockfd = socket_fd_invalid; current_sock_ptr->uid = 0; return; } int32_t ConnectFrame::recv_messages() { int32_t timeout = 1; int fd_event_count = 0; fd_event_count = epoll_wait(epoll_fd, epoll_ptr, MAX_SOCKET_COUNT, timeout); if (fd_event_count < 0){ return FAIL; } int sock_fd = socket_fd_invalid; struct epoll_event* event_ptr = epoll_ptr; SockInfo* current_socket_ptr = nullptr; for (int i = 0; i < fd_event_count; ++i) { sock_fd = event_ptr->data.fd; if (sock_fd < 0 || sock_fd > static_cast<int> ((sizeof(socket_info) / sizeof(socket_info[0])))) { continue; } if(0 != (EPOLLERR & event_ptr->events)){ clear_socket(sock_fd); continue; } if (0 == (EPOLLIN & event_ptr->events)) { continue; } int accepted_sockfd = socket_fd_invalid; struct sockaddr_in socket_address; socklen_t socket_address_len = static_cast<socklen_t> (sizeof(socket_address)); current_socket_ptr = &socket_info[sock_fd]; //¼àÌý¶Ë¿Ú if (current_socket_ptr->socket_type == SOCKET_LISTEN) { accepted_sockfd = accept(sock_fd, (struct sockaddr*) &socket_address, &socket_address_len); if (accepted_sockfd <= 0) { continue; } if (accepted_sockfd >= MAX_SOCKET_COUNT) { continue; } int flags = 1; if (ioctl(accepted_sockfd, FIONBIO, &flags) && ((flags = fcntl(accepted_sockfd, F_GETFL, 0)) < 0 || fcntl(accepted_sockfd, F_SETFL, flags | O_NONBLOCK) < 0)) { close(accepted_sockfd); continue; } int ret = 0; ret = epoll_new_socket(accepted_sockfd); if (ret < 0) { clear_socket(accepted_sockfd); continue; } socket_info[accepted_sockfd].sockfd = accepted_sockfd; socket_info[accepted_sockfd].is_sent_message = false; socket_info[accepted_sockfd].create_time = time(NULL); socket_info[accepted_sockfd].uid = 0; socket_info[accepted_sockfd].recvd_bytes = 0; socket_info[accepted_sockfd].socket_type = SOCKET_TRANSIT; } else{ recv_messages(sock_fd); } } return SUCCESS; } int32_t ConnectFrame::recv_messages(int32_t fd) { SockInfo* current_socket_ptr = &socket_info[fd]; int sock_fd = current_socket_ptr->sockfd; if (fd != sock_fd) { return FAIL; } int32_t buffer_size = static_cast<int32_t> (sizeof(msg_buffer)); int32_t received = socket_recv(sock_fd, msg_buffer, buffer_size); if (received <= 0) { clear_socket(sock_fd, __FUNCTION__, __LINE__); return FAIL; } //printf("%s, message is %s.\n", __FUNCTION__, msg_buffer); int32_t sent = socket_send(current_socket_ptr->sockfd, msg_buffer, received); if (sent != received) { return FAIL; } return SUCCESS; } int32_t ConnectFrame::socket_recv(int32_t fd, char* data, int32_t length) { if (data == nullptr || length < 0) { return FAIL; } size_t received = 0; while (true) { received = recv(fd, data, length, 0); if (received >= 0) { return received; } else { if (EAGAIN == errno || EINTR == errno) { continue; } return received; } } return FAIL; } int32_t ConnectFrame::socket_send(int32_t fd, char* data, int32_t length) { if (data == nullptr || length < 0) { return FAIL; } int32_t remainded = length; int32_t sended = 0; char* tmp = data; while (remainded > 0){ sended = send(fd, tmp, (size_t)remainded, 0); if (sended > 0) { tmp += sended; remainded -= sended; } else { if (errno != EINTR && errno != EAGAIN) { break; } } } return (length - remainded); } }
9025732006841fd8dd959ed8b41cecbce593df33
462ce2c462718ff1b991f942e5f5316a6fe1e906
/Library/ADMIN.cpp
7484df51f9613e8f0a947c6b5d513c5c082f2e50
[]
no_license
trinitiwowka/Library
78f5f54723398c8e8ad64c8e5ef6811713dd9ea8
3d15e12d3086b8a1ca83a90e75806026b4d36f0a
refs/heads/master
2021-01-10T02:45:34.899719
2015-12-08T18:31:13
2015-12-08T18:31:13
47,641,350
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
468
cpp
ADMIN.cpp
#include"ADMIN.h" void ADMIN::ShowDataUsers() { int const N=60; FILE* f1 = fopen("User_databaze.txt", "r"); char buf[N]; //show about hader file while(!feof(f1)) { fgets(buf,N,f1); char* seps={"$"}; char *token = strtok(buf ,seps);//пошук першого слова while( token != NULL ) { if(token!=NULL) std::cout<<token<<"\t"; token = strtok(NULL, seps );//пошук наступного слова } std::cout<<std::endl; } }
640d6f9b8332d836dee671e21bef6058b1613eec
1a0bb8dc80f1283f552baf436d9a8e722c22a8f1
/proj/fpga/ultra96/camera/Vitis-AI/alveo/apps/face_detect/evaluation/OpenCVUtils.cpp
f4037a0aa1945317adbac42e0c2bd0b728364fe1
[ "Apache-2.0", "MIT" ]
permissive
embedded-bitai/Mercenary
d457dcc2ace4dd4fe4a82489ecd28c61e3b4fe7a
7762bad28e4f49b2ad84fb8abbd8056bd01f61d4
refs/heads/master
2023-01-09T09:24:52.331403
2020-11-16T09:22:39
2020-11-16T09:22:39
297,019,610
4
9
MIT
2020-11-16T09:22:40
2020-09-20T06:53:53
C++
UTF-8
C++
false
false
5,030
cpp
OpenCVUtils.cpp
#ifndef __OPENCVUTILS_HPP__ #define __OPENCVUTILS_HPP__ #include "OpenCVUtils.hpp" using namespace std; void matPrint(string s, const CvArr *M){ assert(M != NULL); if(!s.empty()) cerr << s; CvTypeInfo *info = cvTypeOf(M); if(!strcmp(info->type_name, CV_TYPE_NAME_IMAGE)){ CvScalar s; IplImage *I = (IplImage *)M; for(int i=0; i< I->height; i++){ for(int j=0; j< I->width; j++){ s = cvGet2D(I,i,j); cerr << s.val[0] << " "; } cerr << endl; } }else if(!strcmp(info->type_name, CV_TYPE_NAME_MAT)){ CvMat *M1 = (CvMat *)M; for(int i=0; i< M1->height; i++){ for(int j=0; j< M1->width; j++) cerr << cvmGet(M1, i, j) << " "; cerr << endl; } }else{ assert(false); } } void matRotate(const CvArr * src, CvArr * dst, double angle){ float m[6]; //double factor = (cos(angle*CV_PI/180.) + 1.1)*3; double factor = 1; CvMat M = cvMat( 2, 3, CV_32F, m ); int w = ((CvMat *)src)->width; int h = ((CvMat *)src)->height; m[0] = (float)(factor*cos(-angle*CV_PI/180.)); m[1] = (float)(factor*sin(-angle*CV_PI/180.)); m[2] = (w-1)*0.5f; m[3] = -m[1]; m[4] = m[0]; m[5] = (h-1)*0.5f; cvGetQuadrangleSubPix( src, dst, &M); } void matCopyStuffed(const CvArr *src, CvArr *dst){ // TODO: get a flag for default value //double tMin, tMax; //cvMinMaxLoc(src, &tMin, &tMax); cvSet(dst, cvScalar(0)); CvMat *SMat = (CvMat *)src; CvMat *DMat = (CvMat *)dst; int sRow, dRow, sCol, dCol; if(SMat->rows >= DMat->rows){ sRow = (SMat->rows - DMat->rows)/2; dRow = 0; }else{ sRow = 0; dRow = (DMat->rows - SMat->rows)/2; } if(SMat->cols >= DMat->cols){ sCol = (SMat->cols - DMat->cols)/2; dCol = 0; }else{ sCol = 0; dCol = (DMat->cols - SMat->cols)/2; } //cerr << "src start " << sRow << " " << sCol << " dst " << dRow << " " << dCol << endl; /* for(int di =0; di < dRow; di++) for(int dj = 0; (dj < DMat->cols) && (dj < SMat->cols) ; dj++) cvmSet(DMat, di, dj, cvmGet(SMat, sRow, dj)); for(int dj =0; dj < dCol; dj++) for(int di = 0; (di < DMat->rows) && (di < SMat->rows) ; di++) cvmSet(DMat, di, dj, cvmGet(SMat, di, sCol)); */ for( int si = sRow, di = dRow ; (si<SMat->rows && di<DMat->rows); si++, di++) for( int sj = sCol, dj = dCol ; (sj<SMat->cols && dj<DMat->cols); sj++, dj++) cvmSet(DMat, di, dj, cvmGet(SMat, si, sj)); } void matNormalize(const CvArr * src, CvArr *dst, double minVal, double maxVal){ double tMin, tMax; cvMinMaxLoc(src, &tMin, &tMax); double scaleFactor = (maxVal-minVal)/(tMax-tMin); cvSubS(src, cvScalar(tMin), dst); cvConvertScale(dst, dst, scaleFactor, minVal); } double matMedian(const CvArr *M){ int starti=0, startj=0, height, width; CvTypeInfo *info = cvTypeOf(M); if(!strcmp(info->type_name, CV_TYPE_NAME_IMAGE)){ CvRect r = cvGetImageROI((IplImage *)M); height = r.height; width = r.width; startj = r.x; starti = r.y; }else if(!strcmp(info->type_name, CV_TYPE_NAME_MAT)){ height = ((CvMat *)M)->height; width = ((CvMat *)M)->width; }else{ assert(false); } // push elements into a vector vector<double> v; for(int i=0; i< height; i++) for(int j=0; j<width; j++){ v.push_back(cvGet2D(M,i,j).val[0]); } // sort the vector and return the median element sort(v.begin(), v.end()); return *(v.begin() + v.size()/2); } void showImage(string title, const CvArr *M){ const char *s = title.c_str(); cvNamedWindow(s, 0); cvMoveWindow(s, 100, 400); cvShowImage(s, M); cvWaitKey(0); cvDestroyWindow(s); } // like imagesc void showImageSc(string title, const CvArr *M, int height, int width){ const char *s = title.c_str(); IplImage *I1; CvTypeInfo *info = cvTypeOf(M); if(!strcmp(info->type_name, CV_TYPE_NAME_IMAGE)){ I1 = (IplImage *)M; }else if(!strcmp(info->type_name, CV_TYPE_NAME_MAT)){ CvMat *M2 = cvCloneMat((CvMat *)M); matNormalize(M, M2, 0, 255); double tMin, tMax; cvMinMaxLoc(M2, &tMin, &tMax); I1 = cvCreateImage(cvGetSize(M2), IPL_DEPTH_8U,1); cvConvertScale(M2, I1); }else{ assert(false); } IplImage *I = cvCreateImage(cvSize(height, width), I1->depth,1); cvResize(I1, I); cvNamedWindow(s, 0); cvMoveWindow(s, 100, 400); cvShowImage(s, I); cvWaitKey(0); cvDestroyWindow(s); cvReleaseImage(&I); cvReleaseImage(&I1); } IplImage *readImage(const char *fileName, int useColorImage){ #ifdef _WIN32 IplImage *img = cvLoadImage(fileName, useColorImage); #else // check the extension for jpg files; OpenCV has issues with reading jpg files. int randInt = rand(); char randIntStr[128]; sprintf(randIntStr, "%d", randInt); string tmpPPMFile("cacheReadImage"); tmpPPMFile += randIntStr; tmpPPMFile += ".ppm"; string sysCommand = "convert "; sysCommand += fileName; sysCommand += " " + tmpPPMFile; system(sysCommand.c_str()); IplImage *img = cvLoadImage(tmpPPMFile.c_str(), useColorImage); if(img == NULL) { cerr << " Could not read image" << endl; } sysCommand = "rm -f "; sysCommand += tmpPPMFile; system(sysCommand.c_str()); #endif return img; } #endif
cfc1179ca4de4982e32715083e7c74c677df4f67
de1c1b4bde742a316c8f179b20047876afd01f2e
/creyons.cpp
ad0a05fa467abc96bbd512440bc70006f04e60c7
[]
no_license
flavmodan/MySources
4f258563b87d97da7adc2b7d533e05587ccb94a8
927efc7eba95524cc570d0a3e5b4618630824c9a
refs/heads/master
2021-09-02T05:39:52.392585
2017-12-30T20:03:55
2017-12-30T20:03:56
111,738,032
0
0
null
null
null
null
UTF-8
C++
false
false
1,163
cpp
creyons.cpp
#include<iostream> #include<fstream> #include<deque> #include<string> using namespace std; bool colors[]={1,1,1,0,0,0,0,0,0,0,0}; int red_num=2; int black_num=3; bool appears(deque<int> sol,int k){ for (auto i = 0; i < sol.size(); ++i) { if(k==sol[i]) return true; } return false; } void count(deque<int> sol,int &red,int &black){ red=0; for (auto i = 0; i < sol.size(); ++i) { if(colors[sol[i]]){ red++; } } black=0; for (auto i = 0; i < sol.size(); ++i) { if(!colors[sol[i]]){ black++; } } } deque<int> s; int num=0; void bkt(){ for (auto i = 0; i < 11; i++) { if(!appears(s,i)){ s.push_back(i); int red,black; count(s,red,black); //cout<<red<<" "<<black<<endl; if(s.size()<=red_num+black_num && red<=red_num && black<=black_num){ if(red==red_num && black==black_num){ cout<<num<<" : "; for (auto j = 0; j < s.size(); ++j) { cout<<s[j]<<" -> "<<colors[s[j]]<<" | "; } cout<<endl; num++; } bkt(); } s.pop_back(); } } } int main(){ bkt(); cout<<num; }
998d41ba327cf574c94b6e05e70a33d32adecdd0
a3d463a887e1f2cd1d91ce451485a903957d14e8
/MyTestProject/C++ Primer Plus/编程练习/chapter 10/10-10-8-2.cpp
abd8d8a9761a3327e0ec6f84abec2abbd0d1acb2
[]
no_license
GodBless112/MyTestProject
b7c95018fbf7ec01e16f2e1b07570dcd9fe7d396
aa5e784975b1d207ffe0a1424db5f45c269b304a
refs/heads/master
2021-01-12T05:46:30.805488
2017-05-31T16:04:27
2017-05-31T16:04:27
77,196,106
1
0
null
null
null
null
UTF-8
C++
false
false
417
cpp
10-10-8-2.cpp
#include <iostream> #include "test.h" List::List() { count = 0; } bool List::isempty() { return count == 0; } bool List::isfull() { return count == ListLen; } int List::itemcount() { return count; } bool List::additem(Item & item) { if (count == ListLen) return false; else items[count++] = item; return true; } void List::visit(void(*pf)(Item &)) { for (int i = 0; i < count; i++) (*pf)(items[i]); }
c2e6d572033db1bfbc3310c715594f26631086a0
e031b8c2267adf33b75880fc109c40526da2e355
/IKnizhnik/football.cpp
34e6971b9d2fcc09a050b490415d4c7040e41990
[]
no_license
kartoshka7777/BFU
3dafd6a4cd110cf4d35815506b2525855c6cda48
e7af3ba3fb164d902153034272cf55b7db022f21
refs/heads/master
2018-01-16T07:11:04.095981
2015-05-09T16:59:09
2015-05-09T16:59:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
264
cpp
football.cpp
#include <iostream> #include <cstdio> void f(int n, int **a) { setlocale(LC_ALL, "Russian"); for (int i = 0; i < n - 1; i++){ for (int j = i + 1; j < n; j++) printf("Команда%d - Команда%d: Счёт %d-%d\n", i+1, j+1, a[i][j], a[j][i]); } }
7c9e5b4e58d60c7004b1f45ff0c5c0a546790bac
ce719abb87292b6c5a8f87f22fb04ba64c8be07d
/src/Shady Snake/Shady Snake/shadyengine/timer.h
c7037d82685ef9af444e3bff0bfb267f98776ffc
[]
no_license
ankitsinghkushwah/Shady-Snake
29c4021da1535bcc1c0ec7404e411b858cd99ffd
179d079b0016f3a474c4d98923a716f67b7de9a3
refs/heads/master
2022-12-20T23:23:54.364718
2017-10-26T15:45:11
2017-10-26T15:45:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
745
h
timer.h
#ifndef INC_SHADY_ENGINE_TIMER_H #define INC_SHADY_ENGINE_TIMER_H //C++ headers #include<memory> #include<chrono> namespace shady_engine { class timer { public: timer(); void init(); void update(); inline double get_elapsed_time() const { return mElapsedTime; } inline unsigned int get_FPS() const { return mFPS; } private: typedef std::chrono::high_resolution_clock mClock; typedef std::chrono::microseconds mMicroseconds; //for elapsed time mClock::time_point mLast; mClock::time_point mCurrent; double mElapsedTime; //For FPS unsigned int mFPS; unsigned int mCounter; mClock::time_point mLastTime; double in_seconds(mClock::duration pDuration) const; }; } #endif
6421239d27985145b446da79d34836eac3d63fe6
9d3f5b8e176e4c6e30115d0e6947a1cbc3cabf8a
/Loops/sum of digit.cpp
e605a32a6b79066eb04f0cbe23ea6a5e7234d8f6
[]
no_license
mohsin0176/C-PlusPlus-Programmes
d872ff202ec52241bda695ff76050c0801d7c28e
0b00811f945052d08a6b2f24b5267508337382cd
refs/heads/master
2023-02-15T14:39:23.410831
2021-01-14T13:18:01
2021-01-14T13:18:01
326,896,974
0
0
null
null
null
null
UTF-8
C++
false
false
209
cpp
sum of digit.cpp
#include<iostream> using namespace std; int main() { long int n,r,sum; cin>>n; sum=0; while(n!=0) { r=n%10; sum=sum+r; n=n/10; } cout<<sum; return 0; }
6bd8f42c2c18467014946656bb552540675d5fa5
fb39726be5a78bfadbba48181f6deee84c9b5a83
/SparkD/Engine/cvlibbase/Inc/cvbase.h
bb4cf092835d3c09f941031bd27a9f5c7354ddac
[]
no_license
kmhk/SparkD
b6833b93803b181ef997a4d7388fa73fa2ca6250
9ed72f0b5a22d835a4695cb9e4d7c7a6b532d217
refs/heads/master
2022-11-06T21:49:24.709316
2020-07-01T04:35:34
2020-07-01T04:35:34
269,883,069
0
0
null
null
null
null
UTF-8
C++
false
false
26,741
h
cvbase.h
/*! * \file * \brief . * \author */ #pragma once #include "cvlibbaseDef.h" #include "cvlibutil.h" namespace cvlib { #define CVLIB_MAGIC_MASK 0xFFFF0000 /******************************Mat type****************************/ //#define CVLIB_MAT_CN_MASK ((CVLIB_CN_MAX - 1) << CVLIB_CN_SHIFT) //#define CVLIB_MAT_CN(flags) ((((flags) & CVLIB_MAT_CN_MASK) >> CVLIB_CN_SHIFT) + 1) //#define CVLIB_MAT_DEPTH_MASK (CVLIB_DEPTH_MAX - 1) //#define CVLIB_MAT_TYPE_MASK (CVLIB_DEPTH_MAX*CVLIB_CN_MAX - 1) //#define CVLIB_MAT_TYPE(flags) ((flags) & CVLIB_MAT_TYPE_MASK) #define CVLIB_MAT_CONT_FLAG_SHIFT 14 #define CVLIB_MAT_CONT_FLAG (1 << CVLIB_MAT_CONT_FLAG_SHIFT) #define CVLIB_IS_MAT_CONT(flags) ((flags) & CVLIB_MAT_CONT_FLAG) #define CVLIB_IS_CONT_MAT CVLIB_IS_MAT_CONT #define CVLIB_MAT_TEMP_FLAG_SHIFT 15 #define CVLIB_MAT_TEMP_FLAG (1 << CVLIB_MAT_TEMP_FLAG_SHIFT) #define CVLIB_IS_TEMP_MAT(flags) ((flags) & CVLIB_MAT_TEMP_FLAG) #define CVLIB_MAGIC_MASK 0xFFFF0000 #define CVLIB_MAT_MAGIC_VAL 0x42420000 /* default alignment for dynamic data strucutures, resided in storages. */ #define CVLIB_STRUCT_ALIGN ((int)sizeof(double)) /****************************************************************************************\ * Sequence types * \****************************************************************************************/ #define CVLIB_32FC1 CVLIB_MAKETYPE(CVLIB_32F,1) #define CVLIB_32FC2 CVLIB_MAKETYPE(CVLIB_32F,2) #define CVLIB_32FC3 CVLIB_MAKETYPE(CVLIB_32F,3) #define CVLIB_32FC4 CVLIB_MAKETYPE(CVLIB_32F,4) #define CVLIB_32FC(n) CVLIB_MAKETYPE(CVLIB_32F,(n)) #define CVLIB_32SC1 CVLIB_MAKETYPE(CVLIB_32S,1) #define CVLIB_32SC2 CVLIB_MAKETYPE(CVLIB_32S,2) #define CVLIB_32SC3 CVLIB_MAKETYPE(CVLIB_32S,3) #define CVLIB_32SC4 CVLIB_MAKETYPE(CVLIB_32S,4) #define CVLIB_32SC(n) CVLIB_MAKETYPE(CVLIB_32S,(n)) #define CVLIB_8SC1 CVLIB_MAKETYPE(CVLIB_8S,1) #define CVLIB_8SC2 CVLIB_MAKETYPE(CVLIB_8S,2) #define CVLIB_8SC3 CVLIB_MAKETYPE(CVLIB_8S,3) #define CVLIB_8SC4 CVLIB_MAKETYPE(CVLIB_8S,4) #define CVLIB_8SC(n) CVLIB_MAKETYPE(CVLIB_8S,(n)) /* IEEE754 constants and macros */ #define CVLIB_POS_INF 0x7f800000 #define CVLIB_NEG_INF 0x807fffff /* CVLIB_TOGGLE_FLT(0xff800000) */ #define CVLIB_1F 0x3f800000 #define CVLIB_TOGGLE_FLT(x) ((x)^((int)(x) < 0 ? 0x7fffffff : 0)) #define CVLIB_TOGGLE_DBL(x) \ ((x)^((int64)(x) < 0 ? CV_BIG_INT(0x7fffffffffffffff) : 0)) #define CVLIB_SEQ_MAGIC_VAL 0x42990000 #define CVLIB_IS_SEQ(seq) \ ((seq) != NULL && (((Sequence*)(seq))->flags & CVLIB_MAGIC_MASK) == CVLIB_SEQ_MAGIC_VAL) #define CVLIB_SET_MAGIC_VAL 0x42980000 #define CVLIB_IS_SET(set) \ ((set) != NULL && (((Sequence*)(set))->flags & CVLIB_MAGIC_MASK) == CVLIB_SET_MAGIC_VAL) #define CVLIB_SEQ_ELTYPE_BITS 9 #define CVLIB_SEQ_ELTYPE_MASK ((1 << CVLIB_SEQ_ELTYPE_BITS) - 1) #define CVLIB_SEQ_ELTYPE_POINT CVLIB_32SC2 /* (x,y) */ #define CVLIB_SEQ_ELTYPE_CODE CVLIB_8UC1 /* freeman code: 0..7 */ #define CVLIB_SEQ_ELTYPE_GENERIC 0 #define CVLIB_SEQ_ELTYPE_PTR CVLIB_USRTYPE1 #define CVLIB_SEQ_ELTYPE_PPOINT CVLIB_SEQ_ELTYPE_PTR /* &(x,y) */ #define CVLIB_SEQ_ELTYPE_INDEX CVLIB_32SC1 /* #(x,y) */ #define CVLIB_SEQ_ELTYPE_GRAPH_EDGE 0 /* &next_o, &next_d, &vtx_o, &vtx_d */ #define CVLIB_SEQ_ELTYPE_GRAPH_VERTEX 0 /* first_edge, &(x,y) */ #define CVLIB_SEQ_ELTYPE_TRIAN_ATR 0 /* vertex of the binary tree */ #define CVLIB_SEQ_ELTYPE_CONNECTED_COMP 0 /* connected component */ #define CVLIB_SEQ_ELTYPE_POINT3D CVLIB_32FC3 /* (x,y,z) */ #define CVLIB_SEQ_KIND_BITS 3 #define CVLIB_SEQ_KIND_MASK (((1 << CVLIB_SEQ_KIND_BITS) - 1)<<CVLIB_SEQ_ELTYPE_BITS) /* types of sequences */ #define CVLIB_SEQ_KIND_GENERIC (0 << CVLIB_SEQ_ELTYPE_BITS) #define CVLIB_SEQ_KIND_CURVE (1 << CVLIB_SEQ_ELTYPE_BITS) #define CVLIB_SEQ_KIND_BIN_TREE (2 << CVLIB_SEQ_ELTYPE_BITS) #define CVLIB_8U 0 #define CVLIB_8S 1 #define CVLIB_16U 2 #define CVLIB_16S 3 #define CVLIB_32S 4 #define CVLIB_32F 5 #define CVLIB_64F 6 #define CVLIB_USRTYPE1 7 #define CVLIB_8UC1 CVLIB_MAKETYPE(CVLIB_8U,1) #define CVLIB_SEQ_ELTYPE_CODE CVLIB_8UC1 /* freeman code: 0..7 */ /* chain-coded curves */ #define CVLIB_SEQ_CHAIN (CVLIB_SEQ_KIND_CURVE | CVLIB_SEQ_ELTYPE_CODE) #define CVLIB_SEQ_CHAIN_CONTOUR (CVLIB_SEQ_FLAG_CLOSED | CVLIB_SEQ_CHAIN) /* point sets */ #define CVLIB_SEQ_POINT_SET (CVLIB_SEQ_KIND_GENERIC| CVLIB_SEQ_ELTYPE_POINT) #define CVLIB_SEQ_POINT3D_SET (CVLIB_SEQ_KIND_GENERIC| CVLIB_SEQ_ELTYPE_POINT3D) #define CVLIB_SEQ_POLYLINE (CVLIB_SEQ_KIND_CURVE | CVLIB_SEQ_ELTYPE_POINT) #define CVLIB_SEQ_POLYGON (CVLIB_SEQ_FLAG_CLOSED | CVLIB_SEQ_POLYLINE ) #define CVLIB_SEQ_CONTOUR CVLIB_SEQ_POLYGON #define CVLIB_SEQ_SIMPLE_POLYGON (CVLIB_SEQ_FLAG_SIMPLE | CVLIB_SEQ_POLYGON ) #define CVLIB_SEQ_KIND_BITS 3 #define CVLIB_SEQ_ELTYPE_BITS 9 #define CVLIB_SEQ_FLAG_SHIFT (CVLIB_SEQ_KIND_BITS + CVLIB_SEQ_ELTYPE_BITS) /* flags for curves */ #define CVLIB_SEQ_FLAG_CLOSED (1 << CVLIB_SEQ_FLAG_SHIFT) #define CVLIB_SEQ_FLAG_SIMPLE (2 << CVLIB_SEQ_FLAG_SHIFT) #define CVLIB_SEQ_FLAG_CONVEX (4 << CVLIB_SEQ_FLAG_SHIFT) #define CVLIB_SEQ_FLAG_HOLE (8 << CVLIB_SEQ_FLAG_SHIFT) /* sequence of the integer numbers */ #define CVLIB_SEQ_INDEX (CVLIB_SEQ_KIND_GENERIC | CVLIB_SEQ_ELTYPE_INDEX) #define CVLIB_SEQ_ELTYPE( seq ) ((seq)->flags & CVLIB_SEQ_ELTYPE_MASK) #define CVLIB_SEQ_KIND( seq ) ((seq)->flags & CVLIB_SEQ_KIND_MASK ) /* flag checking */ #define CVLIB_IS_SEQ_INDEX( seq ) ((CVLIB_SEQ_ELTYPE(seq) == CVLIB_SEQ_ELTYPE_INDEX) && \ (CVLIB_SEQ_KIND(seq) == CVLIB_SEQ_KIND_GENERIC)) #define CVLIB_IS_SEQ_CURVE( seq ) (CVLIB_SEQ_KIND(seq) == CVLIB_SEQ_KIND_CURVE) #define CVLIB_IS_SEQ_CLOSED( seq ) (((seq)->flags & CVLIB_SEQ_FLAG_CLOSED) != 0) #define CVLIB_IS_SEQ_CONVEX( seq ) (((seq)->flags & CVLIB_SEQ_FLAG_CONVEX) != 0) #define CVLIB_IS_SEQ_HOLE( seq ) (((seq)->flags & CVLIB_SEQ_FLAG_HOLE) != 0) #define CVLIB_IS_SEQ_SIMPLE( seq ) ((((seq)->flags & CVLIB_SEQ_FLAG_SIMPLE) != 0) || \ CVLIB_IS_SEQ_CONVEX(seq)) #define CVLIB_MEMCPY_AUTO( dst, src, len ) \ { \ int _icv_memcpy_i_, _icv_memcpy_len_ = (len); \ char* _icv_memcpy_dst_ = (char*)(dst); \ const char* _icv_memcpy_src_ = (const char*)(src); \ if( (_icv_memcpy_len_ & (sizeof(int)-1)) == 0 ) \ { \ assert( ((intptr_t)_icv_memcpy_src_&(sizeof(int)-1)) == 0 && \ ((intptr_t)_icv_memcpy_dst_&(sizeof(int)-1)) == 0 ); \ for( _icv_memcpy_i_ = 0; _icv_memcpy_i_ < _icv_memcpy_len_; \ _icv_memcpy_i_+=sizeof(int) ) \ { \ *(int*)(_icv_memcpy_dst_+_icv_memcpy_i_) = \ *(const int*)(_icv_memcpy_src_+_icv_memcpy_i_); \ } \ } \ else \ { \ for(_icv_memcpy_i_ = 0; _icv_memcpy_i_ < _icv_memcpy_len_; _icv_memcpy_i_++)\ _icv_memcpy_dst_[_icv_memcpy_i_] = _icv_memcpy_src_[_icv_memcpy_i_]; \ } \ } /* initializes 8-element array for fast access to 3x3 neighborhood of a pixel */ #define CVLIB_INIT_3X3_DELTAS( deltas, step, nch ) \ ((deltas)[0] = (nch), (deltas)[1] = -(step) + (nch), \ (deltas)[2] = -(step), (deltas)[3] = -(step) - (nch), \ (deltas)[4] = -(nch), (deltas)[5] = (step) - (nch), \ (deltas)[6] = (step), (deltas)[7] = (step) + (nch)) /******************************** Memory storage ****************************************/ struct CVLIB_DECLSPEC MemBlock { struct MemBlock* prev; struct MemBlock* next; }; #define CVLIB_STORAGE_MAGIC_VAL 0x42890000 struct CVLIB_DECLSPEC MemStorage { int signature; MemBlock* bottom;/* first allocated block */ MemBlock* top; /* current memory block - top of the stack */ MemStorage* parent; /* borrows new blocks from */ int block_size; /* block size */ int free_space; /* free space in the current block */ }; #define CVLIB_IS_STORAGE(storage) \ ((storage) != NULL && \ (((MemStorage*)(storage))->signature & CVLIB_MAGIC_MASK) == CVLIB_STORAGE_MAGIC_VAL) struct CVLIB_DECLSPEC MemStoragePos { MemBlock* top; int free_space; }; typedef union Cv32suf { int i; unsigned u; float f; } Cv32suf; struct CvPair32s32f { int i; float val; }; /*********************************** Sequence *******************************************/ struct CVLIB_DECLSPEC SeqBlock { struct SeqBlock* prev; /* previous sequence block */ struct SeqBlock* next; /* next sequence block */ int start_index; /* index of the first element in the block + sequence->first->start_index */ int count; /* number of elements in the block */ char* data; /* pointer to the first element of the block */ }; #define CVLIB_TREE_NODE_FIELDS(node_type) \ int flags; /* micsellaneous flags */ \ int header_size; /* size of sequence header */ \ struct node_type* h_prev; /* previous sequence */ \ struct node_type* h_next; /* next sequence */ \ struct node_type* v_prev; /* 2nd previous sequence */ \ struct node_type* v_next; /* 2nd next sequence */ /* read/write sequence. Elements can be dynamically inserted to or deleted from the sequence. */ #define CVLIB_SEQUENCE_FIELDS() \ CVLIB_TREE_NODE_FIELDS(Sequence) \ int total; /* total number of elements */ \ int elem_size; /* size of sequence element in bytes */ \ char* block_max; /* maximal bound of the last block */ \ char* ptr; /* current write pointer */ \ int delta_elems; /* how many elements allocated when the seq grows */ \ MemStorage* storage; /* where the seq is stored */ \ SeqBlock* free_blocks; /* free blocks list */ \ SeqBlock* first; /* pointer to the first sequence block */ struct CVLIB_DECLSPEC Sequence { Sequence(){}; CVLIB_SEQUENCE_FIELDS() }; /****************************************************************************************/ /* Sequence writer & reader */ /****************************************************************************************/ #define SEQ_WRITER_FIELDS() \ int header_size; \ Sequence* seq; /* the sequence written */ \ SeqBlock* block; /* current block */ \ char* ptr; /* pointer to free space */ \ char* block_min; /* pointer to the beginning of block*/ \ char* block_max; /* pointer to the end of block */ struct CVLIB_DECLSPEC SeqWriter { SEQ_WRITER_FIELDS() }; #define SEQ_READER_FIELDS() \ int header_size; \ Sequence* seq; /* sequence, beign read */ \ SeqBlock* block; /* current block */ \ char* ptr; /* pointer to element be read next */ \ char* block_min; /* pointer to the beginning of block */\ char* block_max; /* pointer to the end of block */ \ int delta_index;/* = seq->first->start_index */ \ char* prev_elem; /* pointer to previous element */ struct CVLIB_DECLSPEC SeqReader { SEQ_READER_FIELDS() }; /*************************************** Set ********************************************/ /* Set. Order is not preserved. There can be gaps between sequence elements. After the element has been inserted it stays in the same place all the time. The MSB(most-significant or sign bit) of the first field (flags) is 0 iff the element exists. */ #define CVLIB_SET_ELEM_FIELDS(elem_type) \ int flags; \ struct elem_type* next_free; struct CVLIB_DECLSPEC SetElem { CVLIB_SET_ELEM_FIELDS(SetElem) }; #define CVLIB_SET_FIELDS() \ CVLIB_SEQUENCE_FIELDS() \ SetElem* free_elems; \ int active_count; struct CVLIB_DECLSPEC Set { CVLIB_SET_FIELDS() }; #define CVLIB_SET_ELEM_IDX_MASK ((1 << 26) - 1) #define CVLIB_SET_ELEM_FREE_FLAG (1 << (sizeof(int)*8-1)) /* Checks whether the element pointed by ptr belongs to a set or not */ #define CVLIB_IS_SET_ELEM( ptr ) (((SetElem*)(ptr))->flags >= 0) struct CVLIB_DECLSPEC TreeNode { int flags; /* micsellaneous flags */ int header_size; /* size of sequence header */ struct TreeNode* h_prev; /* previous sequence */ struct TreeNode* h_next; /* next sequence */ struct TreeNode* v_prev; /* 2nd previous sequence */ struct TreeNode* v_next; /* 2nd next sequence */ }; typedef void Arr; ////////////////////////////////////////////////////////////////////////// /************************************* CvSlice ******************************************/ #define CVLIB_WHOLE_SEQ_END_INDEX 0x3fffffff #define CVLIB_WHOLE_SEQ Slice(0, CVLIB_WHOLE_SEQ_END_INDEX) #define CVLIB_MALLOC_ALIGN 32 #define ICV_FREE_PTR(storage) \ ((char*)(storage)->top + (storage)->block_size - (storage)->free_space) #define ICV_ALIGNED_SEQ_BLOCK_SIZE \ (int)alignSize(sizeof(SeqBlock), CVLIB_STRUCT_ALIGN) #define CVLIB_WRITE_SEQ_ELEM( elem, writer ) \ { \ assert( (writer).seq->elem_size == sizeof(elem)); \ if( (writer).ptr >= (writer).block_max ) \ { \ createSeqBlock( &writer); \ } \ assert( (writer).ptr <= (writer).block_max - sizeof(elem));\ memcpy((writer).ptr, &(elem), sizeof(elem)); \ (writer).ptr += sizeof(elem); \ } /* move reader position forward */ #define CVLIB_NEXT_SEQ_ELEM( elem_size, reader ) \ { \ if( ((reader).ptr += (elem_size)) >= (reader).block_max ) \ { \ changeSeqBlock( &(reader), 1 ); \ } \ } /* read element and move read position forward */ #define CVLIB_READ_SEQ_ELEM( elem, reader ) \ { \ assert( (reader).seq->elem_size == sizeof(elem)); \ memcpy( &(elem), (reader).ptr, sizeof((elem))); \ CVLIB_NEXT_SEQ_ELEM( sizeof(elem), reader ) \ } /* maximum size of dynamic memory buffer. cvAlloc reports an error if a larger block is requested. */ #define CVLIB_MAX_ALLOC_SIZE (((int)1 << (sizeof(int)*8-2))) #define CVLIB_MEMCPY_INT( dst, src, len ) \ { \ int _icv_memcpy_i_, _icv_memcpy_len_ = (len); \ int* _icv_memcpy_dst_ = (int*)(dst); \ const int* _icv_memcpy_src_ = (const int*)(src); \ assert( ((intptr_t)_icv_memcpy_src_&(sizeof(int)-1)) == 0 && \ ((intptr_t)_icv_memcpy_dst_&(sizeof(int)-1)) == 0 ); \ \ for(_icv_memcpy_i_=0;_icv_memcpy_i_<_icv_memcpy_len_;_icv_memcpy_i_++) \ _icv_memcpy_dst_[_icv_memcpy_i_] = _icv_memcpy_src_[_icv_memcpy_i_]; \ } #define CVLIB_GET_LAST_ELEM( seq, block ) \ ((block)->data + ((block)->count - 1)*((seq)->elem_size)) /* default storage block size */ #define CVLIB_STORAGE_BLOCK_SIZE ((1<<16) - 128) /* type checking macros */ #define CVLIB_IS_SEQ_POINT_SET( seq ) \ ((CVLIB_SEQ_ELTYPE(seq) == CVLIB_32SC2 || CVLIB_SEQ_ELTYPE(seq) == CVLIB_32FC2)) #define CVLIB_IS_MAT_HDR(mat) \ ((mat) != NULL && \ (CVLIB_MAGIC_MASK) == CVLIB_MAT_MAGIC_VAL && \ ((const Mat*)(mat))->cols() > 0 && ((const Mat*)(mat))->rows() > 0) #define CVLIB_IS_MAT(mat) \ (CVLIB_IS_MAT_HDR(mat) && ((const Mat*)(mat))->data.ptr != NULL) #define ICVLIB_SHIFT_TAB_MAX 32 ////////////////////////////////////////////////////////////////////////// // default <free> inline static int defaultFree( void* ptr, void* ) { // Pointer must be aligned by CVLIB_MALLOC_ALIGN if( ((intptr_t)ptr & (CVLIB_MALLOC_ALIGN-1)) != 0 ) return -49; free( *((char**)ptr - 1) ); return 0; } inline static void* defaultAlloc( int size, void* ) { char *ptr, *ptr0 = (char*)malloc( (int)(size + CVLIB_MALLOC_ALIGN*((size >= 4096) + 1) + sizeof(char*))); if( !ptr0 ) return 0; // align the pointer ptr = (char*)alignPtr(ptr0 + sizeof(char*) + 1, CVLIB_MALLOC_ALIGN); *(char**)(ptr - sizeof(char*)) = ptr0; return ptr; } #define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0) // pointers to allocation functions, initially set to default typedef void* (/*CV_CDECL*/ *AllocFunc)(int size, void* userdata); typedef int (/*CV_CDECL*/ *FreeFunc)(void* pptr, void* userdata); static AllocFunc p_cvAlloc = defaultAlloc; static FreeFunc p_cvFree = defaultFree; static void* p_cvAllocUserData = 0; inline bool cvFree_( void* ptr ) { if( ptr ) { int status = p_cvFree( ptr, p_cvAllocUserData ); if( status < 0 ) return false ; } return true ; } /* finds sequence element by its index */ CVLIB_DECLSPEC char* getSeqElem( const Sequence *seq, int index ) ; /* pushes element to the sequence */ CVLIB_DECLSPEC char* seqPush( Sequence *seq, const void *element ) ; /* pops the last element out of the sequence */ CVLIB_DECLSPEC int seqPop( Sequence *seq, void *element ) ; /* recycles a sequence block for the further use */ CVLIB_DECLSPEC int freeSeqBlock( Sequence *seq, int in_front_of ) ; /* constructs sequence from array without copying any data. the resultant sequence can't grow above its initial size */ CVLIB_DECLSPEC Sequence* makeSeqHeaderForArray( int seq_flags, int header_size, int elem_size, void *array, int total, Sequence *seq, SeqBlock * block ) ; CVLIB_DECLSPEC int sliceLength( Slice slice, const Sequence* seq ) ; /* returns the current reader position */ CVLIB_DECLSPEC int getSeqReaderPos( SeqReader* reader ) ; /* Adds several new elements to the end of sequence */ CVLIB_DECLSPEC void seqPushMulti( Sequence* seq, const void* elements, int count, int in_front=0 ); /* removes several elements from the end of sequence */ CVLIB_DECLSPEC char* seqPushFront( Sequence *seq, const void *element ); CVLIB_DECLSPEC void seqPopMulti( Sequence *seq, void *_elements, int count, int front=0 ) ; CVLIB_DECLSPEC void clearSeq(Sequence *seq); CVLIB_DECLSPEC void seqPopFront( Sequence* seq, void* element); CVLIB_DECLSPEC char* seqInsert( Sequence *seq, int before_index, const void *element ); CVLIB_DECLSPEC void seqInsertSlice( Sequence* seq, int index, const Arr* from_arr ); CVLIB_DECLSPEC void seqRemove( Sequence *seq, int index ); CVLIB_DECLSPEC void seqRemoveSlice( Sequence* seq, Slice slice ); /* sets reader position to given absolute or relative (relatively to the current one) position */ CVLIB_DECLSPEC int setSeqReaderPos( SeqReader* reader, int index, int is_relative = 0 ) ; CVLIB_DECLSPEC int changeSeqBlock( void* _reader, int direction ); /*=====================================Memory Functions=========================================*/ /****************************************Sequence Operations*************************************/ /****************************************************************************************/ /* Operations on sequences */ /****************************************************************************************/ #define CVLIB_SEQ_ELEM( seq, elem_type, index ) \ /* assert gives some guarantee that <seq> parameter is valid */ \ ( assert(sizeof((seq)->first[0]) == sizeof(SeqBlock) && \ (seq)->elem_size == sizeof(elem_type)), \ (elem_type*)((seq)->first && (unsigned)index < \ (unsigned)((seq)->first->count) ? \ (seq)->first->data + (index) * sizeof(elem_type) : \ getSeqElem( (Sequence*)(seq), (index) ))) #define CVLIB_GET_SEQ_ELEM( elem_type, seq, index ) CVLIB_SEQ_ELEM( (seq), elem_type, (index) ) /* add element to sequence: */ #define CVLIB_WRITE_SEQ_ELEM_VAR( elem_ptr, writer ) \ { \ if( (writer).ptr >= (writer).block_max ) \ { \ createSeqBlock( &writer); \ } \ memcpy((writer).ptr, elem_ptr, (writer).seq->elem_size);\ (writer).ptr += (writer).seq->elem_size; \ } /* Move reader position backward: */ #define CVLIB_PREV_SEQ_ELEM( elem_size, reader ) \ { \ if( ((reader).ptr -= (elem_size)) < (reader).block_min ) \ { \ changeSeqBlock( &(reader), -1 ); \ } \ } /* read element and move read position forward: */ #define CVLIB_READ_SEQ_ELEM( elem, reader ) \ { \ assert( (reader).seq->elem_size == sizeof(elem)); \ memcpy( &(elem), (reader).ptr, sizeof((elem))); \ CVLIB_NEXT_SEQ_ELEM( sizeof(elem), reader ) \ } /* read element and move read position backward: */ #define CVLIB_REV_READ_SEQ_ELEM( elem, reader ) \ { \ assert( (reader).seq->elem_size == sizeof(elem)); \ memcpy(&(elem), (reader).ptr, sizeof((elem))); \ CVLIB_PREV_SEQ_ELEM( sizeof(elem), reader ) \ } #define CVLIB_READ_CHAIN_POINT( _pt, reader ) \ { \ (_pt) = (reader).pt; \ if( (reader).ptr ) \ { \ CVLIB_READ_SEQ_ELEM( (reader).code, (reader)); \ assert( ((reader).code & ~7) == 0 ); \ (reader).pt.x += (reader).deltas[(int)(reader).code][0]; \ (reader).pt.y += (reader).deltas[(int)(reader).code][1]; \ } \ } #define CVLIB_CURRENT_POINT( reader ) (*((vec2i*)((reader).ptr))) #define CVLIB_PREV_POINT( reader ) (*((vec2i*)((reader).prev_elem))) #define CVLIB_READ_EDGE( pt1, pt2, reader ) \ { \ assert( sizeof(pt1) == sizeof(CvPoint) && \ sizeof(pt2) == sizeof(CvPoint) && \ reader.seq->elem_size == sizeof(CvPoint)); \ (pt1) = CVLIB_PREV_POINT( reader ); \ (pt2) = CVLIB_CURRENT_POINT( reader ); \ (reader).prev_elem = (reader).ptr; \ CVLIB_NEXT_SEQ_ELEM( sizeof(CvPoint), (reader)); \ } CVLIB_DECLSPEC void* alloc( int size ) ; CVLIB_DECLSPEC Sequence* createSeq( int seq_flags, int header_size, int elem_size, MemStorage * storage ) ; CVLIB_DECLSPEC int createSeqBlock( SeqWriter * writer ) ; CVLIB_DECLSPEC int insertNodeIntoTree( void* _node, void* _parent, void* _frame ) ; CVLIB_DECLSPEC int setSeqBlockSize( Sequence *seq, int delta_elements ) ; CVLIB_DECLSPEC int startAppendToSeq( Sequence *seq, SeqWriter * writer ) ; CVLIB_DECLSPEC int startReadSeq( const Sequence *seq, SeqReader * reader, int reverse=0 ) ; CVLIB_DECLSPEC int startWriteSeq( int seq_flags, int header_size, int elem_size, MemStorage * storage, SeqWriter * writer ) ; CVLIB_DECLSPEC Rect boundingRect( Arr* array, int update ) ; //SeqWiriter funcs /* calls icvFlushSeqWriter and finishes writing process */ CVLIB_DECLSPEC Sequence* endWriteSeq( SeqWriter * writer ) ; CVLIB_DECLSPEC int flushSeqWriter( SeqWriter * writer ) ; CVLIB_DECLSPEC int growSeq( Sequence *seq, int in_front_of ) ; CVLIB_DECLSPEC int goNextMemBlock( MemStorage * storage ) ; CVLIB_DECLSPEC int setAdd( Set* set, SetElem* element, SetElem** inserted_element ) ; //memstorage CVLIB_DECLSPEC MemStorage* createMemStorage( int block_size=0 ) ; /* creates empty set */ CVLIB_DECLSPEC Set* createSet( int set_flags, int header_size, int elem_size, MemStorage * storage ) ; /* creates child memory storage */ CVLIB_DECLSPEC MemStorage* createChildMemStorage( MemStorage * parent ) ; /* initializes allocated storage */ CVLIB_DECLSPEC int initMemStorage( MemStorage* storage, int block_size ) ; CVLIB_DECLSPEC int saveMemStoragePos( const MemStorage * storage, MemStoragePos * pos ) ; CVLIB_DECLSPEC int restoreMemStoragePos( MemStorage * storage, MemStoragePos * pos ) ; CVLIB_DECLSPEC int clearMemStorage( MemStorage * storage ) ; CVLIB_DECLSPEC int releaseMemStorage( MemStorage** storage ) ; CVLIB_DECLSPEC void* memStorageAlloc( MemStorage* storage, int size ) ; CVLIB_DECLSPEC int destroyMemStorage( MemStorage* storage ) ; CVLIB_DECLSPEC int iMemCopy( double **buf1, double **buf2, double **buf3, int *b_max ); }
6a7519ec552748970dfcfabc23d832804b45c870
1de937933b839b16578bdfbf5459a7a35cc42e1e
/sources/Common/Log.hpp
10a267833c695e56593f4745f76f317927a31551
[]
no_license
benit8/Cpp-Template
d294e9607aab0d68c0d312f98b74af1271d13cd4
585e58c908d4ffa4bea39181a14d84018693789b
refs/heads/master
2023-06-12T18:03:49.121599
2021-07-04T15:53:24
2021-07-04T15:53:24
269,222,323
0
0
null
null
null
null
UTF-8
C++
false
false
2,244
hpp
Log.hpp
/* ** {{ PROJECT_NAME }}, {{ YEAR }} ** Benoît Lormeau <blormeau@outlook.com> ** Common / Log.hpp */ #pragma once // ----------------------------------------------------------------------------- #include "fmt/core.h" #include <iostream> // ----------------------------------------------------------------------------- class Log { public: enum Level { Trace, Debug, Info, Notice, Warning, Error, Critical, Alert, Emergency, }; public: template <typename S, typename... Args> static void trace(const S& f, Args&&... args) { return log(Level::Trace, f, fmt::make_args_checked<Args...>(f, args...)); } template <typename S, typename... Args> static void debug(const S& f, Args&&... args) { return log(Level::Debug, f, fmt::make_args_checked<Args...>(f, args...)); } template <typename S, typename... Args> static void info(const S& f, Args&&... args) { return log(Level::Info, f, fmt::make_args_checked<Args...>(f, args...)); } template <typename S, typename... Args> static void notice(const S& f, Args&&... args) { return log(Level::Notice, f, fmt::make_args_checked<Args...>(f, args...)); } template <typename S, typename... Args> static void warning(const S& f, Args&&... args) { return log(Level::Warning, f, fmt::make_args_checked<Args...>(f, args...)); } template <typename S, typename... Args> static void error(const S& f, Args&&... args) { return log(Level::Error, f, fmt::make_args_checked<Args...>(f, args...)); } template <typename S, typename... Args> static void critical(const S& f, Args&&... args) { return log(Level::Critical, f, fmt::make_args_checked<Args...>(f, args...)); } template <typename S, typename... Args> static void alert(const S& f, Args&&... args) { return log(Level::Alert, f, fmt::make_args_checked<Args...>(f, args...)); } template <typename S, typename... Args> static void emergency(const S& f, Args&&... args) { return log(Level::Emergency, f, fmt::make_args_checked<Args...>(f, args...)); } static Level level() { return s_level; } static void set_level(Level level) { s_level = level; } private: static void log(Level level, fmt::string_view format, fmt::format_args args); private: static Level s_level; };
e45951b6d08ada8b608ff4619027fddb8980655b
53fc99d472e2e66e57568e338e1897bc29224fa4
/Queue/deque.cpp
c5ada3572a0cd10fff29d57d952360cd700e2ba3
[]
no_license
SeMyeongJin/DataStructure
ca55b88fbc1a602a438e703a1e05bcd24c96d35f
4cf718fc8b0f1cf5c06633c93f917473f79b3d9e
refs/heads/master
2020-04-22T18:08:05.008994
2019-10-31T17:20:39
2019-10-31T17:20:39
170,567,200
0
0
null
null
null
null
UTF-8
C++
false
false
1,906
cpp
deque.cpp
#include <stdio.h> #include <stdlib.h> #include "deque.h" void DequeInit(Deque* pDeque) { pDeque->pHead = NULL; pDeque->pTail = NULL; } int DequeIsEmpty(Deque* pDeque) { if (pDeque->pHead == NULL) return TRUE; else return FALSE; } void DequeAddFirst(Deque* pDeque, Data element) { DequeNode* pNewNode = (DequeNode*)malloc(sizeof(DequeNode)); pNewNode->data = element; pNewNode->pRLink = pDeque->pHead; if (DequeIsEmpty(pDeque)) pDeque->pTail = pNewNode; else pDeque->pHead->pLLink = pNewNode; pNewNode->pLLink = NULL; pDeque->pHead = pNewNode; } void DequeAddLast(Deque* pDeque, Data element) { DequeNode* pNewNode = (DequeNode*)malloc(sizeof(DequeNode)); pNewNode->data = element; pNewNode->pLLink = pDeque->pTail; if (DequeIsEmpty(pDeque)) pDeque->pHead = pNewNode; else pDeque->pTail->pRLink = pNewNode; pNewNode->pRLink = NULL; pDeque->pTail = pNewNode; } Data DequeRemoveFirst(Deque* pDeque) { DequeNode* pRNode = pDeque->pHead; Data data; if(DequeIsEmpty(pDeque)){ printf("Deque Memory Error\n"); exit(-1); } data = pDeque->pHead->data; pDeque->pHead = pDeque->pHead->pRLink; free(pRNode); if (pDeque->pHead == NULL) pDeque->pTail = NULL; else pDeque->pHead->pLLink = NULL; return data; } Data DequeRemoveLast(Deque* pDeque) { DequeNode* pRNode = pDeque->pTail; Data data; if (DequeIsEmpty(pDeque)) { printf("Deque Memory Error\n"); exit(-1); } data = pDeque->pTail->data; pDeque->pTail = pDeque->pTail->pLLink; free(pRNode); if (pDeque->pTail == NULL) pDeque->pHead = NULL; else pDeque->pTail->pRLink = NULL; return data; } Data DequeGetFirst(Deque* pDeque) { if (DequeIsEmpty(pDeque)) { printf("Deque Memory Error\n"); exit(-1); } return pDeque->pHead->data; } Data DequeGetLast(Deque* pDeque) { if (DequeIsEmpty(pDeque)) { printf("Deque Memory Error\n"); exit(-1); } return pDeque->pTail->data; }
4b10a3b3384193bf6ab7ac04639f9d18642896ba
6af4068cf5ce7bf3f198c1c61b2507d723b838ad
/StringAlgorithms/buildSuffixArray.cpp
5802980a20d8e41b3cf9b9b646d0a5b6ea59e49e
[]
no_license
monk78/Standard-Algorithms
87a06b8614b8bf73d56eaa6f7fda1507944a98db
ad31a7adb2560150509a6476878cfdadc7a5fdc4
refs/heads/master
2023-02-26T10:41:29.570831
2021-01-29T12:45:00
2021-01-29T12:45:00
290,782,763
0
0
null
null
null
null
UTF-8
C++
false
false
2,009
cpp
buildSuffixArray.cpp
/* Author:monk78 * Morris-Pratt */ #include<bits/stdc++.h> using namespace std; typedef vector<int>Vl; typedef pair<int,int>PII; typedef vector<PII>Vll; #define S second #define F first #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end));i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define mp make_pair #define ms(x,y) memset(x,y,sizeof(x)) #define pb push_back #define mod 1000000009 #define MAX 100005 #define f(i,a,b) for(int i=(a);i<(b);i++) #define rf(i,a,b) for(int i=(a);i>=b;i--) #define sl(n) scanf("%lld",&n) #define pl(n) printf("%lld ",n) struct Suffix{ int index; int rank[2]; }; int cmp(Suffix a,Suffix b){ return (a.rank[0] == b.rank[0])? (a.rank[1] < b.rank[1] ?1: 0): (a.rank[0] < b.rank[0] ?1: 0); } vector<int>build(string txt) { int n=txt.length(); Suffix arr[n]; for(int i=0;i<n;i++){ arr[i].index=i; arr[i].rank[0]=txt[i]-'a'; arr[i].rank[1]=((i+1)<n)?(txt[i+1]-'a'):-1; } sort(arr,arr+n,cmp); int ind[n]; for(int k=4;k<2*n;k=k*2) { int rank=0; int prevrank=arr[0].rank[0]; arr[0].rank[0]=rank; ind[arr[0].index]=0; for(int i=1;i<n;i++) { if(arr[i].rank[0]==prevrank && arr[i].rank[1]==arr[i-1].rank[1]) { prevrank=arr[i].rank[0]; arr[i].rank[0]=rank; } else { prevrank=arr[i].rank[0]; arr[i].rank[0]=++rank; } ind[arr[i].index]=i; } for(int i=0;i<n;i++) { int next=arr[i].index+ k/2; arr[i].rank[1]=(next<n)?arr[ind[next]].rank[0]:-1; } sort(arr,arr+n,cmp); } vector<int>vec; for(int i=0;i<n;i++){ vec.pb(arr[i].index); } return vec; } //lps---kasai vector<int>LCP(string str,vector<int>sa){ int n=sa.size(); int k=0; vector<int>lcp(n,0); vector<int>rank(n,0); for(int i=0;i<n;i++)rank[sa[i]]=i; for(int i=0;i<n;i++,k?k--:0){ if(rank[i]==n-1){ } } return lcp; } signed main(){ string str; cin>>str; Vl ans=build(str); for(auto it:ans)cout<<it<<" "; return 0; }
caac0ac5a0629db75f8cd838249d0cc38c9bdb19
ab7c7d032a30f0c82d5544bc3c759fd710888646
/array/find_tapping_water.cpp
c7d4fb1959d919cb3f37a362da2acfaf7e65692c
[]
no_license
pratikdas44/codingPratice_cpp
5f3df6a817a3f31354fac83b0722db98d9e07dd0
c52513f988715b758c8b117dde58a7970615ad0d
refs/heads/master
2021-06-13T13:12:54.580317
2021-03-09T13:58:48
2021-03-09T13:58:48
166,235,198
0
0
null
null
null
null
UTF-8
C++
false
false
1,546
cpp
find_tapping_water.cpp
//find number of units that can be filled. //Only cell with both left and right cell higher than it can store water(u know) #include <bits/stdc++.h> using namespace std; int findWater(int A[], int n){ int sum = 0; int s1 = 0; int i = 1; while(i < n){ while(A[i] < A[s1]){ i++; } for(int k = s1; k < i; k++){ sum += (std::min(A[s1], A[i]) - A[k]); A[k] += (std::min(A[s1], A[i]) - A[k]); } while(A[s1] <= A[i] && i < n){ A[s1] = A[i]; s1++; i++; } } return sum; } int main() { int t; cin >> t; while(t--) { int n; cin >>n ; int arr[n]; for(int i=0;i<n;i++) { cin >> arr[i]; } // left[i] contains height of tallest bar to the // left of i'th bar including itself int left[n]; // Right [i] contains height of tallest bar to // the right of ith bar including itself int right[n]; // Initialize result int water = 0; // Fill left array left[0] = arr[0]; for (int i = 1; i < n; i++) left[i] = max(left[i-1], arr[i]); // Fill right array right[n-1] = arr[n-1]; for (int i = n-2; i >= 0; i--) right[i] = max(right[i+1], arr[i]); // Calculate the accumulated water element by element // consider the amount of water on i'th bar, the // amount of water accumulated on this particular // bar will be equal to min(left[i], right[i]) - arr[i] . for (int i = 0; i < n; i++) water += min(left[i],right[i]) - arr[i]; cout << water << "\n"; } return 0; }
402ce890f682fda9a22d40c51d1a08237ac168ed
c993ecac7b8993edd915b45a2ae16dd56b6f7608
/TextDetector/ImageBinarization.h
1626a4ea20ecc7ba69d4a5bbf6a0cd8a0326b25f
[]
no_license
minhnd3796/fti_id
0f06c39ed333713394026578792b6fe930cc871b
0ff361d97282e9beb32a000cb4c449962f682593
refs/heads/master
2020-03-17T08:34:13.652174
2018-05-15T09:15:20
2018-05-15T09:15:20
128,859,444
1
0
null
null
null
null
UTF-8
C++
false
false
962
h
ImageBinarization.h
/* * Implements binarization of documents * Check this paper: DOI 10.1007/s10032-010-0142-4 * Christian Wolf, Jean-Michel Jolion and Francoise Chassaing. * Text Localization, Enhancement and Binarization in Multimedia Documents. * International Conference on Pattern Recognition (ICPR), * volume 4, pages 1037-1040, 2002. */ #ifndef IMAGEBINARIZATION_H #define IMAGEBINARIZATION_H #include "opencv2/opencv.hpp" #include "opencv2/imgproc.hpp" #include <time.h> enum NiblackVersion { NIBLACK=0, SAUVOLA, WOLFJOLION, }; class ImageBinarization { public: ImageBinarization(); virtual ~ImageBinarization(); void convertToBin(cv::Mat &bin, cv::Mat &image); void calcLocalStats(double &res, cv::Mat &im, cv::Mat &map_m, cv::Mat &map_s, int &winx, int &winy); void applyNiblackSauvolaWolfJolion(cv::Mat &im, cv::Mat &output, NiblackVersion version =WOLFJOLION, double k=0.5, double dR = 128); }; #endif // IMAGEBINARIZATION_H
08f6804329b6c1126964cbd171e53fe84356b2ec
4483bfc80fc862abda43d35ccf977411edc3a31f
/tsp_with_single_optimal/TSP.cpp
35f21ec6712a3a444b2f4a301ee11a795e0f6696
[]
no_license
dapu81000/Optimal-Approximation-for-TSP-and-NSGA2
3546cfad117d9a66e557b0755a581e980ca3bcc7
244cbd3a7e2d03e993c7745decf7f63923582a1a
refs/heads/main
2023-07-18T10:31:43.599717
2021-08-30T09:05:59
2021-08-30T09:05:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,136
cpp
TSP.cpp
#include<bits/stdc++.h> #include"GA.cpp" #include"SA.cpp" #include"Brute_Force.cpp" #include"ACO.cpp" using namespace std; class TSP_solution { public: TSP_solution(vector<vector<int>> graph) :Graph(graph) {} vector<int> TSP() { /*Brute_Force Brute_Force_solver(Graph); Brute_Force_solver.Force_solution(); return Brute_Force_solver.goodOrder;*/ int max_round=5000; SA SA_solver(Graph,max_round); SA_solver.main_algorithm(max_round); //return SA_solver.goodOrder; ACO ACO_solver(Graph, 20); ACO_solver.init(); ACO_solver.Round(0); //return ACOsolver.goodPath; GA GA_solver(Graph,20); GA_solver.Init(); GA_solver.update_candidate(0); cout<<"SA result : "<<SA_solver.goodOrderScore<<"\n"; for(int num:SA_solver.goodOrder) cout<<num<<" "; cout<<endl; cout<<"ACO result : "<<ACO_solver.goodPathLength<<"\n"; for(int num:ACO_solver.goodPath) cout<<num<<" "; cout<<endl; cout<<"GA result : "<<GA_solver.route_length(GA_solver.candidate_route[0].first)<<"\n"; for(int num:GA_solver.candidate_route[0].first) cout<<num<<" "; cout<<endl; return GA_solver.candidate_route[0].first; } vector<vector<int>> Graph; }; int main() { const int node_num = 10; default_random_engine generator = default_random_engine(time(NULL)); uniform_int_distribution<int> distribution_int(0,2*node_num-1); auto rand_int=bind(distribution_int,generator); vector<vector<int>> graph(node_num, vector<int>(node_num)); for (int i = 0; i < node_num; i++) { for (int j = 0; j < node_num; j++) { if (i == j) graph[i][j] = 0; else if (i > j)graph[i][j] = graph[j][i]; else graph[i][j] = rand_int(); } } for (int i = 0; i < node_num; i++) { for (int j = 0; j < node_num; j++) { cout << graph[i][j] << " "; } cout << endl; } TSP_solution solve(graph); solve.TSP(); }
e030af93db85479b7dfbea6ceabbf88b5b95aa5a
433a307109c52de00e1887e425b782f0aba25efe
/hw04/application/api/gateways/BaseGateway.h
6398471c1d47ba1f5ef0ae32ec30a088142c0d51
[]
no_license
YeslieSnayder/pss
7fc9d19ede51f5077cf9c1b66d2fd122e2e0252a
fcacab1b467c00d1d576996655f8d61540d9a418
refs/heads/master
2023-04-13T01:44:10.303830
2021-04-26T19:25:41
2021-04-26T19:25:41
334,693,118
0
0
null
null
null
null
UTF-8
C++
false
false
4,245
h
BaseGateway.h
// // Created by yesliesnayder on 23.04.2021. // #ifndef PSS_BASEGATEWAY_H #define PSS_BASEGATEWAY_H #include "pistache/endpoint.h" using namespace Pistache; class BaseGateway { static string get_json_value(string value) { char t = value[value.size()-1]; while (t == ' ') { value.pop_back(); t = value[value.size()-1]; } bool is_not_number = false; bool has_dot = false; bool has_sign = (value[0] == '-' || value[0] == '+'); for (int i = (has_sign) ? 1 : 0; i < value.size(); i++) { char& n = value[i]; if (n == '.' && !has_dot) has_dot = true; else if (n == '.' && has_dot || !isdigit(n)) { is_not_number = true; break; } } return (is_not_number && value != "true" && value != "false") ? "\"" + value + "\"" : value; } public: static string convert_to_right_json(string json_str) { string correct_json; string value; bool is_key = false, is_value = false; for (int i = 0; i < json_str.size(); i++) { char &c = json_str[i]; if (!is_value && c == '\"') return json_str; if (c == '{') { string s_obj; char t = c; int count = i, braces_num = 1; while (t != '}' || braces_num != 0) { t = json_str[++count]; if (t == '{' || t == '[') braces_num++; else if (t == '}' || t == ']') braces_num--; s_obj += t; } s_obj.pop_back(); correct_json += "{" + convert_to_right_json(s_obj) + "}"; i = count; is_key = false; is_value = true; value.clear(); continue; } else if (c == '[') { string s_arr; char t = c; int count = i, braces_num = 1; while (t != ']' || braces_num != 0) { t = json_str[++count]; if (t == '{' || t == '[') braces_num++; else if (t == '}' || t == ']') braces_num--; s_arr += t; } s_arr.pop_back(); correct_json += "[" + convert_to_right_json(s_arr) + "]"; i = count; is_key = false; is_value = true; value.clear(); continue; } if (isspace(c) && (!is_key && !is_value || is_key && is_value)) continue; else if (!is_key && !is_value) { // key begin is_key = true; correct_json += '\"'; } else if (is_key && c == ':') { // key end char t = correct_json[correct_json.size() - 1]; while (t == ' ') { correct_json.pop_back(); t = correct_json[correct_json.size() - 1]; } correct_json += '\"'; is_value = true; } else if (is_value && c != ',') { // value begin value += c; is_key = false; continue; } else if (is_value && c == ',') { // value end correct_json += get_json_value(value); value.clear(); is_value = false; } correct_json += c; } if (!value.empty()) { correct_json += get_json_value(value); value.clear(); } return correct_json; } static void checkRequest(const Rest::Request &request, Http::Method method, bool requiredBody = false) { if (request.method() != method) throw invalid_argument("Request method is incorrect"); if (requiredBody && request.headers().tryGet<Http::Header::ContentType>() == nullptr) throw invalid_argument("Content type has to be explicitly determine"); if (requiredBody && request.body().empty()) throw invalid_argument("Body is empty"); } }; #endif //PSS_BASEGATEWAY_H
673f6367cb588a39661654d63cabfda85a09d97d
4eb606bc2c42ea64264bd8b160db4d81919b7850
/Lesson07/Total.cpp
1520df25e6073d68bdea763bae439c0be02bddc7
[]
no_license
mjohnson9/cist2362
23ac3ea43c253c8a7e9539d348d6a6da1068c482
294ac0cbbbd6d7007088c1fcf33a33fcc8ba54e1
refs/heads/master
2022-01-16T16:34:14.194118
2019-07-07T14:43:07
2019-07-07T14:43:07
166,576,352
0
0
null
null
null
null
UTF-8
C++
false
false
3,540
cpp
Total.cpp
// Copyright 2019 Michael Johnson #include <cmath> #include <iostream> #include "../common.h" namespace mjohnson { namespace total { // FORWARD DECLARATIONS // Total asks the user for n values and then returns the total of the values // that the user provided. template <class T> T Total(T n); // ValidateNotNegative validates that input by the user is not negative. It // displays an error message and returns false if the value is negative. It // returns true otherwise. bool ValidateInt64NotNegative(int64_t n); bool ValidateDoubleNotNegative(double n); // Unfortunately, these functions can't be a template. The compiler won't infer // the type when it's passed as a reference to another function. In fact, it // can't even handle overloads. // MAIN FUNCTIONS int Run() { // Add the computer's locale to cout. This lets us do thousands separators and // decimal points in the locale of the user. std::cout.imbue(std::locale("")); do { { mjohnson::common::ClearScreen(); const auto n = mjohnson::common::RequestInput<int64_t>( "How many numbers would you like to total? ", ValidateInt64NotNegative); auto total = Total(n); std::cout << "The total of the numbers you entered is: " << total << std::endl << std::endl; } { const auto n = mjohnson::common::RequestInput<double>( "How many decimal numbers would you like to total? ", ValidateDoubleNotNegative); auto total = Total(n); std::cout << "The total of the numbers you entered is: " << total << std::endl << std::endl; } } while (mjohnson::common::RequestContinue()); return 0; } // UTILITY FUNCTIONS template <class T> T Total(T n) { T runningTotal = 0; for (T i = 0; i < n; // NOLINT(clang-analyzer-security.FloatLoopCounter) i++) { auto userValue = mjohnson::common::RequestInput<T>( "Enter a number to be added to the total: ", nullptr); runningTotal += userValue; } return runningTotal; } bool ValidateInt64NotNegative(int64_t n) { if (std::signbit(n)) { // signbit returns true when a number is negative std::cout << "You cannot total a negative number of numbers." << std::endl << std::endl; return false; } if (n < 2) { std::cout << "You must total at least 2 numbers." << std::endl << std::endl; return false; } return true; } bool ValidateDoubleNotNegative(double n) { if (std::signbit(n)) { // signbit returns true when a number is negative std::cout << "You cannot total a negative number of numbers." << std::endl << std::endl; return false; } if (n < 2) { std::cout << "You must total at least 2 numbers." << std::endl << std::endl; return false; } return true; } // UNIT TESTING // RunUnitTests runs the program's unit tests and returns the success or failure // of those unit tests as a boolean. bool RunUnitTests() { bool success = true; return success; } } // namespace total } // namespace mjohnson int main(int argc, char *argv[]) { bool run_unit_tests; if (!mjohnson::common::ParseArgs(argc, argv, &run_unit_tests)) { return 1; } if (run_unit_tests) { const bool result = mjohnson::total::RunUnitTests(); if (!result) { std::cout << "Unit tests failed." << std::endl; return 1; } std::cout << "Unit tests passed." << std::endl; return 0; } return mjohnson::total::Run(); } // Grade: 100
1301ac03cd182262f0c7a7546c150dbf689761c5
3dd2eb78a37315006b95c85c701fa0d963858df5
/Arduino/MiniPro_Reles/MiniPro_Reles.ino
2c214ec4f02a68857df45b9d2407919aeef1c858
[ "MIT" ]
permissive
cgodoi/JAMBAR
45e1b396aa371e67c379c58d8d389e449555776a
eac659eb837b23a1b5c482a1e1acfcf9861f9549
refs/heads/master
2021-01-20T22:28:15.651346
2016-07-28T00:17:19
2016-07-28T00:17:19
63,100,598
0
0
null
null
null
null
UTF-8
C++
false
false
6,101
ino
MiniPro_Reles.ino
//Definir LED,s que maneja este HIJO String strLedControlados ="SWICH;ESTADO;LED01;LED02;LED03;LED04;LED05;LED06;LED07;LED08;SWICH0;SWICH1"; int incomingByte = 0; // para el byte leido String strRFMensaje=""; char c; String strMensajeEntrada ="MRF"; //mensaje RF desde MADRE String strMensajeSalida ="HRF"; //mensaje de hijo a madre (central) String LEDprocesar=""; int intAccion = 0; int blnSwitchNo = 0; //indicador si sistema permite uso manual, osea switch de pared 0 si permite, 1 no permite byte hayCambios =0; //Variables int totLuces = 8; int relesChan1[] = {30,32,34,36,38,40,42,44}; int relesChan2[] = {31,33,35,37,39,41,43,45}; int paredSw[] = {22,23,24,25,26,27,28,29}; int swParedEstadoActual[] = {0,0,0,0,0,0,0,0}; int swParedEstadoAnterior[] = {0,0,0,0,0,0,0,0}; #define intLargoRF 30 void setup() { Serial3.begin(9600); // abre el puerto serie a 9600 bps for (byte idLuz = 0; idLuz < totLuces; idLuz++) { pinMode(relesChan1[idLuz], OUTPUT); pinMode(relesChan2[idLuz], OUTPUT); pinMode(paredSw[idLuz],INPUT); digitalWrite(relesChan2[idLuz],HIGH); } //INICIALIZA ESTADO INICIAL DE SW DE PARED for (byte idLuz = 0; idLuz < totLuces; idLuz++) { swParedEstadoAnterior[idLuz] = digitalRead(paredSw[idLuz]); if (swParedEstadoAnterior[idLuz] == 0 ) { digitalWrite(relesChan1[idLuz],HIGH); }else { digitalWrite(relesChan1[idLuz],LOW); } } } void loop() { // envia datos solamente cuando recibe datos if (blnSwitchNo == 0){ for (int idLuz = 0; idLuz < totLuces; idLuz++) { swParedEstadoActual[idLuz] = digitalRead(paredSw[idLuz]); } /* for (int idLuz = 0; idLuz < totLuces; idLuz++) { Serial3.print("Estado SENSOR SWITCH NRO "); Serial3.print(idLuz +1 ); Serial3.print(" : "); Serial3.println(swParedEstadoActual[idLuz]); }*/ for (int idLuz = 0; idLuz < totLuces; idLuz++) { if (swParedEstadoActual[idLuz] != swParedEstadoAnterior[idLuz]) { Serial3.print("Estado Actual: "); Serial3.print(swParedEstadoActual[idLuz]); Serial3.print(" / Estado anterior:"); Serial3.println(swParedEstadoAnterior[idLuz]); if (digitalRead(relesChan1[idLuz]) == LOW) { digitalWrite(relesChan1[idLuz],HIGH); }else { digitalWrite(relesChan1[idLuz],LOW); } InformaEstadoaCentral(idLuz); hayCambios = 1; swParedEstadoAnterior[idLuz] = swParedEstadoActual[idLuz] ; } } if (hayCambios == 1) { // InformaEstadoaCentral(); hayCambios = 0; } } if (Serial3.available() > 0) { c= Serial3.read(); if (c == '\n' ){ strRFMensaje+="Captado"; char mensajeRF[intLargoRF] ; strRFMensaje.toCharArray(mensajeRF,intLargoRF); // Serial3.println(mensajeRF); //Valida mensaje y procese a realizar accion if (BlnMensajeEsValido()==true){ subEjecutaAccion(); } strRFMensaje =""; }else{ strRFMensaje+= c; } } } //Valida si mensaje es valido y contiene elementos que procesa este modulo (strLedControlados) boolean BlnMensajeEsValido(){ boolean blnValido = false; //Mesaje es de Madre //Serial3.println(strRFMensaje.indexOf(strMensajeEntrada)); if (strRFMensaje.indexOf(strMensajeEntrada)!=-1){ // Serial3.println(strRFMensaje.substring(3,8)); // Serial3.println(strRFMensaje.substring(9,10)); LEDprocesar = strRFMensaje.substring(3,8); //Valido si mensaje trae informacion de LED valido if (strLedControlados.indexOf(LEDprocesar)!=-1){ intAccion = string2int(strRFMensaje.substring(9,10)); blnValido = true; //mensaje trae informacion de led de este modulo/hijo }else{ blnValido = false;//mensaje tiene un led o control no valido para este modulo/hijo } } else { blnValido=false;//Mensaje no contiene formato estandar } return blnValido; } void subEjecutaAccion(){ int relayTrabajar = 0; int luzTrabajar = 0; //Mensaje es de Central y pide estado, entrega estado y termina ciclo if (strRFMensaje.indexOf("ESTADO")!=-1){ InformaEstadoaCentral(-1); return; } if (strRFMensaje.indexOf("SWICH0")!=-1){ blnSwitchNo = 0; Serial3.println("SWICH 0 OK "); return; } if (strRFMensaje.indexOf("SWICH1")!=-1){ blnSwitchNo = 1; Serial3.println("SWICH 1 OK "); return; } //Determina relay a trabajar luzTrabajar = string2int(LEDprocesar.substring(3,5))-1; relayTrabajar = relesChan1[luzTrabajar]; if (relayTrabajar==0){ if (strLedControlados.indexOf("SWICH")!=-1){ //Permite o no uso de switch de pared blnSwitchNo = intAccion; } }else{ if (intAccion==1){ Serial3.println("PRENDO " + luzTrabajar); if (relayTrabajar!=0){ digitalWrite(relayTrabajar,HIGH); } } else if(intAccion==0){ Serial3.println("APAGO " + luzTrabajar); if (relayTrabajar!=0){ digitalWrite(relayTrabajar,LOW); } } intAccion = -1; LEDprocesar=""; } } void InformaEstadoaCentral(int luzfecta) { if (luzfecta == -1){ for (int idLuz = 0; idLuz < totLuces; idLuz++) { delay(20); if (digitalRead(relesChan1[idLuz]) == HIGH){ Serial3.println(strMensajeSalida+"LED0"+String(idLuz)+"=1"); }else{ Serial3.println(strMensajeSalida+"LED0"+String(idLuz)+"=0"); } } }else{ if (digitalRead(relesChan1[luzfecta]) == HIGH){ Serial3.println(strMensajeSalida+"LED0"+String(luzfecta)+"=1"); }else{ Serial3.println(strMensajeSalida+"LED0"+String(luzfecta)+"=0"); } } } int string2int(String string){ char cadena[string.length()+1]; string.toCharArray(cadena, string.length()+1); return atol(cadena); }
b6e5a72c678425ef164ee28be338feee5d0c7af3
5cc6a6d6da114b86ff3ec6cd1ba2f54538141607
/poker_ai/Strategy.hpp
67e290f4c0110c154e8373ca19b06330fafca23d
[]
no_license
louie0817/poker-ai
077ce514a6cdbe90f1442baa9628ea07694653a9
bf1d85acfab2e6c07f5d23a9a0b5d496aa86028b
refs/heads/master
2023-03-15T12:54:04.562351
2016-12-19T19:14:57
2016-12-19T19:14:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,341
hpp
Strategy.hpp
#ifndef STRATEGY_HPP #define STRATEGY_HPP #include <occi.h> #include <vector> #include "Logger.hpp" #include "Util.hpp" #include "PythonManager.hpp" class StrategyEvaluationDataProvider; class Strategy { friend class StrategyEvaluationDataProvider; public: void initialize( oracle::occi::Connection* con, PythonManager* pythonManager, bool loggingEnabled ); void assignNewStrategyId(); void loadById(unsigned int loadStrategyId); unsigned int generateFromRandom(unsigned int generation); void generateStrategyUnitDecisionProcedures(); std::vector<bool>* getChromosome(unsigned int strategyUnitId); unsigned int getStrategyId() const; unsigned int getGeneration() const; void setGeneration(unsigned int generation); void setTrialId(unsigned int trialId); void save(); ~Strategy(); const unsigned int strategyUnitCount = 4; private: struct ValueExpressionOperand { std::vector<bool> valueExpressionOperandBitString; unsigned int valueExpressionOperandBitStringLength; unsigned int valueExpressionOperandChromosomeStartIndex; unsigned int valueExpressionOperandId; }; struct ValueExpressionOperator { std::vector<bool> valueExpressionOperatorBitString; unsigned int valueExpressionOperatorBitStringLength; unsigned int valueExpressionOperatorChromosomeStartIndex; unsigned int valueExpressionOperatorId; }; struct ValueExpression { unsigned int valueExpressionSlotId; ValueExpressionOperand leftValueExpressionOperand; ValueExpressionOperator valueExpressionOperator; ValueExpressionOperand rightValueExpressionOperand; }; struct DecisionOperator { std::vector<bool> decisionOperatorBitString; unsigned int decisionOperatorBitStringLength; unsigned int decisionOperatorChromosomeStartIndex; unsigned int decisionOperatorId; }; struct AmountMultiplier { std::vector<bool> amountMultiplierBitString; unsigned int amountMultiplierBitStringLength; unsigned int amountMultiplierChromosomeStartIndex; unsigned int amountMultiplierId; }; struct DecisionTreeUnit { ValueExpression leftValueExpression; DecisionOperator decisionOperator; ValueExpression rightValueExpression; AmountMultiplier leftAmountMultiplier; AmountMultiplier rightAmountMultiplier; }; struct StrategyUnit { std::vector<bool> chromosome; std::string decisionProcedure; std::vector<DecisionTreeUnit> decisionTreeUnits; PyObject* compiledDecisionProcedure; }; void setDecisionTreeAttributes(unsigned int strategyUnitId); void generateDecisionProcedure(unsigned int strategyUnitId); std::string getDecisionTree(unsigned int strategyUnitId, unsigned int decisionTreeUnitId) const; void getChromosomeSection(std::vector<bool>* chromosome, unsigned int startIndex, unsigned int length, std::vector<bool>& destination); unsigned int getIdFromBitString(const std::vector<bool>& bitString) const; std::string getExpressionValueOperatorText(unsigned int expressionValueOperatorId) const; std::string getDecisionOperatorText(unsigned int decisionOperatorId) const; double getAmountMultiplierFromId(unsigned int amountMultiplierId) const; ValueExpression* getValueExpression(unsigned int strategyUnitId, unsigned int expId); std::string indent(unsigned int tabCount) const; const unsigned int valueExpressionOperandIdBitLength = 10; const unsigned int valueExpressionOperatorIdBitLength = 2; const unsigned int decisionOperatorBitLength = 3; const unsigned int amountMultiplierBitLength = 8; const unsigned int treeDepth = 8; const unsigned int valueExpressionBitLength = (2 * valueExpressionOperandIdBitLength) + valueExpressionOperatorIdBitLength; // 22 const unsigned int decisionTreeUnitBitLength = (2 * valueExpressionBitLength) + decisionOperatorBitLength + (2 * amountMultiplierBitLength); // 44 + 3 + 16 = 63 const unsigned int decisionTreeUnitSlots = (unsigned int) pow(2, treeDepth - 1) - 1; // 127 const unsigned int chromosomeBitLength = decisionTreeUnitBitLength * decisionTreeUnitSlots; // 63 * 127 = 8001 const unsigned int valueExpressionSlotIdCount = 2 * decisionTreeUnitSlots; // 254 unsigned int trialId = 0; unsigned int generation; unsigned int strategyId; std::vector<StrategyUnit> strategyUnits; PythonManager* pythonManager; oracle::occi::Connection* con; Logger logger; Util::RandomNumberGenerator randomNumberGenerator; }; #endif
755392aa646557a25bacbba4493837ded473710e
21b455fb30b6ae30ea79d67c77fc78b5199a7c97
/include/node0/SceneTreeHelper.h
79e7a3879210a8ed5bdd0c8698f8f9b03db6779a
[ "MIT" ]
permissive
xzrunner/node0
501ce7d17ba3715c7c1de9fead80c913493affd4
a597f360308bbdb6727efe2283968eb49843a8e5
refs/heads/master
2021-05-04T02:54:37.700056
2019-12-05T23:12:48
2019-12-05T23:12:48
120,367,576
0
0
null
null
null
null
UTF-8
C++
false
false
238
h
SceneTreeHelper.h
#pragma once #include "node0/typedef.h" #include <vector> namespace n0 { class SceneTreeHelper { public: static void GetPathToRoot(const SceneNodePtr& root, size_t end_id, std::vector<SceneNodePtr>& path); }; // SceneTreeHelper }
2a302c3b425cfbd5e5af43dbbf17847d39cf8f40
08960f0d6b945d15cb9c0f0ca6c191dcb4528025
/Animations/src/platform/PlatformWin32.cpp
cedbd5288a44d88083fe10fe355d9571bdf733f1
[]
no_license
ambrosiogabe/MathAnimation
ed2a84022531211906410c07190e475cab4ba744
c9feb9289c06a0195a0fa412d712e2e157ed6ac5
refs/heads/master
2023-09-04T05:33:54.508179
2023-08-19T17:18:08
2023-08-19T17:18:08
388,966,721
895
45
null
2023-08-19T17:18:10
2021-07-24T01:13:00
C++
UTF-8
C++
false
false
17,307
cpp
PlatformWin32.cpp
#ifdef _WIN32 #include "platform/Platform.h" #include "core.h" #include "core/Window.h" #define GLFW_EXPOSE_NATIVE_WIN32 #include <glfw/glfw3native.h> #undef GLFW_EXPOSE_NATIVE_WIN32 #include <io.h> #include <Windows.h> #include <shlobj_core.h> #ifdef min #undef min #endif namespace MathAnim { struct MemMapUserData { HANDLE fileHandle; HANDLE fileMappingHandle; }; namespace Platform { // --------------- Internal Functions --------------- static void wideToChar(const WCHAR* wide, char* buffer, size_t bufferLength); static bool stringsEqualIgnoreCase(const char* str1, const char* str2); static std::vector<std::string> availableFonts = {}; static bool availableFontsCached = false; static HCRYPTPROV hCryptoProvider = 0; void free() { if (hCryptoProvider != 0) { CryptReleaseContext(hCryptoProvider, 0); } } const std::vector<std::string>& getAvailableFonts() { if (!availableFontsCached) { char szPath[MAX_PATH]; if (SHGetFolderPathA(NULL, CSIDL_FONTS, NULL, 0, szPath) == S_OK) { for (auto file : std::filesystem::directory_iterator(szPath)) { if (file.path().extension() == ".ttf" || file.path().extension() == ".TTF") { availableFonts.push_back(file.path().string()); } } } availableFontsCached = true; } return availableFonts; } // Adapted from https://stackoverflow.com/questions/2467429/c-check-installed-programms bool isProgramInstalled(const char* displayName) { constexpr int bufferMaxSize = 1024; // Open the "Uninstall" key. const WCHAR* uninstallRoot = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; HKEY uninstallKey = NULL; if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, uninstallRoot, 0, KEY_READ, &uninstallKey) != ERROR_SUCCESS) { return false; } DWORD keyIndex = 0; long result = ERROR_SUCCESS; while (result == ERROR_SUCCESS) { //Enumerate all sub keys... WCHAR appKeyName[bufferMaxSize]; DWORD appKeyNameBufferSize = sizeof(appKeyName); result = RegEnumKeyExW( uninstallKey, keyIndex, appKeyName, &appKeyNameBufferSize, NULL, NULL, NULL, NULL ); if (result == ERROR_SUCCESS) { // Open the sub key. WCHAR subKey[bufferMaxSize]; HKEY appKey = NULL; wsprintfW(subKey, L"%s\\%s", uninstallRoot, appKeyName); if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, subKey, 0, KEY_READ, &appKey) != ERROR_SUCCESS) { // No more keys RegCloseKey(appKey); RegCloseKey(uninstallKey); return false; } // Get the display name value from the application's sub key. DWORD keyType = KEY_ALL_ACCESS; WCHAR currentDisplayNameWide[bufferMaxSize]; DWORD currentDisplayNameBufferSize = sizeof(currentDisplayNameWide); long queryResult = RegQueryValueExW( appKey, L"DisplayName", NULL, &keyType, (unsigned char*)currentDisplayNameWide, &currentDisplayNameBufferSize ); if (queryResult == ERROR_SUCCESS) { char currentDisplayName[bufferMaxSize]; wideToChar(currentDisplayNameWide, currentDisplayName, bufferMaxSize); if (stringsEqualIgnoreCase((char*)currentDisplayName, displayName)) { RegCloseKey(appKey); RegCloseKey(uninstallKey); return true; } } RegCloseKey(appKey); } keyIndex++; } RegCloseKey(uninstallKey); return false; } bool getProgramInstallDir(const char* programDisplayName, char* buffer, size_t bufferLength) { if (bufferLength <= 0) { return false; } constexpr int bufferMaxSize = 1024; // Open the "Uninstall" key. const WCHAR* uninstallRoot = L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"; HKEY uninstallKey = NULL; if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, uninstallRoot, 0, KEY_READ, &uninstallKey) != ERROR_SUCCESS) { return false; } DWORD keyIndex = 0; long result = ERROR_SUCCESS; while (result == ERROR_SUCCESS) { //Enumerate all sub keys... WCHAR appKeyName[bufferMaxSize]; DWORD appKeyNameBufferSize = sizeof(appKeyName); result = RegEnumKeyExW( uninstallKey, keyIndex, appKeyName, &appKeyNameBufferSize, NULL, NULL, NULL, NULL ); if (result == ERROR_SUCCESS) { // Open the sub key. WCHAR subKey[bufferMaxSize]; HKEY appKey = NULL; wsprintfW(subKey, L"%s\\%s", uninstallRoot, appKeyName); if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, subKey, 0, KEY_READ, &appKey) != ERROR_SUCCESS) { // No more keys RegCloseKey(appKey); RegCloseKey(uninstallKey); return false; } // Get the display name value from the application's sub key. DWORD keyType = KEY_ALL_ACCESS; WCHAR currentDisplayNameWide[bufferMaxSize]; DWORD currentDisplayNameBufferSize = sizeof(currentDisplayNameWide); long queryResult = RegQueryValueExW( appKey, L"DisplayName", NULL, &keyType, (unsigned char*)currentDisplayNameWide, &currentDisplayNameBufferSize ); if (queryResult == ERROR_SUCCESS) { char currentDisplayName[bufferMaxSize]; wideToChar(currentDisplayNameWide, currentDisplayName, bufferMaxSize); if (stringsEqualIgnoreCase((char*)currentDisplayName, programDisplayName)) { // Try to get install path WCHAR installPath[bufferMaxSize]; DWORD installPathBufferSize = sizeof(installPath); RegQueryValueExW( appKey, L"InstallLocation", NULL, &keyType, (unsigned char*)installPath, &installPathBufferSize ); if (queryResult == ERROR_SUCCESS) { if (installPathBufferSize <= bufferLength) { // Conver the wide path to the regular size wideToChar(installPath, buffer, bufferLength); RegCloseKey(appKey); RegCloseKey(uninstallKey); return true; } else { g_logger_warning("Buffer too small to contain install location for '{}'.", currentDisplayName); buffer[0] = '\0'; RegCloseKey(appKey); RegCloseKey(uninstallKey); return false; } } g_logger_warning("Found app '{}' but failed to find the InstallLocation.", currentDisplayName); RegCloseKey(appKey); RegCloseKey(uninstallKey); return false; } } RegCloseKey(appKey); } keyIndex++; } RegCloseKey(uninstallKey); return false; } bool executeProgram(const char* programFilepath, const char* cmdLineArgs, const char* workingDirectory, const char* executionOutputFilename) { STARTUPINFOA si = { 0 }; si.cb = sizeof(si); si.wShowWindow = false; PROCESS_INFORMATION pi = { 0 }; HANDLE fileHandle = 0; std::string finalArgs = std::string("\"") + programFilepath + std::string("\" ") + cmdLineArgs; if (executionOutputFilename) { SECURITY_ATTRIBUTES sa = { 0 }; sa.nLength = sizeof(sa); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; std::string filepath = executionOutputFilename; if (workingDirectory) { filepath = std::string(workingDirectory) + std::string("/") + executionOutputFilename; } fileHandle = CreateFileA( filepath.c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); if (fileHandle != INVALID_HANDLE_VALUE) { si.dwFlags |= STARTF_USESTDHANDLES; si.hStdInput = NULL; si.hStdError = fileHandle; si.hStdOutput = fileHandle; } else { fileHandle = NULL; } } if (!CreateProcessA( NULL, (char*)finalArgs.c_str(), NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, workingDirectory, &si, &pi )) { DWORD dwStatus = GetLastError(); g_logger_error("Failed to launch process '{}': ", dwStatus); TerminateProcess(pi.hProcess, 0); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); if (fileHandle) CloseHandle(fileHandle); return false; } // Wait until child process exits. g_logger_log("Running program: '{}'", finalArgs); WaitForSingleObject(pi.hProcess, 25000); TerminateProcess(pi.hProcess, 0); if (fileHandle) CloseHandle(fileHandle); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); return true; } bool openFileWithDefaultProgram(const char* filepath) { return (uint64)ShellExecuteA(NULL, "code", filepath, NULL, NULL, SW_SHOW) > 32; } bool openFileWithVsCode(const char* filepath, int lineNumber) { std::string command = lineNumber >= 0 ? std::string("/c code --goto \"") + filepath + ":" + std::to_string(lineNumber) + "\"" : std::string("/c code --goto \"") + filepath + "\""; return (uint64)ShellExecuteA(NULL, "open", "cmd", command.c_str(), NULL, SW_HIDE); } bool fileExists(const char* filename) { DWORD dwAttrib = GetFileAttributesA(filename); return (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } bool dirExists(const char* dirName) { DWORD dwAttrib = GetFileAttributesA(dirName); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); } bool deleteFile(const char* filename) { if (!DeleteFileA(filename)) { g_logger_error("Delete file '{}' failed with: {}", filename, GetLastError()); return false; } return true; } std::string tmpFilename(const std::string& directory) { char outPath[_MAX_PATH]; uint32 res = GetTempFileNameA( directory.c_str(), "TMP", 0, outPath ); if (res == 0) { return std::string(""); } return std::string(outPath); } std::string getSpecialAppDir() { CHAR szPath[MAX_PATH]; if (SHGetFolderPathA(NULL, CSIDL_APPDATA, NULL, 0, szPath) == ERROR_SUCCESS) { return std::string(szPath); } return ""; } MemMappedFile* createTmpMemMappedFile(const std::string& directory, size_t size) { MemMappedFile* res = (MemMappedFile*)g_memory_allocate(sizeof(MemMappedFile)); g_memory_zeroMem(res, sizeof(MemMappedFile)); res->userData = (MemMapUserData*)g_memory_allocate(sizeof(MemMapUserData)); res->userData->fileHandle = INVALID_HANDLE_VALUE; res->userData->fileMappingHandle = INVALID_HANDLE_VALUE; std::string filepath = tmpFilename(directory); res->userData->fileHandle = CreateFileA( filepath.c_str(), GENERIC_READ | GENERIC_WRITE, 0, // Specify exclusive access for memmapped file NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, NULL ); if (res->userData->fileHandle == INVALID_HANDLE_VALUE) { g_logger_error("Failed to create file '{}' for memmapping. Last error: {}", filepath, GetLastError()); freeMemMappedFile(res); return nullptr; } DWORD sizeHigh = (size >> 32) & 0xFFFFFFFF; if constexpr (sizeof(size) < sizeof(uint64)) { // Protect against overflow on machines with <64-bit architectures (even though this // isn't meant to be run on <64-bit architectures) sizeHigh = 0; } DWORD sizeLow = (size) & 0xFFFFFFFF; res->userData->fileMappingHandle = CreateFileMappingA( // TODO: Maybe this should be INVALID_HANDLE_VALUE so that the // OS will automatically use disk only if RAM usage is too high??? res->userData->fileHandle, NULL, PAGE_READWRITE, sizeHigh, sizeLow, NULL ); if (res->userData->fileMappingHandle == NULL) { res->userData->fileMappingHandle = INVALID_HANDLE_VALUE; g_logger_error("Failed to memmap a temporary file. Last error: '{}'", GetLastError()); freeMemMappedFile(res); return nullptr; } uint8* baseAddress = (uint8*)MapViewOfFile( res->userData->fileMappingHandle, FILE_MAP_ALL_ACCESS, 0, 0, size ); if (baseAddress == NULL) { g_logger_error("Failed to create a mapped view of the memmap handle. Last Error: '{}'", GetLastError()); freeMemMappedFile(res); return nullptr; } res->dataSize = size; // NOTE: This is kind of gross, but hopefully it communicates to the end user // that this pointer is not supposed to be changed, and if they do something // similar bad stuff is gonna happen #pragma warning( push ) #pragma warning( disable : 4213 ) (uint8*)res->data = baseAddress; #pragma warning( pop ) return res; } void freeMemMappedFile(MemMappedFile* file) { if (!file) { return; } if (file->data) { BOOL res = UnmapViewOfFile(file->data); if (!res) { g_logger_error("Failed to unmap the file view for a memmapped file. Last error: '{}'", GetLastError()); } } if (file->userData) { if (file->userData->fileMappingHandle != INVALID_HANDLE_VALUE) { BOOL res = CloseHandle(file->userData->fileMappingHandle); if (!res) { g_logger_error("Failed to close file mapping handle for a memmapped file. Last error: '{}'", GetLastError()); } } if (file->userData->fileHandle != INVALID_HANDLE_VALUE) { BOOL res = CloseHandle(file->userData->fileHandle); if (!res) { g_logger_error("Failed to close file handle for a memmapped file. Last error: '{}'", GetLastError()); } } g_memory_free(file->userData); file->userData = nullptr; } g_memory_zeroMem(file, sizeof(MemMappedFile)); g_memory_free(file); } void createDirIfNotExists(const char* dirName) { CreateDirectoryA(dirName, NULL); } std::string md5FromString(const std::string& str, int md5Length) { return md5FromString(str.c_str(), str.length(), md5Length); } std::string md5FromString(const char* str, size_t length, int md5Length) { constexpr int maxMd5Length = 1024; g_logger_assert(md5Length < maxMd5Length, "Cannot generate md5 greater than '{}' characters.", maxMd5Length); // Get handle to the crypto provider if (hCryptoProvider == 0) { if (!CryptAcquireContext(&hCryptoProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { DWORD dwStatus = GetLastError(); g_logger_error("CryptAcquireContext failed: '{}'", dwStatus); return ""; } } HCRYPTHASH hHash = 0; if (!CryptCreateHash(hCryptoProvider, CALG_MD5, 0, 0, &hHash)) { DWORD dwStatus = GetLastError(); g_logger_error("CryptAcquireContext failed: '{}'", dwStatus); CryptReleaseContext(hCryptoProvider, 0); return ""; } // Reinterpret the char's as unsigned char's // shouldn't make any difference since the data // doesn't matter, just the bits if (!CryptHashData(hHash, (BYTE*)str, (DWORD)length, 0)) { DWORD dwStatus = GetLastError(); g_logger_error("CryptHashData failed: '{}'", dwStatus); CryptReleaseContext(hCryptoProvider, 0); CryptDestroyHash(hHash); return ""; } BYTE rgbHash[maxMd5Length]; CHAR hexDigits[] = "0123456789abcdef"; DWORD cbHash = md5Length; std::string hashRes = ""; if (CryptGetHashParam(hHash, HP_HASHVAL, rgbHash, &cbHash, 0)) { for (DWORD i = 0; i < cbHash; i++) { hashRes += hexDigits[rgbHash[i] >> 4]; hashRes += hexDigits[rgbHash[i] & 0xf]; } } else { DWORD dwStatus = GetLastError(); g_logger_error("CryptGetHashParam failed: '{}'", dwStatus); } CryptDestroyHash(hHash); return hashRes; } bool setCursorPos(const Window& window, const Vec2i& cursorPos) { RECT rect; if (GetWindowRect(glfwGetWin32Window((GLFWwindow*)window.windowPtr), &rect)) { int titleBarHeight = GetSystemMetrics(SM_CYCAPTION); int resizableHeight = GetSystemMetrics(SM_CYFRAME) + GetSystemMetrics(SM_CXPADDEDBORDER); return (bool)SetCursorPos(cursorPos.x + rect.left, cursorPos.y + rect.top + titleBarHeight + resizableHeight); } return false; } // --------------- Internal Functions --------------- static void wideToChar(const WCHAR* wide, char* buffer, size_t bufferLength) { size_t wideLength = std::wcslen(wide); if (wideLength + 1 >= bufferLength) { buffer[0] = '\0'; g_logger_warning("Could not convert wide string to char string. Wide string length '{}' buffer length '{}'.", wideLength, bufferLength); return; } for (size_t i = 0; i < wideLength; i++) { if (i < bufferLength) { // Truncate buffer[i] = (char)wide[i]; } } buffer[wideLength] = '\0'; } static bool stringsEqualIgnoreCase(const char* str1, const char* str2) { size_t lenStr1 = std::strlen(str1); size_t lenStr2 = std::strlen(str2); if (lenStr1 != lenStr2) { return false; } size_t minLength = glm::min(lenStr1, lenStr2); for (size_t i = 0; i < minLength; i++) { if (str1[i] != str2[i]) { char str1Lower = str1[i] >= 'A' && str1[i] <= 'Z' ? str1[i] - 'A' + 'a' : str1[i]; char str2Lower = str2[i] >= 'A' && str2[i] <= 'Z' ? str2[i] - 'A' + 'a' : str2[i]; if (str1Lower != str2Lower) { return false; } } } return true; } } } #endif