hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ef8c888becd0e0a6ca8f8b9de99a57389fd0b41f
2,121
cpp
C++
Day 06 Part 2/main.cpp
Miroslav-Cetojevic/aoc-2015
2807fcd3fc684843ae4222b25af6fd086fac77f5
[ "Unlicense" ]
1
2019-11-19T20:19:18.000Z
2019-11-19T20:19:18.000Z
Day 06 Part 2/main.cpp
Miroslav-Cetojevic/aoc-2015
2807fcd3fc684843ae4222b25af6fd086fac77f5
[ "Unlicense" ]
null
null
null
Day 06 Part 2/main.cpp
Miroslav-Cetojevic/aoc-2015
2807fcd3fc684843ae4222b25af6fd086fac77f5
[ "Unlicense" ]
null
null
null
#include <array> #include <fstream> #include <iostream> #include <numeric> #include <string_view> #include <unordered_map> #include <boost/range/irange.hpp> #include <boost/range/istream_range.hpp> enum class Cmd { on, off, toggle }; using uint64 = std::uint64_t; struct Position { uint64 row, col; }; struct EndPoints { std::string state; Position first, last; }; auto& operator>>(std::istream& in, Position& pos) { return in >> pos.row >> pos.col; } auto& operator>>(std::istream& in, EndPoints& pos) { return in >> pos.state >> pos.first >> pos.last; } auto get_total_brightness(std::fstream& file) { constexpr auto gridlen = uint64{1000}; constexpr auto numlights = (gridlen * gridlen); auto grid = std::array<uint64, numlights>{}; const auto commands = std::unordered_map<std::string_view, Cmd>{ {"on", Cmd::on}, {"off", Cmd::off}, {"toggle", Cmd::toggle} }; const auto stream = boost::istream_range<EndPoints>(file); for(const auto& endpoints : stream) { const auto command = commands.find(endpoints.state)->second; const auto& first = endpoints.first; const auto& last = endpoints.last; const auto begin_row = first.row; const auto end_row = (last.row + 1); for(const auto row : boost::irange(begin_row, end_row)) { const auto begin_col = first.col; const auto end_col = (last.col + 1); for(const auto col : boost::irange(begin_col, end_col)) { const auto pos = (row * gridlen + col); switch(command) { case Cmd::on: ++grid[pos]; break; case Cmd::off: grid[pos] -= (grid[pos] > 0); break; case Cmd::toggle: grid[pos] += 2; break; default: std::cerr << "WTF?!? Something went really wrong!" << std::endl; } } } } return std::accumulate(grid.begin(), grid.end(), uint64{}); } int main() { const auto filename = std::string{"instructions.txt"}; auto file = std::fstream{filename}; if(file.is_open()) { std::cout << get_total_brightness(file) << std::endl; } else { std::cerr << "Error! Could not open \"" << filename << "\"!" << std::endl; } return 0; }
21
76
0.634135
Miroslav-Cetojevic
ef8e15eaa0e8267adccdb721ed462f9d1aaacda9
2,069
cpp
C++
lib/lib_http/lib_http.cpp
genesos/brain-launcher-bhdll
6a352bb6a7db9b9c74d940d476ee8a2e7c586683
[ "OML" ]
null
null
null
lib/lib_http/lib_http.cpp
genesos/brain-launcher-bhdll
6a352bb6a7db9b9c74d940d476ee8a2e7c586683
[ "OML" ]
null
null
null
lib/lib_http/lib_http.cpp
genesos/brain-launcher-bhdll
6a352bb6a7db9b9c74d940d476ee8a2e7c586683
[ "OML" ]
null
null
null
#include <afxinet.h> #include "lib_http.h" #include "../GenesisLib/file.h" #include <memory> using std::auto_ptr; using std::wstring; void getWebDownloadToFileCurDir( wstring target, wstring to, boost::function<void(int, bool&)> callback) { getWebDownloadToFile(target, getModuleAbsPath() + to, callback); } void getWebDownloadToFile( wstring target, wstring to, boost::function<void(int, bool&)> callback) { wstringstream wsslog; wsslog<<target<<_T(" => ")<<to; LOG(wsslog); try { wstring fileName = to; wstring dir; { int dirIndex = to.find_last_of(L'\\'); if(dirIndex>=0) { fileName = to.substr(dirIndex+1); dir = to.substr(0,dirIndex); } } if(fileName[0]==L'-') { to = dir+L"\\"+fileName.substr(1); CFile::Remove(to.c_str()); RemoveDirectory(to.c_str()); } else { if(dir.length()>0) { CreateDirectory(dir.c_str(),0); } CFile fDestFile((to).c_str(),CFile::modeCreate|CFile::modeWrite|CFile::typeBinary); CInternetSession netSession; auto_ptr<CStdioFile> fTargetFile(netSession.OpenURL(target.c_str(),1,INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD)); bool shutdownDownload = 0; if(fTargetFile.get()) { UINT readLen; char buf[512]; while (readLen = fTargetFile->Read(buf,512)) { fDestFile.Write(buf,readLen); if(callback) { callback(readLen, shutdownDownload); if(shutdownDownload) return; } } } } } catch(CInternetException*) { } catch(CFileException*) { } catch(CException*) { } } wstring getWebDownloadToString( wstring target) { wstringstream wsslog; wsslog<<target<<_T(" => [LOCAL]"); LOG(wsslog); string ret(""); try { CInternetSession netSession; auto_ptr<CStdioFile> fTargetFile(netSession.OpenURL(target.c_str(),1,INTERNET_FLAG_TRANSFER_ASCII|INTERNET_FLAG_RELOAD)); if(fTargetFile.get()) { UINT readLen; char buf[512]; while (readLen=fTargetFile->Read(buf,512)) ret.append(buf,readLen); } } catch(CInternetException*) { } return encodeUNI(ret); }
19.704762
125
0.666022
genesos
ef8e6be06ae45c92cfcdd49c16833dbfe7413078
3,812
cc
C++
src/core/image_io/image_io_png.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
src/core/image_io/image_io_png.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
src/core/image_io/image_io_png.cc
zhehangd/qjulia2
b6816f5af580534fdb27051ae2bfd7fe47a1a60c
[ "MIT" ]
null
null
null
#include "image_io_png.h" #include <cstring> #include <vector> #include <png.h> namespace qjulia { void PNGImageReader::ReadImage(const std::string &filename, RGBImage &image) { FILE *fp = fopen(filename.c_str(), "rb"); CHECK(fp); png_byte header[8]; CHECK_EQ(8, fread(header, 1, 8, fp)); CHECK (png_sig_cmp(header, 0, 8) == 0); auto* png_ptr = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); CHECK(png_ptr); auto *info_ptr = png_create_info_struct(png_ptr); CHECK(info_ptr); int setjmp_ret = setjmp(png_jmpbuf(png_ptr)); CHECK(setjmp_ret == 0); png_init_io(png_ptr, fp); png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); int width = png_get_image_width(png_ptr, info_ptr); int height = png_get_image_height(png_ptr, info_ptr); png_byte color_type = png_get_color_type(png_ptr, info_ptr); png_byte bit_depth = png_get_bit_depth(png_ptr, info_ptr); CHECK_EQ(bit_depth, 8); CHECK_EQ(color_type, PNG_COLOR_TYPE_RGB); int number_of_passes = png_set_interlace_handling(png_ptr); (void)number_of_passes; png_read_update_info(png_ptr, info_ptr); setjmp_ret = setjmp(png_jmpbuf(png_ptr)); CHECK(setjmp_ret == 0); auto btype_per_row = png_get_rowbytes(png_ptr, info_ptr); CHECK((int)btype_per_row == width * 3); image.Resize(Size(width, height)); auto *data_ptr = image.Data()->vals; std::vector<png_bytep> row_ptrs(height); for (int r = 0; r < height; ++r) {row_ptrs[r] = data_ptr + r * btype_per_row;} png_read_image(png_ptr, row_ptrs.data()); png_read_end(png_ptr, info_ptr); fclose(fp); } void PNGImageReader::ReadImage(const std::string &filename, RGBFloatImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } void PNGImageReader::ReadImage(const std::string &filename, GrayscaleImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } void PNGImageReader::ReadImage(const std::string &filename, GrayscaleFloatImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } void PNGImageWriter::WriteImage(const std::string &filename, const RGBImage &image) { FILE *fp = fopen(filename.c_str(), "wb"); CHECK_NOTNULL(fp); auto* png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); CHECK_NOTNULL(png_ptr); auto* info_ptr = png_create_info_struct(png_ptr); CHECK_NOTNULL(info_ptr); CHECK_EQ(setjmp(png_jmpbuf(png_ptr)), 0); png_init_io(png_ptr, fp); CHECK_EQ(setjmp(png_jmpbuf(png_ptr)), 0); png_byte bit_depth = 8; png_byte color_type = PNG_COLOR_TYPE_RGB; int width = image.Width(); int height = image.Height(); png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_write_info(png_ptr, info_ptr); CHECK_EQ(setjmp(png_jmpbuf(png_ptr)), 0); auto *data_ptr = image.Data()->vals; std::vector<png_bytep> row_ptrs(height); for (int r = 0; r < height; ++r) {row_ptrs[r] = const_cast<png_bytep>(data_ptr) + r * width * 3;} png_write_image(png_ptr, row_ptrs.data()); CHECK_EQ(setjmp(png_jmpbuf(png_ptr)), 0); png_write_end(png_ptr, NULL); fclose(fp); } void PNGImageWriter::WriteImage(const std::string &filename, const RGBFloatImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } void PNGImageWriter::WriteImage(const std::string &filename, const GrayscaleImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } void PNGImageWriter::WriteImage(const std::string &filename, const GrayscaleFloatImage &image) { (void)filename; (void)image; throw NoImageSpecificationSupport(""); } }
28.237037
99
0.71852
zhehangd
ef92dc4f05392a981f980e0039803d85ac935153
519
hpp
C++
include/controller/guards/is_swap_items_winning.hpp
modern-cpp-examples/match3
bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e
[ "BSL-1.0" ]
166
2016-04-27T19:01:00.000Z
2022-03-27T02:16:55.000Z
include/controller/guards/is_swap_items_winning.hpp
Fuyutsubaki/match3
bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e
[ "BSL-1.0" ]
4
2016-05-19T07:47:38.000Z
2018-03-22T04:33:00.000Z
include/controller/guards/is_swap_items_winning.hpp
Fuyutsubaki/match3
bb1f4de11db9e92b6ebdf80f1afe9245e6f86b7e
[ "BSL-1.0" ]
17
2016-05-18T21:17:39.000Z
2022-03-20T22:37:14.000Z
// // Copyright (c) 2016 Krzysztof Jusiak (krzysztof at jusiak dot net) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #pragma once #include <cassert> #include "controller/data/selected.hpp" #include "model/board.hpp" namespace match3 { const auto is_swap_items_winning = [](const board& b, const selected& s) { assert(s.size() == 2); return b.is_match(s[0]) || b.is_match(s[1]); }; } // match3
23.590909
74
0.697495
modern-cpp-examples
ef94f926c766100b8c004d9d63e70ce4289adc37
417
cpp
C++
leetcode/12.cpp
windniw/just-for-fun
54e5c2be145f3848811bfd127f6a89545e921570
[ "Apache-2.0" ]
1
2019-08-28T23:15:25.000Z
2019-08-28T23:15:25.000Z
leetcode/12.cpp
windniw/just-for-fun
54e5c2be145f3848811bfd127f6a89545e921570
[ "Apache-2.0" ]
null
null
null
leetcode/12.cpp
windniw/just-for-fun
54e5c2be145f3848811bfd127f6a89545e921570
[ "Apache-2.0" ]
null
null
null
class Solution { public: string intToRoman(int num) { string arr[] ={"","I","II","III","IV","V","VI","VII","VIII","IX", "","X","XX","XXX","XL","L","LX","LXX","LXXX","XC", "","C","CC","CCC","CD","D","DC","DCC","DCCC","CM", "","M","MM","MMM"}; return arr[30+num/1000]+arr[20+num%1000/100]+arr[10+num%100/10]+arr[num%10]; } };
37.909091
84
0.407674
windniw
ef96f571444f20231766f10544923f83f839b25d
4,586
cpp
C++
src/backend/VirtualMemory.cpp
athenaforai/athena
20381d9069fac901666fe5296cdb443c8969bf4a
[ "MIT" ]
null
null
null
src/backend/VirtualMemory.cpp
athenaforai/athena
20381d9069fac901666fe5296cdb443c8969bf4a
[ "MIT" ]
null
null
null
src/backend/VirtualMemory.cpp
athenaforai/athena
20381d9069fac901666fe5296cdb443c8969bf4a
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018 Athena. All rights reserved. * https://athenaframework.ml * * Licensed under MIT license. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an “AS IS” BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ #include "VirtualMemory.h" #include <core/DataType.h> athena::backend::VirtualMemory::VirtualMemory () { head = new VMemoryBlock; head->isUsed = false; head->startAddress = 1; head->endAddress = LONG_MAX; head->nextBlock = nullptr; head->prevBlock = nullptr; maxMemoryUsage = 0; curMemoryUsage = 0; } vm_word athena::backend::VirtualMemory::allocate ( athena::core::Tensor* tensor ) { VMemoryBlock* cur = head; unsigned long memNeeded = tensor->getShape().totalSize() * athena::core::typesize( tensor->getType()); bool allocated = false; while ( cur != nullptr && !allocated ) { if ( !cur->isUsed && (cur->endAddress - cur->startAddress) >= memNeeded ) { auto newUsedBlock = new VMemoryBlock; newUsedBlock->isUsed = true; newUsedBlock->startAddress = cur->startAddress; newUsedBlock->endAddress = newUsedBlock->startAddress + memNeeded; newUsedBlock->prevBlock = cur->prevBlock; if ( cur->prevBlock != nullptr ) { cur->prevBlock->nextBlock = newUsedBlock; } if ( cur->endAddress - cur->startAddress > memNeeded ) { auto freeBlock = new VMemoryBlock; freeBlock->isUsed = false; freeBlock->startAddress = newUsedBlock->endAddress; freeBlock->endAddress = cur->endAddress; freeBlock->nextBlock = cur->nextBlock; freeBlock->prevBlock = newUsedBlock; newUsedBlock->nextBlock = freeBlock; if ( cur->nextBlock != nullptr ) { cur->nextBlock->prevBlock = freeBlock; } } else { newUsedBlock->nextBlock = cur->nextBlock; if ( cur->nextBlock != nullptr ) { cur->nextBlock->prevBlock = newUsedBlock; } } allocated = true; curMemoryUsage += memNeeded; if ( curMemoryUsage > maxMemoryUsage ) { maxMemoryUsage = curMemoryUsage; } cur->nextBlock = nullptr; cur->prevBlock = nullptr; if ( cur == head ) { head = newUsedBlock; } delete cur; cur = newUsedBlock; } else { cur = cur->nextBlock; } } if ( !allocated ) { throw std::runtime_error( "OutOfMemory error" ); } tensor->setStartAddress( cur->startAddress ); tensors.push_back( tensor ); return cur->startAddress; } void athena::backend::VirtualMemory::free ( vm_word virtualAddress ) { VMemoryBlock *cur = head; bool found = false; while ( cur != nullptr && !found ) { if ( cur->startAddress == virtualAddress ) { cur->isUsed = false; curMemoryUsage -= cur->endAddress - cur->startAddress; // merge two free blocks if ( cur->nextBlock != nullptr && !cur->nextBlock->isUsed ) { VMemoryBlock *old = cur->nextBlock; cur->endAddress = old->endAddress; if ( old->nextBlock != nullptr ) { old->nextBlock->prevBlock = cur; } cur->nextBlock = old->nextBlock; old->nextBlock = nullptr; old->prevBlock = nullptr; delete old; } found = true; } else { cur = cur->nextBlock; } } for ( unsigned long i = 0; i < tensors.size(); i++ ) { if ( tensors[ i ]->getStartAddress() == virtualAddress ) { tensors.erase( tensors.begin() + i ); break; } } } void athena::backend::VirtualMemory::free ( athena::core::Tensor* tensor ) { free( tensor->getStartAddress()); } athena::core::Tensor* athena::backend::VirtualMemory::getTensor ( vm_word address ) { for ( auto &tensor : tensors ) { if ( tensor->getStartAddress() == address ) { return tensor; } } return nullptr; }
30.573333
85
0.551243
athenaforai
ef9741d94d95e954c3f79546db000b312ba003c0
1,047
cpp
C++
LightOJ/1017 - Brush (III)/sol.cpp
Tahsin716/OnlineJudge
a5d15f37a8c260740c148370ced7a2a9096050c1
[ "MIT" ]
null
null
null
LightOJ/1017 - Brush (III)/sol.cpp
Tahsin716/OnlineJudge
a5d15f37a8c260740c148370ced7a2a9096050c1
[ "MIT" ]
null
null
null
LightOJ/1017 - Brush (III)/sol.cpp
Tahsin716/OnlineJudge
a5d15f37a8c260740c148370ced7a2a9096050c1
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int points[101], dp[101][101]; int n, brushWidth, moves; int rec(int position, int remainingMoves) { if (position >= n || remainingMoves == 0) { return 0; } if (dp[position][remainingMoves] != -1) return dp[position][remainingMoves]; int ret = -1; int brushCoverage = points[position] + brushWidth; int taken = 0, index; for (index = position; index < n && points[index] <= brushCoverage; index++) { taken++; } taken += rec(index, remainingMoves - 1); int not_taken = rec(position + 1, remainingMoves); ret = max(taken, not_taken); return dp[position][remainingMoves] = ret; } int main() { int T, testCase = 0; int x, y; scanf("%d", &T); while (T--) { scanf("%d%d%d", &n, &brushWidth, &moves); memset(dp, -1, sizeof dp); for (int i = 0; i < n; i++) { scanf("%d%d", &x, &y); points[i] = y; } sort(points, points + n); printf("Case %d: %d\n", ++testCase, rec(0, moves)); } return 0; }
16.359375
77
0.606495
Tahsin716
ef97f81a67b5d6357f333e7a5bd0d70465cae787
1,685
hpp
C++
src/hanoi.hpp
deepgrace/giant
4070c79892957c8e9244eb7a3d7690a25970f769
[ "BSL-1.0" ]
6
2019-04-02T07:47:37.000Z
2021-05-31T08:01:04.000Z
src/hanoi.hpp
deepgrace/giant
4070c79892957c8e9244eb7a3d7690a25970f769
[ "BSL-1.0" ]
null
null
null
src/hanoi.hpp
deepgrace/giant
4070c79892957c8e9244eb7a3d7690a25970f769
[ "BSL-1.0" ]
4
2019-04-15T08:52:17.000Z
2022-03-25T10:29:57.000Z
// // Copyright (c) 2016-present DeepGrace (complex dot invoke at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/deepgrace/giant // #include <stack> #include <array> #include <iostream> using namespace std; /* _ _ _ | | | | | | _| |_ | | | | |_____| | | | | |_______| | | | | |_________| | | | | |___________| | | | | |_____________| | | | | |_______________| _______| |_______ _______| |_______ | | | | | | ----------------------------------------------------------------------------- #0 #1 #2 */ template <typename T> void hanoi(int n, array<stack<T>, 3>& peg, int from, int to, int use) { if (n > 0) { hanoi(n - 1, peg, from, use, to); peg[to].push(peg[from].top()); peg[from].pop(); cout << from << " -> " << to << endl; hanoi(n - 1, peg, use, to, from); } } template <typename T = int> void move(int n) { array<stack<T>, 3> peg; for (int i = n; i > 0; --i) peg[0].push(i); hanoi(n, peg, 0, 1, 2); }
33.039216
90
0.35727
deepgrace
aab3bdd54d06c97c9e82906418a8305c2d016a62
32,698
cpp
C++
src/net.cpp
philipturner/opencl-backend
dd0bdd2c00a4c4d62ff76806048f1c7b2d737284
[ "MIT" ]
null
null
null
src/net.cpp
philipturner/opencl-backend
dd0bdd2c00a4c4d62ff76806048f1c7b2d737284
[ "MIT" ]
null
null
null
src/net.cpp
philipturner/opencl-backend
dd0bdd2c00a4c4d62ff76806048f1c7b2d737284
[ "MIT" ]
null
null
null
#include <dlprim/net.hpp> #include <dlprim/json.hpp> #include <dlprim/shared_resource.hpp> #include <dlprim/ops/initialization.hpp> #include <dlprim/model.hpp> #include <sstream> #include <fstream> #include <set> #include <list> #include <algorithm> #ifndef DISABLE_HDF5 #include "H5Cpp.h" #endif namespace dlprim { Net::Net(Context &ctx) : ctx_(ctx), shared_resource_(new SharedResource()), mode_(CalculationsMode::predict), keep_intermediate_tensors_(false) { } void Net::mode(CalculationsMode m) { mode_ = m; for(auto &c:connections_) c.op->mode(m); } void Net::add_input_tensor(std::string const &name,TensorSpecs const &ts,bool requires_gradient) { TensorSpecs new_ts(ts.shape(),ts.dtype(),requires_gradient); if(!tensor_specs_.insert(std::make_pair(name,new_ts)).second) { throw ValidationError("Tensor " + name + " already exists"); } inputs_.push_back(name); } void Net::set_loss_weight(std::string const &name,float lw) { mark_output_tensor(name); loss_weights_[name] = lw; } void Net::mark_output_tensor(std::string const &name) { if(tensor_specs_.find(name) == tensor_specs_.end()) { throw ValidationError("mark_output_tensor::No such tensor name " + name); } if(std::find(outputs_.begin(),outputs_.end(),name)==outputs_.end()) { outputs_.push_back(name); if(name.find("loss")==0) loss_weights_[name] = 1.0f; } } void Net::save_parameters(std::string const &fname) { json::value header; json::value &tensors = header["tensors"]; tensors = json::object(); size_t start_pos = 0; for(auto &pr : parameters_) { std::string name = pr.first; json::value &tensor_specs = tensors[name]; tensor_specs["dtype"] = data_type_to_string(pr.second.dtype()); Shape shape = pr.second.shape(); for(int i=0;i<shape.size();i++) tensor_specs["shape"][i] = shape[i]; size_t mem = pr.second.memory_size(); tensor_specs["size"] = mem; tensor_specs["start"] = start_pos; start_pos += mem; } std::ostringstream ss; ss << header; std::string header_content = ss.str(); unsigned len = header_content.size(); std::ofstream f(fname,std::fstream::binary); f<< "DLPW"; for(int i=0;i<4;i++) { unsigned char v = 0xFF & (len >> (24 - i*8)); f << (char)(v); } f << header_content; for(auto &pr : parameters_) { void *ptr = pr.second.host_data(); size_t len = pr.second.memory_size(); f.write((char*)ptr,len); } f.flush(); if(!f) { throw ValidationError("I/O error in saving to " + fname); } } void Net::load_model(ModelBase &model) { load_from_json(model.network()); setup(); load_parameters(model); } #ifdef DISABLE_HDF5 void Net::save_parameters_to_hdf5(std::string const &) { throw ValidationError("Library was build without HDF5 support"); } void Net::load_parameters_from_hdf5(std::string const &,bool) { throw ValidationError("Library was build without HDF5 support"); } #else void Net::save_parameters_to_hdf5(std::string const &fname) { try { H5::H5File f(fname,H5F_ACC_TRUNC); for(auto &pr : parameters_) { std::string name = pr.first; Tensor &tensor = pr.second; Shape shape = tensor.shape(); std::vector<hsize_t> dims(1 + shape.size()); for(int i=0;i<shape.size();i++) dims[i] = shape[i]; H5::DataSpace dsp(shape.size(),dims.data()); H5::FloatType datatype( H5::PredType::NATIVE_FLOAT ); datatype.setOrder( H5T_ORDER_LE ); H5::DataSet dataset = f.createDataSet( name , datatype, dsp ); if(tensor.dtype() == float_data) { dataset.write(tensor.data<float>(),H5::PredType::NATIVE_FLOAT); } else { throw ValidationError("FIXME load float16 from hdf5"); } } f.close(); } catch(H5::Exception const &e) { throw ValidationError("Failed to load HDF5 file " + fname + ": " + std::string(e.getCDetailMsg())); } } void Net::load_parameters_from_hdf5(std::string const &fname,bool allow_missing) { try { H5::H5File f(fname,H5F_ACC_RDONLY); for(auto &pr : parameters_) { std::string name = pr.first; Tensor &tensor = pr.second; H5::DataSet dataset; try { dataset = f.openDataSet(name); } catch(H5::Exception const &e) { if(allow_missing) continue; throw; } H5::DataSpace dsp = dataset.getSpace(); int ndims = dsp.getSimpleExtentNdims(); std::vector<hsize_t> dims(ndims); dsp.getSimpleExtentDims(dims.data(),nullptr); Shape ds_shape=Shape::from_range(dims.begin(),dims.end()); if(ds_shape != tensor.shape()) { std::ostringstream ss; ss << "Tensor shape mistmatch for " << name << " expecting " << tensor.shape() << " got " << ds_shape; throw ValidationError(ss.str()); } if(tensor.dtype() == float_data) { dataset.read(tensor.data<float>(),H5::PredType::NATIVE_FLOAT); } else { throw ValidationError("FIXME load float16 from hdf5"); } } } catch(H5::Exception const &e) { throw ValidationError("Failed to load HDF5 file " + fname + ": " + std::string(e.getCDetailMsg())); } copy_parameters_to_device(); } #endif void Net::initialize_parameters(ExecutionContext const &e) { for(auto &conn : connections_) { conn.op->initialize_params(conn.parameters,e); } if(mode() == CalculationsMode::train) { // set loss diff for(auto const &name : output_names()) { if(is_loss(name)) set_to_constant(tensor_diff(name),loss_weights_[name],e); } } } void Net::load_header(std::istream &f,json::value &v) { unsigned char buf[8]={0}; f.read((char*)buf,8); if(memcmp(buf,"DLPW",4) != 0) throw ValidationError("Invalid File Format"); unsigned len = 0; for(int i=0;i<4;i++) { len |= unsigned(buf[4+i]) << ((3-i)*8); } if(len > 1024*1024*64) throw ValidationError("Header seems to be too big"); std::vector<char> buffer(len+1); f.read(buffer.data(),len); if(!f) throw ValidationError("Problem readfing file"); buffer[len] = 0; char const *begin=&buffer[0]; char const *end =&buffer[len]; // (there is +1) if(!v.load(begin,end,true)) { throw ValidationError("Problem parsing content"); } } void Net::load_parameters(std::string const &file_name,bool allow_missing) { std::ifstream f(file_name,std::ifstream::binary); char buf[5]={}; f.read(buf,4); if(buf==std::string("DLPW")) { f.seekg(0); try { load_parameters(f,allow_missing); } catch(std::exception const &e) { throw ValidationError(std::string(e.what()) + " in file " + file_name); } } else if(buf==std::string("\211HDF")) { f.close(); load_parameters_from_hdf5(file_name,allow_missing); } else { throw ValidationError("Unidentified majic number for " + file_name); } } void Net::load_parameters(ModelBase &model,bool allow_missing) { for(auto &pr : parameters_) { std::string name = pr.first; Tensor &tensor = pr.second; Tensor value = model.get_parameter(name); if(value.shape().size() == 0) { if(allow_missing) continue; throw ValidationError("No parameter " + name + " was found"); } if(tensor.shape() != value.shape() || tensor.dtype() != value.dtype()) { std::ostringstream err; err << "Expected " << tensor << " parameter, got " << value << " for " << name; throw ValidationError(err.str()); } memcpy(tensor.host_data(),value.host_data(),tensor.memory_size()); } copy_parameters_to_device(); } void Net::load_parameters(std::istream &f,bool allow_missing) { json::value v; load_header(f,v); size_t offset = f.tellg(); json::object const &tensors=v.find("tensors").object(); for(auto &pr : parameters_) { std::string name = pr.first; Tensor &tensor = pr.second; auto p = tensors.find(name); if(p == tensors.end()) { if(allow_missing) continue; throw ValidationError("No parameter " + name + " was found"); } std::vector<int> dims = p->second.get<std::vector<int> >("shape"); DataType dt = string_to_data_type(p->second.get<std::string>("dtype")); Shape ds_shape=Shape::from_range(dims.begin(),dims.end()); if(ds_shape != tensor.shape() || dt != tensor.dtype()) { std::ostringstream ss; ss << "Tensor shape/type mistmatch for " << name << " expecting " << tensor << " got " << ds_shape << " " << data_type_to_string(dt); throw ValidationError(ss.str()); } size_t start = p->second.get<size_t>("start"); size_t size = p->second.get<size_t>("size"); if(size != tensor.memory_size()) { throw ValidationError("Object size mistmatch"); } f.seekg(start + offset); f.read(static_cast<char *>(tensor.host_data()),size); if(!f) { throw ValidationError("I/O error"); } } copy_parameters_to_device(); } void Net::load_from_json(json::value const &v) { json::array const &inputs = v["inputs"].array(); for(auto const &input:inputs) { auto const &vsp = input.get<std::vector<int> >("shape"); Shape sp=Shape::from_range(vsp.begin(),vsp.end()); DataType dt(string_to_data_type(input.get("dtype","float"))); TensorSpecs spec(sp,dt); std::string name = input.get("name","data"); add_input_tensor(name,spec); } json::array const &operators = v["operators"].array(); json::value empty_options = json::object(); for(size_t i=0;i<operators.size();i++) { json::value const &op = operators[i]; std::string name = op.get<std::string>("name"); std::string type = op.get<std::string>("type"); bool frozen = op.get<bool>("frozen",false); std::vector<std::string> inputs = op.get("inputs", std::vector<std::string>()); std::vector<std::string> outputs = op.get("outputs",std::vector<std::string>()); std::vector<std::string> params = op.get("params", std::vector<std::string>()); json::value const &opts = op.find("options").is_undefined() ? empty_options : op["options"]; std::unique_ptr<Operator> oper = create_by_name(ctx_,type,opts); add_operator(std::move(oper),name,inputs,outputs,params,frozen); } for(json::value const &output : v["outputs"].array()) { if(output.type() == json::is_string) mark_output_tensor(output.str()); else { std::string const &name = output.get<std::string>("name"); if(output.find("loss_weight").is_undefined()) mark_output_tensor(name); else set_loss_weight(name,output.get<float>("loss_weight")); } } } void Net::load_from_json_file(std::string const &name) { std::ifstream f(name); json::value net; int line=-1; if(!net.load(f,true,&line)) { throw ValidationError("Failed to load json from " + name + ", syntax error at line " + std::to_string(line)); } load_from_json(net); } void Net::add_operator( std::unique_ptr<Operator> op, std::string const &name, std::vector<std::string> const &inputs, std::vector<std::string> const &outputs, std::vector<std::string> const &parameters, bool frozen) { Connection conn; conn.op = std::move(op); conn.op->shared_resource(shared_resource()); conn.op->mode(mode_); conn.frozen = frozen; conn.name = name; if(connections_index_.find(name) != connections_index_.end()) { throw ValidationError("Operator with name " + name + " exists"); } for(size_t i=0;i<inputs.size();i++) { auto spec_it = tensor_specs_.find(inputs[i]); if(spec_it == tensor_specs_.end()) { throw ValidationError("No such tensor " + inputs[i]); } conn.input_specs.push_back(spec_it->second); } conn.input_names = inputs; conn.op->setup(conn.input_specs,conn.output_specs,conn.parameter_specs,conn.ws_size); if(conn.output_specs.size() != outputs.size()) { throw ValidationError("Operator " + name + " expects to have " + std::to_string(conn.output_specs.size()) + " outputs, but only " + std::to_string(outputs.size()) + " provided"); } conn.output_names = outputs; for(size_t i=0;i<outputs.size();i++) { auto p = tensor_specs_.find(outputs[i]); if(p == tensor_specs_.end()) { tensor_specs_[outputs[i]] = conn.output_specs[i]; } else { if(p->second != conn.output_specs[i]) { std::ostringstream ss; ss << "Tensor " << outputs[i] << " is already defined with spec " << p->second << " but operator " << name << " requires following output specs " << conn.output_specs[i]; throw ValidationError(ss.str()); } if(std::find(inputs.begin(),inputs.end(),outputs[i]) == inputs.end()) { throw ValidationError("Output " + outputs[i] + " for operator " + name + " aleady exists " " howover it isn't as as input, output tensor can't have different sources other " " then self/in-place operations "); } } if(conn.op->alias_generator()) { if(inputs.size() != outputs.size()) { throw ValidationError("Inputs need to have same size for operator " + name); } for(size_t i=0;i<inputs.size();i++) { if(conn.input_specs[i].dtype() != conn.output_specs[i].dtype() || conn.input_specs[i].shape().total_size() != conn.output_specs[i].shape().total_size()) { throw ValidationError("Alias operator need to have tensors of same type and size, only shape may be altered for "+ name); } std::string src = inputs[i]; std::map<std::string,std::string>::iterator p; while((p=alias_sources_.find(src))!=alias_sources_.end()) src = p->second; alias_sources_[outputs[i]]=src; } } } if(frozen) { for(auto &spec : conn.parameter_specs) { spec.freeze(); } } unsigned params_no = conn.parameter_specs.size(); if(params_no < parameters.size()) { std::ostringstream ss; ss << "Too many parameter names for operaror " << name << " expecting " << params_no << " got " << parameters.size(); throw ValidationError(ss.str()); } conn.parameter_names = parameters; conn.parameter_names.resize(params_no); for(size_t i=0;i<conn.parameter_names.size();i++) { std::string &pname = conn.parameter_names[i]; if(pname.empty() || pname == "auto") { conn.parameter_names[i] = name + "." + std::to_string(i); } auto p = parameter_specs_.find(pname); if(p==parameter_specs_.end()) { parameter_specs_[pname] = conn.parameter_specs[i]; } else { if(p->second != conn.parameter_specs[i]) { std::ostringstream ss; ss << "Conflicting requirements for parameters specifications " << p->second << " vs " << conn.parameter_specs[i] << " for " << pname; throw ValidationError(ss.str()); } } } connections_index_[name] = connections_.size(); connections_.push_back(std::move(conn)); } void Net::setup() { clear_memory(); mark_backpropagating_edges(); setup_ws(); allocate_tensors(); } void Net::setup_ws() { size_t ws = 0; for(auto &c : connections_) ws = std::max(c.ws_size,ws); if(ws > 0) { if(workspace_.memory_size() < ws) { workspace_ = Tensor(); // clear first workspace_ = Tensor(ctx_,Shape(ws),uint8_data); } } else workspace_ = Tensor(); } bool Net::is_loss(std::string const &name) { return loss_weights_.find(name)!=loss_weights_.end(); } void Net::mark_backpropagating_edges() { std::map<std::string,int> requires_gradient; for(std::string const &name : inputs_) { if(tensor_specs_[name].is_trainable()) requires_gradient[name] |= 1; } for(std::string const &name : outputs_) { if(is_loss(name)) requires_gradient[name] |= 2; } for(size_t i=0;i<connections_.size();i++) { connections_[i].gradient_flags = 0; } // needs gradient for(size_t i=0;i<connections_.size();i++) { int &gradient_flags = connections_[i].gradient_flags; for(auto const &spec : connections_[i].parameter_specs) { if(spec.is_trainable()) { gradient_flags |= 1; break; } } for(auto const &name : connections_[i].input_names) { if(requires_gradient[name] & 1) { gradient_flags |= 1; break; } } if((gradient_flags & 1) == 0) continue; for(auto const &name : connections_[i].output_names) { requires_gradient[name] |= 1; } } // needs gradient for(int i=connections_.size()-1;i>=0;i--) { int &gradient_flags = connections_[i].gradient_flags; for(auto const &name : connections_[i].output_names) { if(requires_gradient[name] & 2) { gradient_flags |= 2; break; } } if((connections_[i].gradient_flags & 2) == 0) continue; for(auto const &name : connections_[i].input_names) { requires_gradient[name] |= 2; } } for(auto &ts : tensor_specs_) { if(requires_gradient[ts.first]!=3) { ts.second.freeze(); } } } void Net::tensor_use_list(std::vector<std::list<std::string> > &start, std::vector<std::list<std::string> > &stop) { std::map<std::string,std::pair<int,int> > used_at; int last = connections_.size()-1; for(auto const &n : inputs_) used_at[n] = std::make_pair(0,last); for(auto const &n : outputs_) used_at[n] = std::make_pair(0,last); for(int i=0;i<int(connections_.size());i++) { for(int dir=0;dir<2;dir++) { for(auto const &tensor_name : (dir == 0 ? connections_[i].input_names : connections_[i].output_names)) { std::string name; auto p = alias_sources_.find(tensor_name); if(p != alias_sources_.end()) name = p->second; else name = tensor_name; if(used_at.find(name) == used_at.end()) { used_at[name] = std::make_pair(i,i); } else { auto &fl = used_at[name]; fl.first = std::min(fl.first,i); fl.second = std::max(fl.second,i); } } } } start.clear(); start.resize(connections_.size()); stop.clear(); stop.resize(connections_.size()); for(auto const &v:used_at) { start[v.second.first].push_back(v.first); stop[v.second.second].push_back(v.first); } } void Net::allocate_optimized_chunks(bool forward) { std::vector<std::list<std::string> > alloc_needed; std::vector<std::list<std::string> > free_needed; tensor_use_list(alloc_needed,free_needed); if(!forward) alloc_needed.swap(free_needed); std::multimap<size_t,int> pool; std::vector<size_t> chunks; std::map<std::string,int> chunks_mapping; int step_offset,step_scale; if(forward) { step_offset = 0; step_scale = 1; } else { step_offset = connections_.size() - 1; step_scale = -1; } for(unsigned i=0;i<connections_.size();i++) { int index = i * step_scale + step_offset; for(auto const &n : alloc_needed[index]) { size_t mem = tensor_specs_[n].memory_size(); if(pool.empty()) { chunks_mapping[n] = chunks.size(); chunks.push_back(mem); } else { auto p = pool.lower_bound(mem); if(p!=pool.end()) { chunks_mapping[n] = p->second; pool.erase(p); } else { auto last = pool.rbegin(); chunks_mapping[n] = last->second; chunks[last->second] = mem; // increase memory pool.erase(std::prev(pool.end())); } } } for(auto const &n : free_needed[index]) { int cid = chunks_mapping[n]; pool.insert(std::make_pair(chunks[cid],cid)); } } memory_.clear(); for(size_t i=0;i<chunks.size();i++) { memory_.push_back(Tensor(ctx_,Shape(chunks[i]),uint8_data)); } tensors_.clear(); tensors_diff_.clear(); for(auto const &ts : tensor_specs_) { if(alias_sources_.count(ts.first) > 0) continue; int cid = chunks_mapping[ts.first]; auto base_tensor = memory_[cid]; Tensor actual_tensor = base_tensor.sub_tensor(0,ts.second.shape(),ts.second.dtype()); if(forward) { tensors_[ts.first ] = actual_tensor; } else { tensors_[ts.first ] = Tensor(ctx_,ts.second.shape(),ts.second.dtype()); tensors_diff_[ts.first ] = actual_tensor; } } allocate_aliases(); } void Net::allocate_chunks() { tensors_.clear(); tensors_diff_.clear(); memory_.clear(); bool train = mode_ == CalculationsMode::train; // normal for(auto const &ts : tensor_specs_) { if(alias_sources_.count(ts.first) != 0) continue; tensors_[ts.first ] = Tensor(ctx_,ts.second.shape(),ts.second.dtype()); if(train) tensors_diff_[ts.first ] = Tensor(ctx_,ts.second.shape(),ts.second.dtype()); } allocate_aliases(); } void Net::allocate_aliases() { bool train = mode_ == CalculationsMode::train; // alias for(auto const &ts : tensor_specs_) { auto p = alias_sources_.find(ts.first); if(p==alias_sources_.end()) continue; std::string src_name = p->second; tensors_[ts.first ] = tensors_[src_name].alias(ts.second.shape()); if(train) tensors_diff_[ts.first ] = tensors_diff_[src_name].alias(ts.second.shape()); } } void Net::allocate_tensors() { tensors_.clear(); tensors_diff_.clear(); parameters_.clear(); bool train = mode_ == CalculationsMode::train; if(keep_intermediate_tensors_) allocate_chunks(); else allocate_optimized_chunks(!train); // forward = !train for(auto const &ps : parameter_specs_) { parameters_[ps.first ] = Tensor(ctx_,ps.second.shape(),ps.second.dtype(),ps.second.is_trainable()); if(train && ps.second.is_trainable()) parameters_diff_[ps.first ] = Tensor(ctx_,ps.second.shape(),ps.second.dtype()); } /// FWD connections for(auto &conn : connections_) { conn.input_tensors.clear(); conn.output_tensors.clear(); for(auto const &name : conn.input_names) { conn.input_tensors.push_back(tensors_[name]); } for(auto const &name : conn.output_names) { conn.output_tensors.push_back(tensors_[name]); } if(conn.parameter_names.empty()) continue; conn.parameters.clear(); for(auto const &name : conn.parameter_names) { conn.parameters.push_back(parameters_[name]); } } /// BWD Connections std::set<std::string> zeroed_grad; for(int index=connections_.size()-1;index>=0;index--) { auto &conn = connections_[index]; conn.in_grad.clear(); conn.out_grad.clear(); conn.param_grad.clear(); bool is_trainable = train && conn.gradient_flags == 3; for(auto const &name : conn.input_names) { bool in_place = std::find(conn.output_names.begin(), conn.output_names.end(), name) != conn.output_names.end(); TensorAndGradient tg; tg.data = tensors_[name]; if(tensor_specs_[name].is_trainable() && is_trainable) { tg.diff = tensors_diff_[name]; if(zeroed_grad.find(name) == zeroed_grad.end() || in_place) { tg.accumulate_gradient = 0.0; // first in BP zeroes gradient zeroed_grad.insert(name); } else { tg.accumulate_gradient = 1.0; // next accumulate } tg.requires_gradient = true; } else tg.requires_gradient = false; conn.in_grad.push_back(tg); } for(auto const &name : conn.output_names) { TensorAndGradient tg; tg.data = tensors_[name]; if(is_trainable) tg.diff = tensors_diff_[name]; tg.accumulate_gradient = 0.0; tg.requires_gradient = true; conn.out_grad.push_back(tg); } if(conn.parameter_names.empty()) continue; for(auto const &name : conn.parameter_names) { TensorAndGradient tg; tg.data = parameters_[name]; if(tg.data.is_trainable() && is_trainable) { tg.diff = parameters_diff_[name]; tg.accumulate_gradient = 1.0f; tg.requires_gradient = true; } else { tg.accumulate_gradient = 0; tg.requires_gradient = false; } conn.param_grad.push_back(tg); } } } void Net::copy_parameters_to_device() { cl::CommandQueue q = ctx_.make_queue(); for(auto &pr : parameters_) { pr.second.to_device(q); } } void Net::copy_parameters_to_host() { cl::CommandQueue q = ctx_.make_queue(); for(auto &pr : parameters_) { pr.second.to_host(q); } } void Net::reshape() { std::vector<Shape> in,out; bool train = mode_ == CalculationsMode::train; for(auto &conn : connections_) { in.clear(); out.clear(); for(Tensor &s : conn.input_tensors) in.push_back(s.shape()); conn.op->reshape(in,out,conn.ws_size); for(unsigned i=0;i<out.size();i++) { conn.output_tensors[i].reshape(out[i]); if(train && tensor_specs_[conn.output_names[i]].is_trainable()) { conn.out_grad[i].diff.reshape(out[i]); } } } setup_ws(); } void Net::clear_memory() { for(auto &conn : connections_) { conn.input_tensors.clear(); conn.output_tensors.clear(); conn.in_grad.clear(); conn.out_grad.clear(); conn.param_grad.clear(); } workspace_ = Tensor(); tensors_.clear(); tensors_diff_.clear(); parameters_.clear(); parameters_diff_.clear(); memory_.clear(); } void Net::forward(ExecutionContext const &e,bool sync) { ExecGuard g(e,"forward"); for(size_t i=0;i<connections_.size();i++) { ExecGuard g(e,connections_[i].name.c_str()); ExecutionContext ec = e.generate_series_context(i,connections_.size()); connections_[i].op->forward( connections_[i].input_tensors, connections_[i].output_tensors, connections_[i].parameters, workspace_, ec); if(sync && ctx_.is_opencl_context()) e.queue().finish(); } } void Net::backward(ExecutionContext const &e,bool sync) { ExecGuard g(e,"backward"); for(int i=connections_.size() - 1,it=0;i >= 0;i--,it++) { ExecGuard g(e,connections_[i].name.c_str()); ExecutionContext ec = e.generate_series_context(it,connections_.size()); if(connections_[i].gradient_flags != 3) continue; connections_[i].op->backward( connections_[i].in_grad, connections_[i].out_grad, connections_[i].param_grad, workspace_, ec); if(sync && ctx_.is_opencl_context()) { e.queue().finish(); } } } }
37.670507
149
0.504557
philipturner
aab53f4a2b75ce272f45d83272aff6173d134b2c
2,882
cc
C++
src/ir/di-location.cc
lung21/llvm-node
e1b800e8023370134684e33ef700dc0e2a83bac2
[ "MIT" ]
null
null
null
src/ir/di-location.cc
lung21/llvm-node
e1b800e8023370134684e33ef700dc0e2a83bac2
[ "MIT" ]
null
null
null
src/ir/di-location.cc
lung21/llvm-node
e1b800e8023370134684e33ef700dc0e2a83bac2
[ "MIT" ]
null
null
null
#include <nan.h> #include "llvm-context.h" #include "di-location.h" #include "di-local-scope.h" NAN_MODULE_INIT(DILocationWrapper::Init) { auto diLocation = Nan::GetFunction(Nan::New(diLocationTemplate())).ToLocalChecked(); Nan::Set(target, Nan::New("DILocation").ToLocalChecked(), diLocation); } llvm::DILocation *DILocationWrapper::getDILocation() { return diLocation; } v8::Local<v8::Object> DILocationWrapper::of(llvm::DILocation *diLocation) { auto constructorFunction = Nan::GetFunction(Nan::New(diLocationTemplate())).ToLocalChecked(); v8::Local<v8::Value> args[1] = { Nan::New<v8::External>(diLocation) }; auto instance = Nan::NewInstance(constructorFunction, 1, args).ToLocalChecked(); Nan::EscapableHandleScope escapeScpoe; return escapeScpoe.Escape(instance); } bool DILocationWrapper::isInstance(v8::Local<v8::Value> value) { return Nan::New(diLocationTemplate())->HasInstance(value); } DILocationWrapper::DILocationWrapper(llvm::DILocation *location): diLocation(location) {} NAN_METHOD(DILocationWrapper::New) { if (!info.IsConstructCall()) { return Nan::ThrowTypeError("DILocation constructor needs to be called with new"); } if (info.Length() < 1 || !info[0]->IsExternal()) { return Nan::ThrowTypeError("Expected type pointer"); } auto *diLocation = static_cast<llvm::DILocation*>(v8::External::Cast(*info[0])->Value()); auto *wrapper = new DILocationWrapper(diLocation); wrapper->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } NAN_METHOD(DILocationWrapper::get) { if (info.Length() != 4 || !LLVMContextWrapper::isInstance(info[0]) || !info[1]->IsInt32() || !info[2]->IsInt32() || !DILocalScopeWrapper::isInstance(info[3])) { return Nan::ThrowTypeError("get accepts only 4 arguments"); } auto &context = LLVMContextWrapper::FromValue(info[0])->getContext(); uint32_t line = Nan::To<uint32_t>(info[1]).FromJust(); uint32_t column = Nan::To<uint32_t>(info[2]).FromJust(); auto *diLocalScope = DILocalScopeWrapper::FromValue(info[3])->getDILocalScope(); auto *diLocation = llvm::DILocation::get(context, line, column, diLocalScope); info.GetReturnValue().Set(DILocationWrapper::of(diLocation)); } Nan::Persistent<v8::FunctionTemplate> &DILocationWrapper::diLocationTemplate() { static Nan::Persistent<v8::FunctionTemplate> functionTemplate; if (functionTemplate.IsEmpty()) { v8::Local<v8::FunctionTemplate> localTemplate = Nan::New<v8::FunctionTemplate>(DILocationWrapper::New); localTemplate->SetClassName(Nan::New("DILocation").ToLocalChecked()); localTemplate->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetMethod(localTemplate, "get", DILocationWrapper::get); functionTemplate.Reset(localTemplate); } return functionTemplate; }
39.479452
111
0.700902
lung21
aab93128100df8f51566e82dc2b73c1839d99f59
2,154
cpp
C++
source/logger.cpp
CraftyBoss/SMO-Galaxy-Gravity
c95f5bb7cd9bda797ce2bec17add559f0b611841
[ "MIT" ]
2
2022-03-19T00:54:16.000Z
2022-03-20T01:56:08.000Z
source/logger.cpp
CraftyBoss/SMO-Galaxy-Gravity
c95f5bb7cd9bda797ce2bec17add559f0b611841
[ "MIT" ]
null
null
null
source/logger.cpp
CraftyBoss/SMO-Galaxy-Gravity
c95f5bb7cd9bda797ce2bec17add559f0b611841
[ "MIT" ]
null
null
null
#include "logger.hpp" Logger *gLogger; void Logger::init() { in_addr hostAddress = {0}; sockaddr serverAddress = {0}; if (this->socket_log_state != SOCKET_LOG_UNINITIALIZED) return; nn::nifm::Initialize(); nn::nifm::SubmitNetworkRequest(); while (nn::nifm::IsNetworkRequestOnHold()) { } if (!nn::nifm::IsNetworkAvailable()) { this->socket_log_state = SOCKET_LOG_UNAVAILABLE; return; } if ((this->socket_log_socket = nn::socket::Socket(2, 1, 0)) < 0) { this->socket_log_state = SOCKET_LOG_UNAVAILABLE; return; } nn::socket::InetAton(this->sock_ip, &hostAddress); serverAddress.address = hostAddress; serverAddress.port = nn::socket::InetHtons(this->port); serverAddress.family = 2; if (nn::socket::Connect(this->socket_log_socket, &serverAddress, sizeof(serverAddress)) != 0) { this->socket_log_state = SOCKET_LOG_UNAVAILABLE; return; } this->socket_log_state = SOCKET_LOG_CONNECTED; this->isDisableName = false; } void Logger::LOG(const char *fmt, ...) { va_list args; va_start(args, fmt); char buf[0x500]; if (nn::util::VSNPrintf(buf, sizeof(buf), fmt, args) > 0) { if (!isDisableName) { char prefix[0x510]; nn::util::SNPrintf(prefix, sizeof(prefix), "[%s] %s", this->sockName, buf); socket_log(prefix); } else { socket_log(buf); } } va_end(args); } void Logger::LOG(const char *fmt, va_list args) { // impl for replacing seads system::print char buf[0x500]; if (nn::util::VSNPrintf(buf, sizeof(buf), fmt, args) > 0) { socket_log(buf); } } s32 Logger::READ(char *out) { return this->socket_read_char(out); } bool Logger::pingSocket() { return socket_log("ping") > 0; // if value is greater than zero, than the socket recieved our message, otherwise the connection was lost. } void tryInitSocket() { __asm("STR X20, [X8,#0x18]"); gLogger = new Logger(GLOBALDEBUGIP, 3080, "MainLogger"); // PLACE LOCAL PC IP ADDRESS HERE }
22.4375
141
0.610028
CraftyBoss
aaba0f8d6bae2a8764c1fffcc2e2e22f39b281a8
1,210
cpp
C++
Intuit/2.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
Intuit/2.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
Intuit/2.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
#include <string> #include <vector> using namespace std; class Solution { public: vector<int> DIR = {0, 1, 0, -1, 0}; bool valid(int i, int j, int n, int m) { return i >= 0 && i < n && j >= 0 && j < m; } bool search(int i, int j, int k, vector<vector<char>>& board, string& word, vector<vector<bool>>& vis) { if (k >= word.size()) { return true; } bool found = false; // cout << board[i][j] << endl; vis[i][j] = true; for (int p = 0; p < 4; p++) { int x = i + DIR[p]; int y = j + DIR[p + 1]; if (valid(x, y, board.size(), board[0].size()) && !vis[x][y] && board[x][y] == word[k]) { found = found || search(x, y, k + 1, board, word, vis); } } vis[i][j] = false; return found; } bool isWordExist(vector<vector<char>>& board, string word) { int n = board.size(), m = board[0].size(); bool found = false; vector<vector<bool>> vis(n, vector<bool>(m, false)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (board[i][j] == word[0]) { found = found || search(i, j, 1, board, word, vis); } } } return found; } };
22.830189
77
0.475207
aabhas-sao
aabd8af909dedee58c1be66537e5ad14d011a12f
82,600
cc
C++
src/ros/src/security/include/modules/perception/proto/perception_obstacle.pb.cc
Kurinkitos/Twizy-Security
38f3ad3d7315f67e8e691dde69b740b00b33d7b4
[ "MIT" ]
1
2018-05-25T07:20:17.000Z
2018-05-25T07:20:17.000Z
src/ros/src/security/include/modules/perception/proto/perception_obstacle.pb.cc
Kurinkitos/Twizy-Security
38f3ad3d7315f67e8e691dde69b740b00b33d7b4
[ "MIT" ]
null
null
null
src/ros/src/security/include/modules/perception/proto/perception_obstacle.pb.cc
Kurinkitos/Twizy-Security
38f3ad3d7315f67e8e691dde69b740b00b33d7b4
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: modules/perception/proto/perception_obstacle.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "modules/perception/proto/perception_obstacle.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace apollo { namespace perception { class PointDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<Point> { } _Point_default_instance_; class PerceptionObstacleDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<PerceptionObstacle> { } _PerceptionObstacle_default_instance_; class PerceptionObstaclesDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<PerceptionObstacles> { } _PerceptionObstacles_default_instance_; namespace protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto { namespace { ::google::protobuf::Metadata file_level_metadata[3]; const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors[2]; } // namespace PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField const TableStruct::entries[] = { {0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0}, }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField const TableStruct::aux[] = { ::google::protobuf::internal::AuxillaryParseTableField(), }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const TableStruct::schema[] = { { NULL, NULL, 0, -1, -1, false }, { NULL, NULL, 0, -1, -1, false }, { NULL, NULL, 0, -1, -1, false }, }; const ::google::protobuf::uint32 TableStruct::offsets[] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, x_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, y_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Point, z_), 0, 1, 2, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, position_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, theta_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, velocity_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, length_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, width_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, height_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, polygon_point_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, tracking_time_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, timestamp_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, point_cloud_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, confidence_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacle, confidence_type_), 4, 0, 2, 1, 3, 6, 7, ~0u, 8, 5, 9, ~0u, 11, 10, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacles, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacles, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacles, perception_obstacle_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacles, header_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PerceptionObstacles, error_code_), ~0u, 0, 1, }; static const ::google::protobuf::internal::MigrationSchema schemas[] = { { 0, 8, sizeof(Point)}, { 11, 30, sizeof(PerceptionObstacle)}, { 44, 52, sizeof(PerceptionObstacles)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&_Point_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&_PerceptionObstacle_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&_PerceptionObstacles_default_instance_), }; namespace { void protobuf_AssignDescriptors() { AddDescriptors(); ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( "modules/perception/proto/perception_obstacle.proto", schemas, file_default_instances, TableStruct::offsets, factory, file_level_metadata, file_level_enum_descriptors, NULL); } void protobuf_AssignDescriptorsOnce() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3); } } // namespace void TableStruct::Shutdown() { _Point_default_instance_.Shutdown(); delete file_level_metadata[0].reflection; _PerceptionObstacle_default_instance_.Shutdown(); delete file_level_metadata[1].reflection; _PerceptionObstacles_default_instance_.Shutdown(); delete file_level_metadata[2].reflection; } void TableStruct::InitDefaultsImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::internal::InitProtobufDefaults(); ::apollo::common::protobuf_modules_2fcommon_2fproto_2ferror_5fcode_2eproto::InitDefaults(); ::apollo::common::protobuf_modules_2fcommon_2fproto_2fheader_2eproto::InitDefaults(); _Point_default_instance_.DefaultConstruct(); _PerceptionObstacle_default_instance_.DefaultConstruct(); _PerceptionObstacles_default_instance_.DefaultConstruct(); _PerceptionObstacle_default_instance_.get_mutable()->position_ = const_cast< ::apollo::perception::Point*>( ::apollo::perception::Point::internal_default_instance()); _PerceptionObstacle_default_instance_.get_mutable()->velocity_ = const_cast< ::apollo::perception::Point*>( ::apollo::perception::Point::internal_default_instance()); _PerceptionObstacles_default_instance_.get_mutable()->header_ = const_cast< ::apollo::common::Header*>( ::apollo::common::Header::internal_default_instance()); } void InitDefaults() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] = { "\n2modules/perception/proto/perception_ob" "stacle.proto\022\021apollo.perception\032%modules" "/common/proto/error_code.proto\032!modules/" "common/proto/header.proto\"(\n\005Point\022\t\n\001x\030" "\001 \001(\001\022\t\n\001y\030\002 \001(\001\022\t\n\001z\030\003 \001(\001\"\231\005\n\022Percepti" "onObstacle\022\n\n\002id\030\001 \001(\005\022*\n\010position\030\002 \001(\013" "2\030.apollo.perception.Point\022\r\n\005theta\030\003 \001(" "\001\022*\n\010velocity\030\004 \001(\0132\030.apollo.perception." "Point\022\016\n\006length\030\005 \001(\001\022\r\n\005width\030\006 \001(\001\022\016\n\006" "height\030\007 \001(\001\022/\n\rpolygon_point\030\010 \003(\0132\030.ap" "ollo.perception.Point\022\025\n\rtracking_time\030\t" " \001(\001\0228\n\004type\030\n \001(\0162*.apollo.perception.P" "erceptionObstacle.Type\022\021\n\ttimestamp\030\013 \001(" "\001\022\027\n\013point_cloud\030\014 \003(\001B\002\020\001\022\025\n\nconfidence" "\030\r \001(\001:\0011\022]\n\017confidence_type\030\016 \001(\01624.apo" "llo.perception.PerceptionObstacle.Confid" "enceType:\016CONFIDENCE_CNN\"i\n\004Type\022\013\n\007UNKN" "OWN\020\000\022\023\n\017UNKNOWN_MOVABLE\020\001\022\025\n\021UNKNOWN_UN" "MOVABLE\020\002\022\016\n\nPEDESTRIAN\020\003\022\013\n\007BICYCLE\020\004\022\013" "\n\007VEHICLE\020\005\"R\n\016ConfidenceType\022\026\n\022CONFIDE" "NCE_UNKNOWN\020\000\022\022\n\016CONFIDENCE_CNN\020\001\022\024\n\020CON" "FIDENCE_RADAR\020\002\"\262\001\n\023PerceptionObstacles\022" "B\n\023perception_obstacle\030\001 \003(\0132%.apollo.pe" "rception.PerceptionObstacle\022%\n\006header\030\002 " "\001(\0132\025.apollo.common.Header\0220\n\nerror_code" "\030\003 \001(\0162\030.apollo.common.ErrorCode:\002OK" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 1036); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "modules/perception/proto/perception_obstacle.proto", &protobuf_RegisterTypes); ::apollo::common::protobuf_modules_2fcommon_2fproto_2ferror_5fcode_2eproto::AddDescriptors(); ::apollo::common::protobuf_modules_2fcommon_2fproto_2fheader_2eproto::AddDescriptors(); ::google::protobuf::internal::OnShutdown(&TableStruct::Shutdown); } void AddDescriptors() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto const ::google::protobuf::EnumDescriptor* PerceptionObstacle_Type_descriptor() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_enum_descriptors[0]; } bool PerceptionObstacle_Type_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const PerceptionObstacle_Type PerceptionObstacle::UNKNOWN; const PerceptionObstacle_Type PerceptionObstacle::UNKNOWN_MOVABLE; const PerceptionObstacle_Type PerceptionObstacle::UNKNOWN_UNMOVABLE; const PerceptionObstacle_Type PerceptionObstacle::PEDESTRIAN; const PerceptionObstacle_Type PerceptionObstacle::BICYCLE; const PerceptionObstacle_Type PerceptionObstacle::VEHICLE; const PerceptionObstacle_Type PerceptionObstacle::Type_MIN; const PerceptionObstacle_Type PerceptionObstacle::Type_MAX; const int PerceptionObstacle::Type_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 const ::google::protobuf::EnumDescriptor* PerceptionObstacle_ConfidenceType_descriptor() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_enum_descriptors[1]; } bool PerceptionObstacle_ConfidenceType_IsValid(int value) { switch (value) { case 0: case 1: case 2: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const PerceptionObstacle_ConfidenceType PerceptionObstacle::CONFIDENCE_UNKNOWN; const PerceptionObstacle_ConfidenceType PerceptionObstacle::CONFIDENCE_CNN; const PerceptionObstacle_ConfidenceType PerceptionObstacle::CONFIDENCE_RADAR; const PerceptionObstacle_ConfidenceType PerceptionObstacle::ConfidenceType_MIN; const PerceptionObstacle_ConfidenceType PerceptionObstacle::ConfidenceType_MAX; const int PerceptionObstacle::ConfidenceType_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Point::kXFieldNumber; const int Point::kYFieldNumber; const int Point::kZFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Point::Point() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:apollo.perception.Point) } Point::Point(const Point& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&x_, &from.x_, reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_) + sizeof(z_)); // @@protoc_insertion_point(copy_constructor:apollo.perception.Point) } void Point::SharedCtor() { _cached_size_ = 0; ::memset(&x_, 0, reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_) + sizeof(z_)); } Point::~Point() { // @@protoc_insertion_point(destructor:apollo.perception.Point) SharedDtor(); } void Point::SharedDtor() { } void Point::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Point::descriptor() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const Point& Point::default_instance() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); return *internal_default_instance(); } Point* Point::New(::google::protobuf::Arena* arena) const { Point* n = new Point; if (arena != NULL) { arena->Own(n); } return n; } void Point::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.perception.Point) if (_has_bits_[0 / 32] & 7u) { ::memset(&x_, 0, reinterpret_cast<char*>(&z_) - reinterpret_cast<char*>(&x_) + sizeof(z_)); } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool Point::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.perception.Point) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional double x = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(9u)) { set_has_x(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &x_))); } else { goto handle_unusual; } break; } // optional double y = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(17u)) { set_has_y(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &y_))); } else { goto handle_unusual; } break; } // optional double z = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(25u)) { set_has_z(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &z_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.perception.Point) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.perception.Point) return false; #undef DO_ } void Point::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.perception.Point) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional double x = 1; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->x(), output); } // optional double y = 2; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->y(), output); } // optional double z = 3; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->z(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.perception.Point) } ::google::protobuf::uint8* Point::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.perception.Point) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional double x = 1; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->x(), target); } // optional double y = 2; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->y(), target); } // optional double z = 3; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->z(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.perception.Point) return target; } size_t Point::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:apollo.perception.Point) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } if (_has_bits_[0 / 32] & 7u) { // optional double x = 1; if (has_x()) { total_size += 1 + 8; } // optional double y = 2; if (has_y()) { total_size += 1 + 8; } // optional double z = 3; if (has_z()) { total_size += 1 + 8; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Point::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.perception.Point) GOOGLE_DCHECK_NE(&from, this); const Point* source = ::google::protobuf::internal::DynamicCastToGenerated<const Point>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.perception.Point) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.perception.Point) MergeFrom(*source); } } void Point::MergeFrom(const Point& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.perception.Point) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 7u) { if (cached_has_bits & 0x00000001u) { x_ = from.x_; } if (cached_has_bits & 0x00000002u) { y_ = from.y_; } if (cached_has_bits & 0x00000004u) { z_ = from.z_; } _has_bits_[0] |= cached_has_bits; } } void Point::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.perception.Point) if (&from == this) return; Clear(); MergeFrom(from); } void Point::CopyFrom(const Point& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.perception.Point) if (&from == this) return; Clear(); MergeFrom(from); } bool Point::IsInitialized() const { return true; } void Point::Swap(Point* other) { if (other == this) return; InternalSwap(other); } void Point::InternalSwap(Point* other) { std::swap(x_, other->x_); std::swap(y_, other->y_); std::swap(z_, other->z_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata Point::GetMetadata() const { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // Point // optional double x = 1; bool Point::has_x() const { return (_has_bits_[0] & 0x00000001u) != 0; } void Point::set_has_x() { _has_bits_[0] |= 0x00000001u; } void Point::clear_has_x() { _has_bits_[0] &= ~0x00000001u; } void Point::clear_x() { x_ = 0; clear_has_x(); } double Point::x() const { // @@protoc_insertion_point(field_get:apollo.perception.Point.x) return x_; } void Point::set_x(double value) { set_has_x(); x_ = value; // @@protoc_insertion_point(field_set:apollo.perception.Point.x) } // optional double y = 2; bool Point::has_y() const { return (_has_bits_[0] & 0x00000002u) != 0; } void Point::set_has_y() { _has_bits_[0] |= 0x00000002u; } void Point::clear_has_y() { _has_bits_[0] &= ~0x00000002u; } void Point::clear_y() { y_ = 0; clear_has_y(); } double Point::y() const { // @@protoc_insertion_point(field_get:apollo.perception.Point.y) return y_; } void Point::set_y(double value) { set_has_y(); y_ = value; // @@protoc_insertion_point(field_set:apollo.perception.Point.y) } // optional double z = 3; bool Point::has_z() const { return (_has_bits_[0] & 0x00000004u) != 0; } void Point::set_has_z() { _has_bits_[0] |= 0x00000004u; } void Point::clear_has_z() { _has_bits_[0] &= ~0x00000004u; } void Point::clear_z() { z_ = 0; clear_has_z(); } double Point::z() const { // @@protoc_insertion_point(field_get:apollo.perception.Point.z) return z_; } void Point::set_z(double value) { set_has_z(); z_ = value; // @@protoc_insertion_point(field_set:apollo.perception.Point.z) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int PerceptionObstacle::kIdFieldNumber; const int PerceptionObstacle::kPositionFieldNumber; const int PerceptionObstacle::kThetaFieldNumber; const int PerceptionObstacle::kVelocityFieldNumber; const int PerceptionObstacle::kLengthFieldNumber; const int PerceptionObstacle::kWidthFieldNumber; const int PerceptionObstacle::kHeightFieldNumber; const int PerceptionObstacle::kPolygonPointFieldNumber; const int PerceptionObstacle::kTrackingTimeFieldNumber; const int PerceptionObstacle::kTypeFieldNumber; const int PerceptionObstacle::kTimestampFieldNumber; const int PerceptionObstacle::kPointCloudFieldNumber; const int PerceptionObstacle::kConfidenceFieldNumber; const int PerceptionObstacle::kConfidenceTypeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 PerceptionObstacle::PerceptionObstacle() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:apollo.perception.PerceptionObstacle) } PerceptionObstacle::PerceptionObstacle(const PerceptionObstacle& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0), polygon_point_(from.polygon_point_), point_cloud_(from.point_cloud_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_position()) { position_ = new ::apollo::perception::Point(*from.position_); } else { position_ = NULL; } if (from.has_velocity()) { velocity_ = new ::apollo::perception::Point(*from.velocity_); } else { velocity_ = NULL; } ::memcpy(&theta_, &from.theta_, reinterpret_cast<char*>(&confidence_) - reinterpret_cast<char*>(&theta_) + sizeof(confidence_)); // @@protoc_insertion_point(copy_constructor:apollo.perception.PerceptionObstacle) } void PerceptionObstacle::SharedCtor() { _cached_size_ = 0; ::memset(&position_, 0, reinterpret_cast<char*>(&timestamp_) - reinterpret_cast<char*>(&position_) + sizeof(timestamp_)); confidence_type_ = 1; confidence_ = 1; } PerceptionObstacle::~PerceptionObstacle() { // @@protoc_insertion_point(destructor:apollo.perception.PerceptionObstacle) SharedDtor(); } void PerceptionObstacle::SharedDtor() { if (this != internal_default_instance()) { delete position_; } if (this != internal_default_instance()) { delete velocity_; } } void PerceptionObstacle::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* PerceptionObstacle::descriptor() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const PerceptionObstacle& PerceptionObstacle::default_instance() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); return *internal_default_instance(); } PerceptionObstacle* PerceptionObstacle::New(::google::protobuf::Arena* arena) const { PerceptionObstacle* n = new PerceptionObstacle; if (arena != NULL) { arena->Own(n); } return n; } void PerceptionObstacle::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.perception.PerceptionObstacle) polygon_point_.Clear(); point_cloud_.Clear(); if (_has_bits_[0 / 32] & 3u) { if (has_position()) { GOOGLE_DCHECK(position_ != NULL); position_->::apollo::perception::Point::Clear(); } if (has_velocity()) { GOOGLE_DCHECK(velocity_ != NULL); velocity_->::apollo::perception::Point::Clear(); } } if (_has_bits_[0 / 32] & 252u) { ::memset(&theta_, 0, reinterpret_cast<char*>(&height_) - reinterpret_cast<char*>(&theta_) + sizeof(height_)); } if (_has_bits_[8 / 32] & 3840u) { ::memset(&tracking_time_, 0, reinterpret_cast<char*>(&timestamp_) - reinterpret_cast<char*>(&tracking_time_) + sizeof(timestamp_)); confidence_type_ = 1; confidence_ = 1; } _has_bits_.Clear(); _internal_metadata_.Clear(); } bool PerceptionObstacle::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.perception.PerceptionObstacle) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional int32 id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u)) { set_has_id(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &id_))); } else { goto handle_unusual; } break; } // optional .apollo.perception.Point position = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_position())); } else { goto handle_unusual; } break; } // optional double theta = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(25u)) { set_has_theta(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &theta_))); } else { goto handle_unusual; } break; } // optional .apollo.perception.Point velocity = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(34u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_velocity())); } else { goto handle_unusual; } break; } // optional double length = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(41u)) { set_has_length(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &length_))); } else { goto handle_unusual; } break; } // optional double width = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(49u)) { set_has_width(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &width_))); } else { goto handle_unusual; } break; } // optional double height = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(57u)) { set_has_height(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &height_))); } else { goto handle_unusual; } break; } // repeated .apollo.perception.Point polygon_point = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(66u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_polygon_point())); } else { goto handle_unusual; } break; } // optional double tracking_time = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(73u)) { set_has_tracking_time(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &tracking_time_))); } else { goto handle_unusual; } break; } // optional .apollo.perception.PerceptionObstacle.Type type = 10; case 10: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(80u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::perception::PerceptionObstacle_Type_IsValid(value)) { set_type(static_cast< ::apollo::perception::PerceptionObstacle_Type >(value)); } else { mutable_unknown_fields()->AddVarint(10, value); } } else { goto handle_unusual; } break; } // optional double timestamp = 11; case 11: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(89u)) { set_has_timestamp(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &timestamp_))); } else { goto handle_unusual; } break; } // repeated double point_cloud = 12 [packed = true]; case 12: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(98u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, this->mutable_point_cloud()))); } else if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(97u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( 1, 98u, input, this->mutable_point_cloud()))); } else { goto handle_unusual; } break; } // optional double confidence = 13 [default = 1]; case 13: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(105u)) { set_has_confidence(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &confidence_))); } else { goto handle_unusual; } break; } // optional .apollo.perception.PerceptionObstacle.ConfidenceType confidence_type = 14 [default = CONFIDENCE_CNN]; case 14: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(112u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::perception::PerceptionObstacle_ConfidenceType_IsValid(value)) { set_confidence_type(static_cast< ::apollo::perception::PerceptionObstacle_ConfidenceType >(value)); } else { mutable_unknown_fields()->AddVarint(14, value); } } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.perception.PerceptionObstacle) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.perception.PerceptionObstacle) return false; #undef DO_ } void PerceptionObstacle::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.perception.PerceptionObstacle) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 id = 1; if (cached_has_bits & 0x00000010u) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->id(), output); } // optional .apollo.perception.Point position = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->position_, output); } // optional double theta = 3; if (cached_has_bits & 0x00000004u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->theta(), output); } // optional .apollo.perception.Point velocity = 4; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *this->velocity_, output); } // optional double length = 5; if (cached_has_bits & 0x00000008u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(5, this->length(), output); } // optional double width = 6; if (cached_has_bits & 0x00000040u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->width(), output); } // optional double height = 7; if (cached_has_bits & 0x00000080u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(7, this->height(), output); } // repeated .apollo.perception.Point polygon_point = 8; for (unsigned int i = 0, n = this->polygon_point_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 8, this->polygon_point(i), output); } // optional double tracking_time = 9; if (cached_has_bits & 0x00000100u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(9, this->tracking_time(), output); } // optional .apollo.perception.PerceptionObstacle.Type type = 10; if (cached_has_bits & 0x00000020u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 10, this->type(), output); } // optional double timestamp = 11; if (cached_has_bits & 0x00000200u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(11, this->timestamp(), output); } // repeated double point_cloud = 12 [packed = true]; if (this->point_cloud_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(12, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_point_cloud_cached_byte_size_); ::google::protobuf::internal::WireFormatLite::WriteDoubleArray( this->point_cloud().data(), this->point_cloud_size(), output); } // optional double confidence = 13 [default = 1]; if (cached_has_bits & 0x00000800u) { ::google::protobuf::internal::WireFormatLite::WriteDouble(13, this->confidence(), output); } // optional .apollo.perception.PerceptionObstacle.ConfidenceType confidence_type = 14 [default = CONFIDENCE_CNN]; if (cached_has_bits & 0x00000400u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 14, this->confidence_type(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.perception.PerceptionObstacle) } ::google::protobuf::uint8* PerceptionObstacle::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.perception.PerceptionObstacle) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional int32 id = 1; if (cached_has_bits & 0x00000010u) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->id(), target); } // optional .apollo.perception.Point position = 2; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->position_, deterministic, target); } // optional double theta = 3; if (cached_has_bits & 0x00000004u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->theta(), target); } // optional .apollo.perception.Point velocity = 4; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, *this->velocity_, deterministic, target); } // optional double length = 5; if (cached_has_bits & 0x00000008u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(5, this->length(), target); } // optional double width = 6; if (cached_has_bits & 0x00000040u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->width(), target); } // optional double height = 7; if (cached_has_bits & 0x00000080u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(7, this->height(), target); } // repeated .apollo.perception.Point polygon_point = 8; for (unsigned int i = 0, n = this->polygon_point_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 8, this->polygon_point(i), deterministic, target); } // optional double tracking_time = 9; if (cached_has_bits & 0x00000100u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(9, this->tracking_time(), target); } // optional .apollo.perception.PerceptionObstacle.Type type = 10; if (cached_has_bits & 0x00000020u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 10, this->type(), target); } // optional double timestamp = 11; if (cached_has_bits & 0x00000200u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(11, this->timestamp(), target); } // repeated double point_cloud = 12 [packed = true]; if (this->point_cloud_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 12, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _point_cloud_cached_byte_size_, target); target = ::google::protobuf::internal::WireFormatLite:: WriteDoubleNoTagToArray(this->point_cloud_, target); } // optional double confidence = 13 [default = 1]; if (cached_has_bits & 0x00000800u) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(13, this->confidence(), target); } // optional .apollo.perception.PerceptionObstacle.ConfidenceType confidence_type = 14 [default = CONFIDENCE_CNN]; if (cached_has_bits & 0x00000400u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 14, this->confidence_type(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.perception.PerceptionObstacle) return target; } size_t PerceptionObstacle::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:apollo.perception.PerceptionObstacle) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } // repeated .apollo.perception.Point polygon_point = 8; { unsigned int count = this->polygon_point_size(); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->polygon_point(i)); } } // repeated double point_cloud = 12 [packed = true]; { unsigned int count = this->point_cloud_size(); size_t data_size = 8UL * count; if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _point_cloud_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } if (_has_bits_[0 / 32] & 255u) { // optional .apollo.perception.Point position = 2; if (has_position()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->position_); } // optional .apollo.perception.Point velocity = 4; if (has_velocity()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->velocity_); } // optional double theta = 3; if (has_theta()) { total_size += 1 + 8; } // optional double length = 5; if (has_length()) { total_size += 1 + 8; } // optional int32 id = 1; if (has_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->id()); } // optional .apollo.perception.PerceptionObstacle.Type type = 10; if (has_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->type()); } // optional double width = 6; if (has_width()) { total_size += 1 + 8; } // optional double height = 7; if (has_height()) { total_size += 1 + 8; } } if (_has_bits_[8 / 32] & 3840u) { // optional double tracking_time = 9; if (has_tracking_time()) { total_size += 1 + 8; } // optional double timestamp = 11; if (has_timestamp()) { total_size += 1 + 8; } // optional .apollo.perception.PerceptionObstacle.ConfidenceType confidence_type = 14 [default = CONFIDENCE_CNN]; if (has_confidence_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->confidence_type()); } // optional double confidence = 13 [default = 1]; if (has_confidence()) { total_size += 1 + 8; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void PerceptionObstacle::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.perception.PerceptionObstacle) GOOGLE_DCHECK_NE(&from, this); const PerceptionObstacle* source = ::google::protobuf::internal::DynamicCastToGenerated<const PerceptionObstacle>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.perception.PerceptionObstacle) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.perception.PerceptionObstacle) MergeFrom(*source); } } void PerceptionObstacle::MergeFrom(const PerceptionObstacle& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.perception.PerceptionObstacle) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; polygon_point_.MergeFrom(from.polygon_point_); point_cloud_.MergeFrom(from.point_cloud_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 255u) { if (cached_has_bits & 0x00000001u) { mutable_position()->::apollo::perception::Point::MergeFrom(from.position()); } if (cached_has_bits & 0x00000002u) { mutable_velocity()->::apollo::perception::Point::MergeFrom(from.velocity()); } if (cached_has_bits & 0x00000004u) { theta_ = from.theta_; } if (cached_has_bits & 0x00000008u) { length_ = from.length_; } if (cached_has_bits & 0x00000010u) { id_ = from.id_; } if (cached_has_bits & 0x00000020u) { type_ = from.type_; } if (cached_has_bits & 0x00000040u) { width_ = from.width_; } if (cached_has_bits & 0x00000080u) { height_ = from.height_; } _has_bits_[0] |= cached_has_bits; } if (cached_has_bits & 3840u) { if (cached_has_bits & 0x00000100u) { tracking_time_ = from.tracking_time_; } if (cached_has_bits & 0x00000200u) { timestamp_ = from.timestamp_; } if (cached_has_bits & 0x00000400u) { confidence_type_ = from.confidence_type_; } if (cached_has_bits & 0x00000800u) { confidence_ = from.confidence_; } _has_bits_[0] |= cached_has_bits; } } void PerceptionObstacle::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.perception.PerceptionObstacle) if (&from == this) return; Clear(); MergeFrom(from); } void PerceptionObstacle::CopyFrom(const PerceptionObstacle& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.perception.PerceptionObstacle) if (&from == this) return; Clear(); MergeFrom(from); } bool PerceptionObstacle::IsInitialized() const { return true; } void PerceptionObstacle::Swap(PerceptionObstacle* other) { if (other == this) return; InternalSwap(other); } void PerceptionObstacle::InternalSwap(PerceptionObstacle* other) { polygon_point_.InternalSwap(&other->polygon_point_); point_cloud_.InternalSwap(&other->point_cloud_); std::swap(position_, other->position_); std::swap(velocity_, other->velocity_); std::swap(theta_, other->theta_); std::swap(length_, other->length_); std::swap(id_, other->id_); std::swap(type_, other->type_); std::swap(width_, other->width_); std::swap(height_, other->height_); std::swap(tracking_time_, other->tracking_time_); std::swap(timestamp_, other->timestamp_); std::swap(confidence_type_, other->confidence_type_); std::swap(confidence_, other->confidence_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata PerceptionObstacle::GetMetadata() const { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // PerceptionObstacle // optional int32 id = 1; bool PerceptionObstacle::has_id() const { return (_has_bits_[0] & 0x00000010u) != 0; } void PerceptionObstacle::set_has_id() { _has_bits_[0] |= 0x00000010u; } void PerceptionObstacle::clear_has_id() { _has_bits_[0] &= ~0x00000010u; } void PerceptionObstacle::clear_id() { id_ = 0; clear_has_id(); } ::google::protobuf::int32 PerceptionObstacle::id() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.id) return id_; } void PerceptionObstacle::set_id(::google::protobuf::int32 value) { set_has_id(); id_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.id) } // optional .apollo.perception.Point position = 2; bool PerceptionObstacle::has_position() const { return (_has_bits_[0] & 0x00000001u) != 0; } void PerceptionObstacle::set_has_position() { _has_bits_[0] |= 0x00000001u; } void PerceptionObstacle::clear_has_position() { _has_bits_[0] &= ~0x00000001u; } void PerceptionObstacle::clear_position() { if (position_ != NULL) position_->::apollo::perception::Point::Clear(); clear_has_position(); } const ::apollo::perception::Point& PerceptionObstacle::position() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.position) return position_ != NULL ? *position_ : *::apollo::perception::Point::internal_default_instance(); } ::apollo::perception::Point* PerceptionObstacle::mutable_position() { set_has_position(); if (position_ == NULL) { position_ = new ::apollo::perception::Point; } // @@protoc_insertion_point(field_mutable:apollo.perception.PerceptionObstacle.position) return position_; } ::apollo::perception::Point* PerceptionObstacle::release_position() { // @@protoc_insertion_point(field_release:apollo.perception.PerceptionObstacle.position) clear_has_position(); ::apollo::perception::Point* temp = position_; position_ = NULL; return temp; } void PerceptionObstacle::set_allocated_position(::apollo::perception::Point* position) { delete position_; position_ = position; if (position) { set_has_position(); } else { clear_has_position(); } // @@protoc_insertion_point(field_set_allocated:apollo.perception.PerceptionObstacle.position) } // optional double theta = 3; bool PerceptionObstacle::has_theta() const { return (_has_bits_[0] & 0x00000004u) != 0; } void PerceptionObstacle::set_has_theta() { _has_bits_[0] |= 0x00000004u; } void PerceptionObstacle::clear_has_theta() { _has_bits_[0] &= ~0x00000004u; } void PerceptionObstacle::clear_theta() { theta_ = 0; clear_has_theta(); } double PerceptionObstacle::theta() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.theta) return theta_; } void PerceptionObstacle::set_theta(double value) { set_has_theta(); theta_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.theta) } // optional .apollo.perception.Point velocity = 4; bool PerceptionObstacle::has_velocity() const { return (_has_bits_[0] & 0x00000002u) != 0; } void PerceptionObstacle::set_has_velocity() { _has_bits_[0] |= 0x00000002u; } void PerceptionObstacle::clear_has_velocity() { _has_bits_[0] &= ~0x00000002u; } void PerceptionObstacle::clear_velocity() { if (velocity_ != NULL) velocity_->::apollo::perception::Point::Clear(); clear_has_velocity(); } const ::apollo::perception::Point& PerceptionObstacle::velocity() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.velocity) return velocity_ != NULL ? *velocity_ : *::apollo::perception::Point::internal_default_instance(); } ::apollo::perception::Point* PerceptionObstacle::mutable_velocity() { set_has_velocity(); if (velocity_ == NULL) { velocity_ = new ::apollo::perception::Point; } // @@protoc_insertion_point(field_mutable:apollo.perception.PerceptionObstacle.velocity) return velocity_; } ::apollo::perception::Point* PerceptionObstacle::release_velocity() { // @@protoc_insertion_point(field_release:apollo.perception.PerceptionObstacle.velocity) clear_has_velocity(); ::apollo::perception::Point* temp = velocity_; velocity_ = NULL; return temp; } void PerceptionObstacle::set_allocated_velocity(::apollo::perception::Point* velocity) { delete velocity_; velocity_ = velocity; if (velocity) { set_has_velocity(); } else { clear_has_velocity(); } // @@protoc_insertion_point(field_set_allocated:apollo.perception.PerceptionObstacle.velocity) } // optional double length = 5; bool PerceptionObstacle::has_length() const { return (_has_bits_[0] & 0x00000008u) != 0; } void PerceptionObstacle::set_has_length() { _has_bits_[0] |= 0x00000008u; } void PerceptionObstacle::clear_has_length() { _has_bits_[0] &= ~0x00000008u; } void PerceptionObstacle::clear_length() { length_ = 0; clear_has_length(); } double PerceptionObstacle::length() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.length) return length_; } void PerceptionObstacle::set_length(double value) { set_has_length(); length_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.length) } // optional double width = 6; bool PerceptionObstacle::has_width() const { return (_has_bits_[0] & 0x00000040u) != 0; } void PerceptionObstacle::set_has_width() { _has_bits_[0] |= 0x00000040u; } void PerceptionObstacle::clear_has_width() { _has_bits_[0] &= ~0x00000040u; } void PerceptionObstacle::clear_width() { width_ = 0; clear_has_width(); } double PerceptionObstacle::width() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.width) return width_; } void PerceptionObstacle::set_width(double value) { set_has_width(); width_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.width) } // optional double height = 7; bool PerceptionObstacle::has_height() const { return (_has_bits_[0] & 0x00000080u) != 0; } void PerceptionObstacle::set_has_height() { _has_bits_[0] |= 0x00000080u; } void PerceptionObstacle::clear_has_height() { _has_bits_[0] &= ~0x00000080u; } void PerceptionObstacle::clear_height() { height_ = 0; clear_has_height(); } double PerceptionObstacle::height() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.height) return height_; } void PerceptionObstacle::set_height(double value) { set_has_height(); height_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.height) } // repeated .apollo.perception.Point polygon_point = 8; int PerceptionObstacle::polygon_point_size() const { return polygon_point_.size(); } void PerceptionObstacle::clear_polygon_point() { polygon_point_.Clear(); } const ::apollo::perception::Point& PerceptionObstacle::polygon_point(int index) const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.polygon_point) return polygon_point_.Get(index); } ::apollo::perception::Point* PerceptionObstacle::mutable_polygon_point(int index) { // @@protoc_insertion_point(field_mutable:apollo.perception.PerceptionObstacle.polygon_point) return polygon_point_.Mutable(index); } ::apollo::perception::Point* PerceptionObstacle::add_polygon_point() { // @@protoc_insertion_point(field_add:apollo.perception.PerceptionObstacle.polygon_point) return polygon_point_.Add(); } ::google::protobuf::RepeatedPtrField< ::apollo::perception::Point >* PerceptionObstacle::mutable_polygon_point() { // @@protoc_insertion_point(field_mutable_list:apollo.perception.PerceptionObstacle.polygon_point) return &polygon_point_; } const ::google::protobuf::RepeatedPtrField< ::apollo::perception::Point >& PerceptionObstacle::polygon_point() const { // @@protoc_insertion_point(field_list:apollo.perception.PerceptionObstacle.polygon_point) return polygon_point_; } // optional double tracking_time = 9; bool PerceptionObstacle::has_tracking_time() const { return (_has_bits_[0] & 0x00000100u) != 0; } void PerceptionObstacle::set_has_tracking_time() { _has_bits_[0] |= 0x00000100u; } void PerceptionObstacle::clear_has_tracking_time() { _has_bits_[0] &= ~0x00000100u; } void PerceptionObstacle::clear_tracking_time() { tracking_time_ = 0; clear_has_tracking_time(); } double PerceptionObstacle::tracking_time() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.tracking_time) return tracking_time_; } void PerceptionObstacle::set_tracking_time(double value) { set_has_tracking_time(); tracking_time_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.tracking_time) } // optional .apollo.perception.PerceptionObstacle.Type type = 10; bool PerceptionObstacle::has_type() const { return (_has_bits_[0] & 0x00000020u) != 0; } void PerceptionObstacle::set_has_type() { _has_bits_[0] |= 0x00000020u; } void PerceptionObstacle::clear_has_type() { _has_bits_[0] &= ~0x00000020u; } void PerceptionObstacle::clear_type() { type_ = 0; clear_has_type(); } ::apollo::perception::PerceptionObstacle_Type PerceptionObstacle::type() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.type) return static_cast< ::apollo::perception::PerceptionObstacle_Type >(type_); } void PerceptionObstacle::set_type(::apollo::perception::PerceptionObstacle_Type value) { assert(::apollo::perception::PerceptionObstacle_Type_IsValid(value)); set_has_type(); type_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.type) } // optional double timestamp = 11; bool PerceptionObstacle::has_timestamp() const { return (_has_bits_[0] & 0x00000200u) != 0; } void PerceptionObstacle::set_has_timestamp() { _has_bits_[0] |= 0x00000200u; } void PerceptionObstacle::clear_has_timestamp() { _has_bits_[0] &= ~0x00000200u; } void PerceptionObstacle::clear_timestamp() { timestamp_ = 0; clear_has_timestamp(); } double PerceptionObstacle::timestamp() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.timestamp) return timestamp_; } void PerceptionObstacle::set_timestamp(double value) { set_has_timestamp(); timestamp_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.timestamp) } // repeated double point_cloud = 12 [packed = true]; int PerceptionObstacle::point_cloud_size() const { return point_cloud_.size(); } void PerceptionObstacle::clear_point_cloud() { point_cloud_.Clear(); } double PerceptionObstacle::point_cloud(int index) const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.point_cloud) return point_cloud_.Get(index); } void PerceptionObstacle::set_point_cloud(int index, double value) { point_cloud_.Set(index, value); // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.point_cloud) } void PerceptionObstacle::add_point_cloud(double value) { point_cloud_.Add(value); // @@protoc_insertion_point(field_add:apollo.perception.PerceptionObstacle.point_cloud) } const ::google::protobuf::RepeatedField< double >& PerceptionObstacle::point_cloud() const { // @@protoc_insertion_point(field_list:apollo.perception.PerceptionObstacle.point_cloud) return point_cloud_; } ::google::protobuf::RepeatedField< double >* PerceptionObstacle::mutable_point_cloud() { // @@protoc_insertion_point(field_mutable_list:apollo.perception.PerceptionObstacle.point_cloud) return &point_cloud_; } // optional double confidence = 13 [default = 1]; bool PerceptionObstacle::has_confidence() const { return (_has_bits_[0] & 0x00000800u) != 0; } void PerceptionObstacle::set_has_confidence() { _has_bits_[0] |= 0x00000800u; } void PerceptionObstacle::clear_has_confidence() { _has_bits_[0] &= ~0x00000800u; } void PerceptionObstacle::clear_confidence() { confidence_ = 1; clear_has_confidence(); } double PerceptionObstacle::confidence() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.confidence) return confidence_; } void PerceptionObstacle::set_confidence(double value) { set_has_confidence(); confidence_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.confidence) } // optional .apollo.perception.PerceptionObstacle.ConfidenceType confidence_type = 14 [default = CONFIDENCE_CNN]; bool PerceptionObstacle::has_confidence_type() const { return (_has_bits_[0] & 0x00000400u) != 0; } void PerceptionObstacle::set_has_confidence_type() { _has_bits_[0] |= 0x00000400u; } void PerceptionObstacle::clear_has_confidence_type() { _has_bits_[0] &= ~0x00000400u; } void PerceptionObstacle::clear_confidence_type() { confidence_type_ = 1; clear_has_confidence_type(); } ::apollo::perception::PerceptionObstacle_ConfidenceType PerceptionObstacle::confidence_type() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacle.confidence_type) return static_cast< ::apollo::perception::PerceptionObstacle_ConfidenceType >(confidence_type_); } void PerceptionObstacle::set_confidence_type(::apollo::perception::PerceptionObstacle_ConfidenceType value) { assert(::apollo::perception::PerceptionObstacle_ConfidenceType_IsValid(value)); set_has_confidence_type(); confidence_type_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacle.confidence_type) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int PerceptionObstacles::kPerceptionObstacleFieldNumber; const int PerceptionObstacles::kHeaderFieldNumber; const int PerceptionObstacles::kErrorCodeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 PerceptionObstacles::PerceptionObstacles() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:apollo.perception.PerceptionObstacles) } PerceptionObstacles::PerceptionObstacles(const PerceptionObstacles& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _has_bits_(from._has_bits_), _cached_size_(0), perception_obstacle_(from.perception_obstacle_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_header()) { header_ = new ::apollo::common::Header(*from.header_); } else { header_ = NULL; } error_code_ = from.error_code_; // @@protoc_insertion_point(copy_constructor:apollo.perception.PerceptionObstacles) } void PerceptionObstacles::SharedCtor() { _cached_size_ = 0; ::memset(&header_, 0, reinterpret_cast<char*>(&error_code_) - reinterpret_cast<char*>(&header_) + sizeof(error_code_)); } PerceptionObstacles::~PerceptionObstacles() { // @@protoc_insertion_point(destructor:apollo.perception.PerceptionObstacles) SharedDtor(); } void PerceptionObstacles::SharedDtor() { if (this != internal_default_instance()) { delete header_; } } void PerceptionObstacles::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* PerceptionObstacles::descriptor() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const PerceptionObstacles& PerceptionObstacles::default_instance() { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::InitDefaults(); return *internal_default_instance(); } PerceptionObstacles* PerceptionObstacles::New(::google::protobuf::Arena* arena) const { PerceptionObstacles* n = new PerceptionObstacles; if (arena != NULL) { arena->Own(n); } return n; } void PerceptionObstacles::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.perception.PerceptionObstacles) perception_obstacle_.Clear(); if (has_header()) { GOOGLE_DCHECK(header_ != NULL); header_->::apollo::common::Header::Clear(); } error_code_ = 0; _has_bits_.Clear(); _internal_metadata_.Clear(); } bool PerceptionObstacles::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.perception.PerceptionObstacles) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .apollo.perception.PerceptionObstacle perception_obstacle = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_perception_obstacle())); } else { goto handle_unusual; } break; } // optional .apollo.common.Header header = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_header())); } else { goto handle_unusual; } break; } // optional .apollo.common.ErrorCode error_code = 3 [default = OK]; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u)) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::common::ErrorCode_IsValid(value)) { set_error_code(static_cast< ::apollo::common::ErrorCode >(value)); } else { mutable_unknown_fields()->AddVarint(3, value); } } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.perception.PerceptionObstacles) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.perception.PerceptionObstacles) return false; #undef DO_ } void PerceptionObstacles::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.perception.PerceptionObstacles) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .apollo.perception.PerceptionObstacle perception_obstacle = 1; for (unsigned int i = 0, n = this->perception_obstacle_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->perception_obstacle(i), output); } cached_has_bits = _has_bits_[0]; // optional .apollo.common.Header header = 2; if (cached_has_bits & 0x00000001u) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->header_, output); } // optional .apollo.common.ErrorCode error_code = 3 [default = OK]; if (cached_has_bits & 0x00000002u) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 3, this->error_code(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.perception.PerceptionObstacles) } ::google::protobuf::uint8* PerceptionObstacles::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.perception.PerceptionObstacles) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .apollo.perception.PerceptionObstacle perception_obstacle = 1; for (unsigned int i = 0, n = this->perception_obstacle_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, this->perception_obstacle(i), deterministic, target); } cached_has_bits = _has_bits_[0]; // optional .apollo.common.Header header = 2; if (cached_has_bits & 0x00000001u) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->header_, deterministic, target); } // optional .apollo.common.ErrorCode error_code = 3 [default = OK]; if (cached_has_bits & 0x00000002u) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 3, this->error_code(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.perception.PerceptionObstacles) return target; } size_t PerceptionObstacles::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:apollo.perception.PerceptionObstacles) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } // repeated .apollo.perception.PerceptionObstacle perception_obstacle = 1; { unsigned int count = this->perception_obstacle_size(); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->perception_obstacle(i)); } } if (_has_bits_[0 / 32] & 3u) { // optional .apollo.common.Header header = 2; if (has_header()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->header_); } // optional .apollo.common.ErrorCode error_code = 3 [default = OK]; if (has_error_code()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->error_code()); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void PerceptionObstacles::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.perception.PerceptionObstacles) GOOGLE_DCHECK_NE(&from, this); const PerceptionObstacles* source = ::google::protobuf::internal::DynamicCastToGenerated<const PerceptionObstacles>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.perception.PerceptionObstacles) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.perception.PerceptionObstacles) MergeFrom(*source); } } void PerceptionObstacles::MergeFrom(const PerceptionObstacles& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.perception.PerceptionObstacles) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; perception_obstacle_.MergeFrom(from.perception_obstacle_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 3u) { if (cached_has_bits & 0x00000001u) { mutable_header()->::apollo::common::Header::MergeFrom(from.header()); } if (cached_has_bits & 0x00000002u) { error_code_ = from.error_code_; } _has_bits_[0] |= cached_has_bits; } } void PerceptionObstacles::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.perception.PerceptionObstacles) if (&from == this) return; Clear(); MergeFrom(from); } void PerceptionObstacles::CopyFrom(const PerceptionObstacles& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.perception.PerceptionObstacles) if (&from == this) return; Clear(); MergeFrom(from); } bool PerceptionObstacles::IsInitialized() const { return true; } void PerceptionObstacles::Swap(PerceptionObstacles* other) { if (other == this) return; InternalSwap(other); } void PerceptionObstacles::InternalSwap(PerceptionObstacles* other) { perception_obstacle_.InternalSwap(&other->perception_obstacle_); std::swap(header_, other->header_); std::swap(error_code_, other->error_code_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata PerceptionObstacles::GetMetadata() const { protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_modules_2fperception_2fproto_2fperception_5fobstacle_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // PerceptionObstacles // repeated .apollo.perception.PerceptionObstacle perception_obstacle = 1; int PerceptionObstacles::perception_obstacle_size() const { return perception_obstacle_.size(); } void PerceptionObstacles::clear_perception_obstacle() { perception_obstacle_.Clear(); } const ::apollo::perception::PerceptionObstacle& PerceptionObstacles::perception_obstacle(int index) const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacles.perception_obstacle) return perception_obstacle_.Get(index); } ::apollo::perception::PerceptionObstacle* PerceptionObstacles::mutable_perception_obstacle(int index) { // @@protoc_insertion_point(field_mutable:apollo.perception.PerceptionObstacles.perception_obstacle) return perception_obstacle_.Mutable(index); } ::apollo::perception::PerceptionObstacle* PerceptionObstacles::add_perception_obstacle() { // @@protoc_insertion_point(field_add:apollo.perception.PerceptionObstacles.perception_obstacle) return perception_obstacle_.Add(); } ::google::protobuf::RepeatedPtrField< ::apollo::perception::PerceptionObstacle >* PerceptionObstacles::mutable_perception_obstacle() { // @@protoc_insertion_point(field_mutable_list:apollo.perception.PerceptionObstacles.perception_obstacle) return &perception_obstacle_; } const ::google::protobuf::RepeatedPtrField< ::apollo::perception::PerceptionObstacle >& PerceptionObstacles::perception_obstacle() const { // @@protoc_insertion_point(field_list:apollo.perception.PerceptionObstacles.perception_obstacle) return perception_obstacle_; } // optional .apollo.common.Header header = 2; bool PerceptionObstacles::has_header() const { return (_has_bits_[0] & 0x00000001u) != 0; } void PerceptionObstacles::set_has_header() { _has_bits_[0] |= 0x00000001u; } void PerceptionObstacles::clear_has_header() { _has_bits_[0] &= ~0x00000001u; } void PerceptionObstacles::clear_header() { if (header_ != NULL) header_->::apollo::common::Header::Clear(); clear_has_header(); } const ::apollo::common::Header& PerceptionObstacles::header() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacles.header) return header_ != NULL ? *header_ : *::apollo::common::Header::internal_default_instance(); } ::apollo::common::Header* PerceptionObstacles::mutable_header() { set_has_header(); if (header_ == NULL) { header_ = new ::apollo::common::Header; } // @@protoc_insertion_point(field_mutable:apollo.perception.PerceptionObstacles.header) return header_; } ::apollo::common::Header* PerceptionObstacles::release_header() { // @@protoc_insertion_point(field_release:apollo.perception.PerceptionObstacles.header) clear_has_header(); ::apollo::common::Header* temp = header_; header_ = NULL; return temp; } void PerceptionObstacles::set_allocated_header(::apollo::common::Header* header) { delete header_; header_ = header; if (header) { set_has_header(); } else { clear_has_header(); } // @@protoc_insertion_point(field_set_allocated:apollo.perception.PerceptionObstacles.header) } // optional .apollo.common.ErrorCode error_code = 3 [default = OK]; bool PerceptionObstacles::has_error_code() const { return (_has_bits_[0] & 0x00000002u) != 0; } void PerceptionObstacles::set_has_error_code() { _has_bits_[0] |= 0x00000002u; } void PerceptionObstacles::clear_has_error_code() { _has_bits_[0] &= ~0x00000002u; } void PerceptionObstacles::clear_error_code() { error_code_ = 0; clear_has_error_code(); } ::apollo::common::ErrorCode PerceptionObstacles::error_code() const { // @@protoc_insertion_point(field_get:apollo.perception.PerceptionObstacles.error_code) return static_cast< ::apollo::common::ErrorCode >(error_code_); } void PerceptionObstacles::set_error_code(::apollo::common::ErrorCode value) { assert(::apollo::common::ErrorCode_IsValid(value)); set_has_error_code(); error_code_ = value; // @@protoc_insertion_point(field_set:apollo.perception.PerceptionObstacles.error_code) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace perception } // namespace apollo // @@protoc_insertion_point(global_scope)
35.866261
144
0.714104
Kurinkitos
aac3c40b4291ce31a7b535e9d7db75c022a1f246
829
cpp
C++
ekf/src_ta/pose.cpp
KerryWu16/src
bed672dc1732cd6af1752bb54ab0abde015bb93a
[ "MIT" ]
2
2017-12-17T11:07:56.000Z
2021-08-19T09:35:11.000Z
ekf/src_working/pose.cpp
KerryWu16/src
bed672dc1732cd6af1752bb54ab0abde015bb93a
[ "MIT" ]
null
null
null
ekf/src_working/pose.cpp
KerryWu16/src
bed672dc1732cd6af1752bb54ab0abde015bb93a
[ "MIT" ]
1
2021-08-19T07:41:48.000Z
2021-08-19T07:41:48.000Z
#include "pose.h" Eigen::Vector3d R_to_rpy(const Eigen::Matrix3d& R) { Eigen::Vector3d rpy; double r = asin(R(2,1)); double p = atan2(-R(2,0)/cos(r), R(2,2)/cos(r)); double y = atan2(-R(0,1)/cos(r), R(1,1)/cos(r)); rpy(0) = r; rpy(1) = p; rpy(2) = y; return rpy; } Eigen::Matrix3d rpy_to_R(const Eigen::Vector3d& rpy) { Eigen::MatrixXd R = Eigen::MatrixXd::Zero(3,3); double r = rpy(0), p = rpy(1), y = rpy(2); R(0,0) = cos(y)*cos(p) - sin(r)*sin(p)*sin(y); R(0,1) = -cos(r)*sin(y); R(0,2) = cos(y)*sin(p) + cos(p)*sin(r)*sin(y); R(1,0) = cos(p)*sin(y) + cos(y)*sin(r)*sin(p); R(1,1) = cos(r)*cos(y); R(1,2) = sin(y)*sin(p) - cos(y)*cos(p)*sin(r); R(2,0) = -cos(r)*sin(p); R(2,1) = sin(r); R(2,2) = cos(r)*cos(p); return R; }
25.121212
53
0.487334
KerryWu16
aac65162c20d2d4fb1a97975af9831c12d95c34c
1,589
cpp
C++
leetcode.com/0241 Different Ways to Add Parentheses/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0241 Different Ways to Add Parentheses/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0241 Different Ways to Add Parentheses/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> using namespace std; class Solution { private: int n; vector<int> nums; vector<char> ops; vector<int> helper(int l, int r) { vector<int> result; if (l == r) return {nums[l]}; for (int i = l; i < r; ++i) { auto left = helper(l, i); auto right = helper(i+1, r); for (int x: left) { for (int y: right) { switch (ops[i]) { case '+': result.push_back(x+y); break; case '-': result.push_back(x-y); break; case '*': result.push_back(x*y); break; } } } } return result; } public: vector<int> diffWaysToCompute(string input) { n = input.length(); const char *input_cstr = input.c_str(); bool get_num = true; for (int i = 0; i < n; get_num = !get_num) { if (get_num) { int tmp; int len; sscanf(input_cstr+i, "%d%n", &tmp, &len); i += len; nums.push_back(tmp); } else { ops.push_back(input_cstr[i++]); } } n = nums.size(); return helper(0, n-1); } }; int main(int argc, char const *argv[]) { Solution s; s.diffWaysToCompute("2-1-1"); return 0; }
25.222222
57
0.390183
sky-bro
aac7c0f1c1a7c9f87d611024111af8f0435cca3c
10,534
cc
C++
audio/audio_receive_stream_unittest.cc
bofeng-song/webrtc
cd06ce5490635ef5ef953b17eabb6e833eed5b76
[ "DOC", "BSD-3-Clause" ]
null
null
null
audio/audio_receive_stream_unittest.cc
bofeng-song/webrtc
cd06ce5490635ef5ef953b17eabb6e833eed5b76
[ "DOC", "BSD-3-Clause" ]
null
null
null
audio/audio_receive_stream_unittest.cc
bofeng-song/webrtc
cd06ce5490635ef5ef953b17eabb6e833eed5b76
[ "DOC", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/audio/audio_receive_stream.h" #include "webrtc/audio/conversion.h" #include "webrtc/modules/remote_bitrate_estimator/include/mock/mock_remote_bitrate_estimator.h" #include "webrtc/modules/rtp_rtcp/source/byte_io.h" #include "webrtc/test/mock_voe_channel_proxy.h" #include "webrtc/test/mock_voice_engine.h" namespace webrtc { namespace test { namespace { using testing::_; using testing::Return; AudioDecodingCallStats MakeAudioDecodeStatsForTest() { AudioDecodingCallStats audio_decode_stats; audio_decode_stats.calls_to_silence_generator = 234; audio_decode_stats.calls_to_neteq = 567; audio_decode_stats.decoded_normal = 890; audio_decode_stats.decoded_plc = 123; audio_decode_stats.decoded_cng = 456; audio_decode_stats.decoded_plc_cng = 789; return audio_decode_stats; } const int kChannelId = 2; const uint32_t kRemoteSsrc = 1234; const uint32_t kLocalSsrc = 5678; const size_t kAbsoluteSendTimeLength = 4; const int kAbsSendTimeId = 2; const int kAudioLevelId = 3; const int kJitterBufferDelay = -7; const int kPlayoutBufferDelay = 302; const unsigned int kSpeechOutputLevel = 99; const CallStatistics kCallStats = { 345, 678, 901, 234, -12, 3456, 7890, 567, 890, 123}; const CodecInst kCodecInst = { 123, "codec_name_recv", 96000, -187, -198, -103}; const NetworkStatistics kNetworkStats = { 123, 456, false, 0, 0, 789, 12, 345, 678, 901, -1, -1, -1, -1, -1, 0}; const AudioDecodingCallStats kAudioDecodeStats = MakeAudioDecodeStatsForTest(); struct ConfigHelper { ConfigHelper() { using testing::Invoke; EXPECT_CALL(voice_engine_, RegisterVoiceEngineObserver(_)).WillOnce(Return(0)); EXPECT_CALL(voice_engine_, DeRegisterVoiceEngineObserver()).WillOnce(Return(0)); AudioState::Config config; config.voice_engine = &voice_engine_; audio_state_ = AudioState::Create(config); EXPECT_CALL(voice_engine_, ChannelProxyFactory(kChannelId)) .WillOnce(Invoke([this](int channel_id) { EXPECT_FALSE(channel_proxy_); channel_proxy_ = new testing::StrictMock<MockVoEChannelProxy>(); EXPECT_CALL(*channel_proxy_, SetLocalSSRC(kLocalSsrc)).Times(1); return channel_proxy_; })); EXPECT_CALL(voice_engine_, SetReceiveAbsoluteSenderTimeStatus(kChannelId, true, kAbsSendTimeId)) .WillOnce(Return(0)); EXPECT_CALL(voice_engine_, SetReceiveAudioLevelIndicationStatus(kChannelId, true, kAudioLevelId)) .WillOnce(Return(0)); stream_config_.voe_channel_id = kChannelId; stream_config_.rtp.local_ssrc = kLocalSsrc; stream_config_.rtp.remote_ssrc = kRemoteSsrc; stream_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kAbsSendTimeId)); stream_config_.rtp.extensions.push_back( RtpExtension(RtpExtension::kAudioLevel, kAudioLevelId)); } MockRemoteBitrateEstimator* remote_bitrate_estimator() { return &remote_bitrate_estimator_; } AudioReceiveStream::Config& config() { return stream_config_; } rtc::scoped_refptr<AudioState> audio_state() { return audio_state_; } MockVoiceEngine& voice_engine() { return voice_engine_; } void SetupMockForGetStats() { using testing::DoAll; using testing::SetArgPointee; using testing::SetArgReferee; EXPECT_CALL(voice_engine_, GetRTCPStatistics(kChannelId, _)) .WillOnce(DoAll(SetArgReferee<1>(kCallStats), Return(0))); EXPECT_CALL(voice_engine_, GetRecCodec(kChannelId, _)) .WillOnce(DoAll(SetArgReferee<1>(kCodecInst), Return(0))); EXPECT_CALL(voice_engine_, GetDelayEstimate(kChannelId, _, _)) .WillOnce(DoAll(SetArgPointee<1>(kJitterBufferDelay), SetArgPointee<2>(kPlayoutBufferDelay), Return(0))); EXPECT_CALL(voice_engine_, GetSpeechOutputLevelFullRange(kChannelId, _)).WillOnce( DoAll(SetArgReferee<1>(kSpeechOutputLevel), Return(0))); EXPECT_CALL(voice_engine_, GetNetworkStatistics(kChannelId, _)) .WillOnce(DoAll(SetArgReferee<1>(kNetworkStats), Return(0))); EXPECT_CALL(voice_engine_, GetDecodingCallStatistics(kChannelId, _)) .WillOnce(DoAll(SetArgPointee<1>(kAudioDecodeStats), Return(0))); } private: MockRemoteBitrateEstimator remote_bitrate_estimator_; testing::StrictMock<MockVoiceEngine> voice_engine_; rtc::scoped_refptr<AudioState> audio_state_; AudioReceiveStream::Config stream_config_; testing::StrictMock<MockVoEChannelProxy>* channel_proxy_ = nullptr; }; void BuildAbsoluteSendTimeExtension(uint8_t* buffer, int id, uint32_t abs_send_time) { const size_t kRtpOneByteHeaderLength = 4; const uint16_t kRtpOneByteHeaderExtensionId = 0xBEDE; ByteWriter<uint16_t>::WriteBigEndian(buffer, kRtpOneByteHeaderExtensionId); const uint32_t kPosLength = 2; ByteWriter<uint16_t>::WriteBigEndian(buffer + kPosLength, kAbsoluteSendTimeLength / 4); const uint8_t kLengthOfData = 3; buffer[kRtpOneByteHeaderLength] = (id << 4) + (kLengthOfData - 1); ByteWriter<uint32_t, kLengthOfData>::WriteBigEndian( buffer + kRtpOneByteHeaderLength + 1, abs_send_time); } size_t CreateRtpHeaderWithAbsSendTime(uint8_t* header, int extension_id, uint32_t abs_send_time) { header[0] = 0x80; // Version 2. header[0] |= 0x10; // Set extension bit. header[1] = 100; // Payload type. header[1] |= 0x80; // Marker bit is set. ByteWriter<uint16_t>::WriteBigEndian(header + 2, 0x1234); // Sequence number. ByteWriter<uint32_t>::WriteBigEndian(header + 4, 0x5678); // Timestamp. ByteWriter<uint32_t>::WriteBigEndian(header + 8, 0x4321); // SSRC. int32_t rtp_header_length = webrtc::kRtpHeaderSize; BuildAbsoluteSendTimeExtension(header + rtp_header_length, extension_id, abs_send_time); rtp_header_length += kAbsoluteSendTimeLength; return rtp_header_length; } } // namespace TEST(AudioReceiveStreamTest, ConfigToString) { AudioReceiveStream::Config config; config.rtp.remote_ssrc = kRemoteSsrc; config.rtp.local_ssrc = kLocalSsrc; config.rtp.extensions.push_back( RtpExtension(RtpExtension::kAbsSendTime, kAbsSendTimeId)); config.voe_channel_id = kChannelId; config.combined_audio_video_bwe = true; EXPECT_EQ( "{rtp: {remote_ssrc: 1234, local_ssrc: 5678, extensions: [{name: " "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time, id: 2}]}, " "receive_transport: nullptr, rtcp_send_transport: nullptr, " "voe_channel_id: 2, combined_audio_video_bwe: true}", config.ToString()); } TEST(AudioReceiveStreamTest, ConstructDestruct) { ConfigHelper helper; internal::AudioReceiveStream recv_stream( helper.remote_bitrate_estimator(), helper.config(), helper.audio_state()); } TEST(AudioReceiveStreamTest, AudioPacketUpdatesBweWithTimestamp) { ConfigHelper helper; helper.config().combined_audio_video_bwe = true; internal::AudioReceiveStream recv_stream( helper.remote_bitrate_estimator(), helper.config(), helper.audio_state()); uint8_t rtp_packet[30]; const int kAbsSendTimeValue = 1234; CreateRtpHeaderWithAbsSendTime(rtp_packet, kAbsSendTimeId, kAbsSendTimeValue); PacketTime packet_time(5678000, 0); const size_t kExpectedHeaderLength = 20; EXPECT_CALL(*helper.remote_bitrate_estimator(), IncomingPacket(packet_time.timestamp / 1000, sizeof(rtp_packet) - kExpectedHeaderLength, testing::_, false)) .Times(1); EXPECT_TRUE( recv_stream.DeliverRtp(rtp_packet, sizeof(rtp_packet), packet_time)); } TEST(AudioReceiveStreamTest, GetStats) { ConfigHelper helper; internal::AudioReceiveStream recv_stream( helper.remote_bitrate_estimator(), helper.config(), helper.audio_state()); helper.SetupMockForGetStats(); AudioReceiveStream::Stats stats = recv_stream.GetStats(); EXPECT_EQ(kRemoteSsrc, stats.remote_ssrc); EXPECT_EQ(static_cast<int64_t>(kCallStats.bytesReceived), stats.bytes_rcvd); EXPECT_EQ(static_cast<uint32_t>(kCallStats.packetsReceived), stats.packets_rcvd); EXPECT_EQ(kCallStats.cumulativeLost, stats.packets_lost); EXPECT_EQ(Q8ToFloat(kCallStats.fractionLost), stats.fraction_lost); EXPECT_EQ(std::string(kCodecInst.plname), stats.codec_name); EXPECT_EQ(kCallStats.extendedMax, stats.ext_seqnum); EXPECT_EQ(kCallStats.jitterSamples / (kCodecInst.plfreq / 1000), stats.jitter_ms); EXPECT_EQ(kNetworkStats.currentBufferSize, stats.jitter_buffer_ms); EXPECT_EQ(kNetworkStats.preferredBufferSize, stats.jitter_buffer_preferred_ms); EXPECT_EQ(static_cast<uint32_t>(kJitterBufferDelay + kPlayoutBufferDelay), stats.delay_estimate_ms); EXPECT_EQ(static_cast<int32_t>(kSpeechOutputLevel), stats.audio_level); EXPECT_EQ(Q14ToFloat(kNetworkStats.currentExpandRate), stats.expand_rate); EXPECT_EQ(Q14ToFloat(kNetworkStats.currentSpeechExpandRate), stats.speech_expand_rate); EXPECT_EQ(Q14ToFloat(kNetworkStats.currentSecondaryDecodedRate), stats.secondary_decoded_rate); EXPECT_EQ(Q14ToFloat(kNetworkStats.currentAccelerateRate), stats.accelerate_rate); EXPECT_EQ(Q14ToFloat(kNetworkStats.currentPreemptiveRate), stats.preemptive_expand_rate); EXPECT_EQ(kAudioDecodeStats.calls_to_silence_generator, stats.decoding_calls_to_silence_generator); EXPECT_EQ(kAudioDecodeStats.calls_to_neteq, stats.decoding_calls_to_neteq); EXPECT_EQ(kAudioDecodeStats.decoded_normal, stats.decoding_normal); EXPECT_EQ(kAudioDecodeStats.decoded_plc, stats.decoding_plc); EXPECT_EQ(kAudioDecodeStats.decoded_cng, stats.decoding_cng); EXPECT_EQ(kAudioDecodeStats.decoded_plc_cng, stats.decoding_plc_cng); EXPECT_EQ(kCallStats.capture_start_ntp_time_ms_, stats.capture_start_ntp_time_ms); } } // namespace test } // namespace webrtc
42.995918
95
0.738466
bofeng-song
aacf32b5da67d6dee429224824258952fb498764
1,804
cpp
C++
linked-list/intersection-point.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
linked-list/intersection-point.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
linked-list/intersection-point.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <unordered_set> using namespace std; struct Node { int data; Node *next; } *head = nullptr, *last = nullptr; int count(Node *node) { int c = 0; while (node) { c++; node = node->next; } return c; } int intersection(Node *l1, Node *l2) { unordered_set<Node *> s; while (l2) { s.insert(l2); l2 = l2->next; } while (l1) { if (s.find(l1) != s.end()) return l1->data; l1 = l1->next; } return 0; } int intersection2(Node *l1, Node *l2) { int c1 = count(l1); int c2 = count(l2); Node *p = c1 > c2 ? l1 : l2; Node *q = (p == l1) ? l2 : l1; for (int i = 0; i < abs(c1 - c2); i++) p = p->next; while (p && q) { if (p == q) return p->data; p = p->next; q = q->next; } return -1; } Node *getIntersectionNode(Node *headA, Node *headB) { Node *p1 = headA; Node *p2 = headB; if (p1 == NULL || p2 == NULL) return NULL; while (p1 != NULL && p2 != NULL && p1 != p2) { p1 = p1->next; p2 = p2->next; // // Any time they collide or reach end together without colliding // then return any one of the pointers. // if (p1 == p2) return p1; // // If one of them reaches the end earlier then reuse it // by moving it to the beginning of other list. // Once both of them go through reassigning, // they will be equidistant from the collision point. // if (p1 == NULL) p1 = headB; if (p2 == NULL) p2 = headA; } return p1; }
20.5
74
0.459534
Strider-7
aacfacef14c504311ccd082fe29853eeb1a38e90
7,420
cpp
C++
projects/test-suite/SingleSource/Benchmarks/Misc-C++/stepanov_container.cpp
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
16
2015-09-08T08:49:11.000Z
2019-07-20T14:46:20.000Z
projects/test-suite/SingleSource/Benchmarks/Misc-C++/stepanov_container.cpp
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
1
2019-02-10T08:27:48.000Z
2019-02-10T08:27:48.000Z
projects/test-suite/SingleSource/Benchmarks/Misc-C++/stepanov_container.cpp
nettrino/IntFlow
0400aef5da2c154268d8b020e393c950435395b3
[ "Unlicense" ]
7
2016-05-26T17:31:46.000Z
2020-11-04T06:39:23.000Z
/* Standard Container Benchmark Version 0.9, May 23, 2003 The primary purpose of this benchmark is to show how different standard containers are in terms of performance. We have observed that programmers often use sets, multisets, deques in the situations where sorted vectors are the optimal solutions. Similarly, programmers often choose lists simply because they do a few insertions and deletions without knowing that vectors are more efficient at that for small containers. Frequently, of course, performance does not matter, but it is important that programmers are aware of the consequences of their choices. We are not saying that only vectors should be used, there are cases when one really needs a more complicated data structure, but one needs to understand the price for additional functionality. The secondary purpose of the benchmark is to encourage compiler and library vendors to keep improving performance. For example, it is not acceptable that some compilers give you a sizable penalty for using vector iterators instead of pointer. It is also quite clear that performance of other standard containers could be improved. The benchmark is doing the same task 7 times using different data structures: array, vector (using a pointer as iterator), vector (using the defailt cector iterator), list, deque, set and multiset. The task is to remove duplicates from a sequence of doubles. This is a simple test, but it illustrates the performance of containers. It is clear that the benchmark needs to be eventually extended to slists and even to hash-sets and hash-maps, but we decided that at present it should work only with the standard containers. As the standard grows, so can the benchmark. The additional benefit of not including hash based containers is that now all the test have identical asymptotic complexity and, even more importantly, do almost the same number of comparisons. The difference is only in data structure overhead and cache behavior. The number of times that a given test is run inversly proportional to NlogN where N is the size of the sequence. This allows one to see how containers of different size behave. The instructive values used for the benchmark are: 10, 100, 1000, 10000, 100000, 1000000. The time taken for a run of the benchmark depends on the machine used, the compiler used, the compiler and optimizer settings used, as well as the standard library. Please note that the time taken could be several minutes - and much more if you use a slow debug mode. The output is a table where columns are separated by tabs and rows by newlines. This is barely ok for a human reader, but ideal for feeding into a program, such as a spreadsheet for display or analysis. If you want to add your own test of a container, add the name of your container to the "header string, write a test function like the existing ones, e.g. vector_test, and add a call of "run" for your test in "run_tests". Alex Stepanov [email protected] Bjarne Stroustrup [email protected] */ #include <stddef.h> // some older implementations lack <cstddef> #include <time.h> #include <math.h> #include <stdlib.h> #include <vector> #include <algorithm> #include <list> #include <deque> #include <set> #include <iostream> #include <iomanip> typedef double element_t; using namespace std; vector<double> result_times; // results are puched into this vector typedef void(*Test)(element_t*, element_t*, int); void run(Test f, element_t* first, element_t* last, int number_of_times) { while (number_of_times-- > 0) f(first,last,number_of_times); } void array_test(element_t* first, element_t* last, int number_of_times) { element_t* array = new element_t[last - first]; copy(first, last, array); sort(array, array + (last - first)); unique(array, array + (last - first)); delete [] array; } void vector_pointer_test(element_t* first, element_t* last, int number_of_times) { vector<element_t> container(first, last); // &*container.begin() gets us a pointer to the first element sort(&*container.begin(), &*container.end()); unique(&*container.begin(), &*container.end()); } void vector_iterator_test(element_t* first, element_t* last, int number_of_times) { vector<element_t> container(first, last); sort(container.begin(), container.end()); unique(container.begin(), container.end()); } void deque_test(element_t* first, element_t* last, int number_of_times) { // deque<element_t> container(first, last); CANNOT BE USED BECAUSE OF MVC++ 6 deque<element_t> container(size_t(last - first), 0.0); copy(first, last, container.begin()); sort(container.begin(), container.end()); unique(container.begin(), container.end()); } void list_test(element_t* first, element_t* last, int number_of_times) { list<element_t> container(first, last); container.sort(); container.unique(); } void set_test(element_t* first, element_t* last, int number_of_times) { set<element_t> container(first, last); } void multiset_test(element_t* first, element_t* last, int number_of_times) { multiset<element_t> container(first, last); typedef multiset<element_t>::iterator iterator; { iterator first = container.begin(); iterator last = container.end(); while (first != last) { iterator next = first; if (++next == last) break; if (*first == *next) container.erase(next); else ++first; } } } void initialize(element_t* first, element_t* last) { element_t value = 0.0; while (first != last) { *first++ = value; value += 1.; } } double logtwo(double x) { return log(x)/log((double) 2.0); } const int largest_size = 1000000; int number_of_tests(int size) { double n = size; double largest_n = largest_size; return int(floor((largest_n * logtwo(largest_n)) / (n * logtwo(n)))); } void run_tests(int size) { const int n = number_of_tests(size); const size_t length = 2*size; result_times.clear(); // make a random test set of the chosen size: vector<element_t> buf(length); element_t* buffer = &buf[0]; element_t* buffer_end = &buf[length]; initialize(buffer, buffer + size); // elements initialize(buffer + size, buffer_end); // duplicate elements random_shuffle(buffer, buffer_end); // test the containers: run(array_test, buffer, buffer_end, n); run(vector_pointer_test, buffer, buffer_end, n); run(vector_iterator_test, buffer, buffer_end, n); run(deque_test, buffer, buffer_end, n); run(list_test, buffer, buffer_end, n); run(set_test, buffer, buffer_end, n); run(multiset_test, buffer, buffer_end, n); } int main() { const int sizes [] = { 100000 }; const int n = sizeof(sizes)/sizeof(int); for (int i = 0; i < n; ++i) run_tests(sizes[i]); }
28.648649
92
0.671024
nettrino
aad5ff8d0dc2a3c2e59f6f6e05a56534fc156222
739
hpp
C++
feather/feather.hpp
msmoiz/feather
a28b593aa1cafd7dd1a4ddeb45641b5871feb620
[ "MIT" ]
null
null
null
feather/feather.hpp
msmoiz/feather
a28b593aa1cafd7dd1a4ddeb45641b5871feb620
[ "MIT" ]
null
null
null
feather/feather.hpp
msmoiz/feather
a28b593aa1cafd7dd1a4ddeb45641b5871feb620
[ "MIT" ]
null
null
null
// Copyright 2021 Mustafa Moiz. #pragma once #include <memory> #include <string> #include "input_handler.hpp" #include "cursor.hpp" #include "output_handler.hpp" #include "serializer.hpp" /** * Text editor that handles the following standard * operations: * - Navigation * - Manipulation * - Display * - Serialization */ class Feather { public: Feather(std::unique_ptr<InputHandler> input_handler, std::unique_ptr<OutputHandler> output_handler, std::unique_ptr<Serializer> serializer); void run(); private: std::unique_ptr<InputHandler> input_handler_{nullptr}; std::unique_ptr<OutputHandler> output_handler_{nullptr}; std::unique_ptr<Serializer> serializer_{nullptr}; std::string text_; Cursor cursor_{0}; };
18.948718
57
0.742896
msmoiz
aad6363410d32aa2cdff10d026b96e71aca82829
4,662
cpp
C++
projects/vkworld/wrappers/VkwMemoryHelper.cpp
Bycob/world
c6d943f9029c1bb227891507e5c6fe2b94cecfeb
[ "MIT" ]
16
2021-03-14T16:30:32.000Z
2022-03-18T13:41:53.000Z
projects/vkworld/wrappers/VkwMemoryHelper.cpp
Bycob/world
c6d943f9029c1bb227891507e5c6fe2b94cecfeb
[ "MIT" ]
1
2020-04-21T12:59:37.000Z
2020-04-23T17:49:03.000Z
projects/vkworld/wrappers/VkwMemoryHelper.cpp
BynaryCobweb/world
c6d943f9029c1bb227891507e5c6fe2b94cecfeb
[ "MIT" ]
4
2020-03-08T14:04:50.000Z
2020-12-03T08:51:04.000Z
#include "VkwMemoryHelper.h" #include "Vulkan.h" namespace world { void VkwMemoryHelper::GPUToImage(IVkwMemoryAccess &memory, Image &img) { GPUToImage(memory, img, img.elemSize()); } void VkwMemoryHelper::GPUToImageu(IVkwMemoryAccess &memory, Image &img) { GPUToImageu(memory, img, img.elemSize()); } // TODO change int to size_t to avoid overflow void VkwMemoryHelper::GPUToImage(IVkwMemoryAccess &memory, Image &img, u32 e) { const int w = img.width(), h = img.height(); const int size = w * h * e; float *buffer = new float[size]; memory.getData(buffer, size * sizeof(float), 0); for (u32 y = 0; y < h; ++y) { for (u32 x = 0; x < w; ++x) { u32 pos = (y * w + x) * e; img.setf(x, y, buffer + pos); } } } void VkwMemoryHelper::GPUToImageu(IVkwMemoryAccess &memory, Image &img, u32 e) { const int w = img.width(), h = img.height(); const int size = w * h * e; u8 *buffer = new u8[size]; memory.getData(buffer, size * sizeof(u8), 0); for (u32 y = 0; y < h; ++y) { for (u32 x = 0; x < w; ++x) { u32 pos = (y * w + x) * e; img.set(x, y, buffer + pos); } } } Image VkwMemoryHelper::GPUToImage(VkwImage &vkimg) { ImageType imType; bool isFloat = false; switch (vkimg.format()) { case vk::Format::eR32G32B32A32Sfloat: isFloat = true; case vk::Format::eR8G8B8A8Unorm: imType = ImageType::RGBA; break; case vk::Format::eR32G32B32Sfloat: isFloat = true; case vk::Format::eR8G8B8Unorm: imType = ImageType::RGB; break; case vk::Format::eR32Sfloat: isFloat = true; case vk::Format::eR8Unorm: imType = ImageType::GREYSCALE; break; default: throw std::runtime_error("GPUToImage: Vk image format not supported (" + std::to_string(int(vkimg.format())) + ")"); } Image img(vkimg.width(), vkimg.height(), imType); if (isFloat) { GPUToImage(vkimg, img); } else { GPUToImageu(vkimg, img); } return img; } void VkwMemoryHelper::imageToGPU(const Image &img, IVkwMemoryAccess &memory) { // TODO VkwMemoryHelper::imageToGPU } void VkwMemoryHelper::GPUToTerrain(IVkwMemoryAccess &memory, Terrain &terrain) { } void VkwMemoryHelper::terrainToGPU(const Terrain &terrain, IVkwMemoryAccess &memory) { int res = terrain.getResolution(); float *buf = new float[res * res]; for (int y = 0; y < res; ++y) { for (int x = 0; x < res; ++x) { buf[y * res + x] = float(terrain(x, y)); } } memory.setData(buf, res * res * sizeof(float), 0); delete[] buf; } void VkwMemoryHelper::GPUToMesh(IVkwMemoryAccess &verticesMemory, IVkwMemoryAccess &indicesMemory, Mesh &mesh) { GPUToVertices(verticesMemory, mesh); GPUToIndices(indicesMemory, mesh); } void VkwMemoryHelper::GPUToVertices(IVkwMemoryAccess &memory, Mesh &mesh) {} void VkwMemoryHelper::GPUToIndices(IVkwMemoryAccess &memory, Mesh &mesh) {} void VkwMemoryHelper::copyBuffer(VkwSubBuffer &from, VkwSubBuffer &to) { auto &ctx = Vulkan::context(); vk::CommandBufferAllocateInfo commandBufInfo( ctx._graphicsCommandPool, vk::CommandBufferLevel::ePrimary, 1); auto commandBuf = ctx._device.allocateCommandBuffers(commandBufInfo).at(0); commandBuf.begin(vk::CommandBufferBeginInfo( vk::CommandBufferUsageFlagBits::eOneTimeSubmit)); /*insertBarrier(commandBuf, {}, vk::AccessFlagBits ::eTransferWrite, vk::ImageLayout::eUndefined, vk::ImageLayout::eGeneral, vk::PipelineStageFlagBits::eTopOfPipe, vk::PipelineStageFlagBits::eTransfer);*/ vk::BufferCopy bufCopy{from.getOffset(), to.getOffset(), from.getSize()}; commandBuf.copyBuffer(from.handle(), to.handle(), bufCopy); /*insertBarrier(commandBuf, vk::AccessFlagBits ::eTransferWrite, vk::AccessFlagBits ::eShaderRead, vk::ImageLayout::eGeneral, vk::ImageLayout::eGeneral, vk::PipelineStageFlagBits::eTransfer, vk::PipelineStageFlagBits::eFragmentShader);*/ commandBuf.end(); auto fence = ctx._device.createFence(vk::FenceCreateInfo()); vk::SubmitInfo submitInfo(0, nullptr, nullptr, 1, &commandBuf); ctx.queue(vk::QueueFlagBits::eGraphics).submit(submitInfo, fence); ctx._device.waitForFences(fence, true, 1000000000000); // Destroy resources ctx._device.freeCommandBuffers(ctx._graphicsCommandPool, commandBuf); ctx._device.destroyFence(fence); } } // namespace world
30.671053
80
0.634921
Bycob
aadf19904a3a35e3c4c7a6bc1dfd52136e45a8c2
13,715
cpp
C++
singlib/src_lib/net.cpp
mdegirolami/stay
b47676e5340c2bbd93fe97d52a12a895a3492b22
[ "BSD-3-Clause" ]
2
2021-08-13T01:00:49.000Z
2021-09-07T17:31:14.000Z
singlib/src_lib/net.cpp
mdegirolami/sing
7f674d3a1d5787b3f4016dc28c14e997149fc9f6
[ "BSD-3-Clause" ]
null
null
null
singlib/src_lib/net.cpp
mdegirolami/sing
7f674d3a1d5787b3f4016dc28c14e997149fc9f6
[ "BSD-3-Clause" ]
null
null
null
#define _WIN32_WINNT 0x600 // vista #include "net.h" #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> #else #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <arpa/inet.h> #endif namespace sing { #ifdef _WIN32 #pragma comment(lib,"ws2_32.lib") void utf8_to_16(const char *src, std::vector<wchar_t> *dst); static int getaddrinfoL(const char *nodename, const char *servname, const struct addrinfo *hints, struct addrinfo **res) { if (nodename != nullptr) { std::vector<wchar_t> wname; std::vector<wchar_t> wservice; utf8_to_16(nodename, &wname); utf8_to_16(servname, &wservice); return(GetAddrInfoW(wname.data(), wservice.data(), (const ADDRINFOW*)hints, (PADDRINFOW*)res)); } return(::getaddrinfo(nodename, servname, hints, res)); } #else typedef int SOCKET; inline void closesocket(int a) { ::close(a); } static const int INVALID_SOCKET = -1; static const int SOCKET_ERROR = -1; static inline int getaddrinfoL(const char *nodename, const char *servname, const struct addrinfo *hints, struct addrinfo **res) { return(::getaddrinfo(nodename, servname, hints, res)); } #endif /////////////////// // // Utilities // ////////////////// const std::string ip4_loopback = "127.0.0.1"; const std::string ip6_loopback = "::1"; static bool createBoundSocketIp4(int32_t port, Sock *out_socket, int socket_type) { struct sockaddr_in addr; memset(addr.sin_zero, 0, sizeof(addr.sin_zero)); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr.s_addr = INADDR_ANY; SOCKET socket = ::socket(addr.sin_family, socket_type, 0); if (socket == INVALID_SOCKET) { return(false); } if (bind(socket, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) { closesocket(socket); *out_socket = (Sock)INVALID_SOCKET; return(false); } *out_socket = (Sock)socket; return(true); } static bool createBoundSocketIp6(int32_t port, Sock *out_socket, int socket_type) { struct sockaddr_in6 addr; memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_addr = in6addr_any; addr.sin6_port = htons(port); SOCKET socket = ::socket(addr.sin6_family, socket_type, 0); if (socket == INVALID_SOCKET) { return(false); } if (bind(socket, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) { closesocket(socket); *out_socket = (Sock)INVALID_SOCKET; return(false); } *out_socket = (Sock)socket; return(true); } static bool createBoundSocket(int32_t port, Sock *socket, int socket_type, IpVersion ipv) { if (port < 0) port = 0; if (ipv == IpVersion::v4) { return(createBoundSocketIp4(port, socket, socket_type)); } else if (ipv == IpVersion::v6) { return(createBoundSocketIp6(port, socket, socket_type)); } return(false); } static int32_t getLocalPortFromSocket(SOCKET socket) { Address addr; socklen_t len = sizeof(addr.add_); if (getsockname(socket, (struct sockaddr *)&addr.add_[0], &len) == 0) { addr.len_ = len; return(addr.getPort()); } return(-1); } // // returns false for error/tout // static bool waitForSocket(int32_t tout, SOCKET socket, bool *timedout) { fd_set fds; struct timeval tv; tout = std::min(tout, 2000000); tout = std::max(tout, 0); tv.tv_sec = 0; tv.tv_usec = tout * 1000; int nn; do { FD_ZERO(&fds); FD_SET(socket, &fds); nn = select(socket+1, &fds, nullptr, nullptr, &tv); } while (nn == -1 && errno == EINTR); *timedout = nn == 0; return(nn == 1); } /////////////////// // // Address implementation // ////////////////// Address::Address() { len_ = 0; } bool Address::set(const char *ip_address, const char *port) { struct addrinfo *servinfo; // will point to the results bool result = false; if (ip_address == nullptr || ip_address[0] == 0) return(false); if (port == nullptr || port[0] == 0) return(false); if (getaddrinfoL(ip_address, port, nullptr, &servinfo) != 0) { return(false); } for(struct addrinfo *ptr=servinfo; ptr != nullptr; ptr=ptr->ai_next) { if (ptr->ai_family == AF_INET || ptr->ai_family == AF_INET6) { if (ptr->ai_addrlen < sizeof(add_)) { len_ = ptr->ai_addrlen; memcpy(&add_[0], ptr->ai_addr, len_); result = true; break; } } } freeaddrinfo(servinfo); return(result); } std::string Address::getIpAddress() const { char print_buffer[INET6_ADDRSTRLEN]; if (len_ == 0) return(""); short family = ((sockaddr_in*)&add_[0])->sin_family; if (family == AF_INET) { if (inet_ntop(AF_INET, &((sockaddr_in*)&add_[0])->sin_addr, print_buffer, INET6_ADDRSTRLEN) != nullptr) { return(print_buffer); } } else if (family == AF_INET6) { if (inet_ntop(AF_INET6, &((sockaddr_in6*)&add_[0])->sin6_addr, print_buffer, INET6_ADDRSTRLEN) != nullptr) { return(print_buffer); } } return(""); } int32_t Address::getPort() const { if (len_ == 0) return(-1); short family = ((sockaddr_in*)&add_[0])->sin_family; if (family == AF_INET) { return(ntohs(((sockaddr_in*)&add_[0])->sin_port)); } else if (family == AF_INET6) { return(ntohs(((sockaddr_in6*)&add_[0])->sin6_port)); } return(-1); } /////////////////// // // ListenerSocket implementation // ////////////////// ListenerSocket::ListenerSocket() { sock_ = INVALID_SOCKET; tout_ = false; } ListenerSocket::~ListenerSocket() { close(); } bool ListenerSocket::open(int32_t localport, int32_t queue_length, IpVersion ipv) { if (!createBoundSocket(localport, &sock_, SOCK_STREAM, ipv)) { return(false); } if (listen((SOCKET)sock_, std::max(queue_length, 1)) == SOCKET_ERROR) { close(); return(false); } return(true); } void ListenerSocket::close() { if (sock_ != INVALID_SOCKET) { closesocket((SOCKET)sock_); sock_ = INVALID_SOCKET; } } bool ListenerSocket::accept(ConnectedSocket *socket, int32_t ms_timeout) { Address remote; SOCKET newsock; if (ms_timeout >= 0 && !waitForSocket(ms_timeout, (SOCKET)sock_, &tout_)) { return(false); } socklen_t len; do { len = sizeof(remote.add_); newsock = ::accept((SOCKET)sock_, (sockaddr*)&remote.add_[0], &len); } while (newsock == INVALID_SOCKET && errno == EINTR); if (newsock == INVALID_SOCKET) { return(false); } remote.len_ = len; socket->setSock(newsock); socket->setRemote(remote); return(true); } int32_t ListenerSocket::getLocalPort() const { return(getLocalPortFromSocket((SOCKET)sock_)); } bool ListenerSocket::timedout() const { return(tout_); } /////////////////// // // ConnectedSocket implementation // ////////////////// ConnectedSocket::ConnectedSocket() { sock_ = INVALID_SOCKET; tout_ = false; } ConnectedSocket::~ConnectedSocket() { close(); } bool ConnectedSocket::open(const Address &addr, int32_t localport) { short family = ((sockaddr_in*)&addr.add_[0])->sin_family; IpVersion ipv = family == AF_INET ? IpVersion::v4 : IpVersion::v6; if (!createBoundSocket(localport, &sock_, SOCK_STREAM, ipv)) { return(false); } int retvalue; do { retvalue = connect((SOCKET)sock_, (sockaddr*)&addr.add_[0], addr.len_); } while (retvalue == SOCKET_ERROR && errno == EINTR); if (retvalue == SOCKET_ERROR) { close(); return(false); } remote_ = addr; return(true); } void ConnectedSocket::close() { if (sock_ != INVALID_SOCKET) { closesocket((SOCKET)sock_); sock_ = INVALID_SOCKET; } } int32_t ConnectedSocket::getLocalPort() const { return(getLocalPortFromSocket((SOCKET)sock_)); } void ConnectedSocket::getRemoteAddress(Address *addr) const { *addr = remote_; } bool ConnectedSocket::timedout() const { return(tout_); } bool ConnectedSocket::rcvString(std::string *value, int64_t maxbytes, int32_t ms_timeout) { if (ms_timeout >= 0 && !waitForSocket(ms_timeout, (SOCKET)sock_, &tout_)) { return(false); } value->resize(maxbytes); int received; do { received = recv((SOCKET)sock_, (char*)value->data(), maxbytes, 0); } while (received == -1 && errno == EINTR); value->resize(std::max(received, 0)); // 0 means 'connection closed' return(received > 0); } bool ConnectedSocket::rcv(std::vector<uint8_t> *dst, int64_t count, int32_t ms_timeout, bool append) { if (ms_timeout >= 0 && !waitForSocket(ms_timeout, (SOCKET)sock_, &tout_)) { return(false); } if (!append) dst->clear(); int orig_size = dst->size(); dst->resize(orig_size + count); uint8_t *pdst = dst->data() + orig_size; int received; do { received = recv((SOCKET)sock_, (char*)pdst, count, 0); } while (received == -1 && errno == EINTR); // 0 means 'connection closed' if (received > 0) { dst->resize(orig_size + received); return(true); } dst->resize(orig_size); return(false); } bool ConnectedSocket::sendString(const char *value) { const char *src = value; int len = strlen(value); while (len > 0) { int sent = ::send((SOCKET)sock_, src, len, 0); if (sent <= 0) { if (errno != EINTR) return(false); sent = 0; } src += sent; len -= sent; } return(true); } bool ConnectedSocket::send(const std::vector<uint8_t> &src, int64_t count, int64_t from) { const uint8_t *psrc = src.data(); int64_t len = (int64_t)src.size(); if (from >= len) return(true); psrc += from; len -= from; len = std::min(len, count); while (len > 0) { int sent = ::send((SOCKET)sock_, (const char*)psrc, len, 0); if (sent <= 0) { if (errno != EINTR) return(false); sent = 0; } psrc += sent; len -= sent; } return(true); } // internal use void ConnectedSocket::setSock(int64_t v) { sock_ = v; } void ConnectedSocket::setRemote(const Address &remote) { remote_ = remote; } /////////////////// // // unconnected Sockets // ////////////////// Socket::Socket() { sock_ = INVALID_SOCKET; tout_ = false; } Socket::~Socket() { close(); } bool Socket::open(int32_t localport, IpVersion ipv) { return(createBoundSocket(localport, &sock_, SOCK_DGRAM, ipv)); } void Socket::close() { if (sock_ != INVALID_SOCKET) { closesocket((SOCKET)sock_); sock_ = INVALID_SOCKET; } } int32_t Socket::getLocalPort() const { return(getLocalPortFromSocket((SOCKET)sock_)); } bool Socket::timedout() const { return(tout_); } bool Socket::rcvString(Address *add, std::string *value, int64_t maxbytes, int32_t ms_timeout) { if (ms_timeout >= 0 && !waitForSocket(ms_timeout, (SOCKET)sock_, &tout_)) { return(false); } value->resize(maxbytes); socklen_t len; int received; do { len = sizeof(add->add_); received = recvfrom((SOCKET)sock_, (char*)value->data(), maxbytes, 0, (sockaddr*)&add->add_[0], &len); } while (received == -1 && errno == EINTR); if (received >= 0) add->len_ = len; value->resize(std::max(received, 0)); // 0 is a legal datagram length return(received >= 0); } bool Socket::rcv(Address *add, std::vector<uint8_t> *dst, int64_t count, int32_t ms_timeout, bool append) { if (ms_timeout >= 0 && !waitForSocket(ms_timeout, (SOCKET)sock_, &tout_)) { return(false); } if (!append) dst->clear(); int orig_size = dst->size(); dst->resize(orig_size + count); uint8_t *pdst = dst->data() + orig_size; socklen_t len; int received; do { len = sizeof(add->add_); received = recvfrom((SOCKET)sock_, (char*)pdst, count, 0, (sockaddr*)&add->add_[0], &len); } while (received == -1 && errno == EINTR); // 0 is a legal datagram length if (received >= 0) { add->len_ = len; dst->resize(orig_size + received); return(true); } dst->resize(orig_size); return(false); } bool Socket::sendString(const Address &add, const char *value) { const char *src = value; int len = strlen(value); while (len > 0) { int sent = ::sendto((SOCKET)sock_, src, len, 0, (sockaddr*)&add.add_[0], add.len_); if (sent <= 0) { if (errno != EINTR) return(false); sent = 0; } src += sent; len -= sent; } return(true); } bool Socket::send(const Address &add, const std::vector<uint8_t> &src, int64_t count, int64_t from) { const uint8_t *psrc = src.data(); int64_t len = (int64_t)src.size(); if (from >= len) return(true); psrc += from; len -= from; len = std::min(len, count); while (len > 0) { int sent = ::sendto((SOCKET)sock_, (const char*)psrc, len, 0, (sockaddr*)&add.add_[0], add.len_); if (sent <= 0) { if (errno != EINTR) return(false); sent = 0; } psrc += sent; len -= sent; } return(true); } /////////////////// // // free functions implementation // ////////////////// #ifdef _WIN32 bool netInit() { WSADATA wsaData; return(WSAStartup(MAKEWORD(2,2), &wsaData) == 0); } void netShutdown() { WSACleanup(); } #else bool netInit() { return(true); } void netShutdown() { } #endif } // namespace
23.893728
127
0.594677
mdegirolami
aaf048f73026d9a8bc5146eded48c7239d1dfa83
3,207
cpp
C++
src/caffe/util/random_helper.cpp
MSRCCS/Caffe
2eb05997f077fe93832b89d56ea0cd1ea72e3275
[ "BSD-2-Clause" ]
null
null
null
src/caffe/util/random_helper.cpp
MSRCCS/Caffe
2eb05997f077fe93832b89d56ea0cd1ea72e3275
[ "BSD-2-Clause" ]
null
null
null
src/caffe/util/random_helper.cpp
MSRCCS/Caffe
2eb05997f077fe93832b89d56ea0cd1ea72e3275
[ "BSD-2-Clause" ]
null
null
null
#include "caffe/util/random_helper.h" #include <iostream> #include <stdexcept> #include <cstdlib> #include <time.h> #include <math.h> namespace caffe { random_helper::random_init_helper random_helper::m_randInit; #if _HAS_CPP0X std::mt19937_64 random_helper::m_generator; std::uniform_int_distribution<unsigned int> random_helper::m_uniformInt; std::uniform_real_distribution<double> random_helper::m_uniformReal; std::normal_distribution<double> random_helper::m_normalReal; #endif random_helper::random_init_helper::random_init_helper() { srand(time(NULL)); #if _HAS_CPP0X m_generator = std::mt19937_64(std::random_device()()); m_uniformInt = std::uniform_int_distribution<unsigned int>(0, UINT_MAX); m_uniformReal = std::uniform_real_distribution<double>(0.0, 1.0); m_normalReal = std::normal_distribution<double>(0.0, 1.0); #endif } random_helper::random_helper() { } random_helper::~random_helper() { } unsigned int random_helper::uniform_int(unsigned int min/* = 0*/, unsigned int max/* = UINT_MAX*/) { if (min >= max) { std::cout << "random_helper::uniform_int must have min >= max" << std::endl; throw std::runtime_error("random_helper::uniform_int must have min >= max"); } unsigned int range = max - min + 1; #ifndef RAND_DEVICE #if _HAS_CPP0X if (m_uniformInt.min() != min || m_uniformInt.max() != max) m_uniformInt = std::uniform_int_distribution<unsigned int>(min, max); return m_uniformInt(m_generator); #else if (max > RAND_MAX) std::cout << "Warning : random_helper::uniform_int with rand() only with range [0, " << RAND_MAX << "]" << std::endl; return rand() % range + min; #endif #else if (max > std::random_device().max()) std::cout << "Warning : random_helper::uniform_int with random_device() only with range [0, " << std::random_device().max() << "]" << std::endl; return std::random_device()() % range + min; #endif } double random_helper::uniform_real(double min/*= 0.0*/, double max/* = 1.0*/) { if (min >= max) { std::cout << "random_helper::uniform_real must have min >= max" << std::endl; throw std::runtime_error("random_helper::uniform_real must have min >= max"); } #ifndef RAND_DEVICE #if _HAS_CPP0X if (m_uniformReal.min() != min || m_uniformReal.max() != max) m_uniformReal = std::uniform_real_distribution<double>(min, max); return m_uniformReal(m_generator); #else return (double)rand() / (double)RAND_MAX * (max - min) + min; #endif #else return (double)std::random_device()() / (double)std::random_device().max() * (max - min) + min; #endif } double random_helper::normal_real() { #ifndef RAND_DEVICE #if _HAS_CPP0X return m_normalReal(m_generator); #else const double PI = 3.1415926535897932384626433832795; double a = ((double)rand() + 1) / ((double)RAND_MAX + 2); double b = (double)rand() / ((double)RAND_MAX + 1); return sqrt(-2 * log(a))*cos(2 * PI*b); #endif #else const double PI = 3.1415926535897932384626433832795; double a = ((double)std::random_device()() + 1) / ((double)std::random_device().max() + 2); double b = (double)std::random_device()() / ((double)std::random_device().max() + 1); return sqrt(-2 * log(a))*cos(2 * PI*b); #endif } }
31.752475
147
0.692859
MSRCCS
aaf556e844e7b1f62fc8c5079d40bac80bf99997
3,044
cpp
C++
src/main/start.cpp
ondra-novak/lnex
d1412be914098c9ae22ee65568895aff6d58d1ba
[ "MIT" ]
null
null
null
src/main/start.cpp
ondra-novak/lnex
d1412be914098c9ae22ee65568895aff6d58d1ba
[ "MIT" ]
null
null
null
src/main/start.cpp
ondra-novak/lnex
d1412be914098c9ae22ee65568895aff6d58d1ba
[ "MIT" ]
null
null
null
#include <userver/http_server.h> #include <shared/default_app.h> #include <couchit/config.h> #include <couchit/couchDB.h> #include <userver/http_client.h> #include <userver/ssl.h> #include "../couchit/src/couchit/changes.h" #include "../userver/static_webserver.h" #include "server.h" #include "walletsvc.h" int main(int argc, char **argv) { using namespace userver; using namespace ondra_shared; using namespace lnex; ondra_shared::DefaultApp app({}, std::cerr); if (!app.init(argc, argv)) { std::cerr<<"Failed to initialize application" << std::endl; return 1; } auto section_server = app.config["server"]; NetAddrList bind_addr = NetAddr::fromString( section_server.mandatory["listen"].getString(), "9500"); unsigned int threads = section_server.mandatory["threads"].getUInt(); unsigned int dispatchers = section_server["dispatchers"].getUInt(1); unsigned int maxupload = section_server.mandatory["max_upload_mb"].getUInt()*1024*1024; auto section_wallet = app.config["wallet"]; std::optional<WalletConfig> wcfg; if (section_wallet["enabled"].getBool(false)) { wcfg.emplace(); wcfg->login = section_wallet.mandatory["login"].getString(); wcfg->password= section_wallet.mandatory["password"].getString(); wcfg->url= section_wallet.mandatory["url"].getString(); } logProgress("---------- SERVER STAR ---------"); for (const auto &x: bind_addr) logInfo("Listen: $1", x.toString(false)); auto section_db = app.config["database"]; couchit::Config dbcfg; dbcfg.authInfo.username = section_db.mandatory["username"].getString(); dbcfg.authInfo.password = section_db.mandatory["password"].getString(); dbcfg.baseUrl = section_db.mandatory["server_url"].getString(); dbcfg.databaseName = section_db.mandatory["db_name"].getString(); auto section_www = app.config["www"]; std::optional<userver::StaticWebserver::Config> www_cfg; if (section_www["enabled"].getBool()) { www_cfg.emplace(); www_cfg->cachePeriod = section_www["cache"].getUInt(); www_cfg->document_root = section_www.mandatory["document_root"].getPath(); www_cfg->indexFile = section_www.mandatory["index_file"].getString(); } couchit::CouchDB couchdb(dbcfg); couchit::ChangesDistributor chdist(couchdb,true,true); ondra_shared::Scheduler sch = sch.create(); if (wcfg.has_value()) { auto wallet = std::make_shared<WalletService>(couchdb,*wcfg, HttpClientCfg{"lnex.cz"}); wallet->init(wallet, chdist, sch); } MyHttpServer server; server.addRPCPath("/RPC", { true,true,true,maxupload }); server.add_listMethods(); server.add_ping(); if (www_cfg.has_value()) { server.addPath("", StaticWebserver(*www_cfg)); } server.start(bind_addr, threads, dispatchers); sch.immediate() >> [provider = server.getAsyncProvider()]{ userver::setThreadAsyncProvider(provider); }; chdist.runService([&]{ userver::setThreadAsyncProvider(server.getAsyncProvider()); }); server.stopOnSignal(); server.addThread(); server.stop(); chdist.stopService(); logProgress("---------- SERVER STOP ---------"); }
29.269231
89
0.718134
ondra-novak
aaf65e5d2920665f8dfad5ffa2d9f06bce4ceb9f
4,081
cpp
C++
dynamic programming/boolean_patenthesization_memoization.cpp
kashyap99saksham/Code
96658d0920eb79c007701d2a3cc9dbf453d78f96
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
dynamic programming/boolean_patenthesization_memoization.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
dynamic programming/boolean_patenthesization_memoization.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
/* Given a boolean expression with following symbols. Symbols 'T' ---> true 'F' ---> false And following operators filled between symbols Operators & ---> boolean AND | ---> boolean OR ^ ---> boolean XOR Count the number of ways we can parenthesize the expression so that the value of expression evaluates to true. For Example: The expression is "T | T & F ^ T", it evaluates true in 4 ways ((T|T)&(F^T)), (T|(T&(F^T))), (((T|T)&F)^T) and (T|((T&F)^T)). Return No_of_ways Mod 1003. Input: First line contains the test cases T. 1<=T<=500 Each test case have two lines First is length of string N. 1<=N<=100 Second line is string S (boolean expression). Output: No of ways Mod 1003. Example: Input: 2 7 T|T&F^T 5 T^F|F Output: 4 2 */ #include<bits/stdc++.h> using namespace std; int dp[201][201][2]; int booleanParenthesis(string s, int i, int j, bool isTrue){ if(i>j) return 0; if(i==j){ if(isTrue==true) return s[i]=='T'; else return s[i]=='F'; } if(dp[i][j][isTrue]!=-1) return dp[i][j][isTrue]; int ans=0, lf, lt, rf, rt; for(int k=i+1;k<j;k+=2){ if(dp[i][k-1][true]!=-1) lt=dp[i][k-1][true]; else { dp[i][k-1][true]=booleanParenthesis(s, i, k-1, true); lt=dp[i][k-1][true]; } if(dp[i][k-1][false]!=-1) lf=dp[i][k-1][false]; else { dp[i][k-1][false]=booleanParenthesis(s, i, k-1,false); lf=dp[i][k-1][false]; } if(dp[k+1][j][true]!=-1) rt=dp[k+1][j][true]; else { dp[k+1][j][true]=booleanParenthesis(s, k+1, j, true); rt=dp[k+1][j][true]; } if(dp[k+1][j][false]!=-1) rf=dp[k+1][j][false]; else { dp[k+1][j][false]=booleanParenthesis(s, k+1, j, false); rf=dp[k+1][j][false]; } if(s[k]=='&'){ if(isTrue==true) ans+=lt*rt; else ans+=lt*rf + lf*rt + lf*rf; } else if(s[k]=='|'){ if(isTrue==true) ans+=lt*rt + lt*rf + lf*rt; else ans+=lf*rf; } else if(s[k]=='^'){ if(isTrue==true) ans+=lt*rf + lf*rt; else ans+=lf*rf + lt*rt; } } return dp[i][j][isTrue]=ans%1003; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin>>t; while(t--){ int n; cin>>n; string s; cin>>s; memset(dp, -1, sizeof(dp)); cout<<booleanParenthesis(s, 0, n-1, true)<<endl; } return 0; } /* Alternative Approach #include<bits/stdc++.h> using namespace std; map<string, int> mp; int booleanParenthesis(string s, int i, int j, bool isTrue){ if(i>j) return 0; if(i==j){ if(isTrue==true) return s[i]=='T'; else return s[i]=='F'; } string tmp=to_string(i); tmp.push_back(' '); tmp.append(to_string(j)); tmp.push_back(' '); tmp.append(to_string(isTrue)); if(mp.find(tmp)!=mp.end()) return mp[tmp]; int ans=0; for(int k=i+1;k<j;k+=2){ int lt=booleanParenthesis(s, i, k-1, true); int lf=booleanParenthesis(s, i, k-1, false); int rt=booleanParenthesis(s, k+1, j, true); int rf=booleanParenthesis(s, k+1, j, false); if(s[k]=='&'){ if(isTrue==true) ans+=lt*rt; else ans+=lt*rf + lf*rt + lf*rf; } else if(s[k]=='|'){ if(isTrue==true) ans+=lt*rt + lt*rf + lf*rt; else ans+=lf*rf; } else if(s[k]=='^'){ if(isTrue==true) ans+=lt*rf + lf*rt; else ans+=lf*rf + lt*rt; } } return mp[tmp]=ans%1003; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin>>t; while(t--){ int n; cin>>n; string s; cin>>s; mp.clear(); cout<<booleanParenthesis(s, 0, n-1, true)<<endl; } return 0; } */
21.707447
110
0.493506
kashyap99saksham
aaf7b8d63b31676a282a2f7410deffb2fdb5e6f7
1,096
cpp
C++
Hacker Rank/Sock Merchant.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
51
2020-02-24T11:14:00.000Z
2022-03-24T09:32:18.000Z
Hacker Rank/Sock Merchant.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
3
2020-10-02T08:16:09.000Z
2021-04-17T16:32:38.000Z
Hacker Rank/Sock Merchant.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
18
2020-04-24T15:33:36.000Z
2022-03-24T09:32:20.000Z
/*Hacker Rank*/ /*Title - Sock Merchant*/ //John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. // //For example, there are n = 7 socks with colors ar = [1,2,1,2,1,3,2] . There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2. // //Function Description // //Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available. // //sockMerchant has the following parameter(s): // //n: the number of socks in the pile //ar: the colors of each sock int sockMerchant(int n, vector<int> ar) { int count=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { if(ar[i]==ar[j] && i!=j) { count++; ar[i]=INT_MAX-i; ar[j]=INT_MAX-j; break; } } } return count; }
32.235294
230
0.629562
Shubhrmcf07
c902e5178700b51e13502179ec3c90727d3221f2
2,215
cpp
C++
src/controls/while_do_else_node.cpp
BehaviorTree/BehaviorTreeCPP
a5411c978ec976f66d83b1df5aa4dd7c632a142c
[ "MIT" ]
null
null
null
src/controls/while_do_else_node.cpp
BehaviorTree/BehaviorTreeCPP
a5411c978ec976f66d83b1df5aa4dd7c632a142c
[ "MIT" ]
null
null
null
src/controls/while_do_else_node.cpp
BehaviorTree/BehaviorTreeCPP
a5411c978ec976f66d83b1df5aa4dd7c632a142c
[ "MIT" ]
null
null
null
/* Copyright (C) 2020 Davide Faconti - All Rights Reserved * * 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 "behaviortree_cpp_v3/controls/while_do_else_node.h" namespace BT { WhileDoElseNode::WhileDoElseNode(const std::string &name) : ControlNode::ControlNode(name, {} ) { setRegistrationID("WhileDoElse"); } void WhileDoElseNode::halt() { ControlNode::halt(); } NodeStatus WhileDoElseNode::tick() { const size_t children_count = children_nodes_.size(); if(children_count != 3) { throw std::logic_error("WhileDoElse must have 3 children"); } setStatus(NodeStatus::RUNNING); NodeStatus condition_status = children_nodes_[0]->executeTick(); if (condition_status == NodeStatus::RUNNING) { return condition_status; } NodeStatus status = NodeStatus::IDLE; if (condition_status == NodeStatus::SUCCESS) { haltChild(2); status = children_nodes_[1]->executeTick(); } else if (condition_status == NodeStatus::FAILURE) { haltChild(1); status = children_nodes_[2]->executeTick(); } if (status == NodeStatus::RUNNING) { return NodeStatus::RUNNING; } else { haltChildren(); return status; } } } // namespace BT
30.342466
161
0.733183
BehaviorTree
c903e520a3785864c52ee95e51d038ba4227aca0
382
cpp
C++
Exercicios/19-08/Exercicio5.cpp
ismaellimadb/Programas-C-
cc626ef3447f699ed8ff9d7619dd78100f299612
[ "Apache-2.0" ]
null
null
null
Exercicios/19-08/Exercicio5.cpp
ismaellimadb/Programas-C-
cc626ef3447f699ed8ff9d7619dd78100f299612
[ "Apache-2.0" ]
null
null
null
Exercicios/19-08/Exercicio5.cpp
ismaellimadb/Programas-C-
cc626ef3447f699ed8ff9d7619dd78100f299612
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <stdlib.h> main() { float t,v,gas,dis; printf("\nDigite o Tempo da viagem em horas\n"); scanf("%f",&t); printf("\nDigite a Velocidade em Km/h\n"); scanf("%f",&v); dis=t*v; gas=dis/2; printf("\nA distancia percorrida pelo automovel foi: %1.f Km\n",dis); printf("\nFoi consumido %.1f litros de combustivel na viagem\n\n",gas); system("pause"); }
23.875
72
0.65445
ismaellimadb
c91163cc5ff613ab35b1c9002838b13b7ec36ad1
16,452
cpp
C++
Source/MyWindow/WindowData.cpp
favorart/robot-hand
55ea2a74573972a6e5efcf525485e56918d81086
[ "MIT" ]
2
2016-01-16T09:28:40.000Z
2016-04-14T05:21:20.000Z
Source/MyWindow/WindowData.cpp
favorart/robot-hand
55ea2a74573972a6e5efcf525485e56918d81086
[ "MIT" ]
null
null
null
Source/MyWindow/WindowData.cpp
favorart/robot-hand
55ea2a74573972a6e5efcf525485e56918d81086
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "WindowData.h" #include "Draw.h" #include "HandMotionLawsCustom.h" #include "Position.h" extern bool zoom; using namespace std; using namespace HandMoves; //------------------------------------------------------------------------------- bool RepeatMove (MyWindowData &wd); bool MakeHandMove (MyWindowData &wd); //------------------------------------------------------------------------------- void MyWindowData::TrajectoryFrames::step (Store &store, Hand &hand, const boost::optional<controling_t> controls) { if ( controls.is_initialized () ) { show_ = true; if ( animation ) { controls_ = controling_t{ *controls }; time_ = Hand::frames_t{ 0U }; for ( iter_ = controls_->begin (); (*iter_) != controls_->end () && (**iter_).start == time_; ++(*iter_) ) { hand.step ((**iter_).muscle, (**iter_).last); } ++(*time_); } else { hand.SET_DEFAULT; Point hand_base = hand.position; hand.move (controls->begin (), controls->end (), &trajectory_); // Point hand_base = trajectory_.front (); // wd.trajectory_frames.pop_front (); store.insert (HandMoves::Record (hand.position, hand_base, hand.position, *controls, trajectory_)); // trajectory_.clear (); } } // ============ for ( size_t i = 0U; i < skip_show_steps; ++i ) { // ============ hand.step (); /* !!! WORKING ONLY FOR NEW_HAND !!! */ // ============ /* Auto-drawing trajectory animation */ if ( show_ && animation && time_.is_initialized () ) { if ( ((*iter_) != (*controls_).end ()) && ((**iter_).start == time_) ) { while ( ((*iter_) != (*controls_).end ()) && ((**iter_).start == time_) ) { hand.step ((**iter_).muscle, (**iter_).last); ++(*iter_); } } // ============ if ( hand.moveEnd ) { const Point &hand_pos = hand.position; trajectory_.push_back (hand_pos); // ------------------------------------------- Point base_pos = trajectory_.front (); // wd.trajectory_.pop_front (); store.insert (HandMoves::Record (hand_pos, base_pos, hand_pos, *controls_, trajectory_)); // ------------------------------------------- controls_ = boost::none; // ------------------------------------------- iter_ = boost::none; time_ = boost::none; // ------------------------------------------- break; } else if ( !(*time_ % hand.visitedSaveEach) ) { trajectory_.push_back (hand.position); } // ============ (*time_) += 1U; // ============ } // end if } // end for } void MyWindowData::TrajectoryFrames::draw (HDC hdc, HPEN hPen) const { if ( show_ ) { DrawTrajectory (hdc, trajectory_, hPen); } } void MyWindowData::TrajectoryFrames::clear () { show_ = false; trajectory_.clear (); // ------------------------------------------- controls_ = boost::none; // ------------------------------------------- time_ = boost::none; iter_ = boost::none; } //------------------------------------------------------------------------------- MyWindowData:: MyWindowData () : pWorkerThread (nullptr), // lt (NULL), hand (/* palm */ Point{ -0.75, 1.05 }, /* hand */ Point{ -0.70, 1.00 }, /* arm */ Point{ 0.10, 0.85 }, /* shoulder */ Point{ 0.75, 0.25 }, /* clavicle */ Point{ 0.75, 0.25 }, /* joints_frames */ { { Hand::Elbow,{ // new MotionLaws::ContinuousSlowAcceleration (), // new MotionLaws::ContinuousFastAcceleration (), // new MotionLaws::ContinuousAccelerationThenStabilization (0.25), new MotionLaws::ContinuousAcceleration (), new MotionLaws::ContinuousDeceleration () //, // new MotionLaws::MangoAcceleration (tstring(_T("Resource/ElbowMoveFrames.txt"))), // new MotionLaws::MangoDeceleration (tstring(_T("Resource/ElbowStopFrames.txt"))) } }, { Hand::Shldr,{ // new MotionLaws::ContinuousSlowAcceleration (), // new MotionLaws::ContinuousFastAcceleration (), // new MotionLaws::ContinuousAccelerationThenStabilization (0.25), new MotionLaws::ContinuousAcceleration (), new MotionLaws::ContinuousDeceleration () //, // new MotionLaws::MangoAcceleration (tstring(_T("Resource/ShoulderMoveFrames.txt"))), // new MotionLaws::MangoDeceleration (tstring(_T("Resource/ShoulderStopFrames.txt"))) } } , // { Hand::Wrist, { new MotionLaws::ContinuousAcceleration (), // new MotionLaws::ContinuousDeceleration () } }, { Hand::Clvcl, { // new MotionLaws::ContinuousSlowAcceleration (), // new MotionLaws::ContinuousFastAcceleration (), // new MotionLaws::ContinuousAccelerationThenStabilization (), new MotionLaws::ContinuousAcceleration (), new MotionLaws::ContinuousDeceleration () } } }), target ( /* 200U, 200U, */ 18U, 18U, -0.41, 0.43, -0.03, -0.85 ), scaleLetters (target.min (), target.max ()) { std::srand ((unsigned int) clock ()); testing = false; working_space_show = false; allPointsDB_show = false; /* создаем ручки */ hPen_grn = CreatePen (PS_SOLID, 1, RGB (100, 180, 050)); hPen_red = CreatePen (PS_SOLID, 2, RGB (255, 000, 000)); hPen_blue = CreatePen (PS_SOLID, 2, RGB (000, 000, 255)); hPen_cian = CreatePen (PS_SOLID, 1, RGB (057, 168, 157)); hPen_orng = CreatePen (PS_SOLID, 2, RGB (255, 128, 000)); /* создаем кисти */ hBrush_white = (HBRUSH) GetStockObject (WHITE_BRUSH); hBrush_null = (HBRUSH) GetStockObject (NULL_BRUSH); hBrush_back = CreateSolidBrush (RGB (235, 235, 255) /* background color */ // RGB (255,204,238) ); // p_x = 0; p_y = 0; // fm = 0; fn = 0; } MyWindowData::~MyWindowData () { // if ( lt ) delete lt; //======================= /* очищаем ручку */ DeleteObject (hPen_grn); DeleteObject (hPen_red); DeleteObject (hPen_blue); DeleteObject (hPen_cian); DeleteObject (hPen_orng); DeleteObject (hBrush_white); DeleteObject (hBrush_null); DeleteObject (hBrush_back); DeleteDC (hStaticDC); DeleteObject (hStaticBitmap); //======================= if ( pWorkerThread ) { pWorkerThread->interrupt (); delete pWorkerThread; pWorkerThread = NULL; } //======================= // store.save (CurFileName); //======================= } //------------------------------------------------------------------------------- void OnPaintStaticBckGrnd (HDC hdc, MyWindowData &wd) { DrawDecardsCoordinates (hdc); wd.target.draw (hdc, wd.hPen_grn, /* false, */ true, // false, false); true, false); } void OnPaintStaticFigures (HDC hdc, MyWindowData &wd) { // -------------------------------------------------------------- if ( wd.working_space_show ) /* u */ DrawTrajectory (hdc, wd.working_space, wd.hPen_orng); // ----- Отрисовка точек БД ------------------------------------- if ( !wd.testing && wd.allPointsDB_show && !wd.store.empty () ) { #ifdef _DRAW_STORE_GRADIENT_ size_t colorGradations = 15U; color_interval_t colors = // make_pair (RGB(0,0,130), RGB(255,0,0)); // 128 make_pair (RGB(150,10,245), RGB(245,10,150)); // make_pair (RGB(130,0,0), RGB(255,155,155)); gradient_t gradient; MakeGradient (colors, colorGradations, gradient); #else gradient_t gradient ({ RGB (25, 255, 25), RGB (25, 25, 255), RGB (255, 25, 25) }); #endif // -------------------------------------------------------------- WorkerThreadRunStoreTask ( wd, _T (" *** drawing *** "), [hdc](HandMoves::Store &store, gradient_t gradient, double r, HandMoves::trajectory_t uncoveredPoints, HPEN hPen) { store.draw (hdc, gradient, r); for ( auto &pt : uncoveredPoints ) if ( zoom ) { DrawCircle (hdc, pt, 0.005, hPen); } else { SetPixel (hdc, Tx (pt.x), Ty (pt.y), RGB (255, 0, 0)); } }, gradient, /* (zoom) ? 0.0005 : */ 0., ( wd.uncovered_show ) ? wd.uncoveredPoints : HandMoves::trajectory_t(), wd.hPen_red); } // end if } void OnPainDynamicFigures (HDC hdc, MyWindowData &wd) { const double CircleRadius = 0.01; // -------------------------------------------------------------- /* Target to achive */ // if ( wd.lt ) wd.lt->draw (hdc, wd); // ----- Отрисовка фигуры --------------------------------------- wd.hand.draw (hdc, wd.hPen_red, wd.hBrush_white); // -------------------------------------------------------------- wd.trajectory_frames.draw (hdc, wd.hPen_orng); // -------------------------------------------------------------- if ( !wd.testing && wd.testing_trajectories_show && !wd.testing_trajectories.empty () ) { #ifdef _TESTING_TRAJECTORIES_ANIMATION_ auto it = wd.testing_trajectories.begin (); for ( size_t i = 0U; i < wd.testing_trajectories_animation_num_iteration; ++i, ++it ) { DrawTrajectory (hdc, *it, wd.hPen_blue); DrawCircle (hdc, it->back (), CircleRadius); } #else // !_TESTING_TRAJECTORIES_ANIMATION_ !not! for ( auto &t : wd.testing_trajectories ) { DrawTrajectory (hdc, t, wd.hPen_blue); } #endif // _TESTING_TRAJECTORIES_ANIMATION_ } // end if // ----- Отрисовка точек БД ------------------------------------- if ( !wd.adjPointsDB.empty () ) { HPEN hPen_old = (HPEN) SelectObject (hdc, wd.hPen_cian); for ( auto &p : wd.adjPointsDB ) { DrawCircle (hdc, p->hit, CircleRadius); } SelectObject (hdc, hPen_old); } // -------------------------------------------------------------- if ( wd.mouse_haved ) { DrawAdjacency (hdc, wd.mouse_aim, wd.radius, ellipse, wd.hPen_cian); } // -------------------------------------------------------------- if ( wd.scaleLetters.show ) { wd.scaleLetters.draw (hdc, wd.hand.jointsPositions (), &wd.hand.position); } // -------------------------------------------------------------- } //------------------------------------------------------------------------------- void WorkerThreadTryJoin (MyWindowData &wd) { if ( wd.pWorkerThread && wd.pWorkerThread->try_join_for (boost::chrono::milliseconds (10)) ) { /* joined */ delete wd.pWorkerThread; wd.pWorkerThread = nullptr; wd.testing = false; #ifdef _TESTING_TRAJECTORIES_ANIMATION_ wd.testing_trajectories_animation_num_iteration = 1; wd.testing_trajectories_animation_show = true; #endif // _TESTING_TRAJECTORIES_ANIMATION_ /* Set text of label 'Stat' */ SendMessage (wd.hLabTest, WM_SETTEXT, NULL, reinterpret_cast<LPARAM> (_T (" Done ")) ); } // end if } //------------------------------------------------------------------------------- void OnShowDBPoints (MyWindowData &wd) { if ( !wd.testing ) { wd.adjPointsDB.clear (); wd.testing_trajectories.clear (); wd.store.adjacencyPoints (wd.adjPointsDB, wd.mouse_aim, wd.radius); } } void OnShowDBTrajes (MyWindowData &wd) { wd.trajectory_frames.clear (); for ( auto &rec : wd.adjPointsDB ) { wd.trajectoriesDB.push_back (make_shared<trajectory_t> (rec->trajectory)); } } //------------------------------------------------------------------------------- void OnWindowTimer (MyWindowData &wd) { if ( !wd.testing ) { wd.trajectory_frames.step (wd.store, wd.hand); #ifdef _TESTING_TRAJECTORIES_ANIMATION_ /* Trajectoriaes animation */ if ( wd.testing_trajectories_animation_show && wd.testing_trajectories_animation_num_iteration < wd.testing_trajectories.size () ) { ++wd.testing_trajectories_animation_num_iteration; } #endif // _TESTING_TRAJECTORIES_ANIMATION_ } // end if } void OnWindowMouse (MyWindowData &wd) { wd.mouse_haved = true; wd.mouse_aim = logic_coord (&wd.mouse_coords); /* Setting the Label's text */ tstring message = tstring (wd.mouse_aim) + _T (" "); SendMessage (wd.hLabMAim, WM_SETTEXT, NULL, (WPARAM) message.c_str ()); // ------------------------------------------------- if ( !wd.testing ) { MakeHandMove (wd); } } //------------------------------------------------------------------------------- bool RepeatMove (MyWindowData &wd) { const Point &aim = wd.mouse_aim; // ------------------------------------------------- const Record &rec = wd.store.ClothestPoint (aim, wd.side); // ------------------------------------------------- if ( boost_distance (rec.hit, aim) <= wd.target.precision () ) { /* Repeat Hand Movement */ wd.hand.SET_DEFAULT; wd.trajectory_frames.step (wd.store, wd.hand, boost::optional<controling_t>{rec.controls}); // ------------------------------------------------- if ( !wd.trajectory_frames.animation ) { if ( !boost::equal (wd.trajectory_frames.trajectory, rec.trajectory) ) { throw std::exception ("Incorrect Repeat Hand Move"); } } // ------------------------------------------------- tstring text = GetTextToString (wd.hLabMAim); tstringstream ss; ss << text << _T ("\r"); for ( const Hand::Control &c : rec.controls ) { ss << c << _T (" "); } // \r SendMessage (wd.hLabMAim, WM_SETTEXT, NULL, (LPARAM) ss.str ().c_str ()); // ------------------------------------------------- return true; } // ------------------------------------------------- return false; } bool MakeHandMove (MyWindowData &wd) { // wd.adjPointsDB.clear (); wd.trajectory_frames.clear (); wd.testing_trajectories.clear (); // ------------------------------------------------- if ( !RepeatMove (wd) ) { const Point &aim = wd.mouse_aim; // ------------------------------------------------- Positions::LearnMovements lm (wd.store, wd.hand, wd.target); lm.gradientMethod_admixture (aim, true); // ------------------------------------------------- if ( 0 /* Around Trajectories !!! */) { // adjacency_refs_t range; // std::pair<Record, Record> x_pair, y_pair; // auto count = wd.store.adjacencyByPBorders (aim, 0.06, x_pair, y_pair); // range, aim, min, max); // // tcout << count << std::endl; // // wd.testing_trajectories.push_back (x_pair.first.trajectory); // wd.testing_trajectories.push_back (y_pair.first.trajectory); // wd.testing_trajectories.push_back (x_pair.second.trajectory); // wd.testing_trajectories.push_back (y_pair.second.trajectory); // return false; } // ------------------------------------------------- if ( 0 /* LinearOperator && SimplexMethod */ ) { // HandMoves::controling_t controls; // Positions::LinearOperator lp (wd.store, wd.mouse_aim, // 0.07, controls, true); // // lp.predict (wd.mouse_aim, controls); // // wd.hand.SET_DEFAULT; // wd.hand.move (controls.begin (), controls.end (), &wd.trajectory_frames.trajectory); } // ------------------------------------------------- return !RepeatMove (wd); } // ------------------------------------------------- return true; } //-------------------------------------------------------------------------------
37.306122
112
0.47903
favorart
c91b9726d365b44398a1b0be35867be214e2fecc
53
cxx
C++
test/input/Typedef-to-Class-template.cxx
radoslawcybulski/CastXML
7d8d719fdea8cad7702e62b6174b2665a4bf2ca5
[ "Apache-2.0" ]
428
2015-01-06T17:01:38.000Z
2022-03-22T12:34:03.000Z
test/input/Typedef-to-Class-template.cxx
radoslawcybulski/CastXML
7d8d719fdea8cad7702e62b6174b2665a4bf2ca5
[ "Apache-2.0" ]
175
2015-01-06T17:07:37.000Z
2022-03-07T23:06:02.000Z
test/input/Typedef-to-Class-template.cxx
radoslawcybulski/CastXML
7d8d719fdea8cad7702e62b6174b2665a4bf2ca5
[ "Apache-2.0" ]
101
2015-01-25T14:18:42.000Z
2022-02-05T08:56:06.000Z
template <typename T> class A; typedef A<int> start;
13.25
21
0.735849
radoslawcybulski
c91eb8c8702492b102c3978e5331c89fc4ffd623
21,342
cpp
C++
external/glu-0.1.0.0/source/texture2d.cpp
spetz911/almaty3d
0dda0f05862be2585eae9b6e2e8cf476c043e3dc
[ "MIT" ]
571
2015-01-08T16:29:38.000Z
2022-03-16T06:45:42.000Z
external/glu-0.1.0.0/source/texture2d.cpp
spetz911/almaty3d
0dda0f05862be2585eae9b6e2e8cf476c043e3dc
[ "MIT" ]
45
2015-01-15T12:47:28.000Z
2022-03-04T09:22:32.000Z
external/glu-0.1.0.0/source/texture2d.cpp
spetz911/almaty3d
0dda0f05862be2585eae9b6e2e8cf476c043e3dc
[ "MIT" ]
136
2015-01-31T15:24:57.000Z
2022-02-17T19:26:24.000Z
/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Image (gli.g-truc.net) /// /// Copyright (c) 2008 - 2013 G-Truc Creation (www.g-truc.net) /// 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. /// /// @ref core /// @file gli/gtx/gl_texture2d.inl /// @date 2010-09-27 / 2013-01-13 /// @author Christophe Riccio /////////////////////////////////////////////////////////////////////////////////// #include <glm/glm.hpp> #include <gli/gli.hpp> namespace glu{ namespace detail { //GL_COMPRESSED_RED, GL_COMPRESSED_RG, GL_COMPRESSED_RGB, GL_COMPRESSED_RGBA, GL_COMPRESSED_SRGB, GL_COMPRESSED_SRGB_ALPHA, //GL_SRGB, GL_SRGB8, GL_SRGB_ALPHA, or GL_SRGB8_ALPHA8 struct texture_desc { GLint InternalFormat; GLint InternalFormatCompressed; GLint InternalFormatSRGB; GLint InternalFormatCompressedSRGB; GLenum ExternalFormat; GLenum ExternalFormatRev; GLenum Type; }; //GL_RED, GL_RG, GL_RGB, GL_BGR, GL_RGBA, and GL_BGRA. //GL_UNSIGNED_BYTE, GL_BYTE, GL_UNSIGNED_SHORT, GL_SHORT, GL_UNSIGNED_INT, //GL_INT, GL_FLOAT, GL_UNSIGNED_BYTE_3_3_2, GL_UNSIGNED_BYTE_2_3_3_REV, //GL_UNSIGNED_SHORT_5_6_5, GL_UNSIGNED_SHORT_5_6_5_REV, GL_UNSIGNED_SHORT_4_4_4_4, //GL_UNSIGNED_SHORT_4_4_4_4_REV, GL_UNSIGNED_SHORT_5_5_5_1, GL_UNSIGNED_SHORT_1_5_5_5_REV, //GL_UNSIGNED_INT_8_8_8_8, GL_UNSIGNED_INT_8_8_8_8_REV, GL_UNSIGNED_INT_10_10_10_2, //GL_UNSIGNED_INT_2_10_10_10_REV # ifndef GL_COMPRESSED_RGBA_BPTC_UNORM_ARB # define GL_COMPRESSED_RGBA_BPTC_UNORM_ARB 0x8E8C # endif # ifndef GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB # define GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB 0x8E8D # endif # ifndef GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB # define GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB 0x8E8E # endif # ifndef GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB # define GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB 0x8E8F # endif inline texture_desc gli2ogl_cast(gli::format const & Format) { texture_desc Cast[] = { {GL_NONE, GL_NONE, GL_NONE, GL_NONE, GL_NONE, GL_NONE, GL_NONE}, //// Normalized //{GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_BYTE}, //{GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_BYTE}, //{GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_BYTE}, //{GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE}, //{GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_SHORT}, //{GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_SHORT}, //{GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_SHORT}, //{GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_SHORT}, //{GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_INT}, //{GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_INT}, //{GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_INT}, //{GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_INT}, // Unsigned {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_BYTE}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_BYTE}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_BYTE}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_BYTE}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_SHORT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_SHORT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_SHORT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_SHORT}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_INT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_INT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_UNSIGNED_INT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_UNSIGNED_INT}, // Signed {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_BYTE}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_BYTE}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_BYTE}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_BYTE}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_SHORT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_SHORT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_SHORT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_SHORT}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_INT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_INT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_INT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_INT}, // Float {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_HALF_FLOAT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_HALF_FLOAT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_HALF_FLOAT}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_FLOAT}, {GL_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, GL_RG, GL_RG, GL_FLOAT}, {GL_RGB, GL_COMPRESSED_RGB, GL_SRGB8, GL_COMPRESSED_SRGB, GL_RGB, GL_BGR, GL_FLOAT}, {GL_RGBA, GL_COMPRESSED_RGBA, GL_SRGB8_ALPHA8, GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_BGRA, GL_FLOAT}, // Packed {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_RGB9_E5, GL_RGB9_E5, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_R11F_G11F_B10F, GL_R11F_G11F_B10F, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_RGBA4, GL_RGBA4, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, {GL_RGB10_A2, GL_RGB10_A2, GL_RED, GL_COMPRESSED_RED, GL_RED, GL_RED, GL_HALF_FLOAT}, // Depth {GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT}, {GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}, {GL_DEPTH24_STENCIL8, GL_DEPTH24_STENCIL8, GL_DEPTH24_STENCIL8, GL_DEPTH24_STENCIL8, GL_DEPTH_COMPONENT, GL_DEPTH_STENCIL, GL_UNSIGNED_INT}, {GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_FLOAT}, {GL_DEPTH32F_STENCIL8, GL_DEPTH32F_STENCIL8, GL_DEPTH32F_STENCIL8, GL_DEPTH32F_STENCIL8, GL_DEPTH_COMPONENT, GL_DEPTH_STENCIL, GL_UNSIGNED_INT}, // Compressed formats {GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED_RGTC1, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_SIGNED_RED_RGTC1, GL_COMPRESSED_SIGNED_RED_RGTC1, GL_COMPRESSED_SIGNED_RED_RGTC1, GL_COMPRESSED_SIGNED_RED_RGTC1, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG_RGTC2, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_SIGNED_RG_RGTC2, GL_COMPRESSED_SIGNED_RG_RGTC2, GL_COMPRESSED_SIGNED_RG_RGTC2, GL_COMPRESSED_SIGNED_RG_RGTC2, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_NONE, GL_NONE, GL_NONE}, {GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB, GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB, GL_NONE, GL_NONE, GL_NONE}, }; return Cast[Format]; } }//namespace detail inline GLuint create_texture_2d(char const * Filename) { gli::texture2D Texture(gli::load_dds(Filename)); if(Texture.empty()) return 0; GLint Alignment(0); glGetIntegerv(GL_UNPACK_ALIGNMENT, &Alignment); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GLuint Name(0); glGenTextures(1, &Name); glTextureStorage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Texture.levels()), static_cast<GLenum>(gli::internal_format(Texture.format())), static_cast<GLsizei>(Texture.dimensions().x), static_cast<GLsizei>(Texture.dimensions().y)); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, Texture.levels() > 1 ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1)); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ALPHA); if(!gli::is_compressed(Texture.format())) { for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glTextureSubImage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Level), 0, 0, static_cast<GLsizei>(Texture[Level].dimensions().x), static_cast<GLsizei>(Texture[Level].dimensions().y), static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLenum>(gli::type_format(Texture.format())), Texture[Level].data()); } } else { for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glCompressedTextureSubImage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Level), 0, 0, static_cast<GLsizei>(Texture[Level].dimensions().x), static_cast<GLsizei>(Texture[Level].dimensions().y), static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLsizei>(Texture[Level].size()), Texture[Level].data()); } } // Restaure previous states glPixelStorei(GL_UNPACK_ALIGNMENT, Alignment); return Name; } inline GLuint create_texture_2d_array(char const * Filename) { gli::texture2DArray Texture(gli::load_dds(Filename)); if(Texture.empty()) return 0; GLint Alignment(0); glGetIntegerv(GL_UNPACK_ALIGNMENT, &Alignment); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); GLuint Name(0); glGenTextures(1, &Name); glTextureStorage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Texture.levels()), static_cast<GLenum>(gli::internal_format(Texture.format())), static_cast<GLsizei>(Texture.dimensions().x), static_cast<GLsizei>(Texture.dimensions().y), static_cast<GLsizei>(Texture.layers())); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, Texture.levels() > 1 ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1)); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_R, GL_RED); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_A, GL_ALPHA); if(!gli::is_compressed(Texture.format())) { for(gli::texture2D::size_type Layer(0); Layer < Texture.layers(); ++Layer) for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glTextureSubImage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Level), 0, 0, static_cast<GLint>(Layer), static_cast<GLsizei>(Texture[Layer][Level].dimensions().x), static_cast<GLsizei>(Texture[Layer][Level].dimensions().y), 1, static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLenum>(gli::type_format(Texture.format())), Texture[Layer][Level].data()); } } else { for(gli::texture2D::size_type Layer(0); Layer < Texture.layers(); ++Layer) for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glCompressedTextureSubImage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Level), 0, 0, static_cast<GLint>(Layer), static_cast<GLsizei>(Texture[Layer][Level].dimensions().x), static_cast<GLsizei>(Texture[Layer][Level].dimensions().y), 1, static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLsizei>(Texture[Layer][Level].size()), Texture[Layer][Level].data()); } } // Restaure previous states glPixelStorei(GL_UNPACK_ALIGNMENT, Alignment); return Name; } inline GLuint create_texture_2d(gli::storage const & Storage) { gli::texture2D Texture(Storage); if(Texture.empty()) return 0; GLuint Name(0); glGenTextures(1, &Name); glTextureStorage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Texture.levels()), static_cast<GLenum>(gli::internal_format(Texture.format())), static_cast<GLsizei>(Texture.dimensions().x), static_cast<GLsizei>(Texture.dimensions().y)); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, Texture.levels() > 1 ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1)); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_RED); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTextureParameteriEXT(Name, GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_A, GL_ALPHA); if(!gli::is_compressed(Texture.format())) { for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glTextureSubImage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Level), 0, 0, static_cast<GLsizei>(Texture[Level].dimensions().x), static_cast<GLsizei>(Texture[Level].dimensions().y), static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLenum>(gli::type_format(Texture.format())), Texture[Level].data()); } } else { for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glCompressedTextureSubImage2DEXT(Name, GL_TEXTURE_2D, static_cast<GLint>(Level), 0, 0, static_cast<GLsizei>(Texture[Level].dimensions().x), static_cast<GLsizei>(Texture[Level].dimensions().y), static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLsizei>(Texture[Level].size()), Texture[Level].data()); } } return Name; } inline GLuint create_texture_2d_array(gli::storage const & Storage) { gli::texture2DArray Texture(Storage); if(Texture.empty()) return 0; GLuint Name(0); glGenTextures(1, &Name); glTextureStorage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Texture.levels()), static_cast<GLenum>(gli::internal_format(Texture.format())), static_cast<GLsizei>(Texture.dimensions().x), static_cast<GLsizei>(Texture.dimensions().y), static_cast<GLsizei>(Texture.layers())); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, Texture.levels() > 1 ? GL_NEAREST_MIPMAP_NEAREST : GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_BASE_LEVEL, 0); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_LEVEL, static_cast<GLint>(Texture.levels() - 1)); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_R, GL_RED); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_G, GL_GREEN); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_B, GL_BLUE); glTextureParameteriEXT(Name, GL_TEXTURE_2D_ARRAY, GL_TEXTURE_SWIZZLE_A, GL_ALPHA); if(!gli::is_compressed(Texture.format())) { for(gli::texture2D::size_type Layer(0); Layer < Texture.layers(); ++Layer) for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glTextureSubImage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Level), 0, 0, static_cast<GLint>(Layer), static_cast<GLsizei>(Texture[Layer][Level].dimensions().x), static_cast<GLsizei>(Texture[Layer][Level].dimensions().y), 1, static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLenum>(gli::type_format(Texture.format())), Texture[Layer][Level].data()); } } else { for(gli::texture2D::size_type Layer(0); Layer < Texture.layers(); ++Layer) for(gli::texture2D::size_type Level(0); Level < Texture.levels(); ++Level) { glCompressedTextureSubImage3DEXT(Name, GL_TEXTURE_2D_ARRAY, static_cast<GLint>(Level), 0, 0, static_cast<GLint>(Layer), static_cast<GLsizei>(Texture[Layer][Level].dimensions().x), static_cast<GLsizei>(Texture[Layer][Level].dimensions().y), 1, static_cast<GLenum>(gli::external_format(Texture.format())), static_cast<GLsizei>(Texture[Layer][Level].size()), Texture[Layer][Level].data()); } } return Name; } class scopedPixelStore { public: scopedPixelStore(GLint Alignment) : SavedAlignment(0) { glGetIntegerv(GL_UNPACK_ALIGNMENT, &this->SavedAlignment); glPixelStorei(GL_UNPACK_ALIGNMENT, Alignment); } ~scopedPixelStore() { glPixelStorei(GL_UNPACK_ALIGNMENT, this->SavedAlignment); } private: GLint SavedAlignment; }; inline GLuint create_texture(char const * Filename) { gli::storage Storage(gli::load_dds(Filename)); scopedPixelStore PixelStore(1); if(Storage.layers() > 1) return create_texture_2d_array(Storage); else return create_texture_2d(Storage); } }//namespace gli
46.598253
203
0.74187
spetz911
c91f6bac4ddac5fccd0f0747a46d7a333465be0d
11,706
cc
C++
ggadget/file_manager_wrapper.cc
suzhe/google-gadgets-for-linux
b58baabd8458c8515c9902b8176151a08d240983
[ "Apache-2.0" ]
175
2015-01-01T12:40:33.000Z
2019-05-24T22:33:59.000Z
ggadget/file_manager_wrapper.cc
suzhe/google-gadgets-for-linux
b58baabd8458c8515c9902b8176151a08d240983
[ "Apache-2.0" ]
11
2015-01-19T16:30:56.000Z
2018-04-25T01:06:52.000Z
ggadget/file_manager_wrapper.cc
suzhe/google-gadgets-for-linux
b58baabd8458c8515c9902b8176151a08d240983
[ "Apache-2.0" ]
97
2015-01-19T15:35:29.000Z
2019-05-15T05:48:02.000Z
/* Copyright 2008 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "file_manager_wrapper.h" #include <vector> #include "gadget_consts.h" #include "light_map.h" #include "logger.h" #include "slot.h" #include "string_utils.h" #include "system_utils.h" #include "small_object.h" namespace ggadget { class FileManagerWrapper::Impl : public SmallObject<> { public: Impl() : default_(NULL) { } ~Impl() { delete default_; default_ = NULL; for (size_t i = 0; i < file_managers_.size(); ++i) delete file_managers_[i].second; file_managers_.clear(); } bool RegisterFileManager(const char *prefix, FileManagerInterface *fm) { // The default FileManager if (!prefix || !*prefix) { if (default_) { LOG("Default file manager must be unregistered before replaced."); return false; } default_ = fm; return true; } if (!fm || !fm->IsValid()) { LOG("An invalid FileManager instance is specified for prefix %s", prefix); return false; } file_managers_.push_back(std::make_pair(std::string(prefix), fm)); return true; } bool UnregisterFileManager(const char *prefix, FileManagerInterface *fm) { // The default FileManager if (!prefix || !*prefix) { if (fm == default_) { default_ = NULL; return true; } LOG("UnregisterFileManager: Default file manager mismatch."); return false; } for (FileManagerPrefixMap::iterator it = file_managers_.begin(); it != file_managers_.end(); ++it) { if (it->first == prefix && it->second == fm) { file_managers_.erase(it); return true; } } LOG("UnregisterFileManager: File manager not found."); return false; } bool IsValid() { if (default_ && default_->IsValid()) return true; for (FileManagerPrefixMap::iterator it = file_managers_.begin(); it != file_managers_.end(); ++it) { if (it->second->IsValid()) return true; } return false; } bool Init(const char *base_path, bool create) { if (default_) return default_->Init(base_path, create); return false; } bool ReadFile(const char *file, std::string *data) { size_t index = 0; FileManagerInterface *fm = NULL; std::string path; bool matched = false; while ((fm = GetNextMatching(file, &index, &path)) != NULL) { matched = true; if (fm->ReadFile(path.c_str(), data)) return true; } if (default_ && !matched) return default_->ReadFile(file, data); return false; } bool WriteFile(const char *file, const std::string &data, bool overwrite) { size_t index = 0; FileManagerInterface *fm = NULL; std::string path; bool matched = false; while ((fm = GetNextMatching(file, &index, &path)) != NULL) { matched = true; // Only writes the file to the first matched FileManager, // unless it fails. if (fm->WriteFile(path.c_str(), data, overwrite)) return true; } if (default_ && !matched) return default_->WriteFile(file, data, overwrite); return false; } bool RemoveFile(const char *file) { size_t index = 0; FileManagerInterface *fm = NULL; std::string path; bool result = false; bool matched = false; while ((fm = GetNextMatching(file, &index, &path)) != NULL) { matched = true; // Removes the file in all matched FileManager instance. if (fm->RemoveFile(path.c_str())) result = true; } if (default_ && !matched) result = default_->RemoveFile(file); return result; } bool ExtractFile(const char *file, std::string *into_file) { size_t index = 0; FileManagerInterface *fm = NULL; std::string path; bool matched = false; while ((fm = GetNextMatching(file, &index, &path)) != NULL) { matched = true; if (fm->ExtractFile(path.c_str(), into_file)) return true; } if (default_ && !matched) return default_->ExtractFile(file, into_file); return false; } bool FileExists(const char *file, std::string *path) { size_t index = 0; FileManagerInterface *fm = NULL; std::string lookup_path; bool matched = false; while ((fm = GetNextMatching(file, &index, &lookup_path)) != NULL) { matched = true; if (fm->FileExists(lookup_path.c_str(), path)) return true; } if (default_ && !matched) return default_->FileExists(file, path); return false; } bool IsDirectlyAccessible(const char *file, std::string *path) { size_t index = 0; FileManagerInterface *fm = NULL; std::string lookup_path; bool matched = false; while ((fm = GetNextMatching(file, &index, &lookup_path)) != NULL) { matched = true; if (fm->IsDirectlyAccessible(lookup_path.c_str(), path)) return true; } if (default_ && !matched) return default_->IsDirectlyAccessible(file, path); return false; } std::string GetFullPath(const char *file) { size_t index = 0; FileManagerInterface *fm = NULL; std::string lookup_path; bool matched = false; while ((fm = GetNextMatching(file, &index, &lookup_path)) != NULL) { matched = true; std::string full_path = fm->GetFullPath(lookup_path.c_str()); if (full_path.length()) return full_path; } if (default_ && !matched) return default_->GetFullPath(file); return std::string(""); } class EnumProxy { public: EnumProxy(LightSet<std::string> *history, const std::string &prefix, Slot1<bool, const char *> *callback) : history_(history), prefix_(prefix), callback_(callback) { } bool Callback(const char *name) { std::string path = BuildFilePath(prefix_.c_str(), name, NULL); if (history_->find(path) == history_->end()) { history_->insert(path); return (*callback_)(BuildFilePath(prefix_.c_str(), name, NULL).c_str()); } return true; } private: LightSet<std::string> *history_; std::string prefix_; Slot1<bool, const char *> *callback_; }; bool EnumerateFiles(const char *dir, Slot1<bool, const char *> *callback) { ASSERT(dir); std::string dir_name(dir); std::string dir_name_with_sep(dir_name); if (!dir_name.empty() && dir_name[dir_name.size() - 1] == kDirSeparator) dir_name.erase(dir_name.size() - 1); if (!dir_name_with_sep.empty() && dir_name_with_sep[dir_name_with_sep.size() - 1] != kDirSeparator) dir_name += kDirSeparator; // Record enumrated files to prevent duplication in multiple managers. bool result = true; LightSet<std::string> history; for (size_t i = 0; result && i < file_managers_.size(); i++) { const std::string &prefix = file_managers_[i].first; FileManagerInterface *fm = file_managers_[i].second; if (GadgetStrNCmp(prefix.c_str(), dir_name.c_str(), prefix.size()) == 0) { // Dir is under this file manager. EnumProxy proxy(&history, "", callback); result = fm->EnumerateFiles(dir_name.c_str() + prefix.size(), NewSlot(&proxy, &EnumProxy::Callback)); } else if (GadgetStrNCmp(prefix.c_str(), dir_name_with_sep.c_str(), dir_name_with_sep.size()) == 0) { // This file manager is under dir. EnumProxy proxy(&history, prefix.substr(dir_name_with_sep.size()), callback); result = fm->EnumerateFiles("", NewSlot(&proxy, &EnumProxy::Callback)); } } if (result && default_) { EnumProxy proxy(&history, "", callback); result = default_->EnumerateFiles(dir_name.c_str(), NewSlot(&proxy, &EnumProxy::Callback)); } delete callback; return result; } uint64_t GetLastModifiedTime(const char *file) { size_t index = 0; FileManagerInterface *fm = NULL; std::string lookup_path; bool matched = false; while ((fm = GetNextMatching(file, &index, &lookup_path)) != NULL) { matched = true; uint64_t result = fm->GetLastModifiedTime(lookup_path.c_str()); if (result > 0) return result; } if (default_ && !matched) return default_->GetLastModifiedTime(file); return 0; } FileManagerInterface *GetNextMatching(const char *path, size_t *index, std::string *lookup_path) { if (*index >= file_managers_.size() || !path || !*path) return NULL; while (*index < file_managers_.size()) { const std::string &prefix = file_managers_[*index].first; FileManagerInterface *fm = file_managers_[*index].second; ++*index; if (GadgetStrNCmp(prefix.c_str(), path, prefix.size()) == 0) { *lookup_path = std::string(path + prefix.size()); return fm; } } return NULL; } typedef std::vector<std::pair<std::string, FileManagerInterface *> > FileManagerPrefixMap; FileManagerPrefixMap file_managers_; FileManagerInterface *default_; }; FileManagerWrapper::FileManagerWrapper() : impl_(new Impl()) { } FileManagerWrapper::~FileManagerWrapper() { delete impl_; impl_ = NULL; } bool FileManagerWrapper::RegisterFileManager(const char *prefix, FileManagerInterface *fm) { return impl_->RegisterFileManager(prefix, fm); } bool FileManagerWrapper::UnregisterFileManager(const char *prefix, FileManagerInterface *fm) { return impl_->UnregisterFileManager(prefix, fm); } bool FileManagerWrapper::IsValid() { return impl_->IsValid(); } bool FileManagerWrapper::Init(const char *base_path, bool create) { return impl_->Init(base_path, create); } bool FileManagerWrapper::ReadFile(const char *file, std::string *data) { return impl_->ReadFile(file, data); } bool FileManagerWrapper::WriteFile(const char *file, const std::string &data, bool overwrite) { return impl_->WriteFile(file, data, overwrite); } bool FileManagerWrapper::RemoveFile(const char *file) { return impl_->RemoveFile(file); } bool FileManagerWrapper::ExtractFile(const char *file, std::string *into_file) { return impl_->ExtractFile(file, into_file); } bool FileManagerWrapper::FileExists(const char *file, std::string *path) { return impl_->FileExists(file, path); } bool FileManagerWrapper::IsDirectlyAccessible(const char *file, std::string *path) { return impl_->IsDirectlyAccessible(file, path); } std::string FileManagerWrapper::GetFullPath(const char *file) { return impl_->GetFullPath(file); } uint64_t FileManagerWrapper::GetLastModifiedTime(const char *file) { return impl_->GetLastModifiedTime(file); } bool FileManagerWrapper::EnumerateFiles(const char *dir, Slot1<bool, const char *> *callback) { return impl_->EnumerateFiles(dir, callback); } } // namespace ggadget
28.975248
80
0.626089
suzhe
c92049a8a890eb5cfc8904ab24729e5274bf7faf
673
cpp
C++
Iomanip.cpp
monicastle/C_PDC_06
e5447d853ae2702341a33cec1448ac500a356540
[ "MIT" ]
null
null
null
Iomanip.cpp
monicastle/C_PDC_06
e5447d853ae2702341a33cec1448ac500a356540
[ "MIT" ]
null
null
null
Iomanip.cpp
monicastle/C_PDC_06
e5447d853ae2702341a33cec1448ac500a356540
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <iomanip> using namespace std; class NT { string a, i, l; public: friend ostream &operator<<( ostream &o, const NT &n ); friend istream &operator>>( istream &i, NT &n ); }; ostream &operator<<( ostream &o, const NT &n ) { o << "(" << n.a << ") " << n.i << "-" << n.l; return o; } istream &operator>>( istream &i, NT &n ) { i.ignore(); i >> setw(3) >> n.a; i.ignore(2); i >> setw(4) >> n.i; i.ignore(); i >> setw(4) >> n.l; return i; } int main() { NT t; cout << "Telefono en la forma (504) 3193-9169:" << endl; cin >> t; cout << "Telefono: " << t << endl; }
23.206897
60
0.506686
monicastle
c9231b3faca86f68810e83440b8ee3c9b4b0ff1f
986
cc
C++
complejos/src/complejos.funciones.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Pablourquia
21990a872be9dbb32722a5f33fe743ba8faecd94
[ "MIT" ]
null
null
null
complejos/src/complejos.funciones.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Pablourquia
21990a872be9dbb32722a5f33fe743ba8faecd94
[ "MIT" ]
null
null
null
complejos/src/complejos.funciones.cc
ULL-ESIT-IB-2020-2021/ib-practica11-oop-cmake-Pablourquia
21990a872be9dbb32722a5f33fe743ba8faecd94
[ "MIT" ]
null
null
null
/** * Universidad de La Laguna * Escuela Superior de Ingeniería y Tecnología * Grado en Ingeniería Informática * Informática Básica * * @file complejos.funciones.cc * @author Pablo Urquía Adrián [email protected] * @date 26 de diciembre de 2020 * @brief El programa calcula la suma o resta de numeros complejos mediantes clases y funciones * @bug No hay bugs conocidos * */ #include <iostream> #include <string> #include <fstream> #include <cstring> #include "complejos.funciones.h" Complejo add(Complejo complejo1, Complejo complejo2){ Complejo result {0, 0}; result.setReal(complejo1.getReal() + complejo2.getReal()); result.setImaginaria(complejo1.getImaginaria() + complejo2.getImaginaria()); return result; } Complejo sub (Complejo complejo1, Complejo complejo2){ Complejo result {0, 0}; result.setReal(complejo1.getReal() - complejo2.getReal()); result.setImaginaria(complejo1.getImaginaria() - complejo2.getImaginaria()); return result; }
29.878788
95
0.747465
ULL-ESIT-IB-2020-2021
c923ed4109d412bf111f807d60eb5d46ed02645c
2,086
cpp
C++
cpp/src/rz/rz-kauvir/rz-graph-core/kernel/graph/rz-re-node.cpp
Mosaic-DigammaDB/SSQM
c150cec88b4ac2d26a972faf38d56e9dfb137ae6
[ "BSL-1.0" ]
null
null
null
cpp/src/rz/rz-kauvir/rz-graph-core/kernel/graph/rz-re-node.cpp
Mosaic-DigammaDB/SSQM
c150cec88b4ac2d26a972faf38d56e9dfb137ae6
[ "BSL-1.0" ]
1
2018-11-13T17:41:46.000Z
2018-11-13T20:54:38.000Z
cpp/src/rz/rz-kauvir/rz-graph-core/kernel/graph/rz-re-node.cpp
Mosaic-DigammaDB/SSQM
c150cec88b4ac2d26a972faf38d56e9dfb137ae6
[ "BSL-1.0" ]
1
2018-11-13T16:43:10.000Z
2018-11-13T16:43:10.000Z
// Copyright Nathaniel Christen 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "rz-re-node.h" #include "token/rz-re-token.h" #include "rzns.h" USING_RZNS(RECore) void RE_Node::each_connection(std::function<void(const RE_Connectors& connector, const RE_Node&, const RE_Connection* connection)> fn) const { targets_iterator_type it(targets_); while(it.hasNext()) { it.next(); const RE_Connectors& connector = *it.key(); const RE_Node& target = *it.value(); fn(connector, target, nullptr); } annotated_targets_iterator_type ait(annotated_targets_); while(ait.hasNext()) { ait.next(); const RE_Connectors& connector = *ait.key(); const RE_Connection* connection = ait.value().first.raw_pointer(); const RE_Node& target = *ait.value().second; fn(connector, target, connection); } } caon_ptr<RZ_Lisp_Token> RE_Node::lisp_token() { if(re_token()) { return re_token()->lisp_token(); } return nullptr; } void RE_Node::debug_connections() { targets_iterator_type it(targets_); while(it.hasNext()) { it.next(); CAON_EVALUATE_DEBUG(RE_Connectors ,key ,it.key()) CAON_EVALUATE_DEBUG(RE_Node ,value ,it.value()) } } void RE_Node::add_hyponode(caon_ptr<RE_Node> n) { hyponodes_.push_back(n); } void RE_Node::swap_relation(const RE_Connectors& connector, caon_ptr<RE_Node> n1, caon_ptr<RE_Node> n2) { CAON_PTR_DEBUG(RE_Node ,n1) CAON_PTR_DEBUG(RE_Node ,n2) #ifdef NO_CAON RE_Connectors* pc = const_cast<RE_Connectors*>( &connector ); targets_.remove(pc, n1); targets_.insert(pc, n2); #else targets_.remove(&connector, n1); targets_.insert(&connector, n2); #endif //NO_CAON } void RE_Node::delete_relation(const RE_Connectors& connector, caon_ptr<RE_Node> n1) { CAON_PTR_DEBUG(RE_Node ,n1) #ifdef NO_CAON RE_Connectors* pc = const_cast<RE_Connectors*>( &connector ); targets_.remove(pc, n1); #else targets_.remove(&connector, n1); #endif //NO_CAON }
21.070707
80
0.71093
Mosaic-DigammaDB
c925d5664112111d13f69559aafad90b42c5da45
178
cpp
C++
Src/Kranos/Entry.cpp
KDahir247/KranosLoader
5e55a0f1a697170020c2601c9b0d04b0da27da93
[ "MIT" ]
null
null
null
Src/Kranos/Entry.cpp
KDahir247/KranosLoader
5e55a0f1a697170020c2601c9b0d04b0da27da93
[ "MIT" ]
null
null
null
Src/Kranos/Entry.cpp
KDahir247/KranosLoader
5e55a0f1a697170020c2601c9b0d04b0da27da93
[ "MIT" ]
null
null
null
// // Created by kdahi on 2020-09-26. // #include "Kranos.h" int main(){ Kranos::Log::Init(); auto app = Kranos::CreateApplication(); app->Run(); delete app; }
13.692308
43
0.578652
KDahir247
c935b56933ae6973b030fa7e611bf911b43362bf
1,156
cpp
C++
competitive programming/leetcode/2020-July-Challenge/Day-26-Add Digits.cpp
kashyap99saksham/Code
96658d0920eb79c007701d2a3cc9dbf453d78f96
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
competitive programming/leetcode/2020-July-Challenge/Day-26-Add Digits.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
competitive programming/leetcode/2020-July-Challenge/Day-26-Add Digits.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. Example: Input: 38 Output: 2 Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. Follow up: Could you do it without any loop/recursion in O(1) runtime? Hide Hint #1 A naive implementation of the above process is trivial. Could you come up with other methods? Hide Hint #2 What are all the possible results? Hide Hint #3 How do they occur, periodically or randomly? Hide Hint #4 You may find this Wikipedia article useful. class Solution { public: int addDigits(int num) { int digitalRoot = 0; while (num > 0) { digitalRoot += num % 10; num = num / 10; if (num == 0 && digitalRoot > 9) { num = digitalRoot; digitalRoot = 0; } } return digitalRoot; } }; class Solution { public: int addDigits(int num) { if (num == 0) return 0; if (num % 9 == 0) return 9; return num % 9; } };
19.266667
100
0.563149
kashyap99saksham
c936fe0dd64bf31918c0c92382614e1a40b655c2
1,101
hpp
C++
include/System/Threading/Mutex.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Threading/Mutex.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/Threading/Mutex.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Threading.WaitHandle #include "System/Threading/WaitHandle.hpp" // Completed includes // Type namespace: System.Threading namespace System::Threading { // Forward declaring type: Mutex class Mutex; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Threading::Mutex); DEFINE_IL2CPP_ARG_TYPE(::System::Threading::Mutex*, "System.Threading", "Mutex"); // Type namespace: System.Threading namespace System::Threading { // Size: 0x29 #pragma pack(push, 1) // Autogenerated type: System.Threading.Mutex // [TokenAttribute] Offset: FFFFFFFF // [ComVisibleAttribute] Offset: 683E3C class Mutex : public ::System::Threading::WaitHandle { public: }; // System.Threading.Mutex #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
34.40625
81
0.700272
v0idp
c9395ba269c386a05d320993fd999853206b271d
7,460
cpp
C++
tests/3d_examples/test_3d_myocaridum/src/muscle_activation.cpp
BenceVirtonomy/SPHinXsys
a86beb4f55fbf501677dac70a293025714f7e9e6
[ "Apache-2.0" ]
92
2019-05-29T10:20:47.000Z
2022-03-28T20:51:32.000Z
tests/3d_examples/test_3d_myocaridum/src/muscle_activation.cpp
ChiZhangatTUM/SPHinXsys
faa88cab07866f9ba5e370654ab3b515c46c6432
[ "Apache-2.0" ]
47
2019-07-18T09:37:11.000Z
2022-03-30T12:10:53.000Z
tests/3d_examples/test_3d_myocaridum/src/muscle_activation.cpp
Xiangyu-Hu/SPHinXsys
faa88cab07866f9ba5e370654ab3b515c46c6432
[ "Apache-2.0" ]
50
2019-05-29T10:20:57.000Z
2022-03-28T03:46:13.000Z
/** * @file muscle_activation.cpp * @brief This is the first example of electro activation of myocardium * @author Chi Zhang and Xiangyu Hu */ #include "sphinxsys.h" /** Name space. */ using namespace SPH; /** Geometry parameters. */ Real PL = 1.0; /**< Length. */ Real PH = 1.0; /**< Thickness for thick plate. */ Real PW = 1.0; /**< Width. */ /**< Initial particle spacing. */ Real resolution_ref = PH / 25.0; Real SL = 4.0 * resolution_ref; /**< Extension for holder. */ /** Domain bounds of the system. */ BoundingBox system_domain_bounds(Vecd(-SL, -SL, -SL), Vecd(PL + SL, PH + SL, PW + SL)); /**< SimTK geometric modeling resolution. */ int resolution(20); /** For material properties of the solid. */ Real rho_0 = 1.0; Real a_0[4] = {0.059, 0.0, 0.0, 0.0}; Real b_0[4] = {8.023, 0.0, 0.0, 0.0}; Vec3d fiber_direction(1.0, 0.0, 0.0); Vec3d sheet_direction(0.0, 1.0, 0.0); Real reference_voltage = 30.0; Real linear_active_stress_factor = - 0.5; /** reference stress to achieve weakly compressible condition */ Real bulk_modulus = 30.0 * reference_voltage * fabs(linear_active_stress_factor); /** Define the geometry. */ TriangleMeshShape* createMyocardium() { Vecd halfsize_myocardium(0.5 * (PL + SL), 0.5 * PH, 0.5 * PW); Vecd translation_myocardium(0.5 * (PL - SL), 0.5 * PH, 0.5*PW); TriangleMeshShape* geometry_myocardium = new TriangleMeshShape(halfsize_myocardium, resolution, translation_myocardium); return geometry_myocardium; } /** Define the holder geometry. */ TriangleMeshShape* CreateHolder() { Vecd halfsize_shape(0.5 * SL, 0.5 * PH, 0.5 * PW); Vecd translation_shape(-0.5 * SL, 0.5 * PH, 0.5 * PW); TriangleMeshShape* geometry = new TriangleMeshShape(halfsize_shape, resolution, translation_shape); return geometry; } /** Define the myocardium body. */ class Myocardium : public SolidBody { public: Myocardium(SPHSystem &system, std::string body_name) : SolidBody(system, body_name) { ComplexShapeTriangleMesh *mesh = new ComplexShapeTriangleMesh(); body_shape_ = new ComplexShape(mesh); mesh->addTriangleMeshShape(createMyocardium(), ShapeBooleanOps::add); } }; /** * @brief define the Holder base which will be constrained. * NOTE: this class can only be instanced after body particles * have been generated */ class Holder : public BodyPartByParticle { public: Holder(SolidBody *solid_body, std::string constrained_region_name) : BodyPartByParticle(solid_body, constrained_region_name) { ComplexShapeTriangleMesh *mesh = new ComplexShapeTriangleMesh(); body_part_shape_ = new ComplexShape(mesh); mesh->addTriangleMeshShape(CreateHolder(), ShapeBooleanOps::add); tagBodyPart(); } }; /** * Assign case dependent muscle activation histroy */ class MyocardiumActivation : public active_muscle_dynamics::MuscleActivation { public: MyocardiumActivation(SolidBody *myocardium) : active_muscle_dynamics::MuscleActivation(myocardium) {}; protected: void Update(size_t index_i, Real dt) override { Real voltage = pos_0_[index_i][0] <= 0 ? 0.0 : reference_voltage * pos_0_[index_i][0] / PL; active_contraction_stress_[index_i] += GlobalStaticVariables::physical_time_ <= 1.0 ? linear_active_stress_factor * voltage * dt : 0.0; }; }; class ConstrainHolder : public solid_dynamics::ConstrainSolidBodyRegion { public: ConstrainHolder(SolidBody* body, BodyPartByParticle* body_part, int axis_id) : solid_dynamics::ConstrainSolidBodyRegion(body, body_part), axis_id_(axis_id) {}; protected: int axis_id_; virtual Vecd getDisplacement(Vecd& pos_0, Vecd& pos_n) { Vecd pos_temp = pos_n; pos_temp[axis_id_] = pos_0[axis_id_]; return pos_temp; }; virtual Vecd getVelocity(Vecd& pos_0, Vecd& pos_n, Vecd& vel_n) { Vecd vel_temp = vel_n; vel_temp[axis_id_] = 0.0; return vel_temp; }; virtual Vecd getAcceleration(Vecd& pos_0, Vecd& pos_n, Vecd& dvel_dt) { Vecd dvel_dt_temp = dvel_dt; dvel_dt_temp[axis_id_] = 0.0; return dvel_dt_temp; }; }; /** * Setup material properties of myocardium */ class ActiveMyocardiumMuscle : public ActiveMuscle<Muscle> { public: ActiveMyocardiumMuscle() : ActiveMuscle<Muscle>() { rho0_ = rho_0; bulk_modulus_ = bulk_modulus; f0_ = fiber_direction; s0_ = sheet_direction; std::copy(a_0, a_0 + 4, a0_); std::copy(b_0, b_0 + 4, b0_); assignDerivedMaterialParameters(); } }; /** * The main program */ int main() { /** Setup the system. */ SPHSystem system(system_domain_bounds, resolution_ref); /** Creat a Myocardium body, corresponding material, particles and reaction model. */ Myocardium *myocardium_muscle_body = new Myocardium(system, "MyocardiumMuscleBody"); ActiveMyocardiumMuscle *active_myocardium_muscle = new ActiveMyocardiumMuscle(); ActiveMuscleParticles myocardium_muscle_particles(myocardium_muscle_body, active_myocardium_muscle); /** topology */ BodyRelationInner* myocardium_muscle_body_inner = new BodyRelationInner(myocardium_muscle_body); /** * This section define all numerical methods will be used in this case. */ /** Corrected strong configuration. */ solid_dynamics::CorrectConfiguration corrected_configuration_in_strong_form(myocardium_muscle_body_inner); /** Time step size calculation. */ solid_dynamics::AcousticTimeStepSize computing_time_step_size(myocardium_muscle_body); /** Compute the active contraction stress */ MyocardiumActivation myocardium_activation(myocardium_muscle_body); /** active and passive stress relaxation. */ solid_dynamics::StressRelaxationFirstHalf stress_relaxation_first_half(myocardium_muscle_body_inner); solid_dynamics::StressRelaxationSecondHalf stress_relaxation_second_half(myocardium_muscle_body_inner); /** Constrain region of the inserted body. */ ConstrainHolder constrain_holder(myocardium_muscle_body, new Holder(myocardium_muscle_body, "Holder"), 0); /** Output */ In_Output in_output(system); BodyStatesRecordingToVtu write_states(in_output, system.real_bodies_); /** * From here the time stepping begines. * Set the starting time. */ GlobalStaticVariables::physical_time_ = 0.0; system.initializeSystemCellLinkedLists(); system.initializeSystemConfigurations(); corrected_configuration_in_strong_form.parallel_exec(); write_states.writeToFile(0); /** Setup physical parameters. */ int ite = 0; Real end_time = 1.2; Real output_period = end_time / 60.0; Real dt = 0.0; /** Statistics for computing time. */ tick_count t1 = tick_count::now(); tick_count::interval_t interval; /** * Main loop */ while (GlobalStaticVariables::physical_time_ < end_time) { Real integration_time = 0.0; while (integration_time < output_period) { if (ite % 100 == 0) { std::cout << "N=" << ite << " Time: " << GlobalStaticVariables::physical_time_ << " dt: " << dt << "\n"; } myocardium_activation.parallel_exec(dt); stress_relaxation_first_half.parallel_exec(dt); constrain_holder.parallel_exec(dt); stress_relaxation_second_half.parallel_exec(dt); ite++; dt = computing_time_step_size.parallel_exec(); integration_time += dt; GlobalStaticVariables::physical_time_ += dt; } tick_count t2 = tick_count::now(); write_states.writeToFile(); tick_count t3 = tick_count::now(); interval += t3 - t2; } tick_count t4 = tick_count::now(); tick_count::interval_t tt; tt = t4 - t1 - interval; std::cout << "Total wall time for computation: " << tt.seconds() << " seconds." << std::endl; return 0; }
31.476793
102
0.732172
BenceVirtonomy
c93af6079e1309e3b8ad50a41e9976cd23f41d2a
3,231
cpp
C++
rh_engine_lib/Engine/VulkanImpl/VulkanTopLevelAccelerationStructure.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
232
2016-08-29T00:33:32.000Z
2022-03-29T22:39:51.000Z
rh_engine_lib/Engine/VulkanImpl/VulkanTopLevelAccelerationStructure.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
10
2021-01-02T12:40:49.000Z
2021-08-31T06:31:04.000Z
rh_engine_lib/Engine/VulkanImpl/VulkanTopLevelAccelerationStructure.cpp
petrgeorgievsky/gtaRenderHook
124358410c3edca56de26381e239ca29aa6dc1cc
[ "MIT" ]
40
2017-12-18T06:14:39.000Z
2022-01-29T16:35:23.000Z
// // Created by peter on 01.05.2020. // #include "VulkanTopLevelAccelerationStructure.h" #include "VulkanCommon.h" #include <DebugUtils/DebugLogger.h> #include <vk_mem_alloc.h> namespace rh::engine { VulkanTopLevelAccelerationStructure::VulkanTopLevelAccelerationStructure( const TLASCreateInfoVulkan &create_info ) : mDevice( create_info.mDevice ) { vk::AccelerationStructureCreateInfoNV vk_ac_create_info{}; mAccelInfo.instanceCount = create_info.mMaxInstanceCount; mAccelInfo.type = vk::AccelerationStructureTypeNV::eTopLevel; vk_ac_create_info.info = mAccelInfo; auto result = mDevice.createAccelerationStructureNV( vk_ac_create_info ); if ( !CALL_VK_API( result.result, TEXT( "Failed to create acceleration structure!" ) ) ) return; mAccel = result.value; vk::AccelerationStructureMemoryRequirementsInfoNV accelerationStructureMemoryRequirementsInfoNv{}; accelerationStructureMemoryRequirementsInfoNv.accelerationStructure = mAccel; vk::MemoryRequirements2 req = mDevice.getAccelerationStructureMemoryRequirementsNV( accelerationStructureMemoryRequirementsInfoNv ); // allocate /*VulkanMemoryAllocationInfo alloc_info{}; alloc_info.mRequirements = req.memoryRequirements; alloc_info.mDeviceLocal = true; mAccelMemory = create_info.mAllocator->AllocateDeviceMemory( alloc_info );*/ mAllocator = create_info.mAllocator->GetImpl(); VkMemoryRequirements requirements = req.memoryRequirements; VmaAllocationInfo allocationDetail{}; VmaAllocationCreateInfo allocationCreateInfo{}; allocationCreateInfo.usage = VmaMemoryUsage::VMA_MEMORY_USAGE_GPU_ONLY; // TODO: HANLE ERRORS vmaAllocateMemory( mAllocator, &requirements, &allocationCreateInfo, &mAllocation, &allocationDetail ); // bind vk::BindAccelerationStructureMemoryInfoNV bind_info{}; bind_info.accelerationStructure = mAccel; bind_info.memory = allocationDetail.deviceMemory; bind_info.memoryOffset = allocationDetail.offset; // bind_info.memory = mAccelMemory; if ( mDevice.bindAccelerationStructureMemoryNV( 1, &bind_info ) != vk::Result::eSuccess ) { debug::DebugLogger::Error( "Failed to bind TLAS memory!" ); std::terminate(); } // compute scratch size vk::AccelerationStructureMemoryRequirementsInfoNV memoryRequirementsInfo{ vk::AccelerationStructureMemoryRequirementsTypeNV::eBuildScratch, mAccel }; mScratchSize = mDevice .getAccelerationStructureMemoryRequirementsNV( memoryRequirementsInfo ) .memoryRequirements.size; } VulkanTopLevelAccelerationStructure::~VulkanTopLevelAccelerationStructure() { mDevice.destroyAccelerationStructureNV( mAccel ); vmaFreeMemory( mAllocator, mAllocation ); /*mDevice.destroyAccelerationStructureNV( mAccel ); mDevice.freeMemory( mAccelMemory );*/ } std::uint64_t VulkanTopLevelAccelerationStructure::GetScratchSize() { return mScratchSize; } } // namespace rh::engine
36.303371
80
0.715258
petrgeorgievsky
c93fe6acfb887be6ef19e8515de16d04d376e2c9
14,092
cpp
C++
die-json-test/testParserOK.cpp
thinlizzy/die-json
11e274fc219a2d6d0c3b4d77333248bc64cf0c81
[ "MIT" ]
1
2015-10-18T16:19:48.000Z
2015-10-18T16:19:48.000Z
die-json-test/testParserOK.cpp
thinlizzy/die-json
11e274fc219a2d6d0c3b4d77333248bc64cf0c81
[ "MIT" ]
null
null
null
die-json-test/testParserOK.cpp
thinlizzy/die-json
11e274fc219a2d6d0c3b4d77333248bc64cf0c81
[ "MIT" ]
null
null
null
#include <tut.h> #include "../die-json.h" #include <sstream> #include <iostream> #include <vector> #include <memory> namespace { struct Value { die::json::Parser::ObjectName name; die::json::ValueType valueType; die::json::Parser::ValueStr value; bool operator==(Value const & v) const { return name == v.name && valueType == v.valueType && value == v.value; }; bool operator!=(Value const & v) const { return ! operator==(v); } }; } namespace { struct setup { die::json::Parser parser; void parseSingleValue(std::string const & strToParse, die::json::ValueType valueType, die::json::Parser::ValueStr const & valueStr) { bool calledV = false; parser.value([&](auto name, auto type, auto value) { tut::ensure_equals(name, "name"); tut::ensure_equals(type, valueType); tut::ensure_equals(value, valueStr); calledV = true; }); std::istringstream iss(strToParse); auto parsed = parser.parse(iss); tut::ensure("parser did not reach final state", parsed); tut::ensure("value has not been called", calledV); } void setParserEvents(std::string & path, std::vector<Value> & values, std::vector<std::string> & arrays) { parser .startObject([&path](auto name) { path += name + "/"; }) .endObject([&path](auto name) { auto rem = name + "/"; auto p = path.rfind(rem); auto ok = p != std::string::npos && path.size() - p == rem.size(); tut::ensure(path + "does not end with " + rem, ok); path.resize(path.size() - rem.size()); }) .value([&values,&path](auto name, auto type, auto value) { values.push_back({path+name,type,value}); }) .startArray([&arrays](auto name) { arrays.push_back(name + '['); }) .endArray([&arrays](auto name) { arrays.push_back(name + ']'); }) ; } }; struct SingleCall { // shared_ptr is a needed kludge here because I am copying into std::function std::shared_ptr<bool> calledPtr = std::make_shared<bool>(false); std::string expectedName; bool called() const { return *calledPtr; } void operator()(std::string const & name) { tut::ensure_equals("regarding object name", expectedName, name); *calledPtr = true; } }; } std::ostream & operator<<(std::ostream & os, Value value) { return os << value.name << ',' << value.valueType << ',' << value.value; } namespace tut { using std::istringstream; typedef test_group<setup> tg; tg parser_test_group("JsonParserOK"); typedef tg::object testobject; template<> template<> void testobject::test<1>() { set_test_name("parse empty"); bool called = false; parser.startObject([&called](auto name) { ensure("root object name should be empty", name.empty()); called = true; }); istringstream iss("{}"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure("startObject has not been called", called); } template<> template<> void testobject::test<2>() { set_test_name("parse single string"); SingleCall startObj,endObj; parser .startObject(startObj) .endObject(endObj); bool calledV = false; parser.value([&calledV](auto name, auto type, auto value) { ensure_equals(name, "name"); ensure_equals(type, die::json::ValueType::string); ensure_equals(value, "value"); calledV = true; }); istringstream iss("{ \"name\" : \"value\" }"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure("startObject has not been called", startObj.called()); ensure("endObject has not been called", endObj.called()); ensure("value has not been called", calledV); } template<> template<> void testobject::test<3>() { set_test_name("string with escape and unicode"); parseSingleValue(R"json({ "name" : "\"value\" \ua1B0 \\ \/ \b\f\n\r\t" })json", die::json::ValueType::string, std::string(R"json("value" \ua1B0 \ / )json") + '\b' + '\f' + '\n' + '\r' + '\t'); } template<> template<> void testobject::test<4>() { set_test_name("parse keywords"); parseSingleValue("{ \"name\" : null }",die::json::ValueType::null,"null"); parseSingleValue("{ \"name\" : true }",die::json::ValueType::boolean,"true"); parseSingleValue("{ \n" "\"name\" : false \n" "}",die::json::ValueType::boolean,"false"); } template<> template<> void testobject::test<5>() { set_test_name("numbers"); parseSingleValue("{ \"name\" : 0 }",die::json::ValueType::number,"0"); parseSingleValue("{ \"name\" : 1029 }",die::json::ValueType::number,"1029"); parseSingleValue("{ \"name\" : -129 }",die::json::ValueType::number,"-129"); parseSingleValue("{ \"name\" : 0.3 }",die::json::ValueType::number,"0.3"); parseSingleValue("{ \"name\" : -1.324 }",die::json::ValueType::number,"-1.324"); parseSingleValue("{ \"name\" : -0.55 }",die::json::ValueType::number,"-0.55"); parseSingleValue("{ \"name\" : 0.55e10 }",die::json::ValueType::number,"0.55e10"); parseSingleValue("{ \"name\" : 55E+88 }",die::json::ValueType::number,"55E+88"); parseSingleValue("{ \"name\" : -4.5E-2878 }",die::json::ValueType::number,"-4.5E-2878"); parseSingleValue("{ \"name\" : 77.66e+20 }",die::json::ValueType::number,"77.66e+20"); } template<> template<> void testobject::test<6>() { set_test_name("more values"); std::vector<Value> values; parser.value([&values](auto name, auto type, auto value) { values.push_back({name,type,value}); }); istringstream iss("{ \n" "\"nameStr\" : \"value\" ,\n" "\"nameNum\" : 10,\n" "\"zero\" : 0,\n" " \"superTrue\":true,\n" "\"myNull\" : null,\n" "\"nameBool\" : false\n" " }"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure_equals(values.size(), 6); ensure_equals(values[0], Value{"nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[1], Value{"nameNum", die::json::ValueType::number, "10"}); ensure_equals(values[2], Value{"zero", die::json::ValueType::number, "0"}); ensure_equals(values[3], Value{"superTrue", die::json::ValueType::boolean, "true"}); ensure_equals(values[4], Value{"myNull", die::json::ValueType::null, "null"}); ensure_equals(values[5], Value{"nameBool", die::json::ValueType::boolean, "false"}); } template<> template<> void testobject::test<7>() { set_test_name("nested objects"); std::string path; std::vector<Value> values; std::vector<std::string> arrays; setParserEvents(path,values,arrays); istringstream iss(R"json( { "nameStr" : "value", "object1" : { "zero":0, "nameStr" : "value", "placeholder" : null }, "object2" : {}, "anotherStr":"valueStr2", "object3" : { "numbah" : 0.5E-23, "nested" : { "meh" : null } }, "lastValue":-1 } )json"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure_equals(values.size(), 8); ensure_equals(values[0], Value{"/nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[1], Value{"/object1/zero", die::json::ValueType::number, "0"}); ensure_equals(values[2], Value{"/object1/nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[3], Value{"/object1/placeholder", die::json::ValueType::null, "null"}); ensure_equals(values[4], Value{"/anotherStr", die::json::ValueType::string, "valueStr2"}); ensure_equals(values[5], Value{"/object3/numbah", die::json::ValueType::number, "0.5E-23"}); ensure_equals(values[6], Value{"/object3/nested/meh", die::json::ValueType::null, "null"}); ensure_equals(values[7], Value{"/lastValue", die::json::ValueType::number, "-1"}); } template<> template<> void testobject::test<8>() { set_test_name("empty array"); SingleCall startObj,endObj,startArr,endArr; startArr.expectedName = "array"; endArr.expectedName = "array"; parser .startObject(startObj) .endObject(endObj) .startArray(startArr) .endArray(endArr); bool calledV = false; parser.value([&calledV](auto name, auto type, auto value) { calledV = true; }); istringstream iss("{ \"array\" : [] }"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure("startObject has not been called", startObj.called()); ensure("startArray has not been called", startArr.called()); ensure("endArray has not been called", endArr.called()); ensure("endObject has not been called", endObj.called()); ensure_not("value should never be called", calledV); } template<> template<> void testobject::test<9>() { set_test_name("arrays of values"); std::vector<Value> values; SingleCall startObj,endObj,startArr,endArr; startArr.expectedName = "array"; endArr.expectedName = "array"; parser .startObject(startObj) .endObject(endObj) .startArray(startArr) .endArray(endArr) .value([&values](auto name, auto type, auto value) { values.push_back({name,type,value}); }) ; istringstream iss("{ \"array\" : [ 1,2, null, \"oi\",false,0 ] }"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure("startObject has not been called", startObj.called()); ensure("startArray has not been called", startArr.called()); ensure("endArray has not been called", endArr.called()); ensure("endObject has not been called", endObj.called()); ensure_equals(values.size(), 6); ensure_equals(values[0], Value{"array", die::json::ValueType::number, "1"}); ensure_equals(values[1], Value{"array", die::json::ValueType::number, "2"}); ensure_equals(values[2], Value{"array", die::json::ValueType::null, "null"}); ensure_equals(values[3], Value{"array", die::json::ValueType::string, "oi"}); ensure_equals(values[4], Value{"array", die::json::ValueType::boolean, "false"}); ensure_equals(values[5], Value{"array", die::json::ValueType::number, "0"}); } template<> template<> void testobject::test<10>() { set_test_name("arrays of objects and values"); std::string path; std::vector<Value> values; std::vector<std::string> arrays; setParserEvents(path,values,arrays); istringstream iss(R"json( { "nameStr" : "value", "myObjects" : [ { "zero":0, "nameStr" : "value", "placeholder" : null }, {}, "valueStr2", { "numbah" : 0.5E-23, "nested" : { "meh" : null } }, -1 ], "otherArray" : [2,1] } )json"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure_equals(values.size(), 10); ensure_equals(values[0], Value{"/nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[1], Value{"/myObjects/zero", die::json::ValueType::number, "0"}); ensure_equals(values[2], Value{"/myObjects/nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[3], Value{"/myObjects/placeholder", die::json::ValueType::null, "null"}); ensure_equals(values[4], Value{"/myObjects", die::json::ValueType::string, "valueStr2"}); ensure_equals(values[5], Value{"/myObjects/numbah", die::json::ValueType::number, "0.5E-23"}); ensure_equals(values[6], Value{"/myObjects/nested/meh", die::json::ValueType::null, "null"}); ensure_equals(values[7], Value{"/myObjects", die::json::ValueType::number, "-1"}); ensure_equals(values[8], Value{"/otherArray", die::json::ValueType::number, "2"}); ensure_equals(values[9], Value{"/otherArray", die::json::ValueType::number, "1"}); ensure_equals(arrays.size(), 4); ensure_equals(arrays[0], "myObjects["); ensure_equals(arrays[1], "myObjects]"); ensure_equals(arrays[2], "otherArray["); ensure_equals(arrays[3], "otherArray]"); } template<> template<> void testobject::test<11>() { set_test_name("arrays of arrays"); std::string path; std::vector<Value> values; std::vector<std::string> arrays; setParserEvents(path,values,arrays); istringstream iss(R"json( { "myObjects" : [ 1, { "zero":0, "nameStr" : "value", "placeholder" : null }, "valueStr3", [1,2,3], { "numbah" : 0.5E-23, "nested" : { "meh" : null } }, [4,5,{ "six": [7,8,9], "ten" : null }, 11 ] ] } )json"); auto parsed = parser.parse(iss); ensure("parser did not reach final state", parsed); ensure_equals(values.size(), 17); ensure_equals(values[0], Value{"/myObjects", die::json::ValueType::number, "1"}); ensure_equals(values[1], Value{"/myObjects/zero", die::json::ValueType::number, "0"}); ensure_equals(values[2], Value{"/myObjects/nameStr", die::json::ValueType::string, "value"}); ensure_equals(values[3], Value{"/myObjects/placeholder", die::json::ValueType::null, "null"}); ensure_equals(values[4], Value{"/myObjects", die::json::ValueType::string, "valueStr3"}); ensure_equals(values[5], Value{"/myObjects", die::json::ValueType::number, "1"}); ensure_equals(values[6], Value{"/myObjects", die::json::ValueType::number, "2"}); ensure_equals(values[7], Value{"/myObjects", die::json::ValueType::number, "3"}); ensure_equals(values[8], Value{"/myObjects/numbah", die::json::ValueType::number, "0.5E-23"}); ensure_equals(values[9], Value{"/myObjects/nested/meh", die::json::ValueType::null, "null"}); ensure_equals(values[10], Value{"/myObjects", die::json::ValueType::number, "4"}); ensure_equals(values[11], Value{"/myObjects", die::json::ValueType::number, "5"}); ensure_equals(values[12], Value{"/myObjects/six", die::json::ValueType::number, "7"}); ensure_equals(values[13], Value{"/myObjects/six", die::json::ValueType::number, "8"}); ensure_equals(values[14], Value{"/myObjects/six", die::json::ValueType::number, "9"}); ensure_equals(values[15], Value{"/myObjects/ten", die::json::ValueType::null, "null"}); ensure_equals(values[16], Value{"/myObjects", die::json::ValueType::number, "11"}); ensure_equals(arrays.size(), 8); ensure_equals(arrays[0], "myObjects["); ensure_equals(arrays[1], "myObjects["); ensure_equals(arrays[2], "myObjects]"); ensure_equals(arrays[3], "myObjects["); ensure_equals(arrays[4], "six["); ensure_equals(arrays[5], "six]"); ensure_equals(arrays[6], "myObjects]"); ensure_equals(arrays[7], "myObjects]"); } }
33.002342
133
0.650156
thinlizzy
c945a5d43a215a57d44512dc6586a9dc74236a81
3,115
cpp
C++
ModuleSceneIntro.cpp
Denisdrk6/Ignition-Engine
bd23fa119452356fce5047236b09b2243346be3e
[ "MIT" ]
1
2021-09-29T14:50:17.000Z
2021-09-29T14:50:17.000Z
ModuleSceneIntro.cpp
Denisdrk6/Ignition-Engine
bd23fa119452356fce5047236b09b2243346be3e
[ "MIT" ]
null
null
null
ModuleSceneIntro.cpp
Denisdrk6/Ignition-Engine
bd23fa119452356fce5047236b09b2243346be3e
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "ModuleSceneIntro.h" #include "Primitive.h" #include "imgui/imgui.h" #include "FbxLoader.h" #include "ModuleCamera3D.h" #include "ModuleRenderer3D.h" ModuleSceneIntro::ModuleSceneIntro(Application* app, bool start_enabled) : Module(app, start_enabled) { } ModuleSceneIntro::~ModuleSceneIntro() {} // Load assets bool ModuleSceneIntro::Start() { App->log->AddLog("Loading Intro Scene\n"); bool ret = true; App->fbx->LoadFbx("Assets/BakerHouse.fbx"); //game_objects.push_back(CreateGameObject()); return ret; } // Update: draw scene update_status ModuleSceneIntro::Update(float dt) { bool ret = true; PrimPlane p(0, 1, 0, 0); p.axis = true; p.Render(); //LOAD FBX 3 for (int i = 0; !App->fbx->meshes.empty() && (i < App->fbx->meshes.size()); i++) App->renderer3D->DrawMesh(App->fbx->meshes.at(i)); for (int i = 0; i < game_objects.size(); i++) game_objects.at(i)->Update(); return UPDATE_CONTINUE; } // Load assets bool ModuleSceneIntro::CleanUp() { App->log->AddLog("Unloading Intro scene\n"); for (int i = 0; i < game_objects.size(); i++) { game_objects.at(i)->CleanUp(); RELEASE(game_objects.at(i)); } game_objects.clear(); /* //__________Unbind buffers____________ glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_TEXTURE_COORD_ARRAY, 0); glBindBuffer(GL_TEXTURE_2D, 0); //___________DISABLE STATES__________ glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); */ return true; } GameObject* ModuleSceneIntro::CreateGameObject() { GameObject* gameObject = new GameObject(); return gameObject; } void ModuleSceneIntro::DrawHierarchy() { ImGui::SetNextWindowSize({ 300.0f, (float)App->window->height - 220.0f }); ImGui::SetNextWindowPos({ 0.0f, 20.0f }); // Main menu bar is 20px high ImGui::Begin("Hierarchy", (bool*)true, ImGuiWindowFlags_NoCollapse); // Cannot be manually closed by user for (int i = 0; i < game_objects.size(); i++) { if (game_objects[i]->children.size() > 0) { if (ImGui::TreeNodeEx(game_objects[i]->name.c_str())) { for (int j = 0; j < game_objects[i]->children.size(); j++) { DrawRecursive(game_objects[i]->children[j]); } ImGui::TreePop(); } } else { ImGui::Text(game_objects[i]->name.c_str()); } } //if (ImGui::IsItemClicked()) ImGui::End(); } void ModuleSceneIntro::DrawRecursive(GameObject* parent) { if (parent->children.size() > 0) { if (ImGui::TreeNodeEx(parent->name.c_str())) { for (int j = 0; j < parent->children.size(); j++) { DrawRecursive(parent->children[j]); } ImGui::TreePop(); } } else { ImGui::Text(parent->name.c_str()); } }
21.93662
109
0.597111
Denisdrk6
c94d50615309a9c267780d41da3124b59fd2a703
2,443
cpp
C++
Ch9_2/Ch9_2/Source.cpp
Es10liv/mcc.cplusplus
23150f2fd5a56dbacc7c1809455e4e85d1fdd29e
[ "MIT" ]
null
null
null
Ch9_2/Ch9_2/Source.cpp
Es10liv/mcc.cplusplus
23150f2fd5a56dbacc7c1809455e4e85d1fdd29e
[ "MIT" ]
null
null
null
Ch9_2/Ch9_2/Source.cpp
Es10liv/mcc.cplusplus
23150f2fd5a56dbacc7c1809455e4e85d1fdd29e
[ "MIT" ]
null
null
null
// Chapter 7 programming challenge 2 test scores #include<iostream> #include<iomanip> using namespace std; // prototype functions void sort(double*, int); double average(double*, int); int main() { // create variables // number of test scores int intTestScores; // pointer to array double *testScorePtr; // average test score double dblTestAverage; // get the number of test scores cout << "How many test scores will you enter?" << endl; cin >> intTestScores; // validate the input prevent user from entering a negative number while (intTestScores < 0) { cout << "The number cannot be negative." << endl; cout << "Enter another number: "; cin >> intTestScores; } // create the array to hold test scores testScorePtr = new double[intTestScores]; // fill the array with a loop for (int count = 0; count < intTestScores; count++) { cout << "\nEnter The test score for test # " << (count + 1) << ": "; cin >> testScorePtr[count]; while (testScorePtr[count] < 0) { cout << "The number cannot be negative." << endl; cout << "Enter another number: "; cin >> intTestScores; } } // sort the test scores sort(testScorePtr, intTestScores); // get the average of the test scores dblTestAverage = average(testScorePtr, intTestScores); // display the sort result and the averages cout << "The average of all tests: " << dblTestAverage << endl; delete[] testScorePtr; testScorePtr = 0; return 0; } // write a function to sort the array in ascending order void sort(double* score, int size) { int startScan, minIndex; double minValue; for (startScan = 0; startScan < (size - 1); startScan++) { minIndex = startScan; minValue = *(score + startScan); for (int index = startScan + 1; index < size; index++) { if (*(score + index) < minValue) { minValue = *(score + index); minIndex = index; } } *(score + minIndex) = *(score + startScan); *(score + startScan) = minValue; } } // Write a function to calculate the average using a pointer to the array of scores double average(double *score, int size) { double total = 0.00; double dblTotalAverage; cout << fixed << showpoint << setprecision(2); for (int count = 0; count < size; count++) { total += *score; score++; dblTotalAverage = total / size; } return dblTotalAverage; }
22.209091
84
0.635694
Es10liv
c94dcf7aa68ccef0767ae0e7a64e6447efd8ca84
3,394
cpp
C++
bin/libs/systemc-2.3.1/src/sysc/datatypes/fx/scfx_pow10.cpp
buaawj/Research
23bf0d0df67f80b7a860f9d2dc3f30b60554c26d
[ "OML" ]
9
2019-07-15T10:05:29.000Z
2022-03-14T12:55:19.000Z
bin/libs/systemc-2.3.1/src/sysc/datatypes/fx/scfx_pow10.cpp
buaawj/Research
23bf0d0df67f80b7a860f9d2dc3f30b60554c26d
[ "OML" ]
2
2019-11-30T23:27:47.000Z
2021-11-02T12:01:05.000Z
systemc-2.3.1/src/sysc/datatypes/fx/scfx_pow10.cpp
tianzhuqiao/bsmedit
3e443ed6db7b44b3b0da0e4bc024b65dcfe8e7a4
[ "MIT" ]
null
null
null
/***************************************************************************** The following code is derived, directly or indirectly, from the SystemC source code Copyright (c) 1996-2014 by all Contributors. All Rights reserved. The contents of this file are subject to the restrictions and limitations set forth in the SystemC Open Source License (the "License"); You may not use this file except in compliance with such restrictions and limitations. You may obtain instructions on how to receive a copy of the License at http://www.accellera.org/. Software distributed by Contributors under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. *****************************************************************************/ /***************************************************************************** scfx_pow10.cpp - Original Author: Robert Graulich, Synopsys, Inc. Martin Janssen, Synopsys, Inc. *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ // $Log: scfx_pow10.cpp,v $ // Revision 1.1.1.1 2006/12/15 20:20:04 acg // SystemC 2.3 // // Revision 1.3 2006/01/13 18:53:58 acg // Andy Goodrich: added $Log command so that CVS comments are reproduced in // the source. // #include "sysc/datatypes/fx/scfx_pow10.h" namespace sc_dt { // ---------------------------------------------------------------------------- // CLASS : scfx_pow10 // // Class to compute (and cache) powers of 10 in arbitrary precision. // ---------------------------------------------------------------------------- scfx_pow10::scfx_pow10() { m_pos[0] = scfx_rep( 10.0 ); m_neg[0] = scfx_rep( 0.1 ); for( int i = 1; i < SCFX_POW10_TABLE_SIZE; i ++ ) { m_pos[i].set_nan(); m_neg[i].set_nan(); } } scfx_pow10::~scfx_pow10() {} const scfx_rep scfx_pow10::operator() ( int i ) { if( i == 0 ) { return scfx_rep( 1.0 ); } if( i > 0 ) { int bit = scfx_find_msb( i ); scfx_rep result = *pos( bit ); if( bit ) { while( -- bit >= 0 ) { if( ( 1 << bit ) & i ) { scfx_rep* tmp = mult_scfx_rep( result, *pos( bit ) ); result = *tmp; delete tmp; } } } return result; } else { i = -i; int bit = scfx_find_msb( i ); scfx_rep result = *neg( bit ); if( bit ) { while( -- bit >= 0 ) { if( ( 1 << bit ) & i ) { scfx_rep* tmp = mult_scfx_rep( result, *neg( bit ) ); result = *tmp; delete tmp; } } } return result; } } scfx_rep* scfx_pow10::pos( int i ) { if( ! m_pos[i].is_normal() ) { multiply( m_pos[i], *pos( i - 1 ), *pos( i - 1 ) ); } return &m_pos[i]; } scfx_rep* scfx_pow10::neg( int i ) { if( ! m_neg[i].is_normal() ) { multiply( m_neg[i], *neg( i - 1 ), *neg( i - 1 ) ); } return &m_neg[i]; } } // namespace sc_dt // Taf!
23.246575
79
0.489393
buaawj
c94fee71ae262ecc5cd5d2c79b3b955f2f5ed8b2
4,328
cpp
C++
tests/test_ocp_to_nlp.cpp
tgurriet/smooth_feedback
1f926cb4269741ddc09ba048af5bea5e0390a053
[ "MIT" ]
null
null
null
tests/test_ocp_to_nlp.cpp
tgurriet/smooth_feedback
1f926cb4269741ddc09ba048af5bea5e0390a053
[ "MIT" ]
null
null
null
tests/test_ocp_to_nlp.cpp
tgurriet/smooth_feedback
1f926cb4269741ddc09ba048af5bea5e0390a053
[ "MIT" ]
null
null
null
// smooth_feedback: Control theory on Lie groups // https://github.com/pettni/smooth_feedback // // Licensed under the MIT License <http://opensource.org/licenses/MIT>. // // Copyright (c) 2021 Petter Nilsson // // 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, EVecPRESS 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 <gtest/gtest.h> #include <Eigen/Core> #include <smooth/so3.hpp> #include "smooth/feedback/ocp_to_nlp.hpp" template<typename T, std::size_t N> using Vec = Eigen::Vector<T, N>; TEST(OcpToNlp, Derivatives2) { // objective auto theta = []<typename T>(T tf, Vec<T, 2> x0, Vec<T, 2> xf, Vec<T, 1> q) -> T { return (tf - 2) * (tf - 2) + x0.cwiseProduct(xf).squaredNorm() + xf.squaredNorm() + q.sum(); }; // dynamics auto f = []<typename T>(T t, Vec<T, 2> x, Vec<T, 1> u) -> Vec<T, 2> { return Vec<T, 2>{{x.y() + t, x.x() * u.x() * u.x()}}; }; // integrals auto g = []<typename T>(T t, Vec<T, 2> x, Vec<T, 1> u) -> Vec<T, 1> { return Vec<T, 1>{{t + t * x.squaredNorm() + u.squaredNorm()}}; }; // running constraint auto cr = []<typename T>(T t, Vec<T, 2> x, Vec<T, 1> u) -> Vec<T, 4> { Vec<T, 4> ret(4); ret << t, t * x * u.x(), u.cwiseAbs2(); return ret; }; // end constraint auto ce = []<typename T>(T tf, Vec<T, 2> x0, Vec<T, 2> xf, Vec<T, 1> q) -> Vec<T, 6> { Vec<T, 6> ret(6); ret << tf, x0.cwiseProduct(xf), xf, q.cwiseAbs2(); return ret; }; const smooth::feedback::OCP< Vec<double, 2>, Vec<double, 1>, decltype(theta), decltype(f), decltype(g), decltype(cr), decltype(ce)> ocp{ .theta = theta, .f = f, .g = g, .cr = cr, .crl = Vec<double, 4>::Constant(4, -1), .cru = Vec<double, 4>::Constant(4, 1), .ce = ce, .cel = Vec<double, 6>::Constant(6, -1), .ceu = Vec<double, 6>::Constant(6, 1), }; smooth::feedback::Mesh<3, 3> mesh; mesh.refine_ph(0, 4); mesh.refine_ph(0, 4); auto nlp = ocp_to_nlp(ocp, mesh); using nlp_t = std::decay_t<decltype(nlp)>; static_assert(smooth::feedback::HessianNLP<nlp_t>); srand(5); const Eigen::VectorXd x = Eigen::VectorXd::Random(nlp.n()); const Eigen::VectorXd lambda = Eigen::VectorXd::Random(nlp.m()); // Analytic derivatives const auto & df_dx = nlp.df_dx(x); const auto & d2f_dx2 = nlp.d2f_dx2(x); const auto & dg_dx = nlp.dg_dx(x); const auto & d2g_dx2 = nlp.d2g_dx2(x, lambda); // Numerical derivatives (of base function) const auto [fval, df_dx_num, d2f_dx2_num] = smooth::diff::dr<2>([&](const auto & xvar) { return nlp.f(xvar); }, smooth::wrt(x)); const auto [gval, dg_dx_num] = smooth::diff::dr<1>([&](const auto & xvar) { return nlp.g(xvar); }, smooth::wrt(x)); const auto g_l_fun = [&](Eigen::VectorXd xvar) -> double { return lambda.dot(nlp.g(xvar)); }; const auto [u1_, u2_, d2g_dx2_num] = smooth::diff::dr<2>(g_l_fun, smooth::wrt(x)); ASSERT_TRUE(Eigen::MatrixXd(df_dx).isApprox(df_dx_num, 1e-4)); ASSERT_TRUE(Eigen::MatrixXd(dg_dx).isApprox(dg_dx_num, 1e-4)); ASSERT_TRUE(Eigen::MatrixXd(Eigen::MatrixXd(d2f_dx2).selfadjointView<Eigen::Upper>()) .isApprox(d2f_dx2_num, 1e-3)); ASSERT_TRUE(Eigen::MatrixXd(Eigen::MatrixXd(d2g_dx2).selfadjointView<Eigen::Upper>()) .isApprox(d2g_dx2_num, 1e-3)); }
35.768595
96
0.635628
tgurriet
c95225d585036ca147288de29f0ad287be22dc49
4,463
cc
C++
src/tools/main_extract_state_from_snaps.cc
Zhang690683220/SHAW
867f0f02114cc339e657714cfaf17887d7e5caae
[ "BSD-3-Clause" ]
null
null
null
src/tools/main_extract_state_from_snaps.cc
Zhang690683220/SHAW
867f0f02114cc339e657714cfaf17887d7e5caae
[ "BSD-3-Clause" ]
null
null
null
src/tools/main_extract_state_from_snaps.cc
Zhang690683220/SHAW
867f0f02114cc339e657714cfaf17887d7e5caae
[ "BSD-3-Clause" ]
null
null
null
#include "CLI11.hpp" #include "Kokkos_Core.hpp" #include "../shared/constants.hpp" #include "../shared/meta/meta_kokkos.hpp" #include "../shared/io/matrix_write.hpp" #include "../shared/io/matrix_read.hpp" #include "../shared/io/vector_write.hpp" #include "utility" int main(int argc, char *argv[]) { CLI::App app{"Extract state(s) at target time steps from a snapshot matrix"}; using pair_t = std::pair<std::string, std::string>; pair_t snaps = {}; std::size_t fSize = 1; std::vector<std::size_t> timeSteps = {}; std::size_t samplingFreq = {}; std::string outputFormat = {}; std::string outFileAppend = {}; app.add_option("--snaps", snaps, "Pair: fullpath_to_snaps binary/ascii")->required(); app.add_option("--samplingfreq", samplingFreq, "Sampling freq used to save snapshot")->required(); app.add_option("--fsize", fSize, "Forcing size used to generate snapshots")->required(); app.add_option("--timesteps", timeSteps, "Target time steps to extract")->required(); app.add_option("--outformat", outputFormat, "Outputformat: binary/ascii")->required(); app.add_option("--outfileappend", outFileAppend, "String to append to output file"); CLI11_PARSE(app, argc, argv); std::cout << "snaps file = " << std::get<0>(snaps) << std::endl; std::cout << "snaps format = " << std::get<1>(snaps) << std::endl; std::cout << "Size of f = " << fSize << std::endl; if (timeSteps[0]==-1){ std::cout << "Target time steps = only last step"; } else{ std::cout << "Target time steps = "; for (auto & it : timeSteps) std::cout << it << " "; std::cout << std::endl; } std::cout << "Sampling freq = " << samplingFreq << std::endl; std::cout << "Output format = " << outputFormat << std::endl; //------------------------------------------------------------ const auto snapFile = std::get<0>(snaps); const bool snapBinary = std::get<1>(snaps)=="binary"; // on input, we have the time steps so we need to convert // from time steps to indices of the snapsshopt matrix std::vector<int> targetIndices = {}; for (auto it : timeSteps){ targetIndices.push_back( it / samplingFreq ); } //------------------------------------------------------------ Kokkos::initialize(); //argc, argv); { using sc_t = double; using kll = Kokkos::LayoutLeft; if (fSize == 1) { //////////////////////////// // this is rank-1 case //////////////////////////// // *** load states *** using snap_t = Kokkos::View<sc_t**, kll, Kokkos::HostSpace>; snap_t snaps("snaps", 1, 1); if (snapBinary){ readBinaryMatrixWithSize(snapFile, snaps); } else{ readAsciiMatrixWithSize(snapFile, snaps); } std::cout << "snap size: " << snaps.extent(0) << " " << snaps.extent(1) << std::endl; for (std::size_t i=0; i<timeSteps.size(); ++i){ const auto thisTimeStep = timeSteps[i]; auto stateFile = "state_timestep_" + std::to_string(thisTimeStep); if (outFileAppend.empty() == false) stateFile += "_" + outFileAppend; auto state = Kokkos::subview(snaps, Kokkos::ALL(), targetIndices[i]-1); writeToFile(stateFile, state, (outputFormat=="binary"), true); } } else if (fSize >= 2) { //////////////////////////// // this is rank-2 case //////////////////////////// // *** load states *** using snap_t = Kokkos::View<sc_t***, kll, Kokkos::HostSpace>; snap_t snaps("snaps", 1, 1, 1); if (snapBinary){ readBinaryMatrixWithSize(snapFile, snaps); } else{ throw std::runtime_error("Rank-2 snaps ascii not supported yet"); } std::cout << "snap size: " << snaps.extent(0) << " " << snaps.extent(1) << " " << snaps.extent(2) << std::endl; for (std::size_t fId=0; fId<snaps.extent(2); ++fId) { const std::string fString = "f_"+std::to_string(fId); for (std::size_t i=0; i<timeSteps.size(); ++i) { const auto thisTimeStep = timeSteps[i]; const auto tsString = "timestep_"+std::to_string(thisTimeStep); auto stateFile = "state_"+tsString+"_"+fString; if (outFileAppend.empty() == false) stateFile += "_" + outFileAppend; auto state = Kokkos::subview(snaps, Kokkos::ALL(), targetIndices[i]-1, fId); writeToFile(stateFile, state, (outputFormat=="binary"), true); } } } } Kokkos::finalize(); std::cout << "success" << std::endl; return 0; }
29.95302
85
0.578759
Zhang690683220
c954364d0ef7fca47eadeb48c2eef07b91d08b14
2,943
hpp
C++
saga/saga/adaptors/register_workitem.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
saga/saga/adaptors/register_workitem.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
saga/saga/adaptors/register_workitem.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
// Copyright (c) 2005-2010 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef SAGA_ADAPTORS_REGISTER_WORKITEM_HPP #define SAGA_ADAPTORS_REGISTER_WORKITEM_HPP #include <saga/saga/util.hpp> #include <saga/saga/session.hpp> #include <boost/date_time/posix_time/posix_time_duration.hpp> #include <boost/date_time/posix_time/ptime.hpp> #include <boost/system/error_code.hpp> // suppress warnings about dependent classes not being exported from the dll #if defined(BOOST_MSVC) #pragma warning(push) #pragma warning(disable: 4251 4231 4660) #endif namespace saga { namespace adaptors { /////////////////////////////////////////////////////////////////////////// // we use the boost::posix_time::ptime type for time representation typedef boost::posix_time::ptime time_type; // we use the boost::posix_time::time_duration type as the duration // representation typedef boost::posix_time::time_duration duration_type; /////////////////////////////////////////////////////////////////////////// // This is the prototype of any work item to be registered with this // interface. The function will be called as soon as the expiration time // specified while registering is reached. This function will be called at // most once, so re-occurring events need to be registered separately. typedef TR1::function<void(boost::system::error_code const&)> workitem_function; /////////////////////////////////////////////////////////////////////////// typedef unsigned int workitem_cookie_handle; /////////////////////////////////////////////////////////////////////////// // This is the main API for adaptors to register a work item to be executed // at a certain point in time or after a certain amount of time SAGA_EXPORT workitem_cookie_handle register_workitem( workitem_function f, time_type const& expire_at, saga::session const& s = saga::detail::get_the_session()); SAGA_EXPORT workitem_cookie_handle register_workitem( workitem_function f, duration_type const& expire_from_now, saga::session const& s = saga::detail::get_the_session()); /////////////////////////////////////////////////////////////////////////// // This is the API allowing to cancel the execution of a registered work // item. Note, this will call the registered function but will get passed // the error code 'booast::asio::error::operation_aborted'. If the // referenced work item has already expired but not called yet it cannot // be unregistered anymore and will be called with a success code. SAGA_EXPORT void unregister_workitem(workitem_cookie_handle, saga::session const& s = saga::detail::get_the_session()); }} #if defined(BOOST_MSVC) #pragma warning(pop) #endif #endif
41.450704
81
0.64526
saga-project
c95697aeea57894759a1f00fa1ca956222cb0415
12,238
cpp
C++
src/helpers.cpp
unbornchikken/nodeanything
dd380645fd61c92cf1874cb2c880a4d00430925a
[ "BSD-3-Clause" ]
115
2015-07-28T10:01:29.000Z
2022-03-05T23:02:11.000Z
src/helpers.cpp
unbornchikken/nodeanything
dd380645fd61c92cf1874cb2c880a4d00430925a
[ "BSD-3-Clause" ]
13
2015-08-03T09:01:37.000Z
2021-01-28T02:49:01.000Z
src/helpers.cpp
unbornchikken/nodeanything
dd380645fd61c92cf1874cb2c880a4d00430925a
[ "BSD-3-Clause" ]
12
2015-10-05T00:15:06.000Z
2019-07-23T09:27:12.000Z
/* Copyright (c) 2014-2015, ArrayFire Copyright (c) 2015 Gábor Mező aka unbornchikken ([email protected]) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the ArrayFire nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "ext.h" #include "helpers.h" #include "errors.h" #include "arraywrapper.h" #include "symbols.h" using namespace std; using namespace v8; using namespace node; pair<af::dtype, unsigned> GetDTypeInfo(unsigned udtype) { unsigned sizeOf; af::dtype dtype; switch (udtype) { case 0: dtype = f32; sizeOf = 32 / 8; break; case 1: dtype = c32; sizeOf = 32 / 8; break; case 2: dtype = f64; sizeOf = 64 / 8; break; case 3: dtype = c64; sizeOf = 64 / 8; break; case 4: dtype = b8; sizeOf = 8 / 8; break; case 5: dtype = s32; sizeOf = 32 / 8; break; case 6: dtype = u32; sizeOf = 32 / 8; break; case 7: dtype = u8; sizeOf = 8 / 8; break; case 8: dtype = s64; sizeOf = 64 / 8; break; case 9: dtype = u64; sizeOf = 64 / 8; break; default: ARRAYFIRE_THROW("DType is out of range."); } return move(make_pair(dtype, sizeOf)); } std::pair<af::dtype, unsigned> GetDTypeInfo(v8::Local<v8::Value> value) { if (value->IsNumber()) { return GetDTypeInfo(value->Uint32Value()); } ARRAYFIRE_THROW("Value is not a number."); } string ErrToString(af_err err) { switch (err) { case AF_ERR_INTERNAL: return "Internal error (AF_ERR_INTERNAL)."; break; case AF_ERR_NO_MEM: return "Not enough memory error (AF_ERR_NO_MEM)."; break; case AF_ERR_DRIVER: return "Driver error (AF_ERR_DRIVER)."; break; case AF_ERR_RUNTIME: return "Runtime error (AF_ERR_RUNTIME)."; break; case AF_ERR_INVALID_ARRAY: return "Invalid array error (AF_ERR_INVALID_ARRAY)."; break; case AF_ERR_ARG: return "Argument error (AF_ERR_ARG)."; break; case AF_ERR_SIZE: return "Size error (AF_ERR_SIZE)."; break; case AF_ERR_DIFF_TYPE: return "Diff type error (AF_ERR_DIFF_TYPE)."; break; case AF_ERR_NOT_SUPPORTED: return "Operation is not supported (AF_ERR_NOT_SUPPORTED)."; break; case AF_ERR_NOT_CONFIGURED: return "Not configured error (AF_ERR_NOT_CONFIGURED)."; break; default: return "Uknown ArrayFire error (AF_ERR_UNKNOWN)."; }; } v8::Local<v8::Object> WrapPointer(void* ptr) { Nan::EscapableHandleScope scope; return scope.Escape(Nan::NewBuffer((char*)ptr, 0, [](char*v1, void*v2) {}, nullptr).ToLocalChecked()); } af::dim4 ToDim4(v8::Local<v8::Object> obj) { Local<Array> dims; if (obj->IsArray()) { dims = obj.As<Array>(); } else { auto member = obj->Get(Nan::New(Symbols::Values)); if (member->IsArray()) { dims = member.As<Array>(); } else { ARRAYFIRE_THROW_ARG_IS_NOT_A_DIM4(); } } int dim0 = 1; int dim1 = 1; int dim2 = 1; int dim3 = 1; if (dims->Length() > 0) { dim0 = dims->Get(0)->Uint32Value(); } if (dims->Length() > 1) { dim1 = dims->Get(1)->Uint32Value(); } if (dims->Length() > 2) { dim2 = dims->Get(2)->Uint32Value(); } if (dims->Length() > 3) { dim3 = dims->Get(3)->Uint32Value(); } return move(af::dim4(dim0, dim1, dim2, dim3)); } af::dim4 ToDim4(v8::Local<v8::Value> value) { if (value->IsObject()) { return ToDim4(value.As<Object>()); } ARRAYFIRE_THROW_ARG_IS_NOT_AN_OBJ(); } af::seq ToSeq(v8::Local<v8::Object> obj) { auto begin = obj->Get(Nan::New(Symbols::Begin)); auto end = obj->Get(Nan::New(Symbols::End)); auto step = obj->Get(Nan::New(Symbols::Step)); auto isGFor = obj->Get(Nan::New(Symbols::IsGFor)); if (begin->IsNumber() && end->IsNumber()) { double stepValue = 1; if (step->IsNumber()) { stepValue = step->NumberValue(); } bool isGForValue = false; if (isGFor->IsBoolean()) { isGForValue = isGFor->BooleanValue(); } if (isGForValue) { return move(af::seq(af::seq(begin->NumberValue(), end->NumberValue(), stepValue), isGForValue)); } return move(af::seq(begin->NumberValue(), end->NumberValue(), stepValue)); } ARRAYFIRE_THROW_ARG_IS_NOT_A_SEQ(); } af::seq ToSeq(v8::Local<v8::Value> value) { if (value->IsObject()) { return ToSeq(value.As<Object>()); } ARRAYFIRE_THROW_ARG_IS_NOT_AN_OBJ(); } af::index ToIndex(v8::Local<v8::Value> value) { if (value->IsNull()) { return af::span; } if (value->IsNumber()) { return af::index(value->Int32Value()); } if (value->IsString()) { String::Utf8Value str(value); if (strcmp(*str, "span") == 0) { return af::span; } else if (strcmp(*str, "end") == 0) { return af::end; } } if (value->IsObject()) { auto pArray = ArrayWrapper::TryGetArray(value); if (pArray) { return af::index(*pArray); } return ToSeq(value.As<Object>()); } ARRAYFIRE_THROW_ARG_IS_NOT_AN_INDEX(); } af::af_cdouble ToDComplex(v8::Local<v8::Object> obj) { auto imag = obj->Get(Nan::New(Symbols::Imag)); auto real = obj->Get(Nan::New(Symbols::Real)); if (imag->IsNumber() && real->IsNumber()) { return { real->NumberValue(), imag->NumberValue() }; } ARRAYFIRE_THROW_ARG_IS_NOT_A_CPLX(); } af::af_cdouble ToDComplex(v8::Local<v8::Value> value) { if (value->IsObject()) { return ToDComplex(value.As<Object>()); } ARRAYFIRE_THROW_ARG_IS_NOT_AN_OBJ(); } af::af_cfloat ToFComplex(v8::Local<v8::Object> obj) { auto imag = obj->Get(Nan::New(Symbols::Imag)); auto real = obj->Get(Nan::New(Symbols::Real)); if (imag->IsNumber() && real->IsNumber()) { return { (float)real->NumberValue(), (float)imag->NumberValue() }; } ARRAYFIRE_THROW_ARG_IS_NOT_A_CPLX(); } af::af_cfloat ToFComplex(v8::Local<v8::Value> value) { if (value->IsObject()) { return ToFComplex(value.As<Object>()); } ARRAYFIRE_THROW_ARG_IS_NOT_AN_OBJ(); } v8::Local<v8::Object> ToV8Complex(const af::af_cdouble& value) { auto obj = Nan::New<Object>(); obj->Set(Nan::New(Symbols::Imag), Nan::New(value.imag)); obj->Set(Nan::New(Symbols::Real), Nan::New(value.real)); return obj; } v8::Local<v8::Object> ToV8Complex(const af::af_cfloat& value) { auto obj = Nan::New<Object>(); obj->Set(Nan::New(Symbols::Imag), Nan::New(value.imag)); obj->Set(Nan::New(Symbols::Real), Nan::New(value.real)); return obj; } std::pair<af::dim4, af::dtype> ParseDimAndTypeArgs(const Nan::FunctionCallbackInfo<v8::Value>& info, int assumedArgsLength, int argsFollowingDims, int dimsStartAt) { if (assumedArgsLength == -1) { assumedArgsLength = info.Length(); if (info[assumedArgsLength - 1]->IsFunction()) { // Async assumedArgsLength--; } } af::dim4 dims(1, 1, 1, 1); bool any = false; for (int idx = dimsStartAt; idx < ((assumedArgsLength - 1) - argsFollowingDims); idx++) { int dimIdx = idx - dimsStartAt; assert(dimIdx < 4); any = true; if (dimIdx == 0 && info[idx]->IsObject()) { dims = move(ToDim4(info[idx].As<Object>())); break; } dims[dimIdx] = info[idx]->Int32Value(); } if (any) { af::dtype type = GetDTypeInfo(info[assumedArgsLength - 1 + dimsStartAt]->Uint32Value()).first; return move(make_pair(move(dims), type)); } ARRAYFIRE_THROW("Cannot extract dimensions and dtype from argumens."); } Nan::Callback* GetCallback(const Nan::FunctionCallbackInfo<v8::Value>& info) { if (info.Length() && info[info.Length() - 1]->IsFunction()) { return new Nan::Callback(info[info.Length() - 1].As<Function>()); } ARRAYFIRE_THROW_CB_EXPECTED(); } v8::Local<v8::Object> ToV8Features(const af::features& feat) { auto obj = Nan::New<Object>(); obj->Set(Nan::New(Symbols::NumFeatures), Nan::New((unsigned)feat.getNumFeatures())); obj->Set(Nan::New(Symbols::X), ArrayWrapper::New(feat.getX())); obj->Set(Nan::New(Symbols::Y), ArrayWrapper::New(feat.getY())); obj->Set(Nan::New(Symbols::Score), ArrayWrapper::New(feat.getScore())); obj->Set(Nan::New(Symbols::Orientation), ArrayWrapper::New(feat.getOrientation())); obj->Set(Nan::New(Symbols::Size), ArrayWrapper::New(feat.getSize())); return obj; } RegionIndex ToRegionIndex(v8::Local<v8::Object> obj) { auto cn = obj->GetConstructorName(); if (cn->Equals(Nan::New(Symbols::RowClass))) { return make_tuple(Region::Row, obj->Get(Nan::New(Symbols::Index))->Uint32Value(), (unsigned)0); } else if (cn->Equals(Nan::New(Symbols::RowsClass))) { return make_tuple(Region::Rows, obj->Get(Nan::New(Symbols::FirstIndex))->Uint32Value(), obj->Get(Nan::New(Symbols::LastIndex))->Uint32Value()); } else if (cn->Equals(Nan::New(Symbols::ColClass))) { return make_tuple(Region::Col, obj->Get(Nan::New(Symbols::Index))->Uint32Value(), (unsigned)0); } else if (cn->Equals(Nan::New(Symbols::ColsClass))) { return make_tuple(Region::Cols, obj->Get(Nan::New(Symbols::FirstIndex))->Uint32Value(), obj->Get(Nan::New(Symbols::LastIndex))->Uint32Value()); } else if (cn->Equals(Nan::New(Symbols::SliceClass))) { return make_tuple(Region::Slice, obj->Get(Nan::New(Symbols::Index))->Uint32Value(), (unsigned)0); } else if (cn->Equals(Nan::New(Symbols::SlicesClass))) { return make_tuple(Region::Slices, obj->Get(Nan::New(Symbols::FirstIndex))->Uint32Value(), obj->Get(Nan::New(Symbols::LastIndex))->Uint32Value()); } return make_tuple(Region::None, (unsigned)0, (unsigned)0); } RegionIndex ToRegionIndex(v8::Local<v8::Value> value) { if (value->IsObject()) { return ToRegionIndex(value.As<Object>()); } return make_tuple(Region::None, (unsigned)0, (unsigned)0); }
29.347722
163
0.592826
unbornchikken
c95774b3dd49362ce5f9283027fc8ecbf94574df
60
hpp
C++
src/boost_mpl_aux__preprocessed_no_ctps_bind_fwd.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_mpl_aux__preprocessed_no_ctps_bind_fwd.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_mpl_aux__preprocessed_no_ctps_bind_fwd.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/mpl/aux_/preprocessed/no_ctps/bind_fwd.hpp>
30
59
0.816667
miathedev
c95c0fddb5f6dd773b7dac909993d18325ddf3d2
6,684
cpp
C++
tst/OpcUaStackCore/ServiceSet/Cancel_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
tst/OpcUaStackCore/ServiceSet/Cancel_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
tst/OpcUaStackCore/ServiceSet/Cancel_t.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
#include "unittest.h" #include "boost/asio.hpp" #include "OpcUaStackCore/BuildInTypes/BuildInTypes.h" #include "OpcUaStackCore/BuildInTypes/OpcUaIdentifier.h" #include "OpcUaStackCore/SecureChannel/MessageHeader.h" #include "OpcUaStackCore/SecureChannel/SequenceHeader.h" #include "OpcUaStackCore/ServiceSet/CancelRequest.h" #include "OpcUaStackCore/ServiceSet/CancelResponse.h" #include "OpcUaStackCore/Base/Utility.h" #include <streambuf> #include <iostream> using namespace OpcUaStackCore; BOOST_AUTO_TEST_SUITE(Cancel_) BOOST_AUTO_TEST_CASE(Cancel_) { std::cout << "Cancel_t" << std::endl; } BOOST_AUTO_TEST_CASE(Cancel_Request) { uint32_t pos; MessageHeader::SPtr messageHeaderSPtr; boost::posix_time::ptime ptime = boost::posix_time::from_iso_string("16010101T000000.000000000"); OpcUaGuid::SPtr opcUaGuidSPtr; CancelRequest::SPtr cancelRequestSPtr; SequenceHeader::SPtr sequenceHeaderSPtr; OpcUaNodeId typeId; // stream boost::asio::streambuf sb1; std::iostream ios1(&sb1); boost::asio::streambuf sb2; std::iostream ios2(&sb2); boost::asio::streambuf sb; std::iostream ios(&sb); // encode channel id OpcUaUInt32 channelId; channelId = 153451225; OpcUaNumber::opcUaBinaryEncode(ios1, channelId); // encode token id OpcUaInt32 tokenId; tokenId = 1; OpcUaNumber::opcUaBinaryEncode(ios1, tokenId); // encode sequence header sequenceHeaderSPtr = constructSPtr<SequenceHeader>(); sequenceHeaderSPtr->sequenceNumber(140); sequenceHeaderSPtr->requestId(90); sequenceHeaderSPtr->opcUaBinaryEncode(ios1); // encode message type id typeId.nodeId((OpcUaUInt32)OpcUaId_CancelRequest_Encoding_DefaultBinary); typeId.opcUaBinaryEncode(ios1); // encode CancelRequest cancelRequestSPtr = constructSPtr<CancelRequest>(); cancelRequestSPtr->requestHandle(4711); cancelRequestSPtr->opcUaBinaryEncode(ios1); // encode MessageHeader messageHeaderSPtr = constructSPtr<MessageHeader>(); messageHeaderSPtr->messageType(MessageType_Message); messageHeaderSPtr->messageSize(OpcUaStackCore::count(sb1)+8); messageHeaderSPtr->opcUaBinaryEncode(ios2); // stream ios << ios2.rdbuf() << ios1.rdbuf(); OpcUaStackCore::dumpHex(ios); std::stringstream ss; ss << "4d 53 47 46 20 00 00 00 d9 7a 25 09 01 00 00 00" << "8c 00 00 00 5a 00 00 00 01 00 df 01 67 12 00 00"; BOOST_REQUIRE(OpcUaStackCore::compare(ios, ss.str(), pos) == true); // decode MessageHeader messageHeaderSPtr = constructSPtr<MessageHeader>(); messageHeaderSPtr->opcUaBinaryDecode(ios); BOOST_REQUIRE(messageHeaderSPtr->messageType() == MessageType_Message); // decode channel id OpcUaNumber::opcUaBinaryDecode(ios, channelId); BOOST_REQUIRE(channelId == 153451225); // decode token id OpcUaNumber::opcUaBinaryDecode(ios, tokenId); BOOST_REQUIRE(tokenId == 1); // decode sequence header sequenceHeaderSPtr = constructSPtr<SequenceHeader>(); sequenceHeaderSPtr->opcUaBinaryDecode(ios); BOOST_REQUIRE(sequenceHeaderSPtr->sequenceNumber() == 140); BOOST_REQUIRE(sequenceHeaderSPtr->requestId() == 90); // decode message type id typeId.opcUaBinaryDecode(ios); BOOST_REQUIRE(typeId.namespaceIndex() == 0); BOOST_REQUIRE(typeId.nodeId<OpcUaUInt32>() == OpcUaId_CancelRequest_Encoding_DefaultBinary); // decode CancelRequest cancelRequestSPtr = constructSPtr<CancelRequest>(); cancelRequestSPtr->opcUaBinaryDecode(ios); } BOOST_AUTO_TEST_CASE(Cancel_Response) { uint32_t pos; MessageHeader::SPtr messageHeaderSPtr; boost::posix_time::ptime ptime = boost::posix_time::from_iso_string("16010101T000000.000000000"); OpcUaGuid::SPtr opcUaGuidSPtr; CancelResponse::SPtr cancelResponseSPtr; SequenceHeader::SPtr sequenceHeaderSPtr; OpcUaNodeId typeId; // stream boost::asio::streambuf sb1; std::iostream ios1(&sb1); boost::asio::streambuf sb2; std::iostream ios2(&sb2); boost::asio::streambuf sb; std::iostream ios(&sb); // encode channel id OpcUaUInt32 channelId; channelId = 153451225; OpcUaNumber::opcUaBinaryEncode(ios1, channelId); // encode token id OpcUaInt32 tokenId; tokenId = 1; OpcUaNumber::opcUaBinaryEncode(ios1, tokenId); // encode sequence header sequenceHeaderSPtr = constructSPtr<SequenceHeader>(); sequenceHeaderSPtr->sequenceNumber(140); sequenceHeaderSPtr->requestId(90); sequenceHeaderSPtr->opcUaBinaryEncode(ios1); // encode message type id typeId.nodeId(OpcUaId_CancelResponse_Encoding_DefaultBinary); typeId.opcUaBinaryEncode(ios1); // encode CancelResponse cancelResponseSPtr = constructSPtr<CancelResponse>(); cancelResponseSPtr->responseHeader()->time(ptime); cancelResponseSPtr->responseHeader()->requestHandle(1); cancelResponseSPtr->responseHeader()->serviceResult(Success); cancelResponseSPtr->cancelCount(1); cancelResponseSPtr->opcUaBinaryEncode(ios1); // encode MessageHeader messageHeaderSPtr = constructSPtr<MessageHeader>(); messageHeaderSPtr->messageType(MessageType_Message); messageHeaderSPtr->messageSize(OpcUaStackCore::count(sb1)+8); messageHeaderSPtr->opcUaBinaryEncode(ios2); // stream ios << ios2.rdbuf() << ios1.rdbuf(); OpcUaStackCore::dumpHex(ios); std::stringstream ss; ss << "4d 53 47 46 38 00 00 00 d9 7a 25 09 01 00 00 00" << "8c 00 00 00 5a 00 00 00 01 00 e2 01 00 00 00 00" << "00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00" << "00 00 00 00 01 00 00 00"; BOOST_REQUIRE(OpcUaStackCore::compare(ios, ss.str(), pos) == true); // decode MessageHeader messageHeaderSPtr = constructSPtr<MessageHeader>(); messageHeaderSPtr->opcUaBinaryDecode(ios); BOOST_REQUIRE(messageHeaderSPtr->messageType() == MessageType_Message); // decode channel id OpcUaNumber::opcUaBinaryDecode(ios, channelId); BOOST_REQUIRE(channelId == 153451225); // decode token id OpcUaNumber::opcUaBinaryDecode(ios, tokenId); BOOST_REQUIRE(tokenId == 1); // decode sequence header sequenceHeaderSPtr = constructSPtr<SequenceHeader>(); sequenceHeaderSPtr->opcUaBinaryDecode(ios); BOOST_REQUIRE(sequenceHeaderSPtr->sequenceNumber() == 140); BOOST_REQUIRE(sequenceHeaderSPtr->requestId() == 90); // decode message type id typeId.opcUaBinaryDecode(ios); BOOST_REQUIRE(typeId.namespaceIndex() == 0); BOOST_REQUIRE(typeId.nodeId<OpcUaUInt32>() == OpcUaId_CancelResponse_Encoding_DefaultBinary); //decode CancelResponse cancelResponseSPtr = constructSPtr<CancelResponse>(); cancelResponseSPtr->opcUaBinaryDecode(ios); BOOST_REQUIRE(cancelResponseSPtr->responseHeader()->time().dateTime() == ptime); BOOST_REQUIRE(cancelResponseSPtr->responseHeader()->requestHandle() == 1); BOOST_REQUIRE(cancelResponseSPtr->responseHeader()->serviceResult() == Success); BOOST_REQUIRE(cancelResponseSPtr->cancelCount() == 1); } BOOST_AUTO_TEST_SUITE_END()
31.677725
98
0.774686
gianricardo
e920dccfe5066f042bc8f7a60f02b5f3528be619
785
cpp
C++
solved/o-q/pole-position/pole.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/o-q/pole-position/pole.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/o-q/pole-position/pole.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <cstdio> #include <cstring> #define MAXN 1000 #define Zero(v) memset((v), 0, sizeof(v)) int N; int grid[MAXN]; int main() { while (true) { scanf("%d", &N); if (N == 0) break; Zero(grid); bool valid = true; for (int i = 0; i < N; ++i) { int C, P; scanf("%d%d", &C, &P); int idx = i + P; if (idx < 0 || idx >= N || grid[idx] != 0) { valid = false; continue; } grid[idx] = C; } if (valid) { printf("%d", grid[0]); for (int i = 1; i < N; ++i) printf(" %d", grid[i]); putchar('\n'); } else puts("-1"); } return 0; }
16.354167
56
0.35414
abuasifkhan
e9267eeda8e83643522c8d052654483f35dc5939
1,392
hpp
C++
include/MyElf/Sections/SectionHeader.hpp
korreborg/MyElf
f7514cb7ecf923702cc34b344d1a0a51419588ee
[ "MIT" ]
1
2022-03-29T21:10:43.000Z
2022-03-29T21:10:43.000Z
include/MyElf/Sections/SectionHeader.hpp
korreborg/MyElf
f7514cb7ecf923702cc34b344d1a0a51419588ee
[ "MIT" ]
6
2022-03-29T20:21:08.000Z
2022-03-29T20:56:09.000Z
include/MyElf/Sections/SectionHeader.hpp
korreborg/MyElf
f7514cb7ecf923702cc34b344d1a0a51419588ee
[ "MIT" ]
null
null
null
#pragma once #include "../Common.hpp" //special section indexes #define SHN_UNDEF 0x0 #define SHN_LORESERVE 0xFF00 #define SHN_LOPROC 0xFF00 #define SHN_HIPROC 0xFF1F #define SHN_ABS 0xFFF1 #define SHN_COMMON 0xFFF2 #define SHN_HIRESERVE 0xFFFF //Section types #define SHT_NULL 0 #define SHT_PROGBITS 1 #define SHT_SYMTAB 2 #define SHT_STRTAB 3 #define SHT_RELA 4 #define SHT_HASH 5 #define SHT_DYNAMIC 6 #define SHT_NOTE 7 #define SHT_NOBITS 8 #define SHT_REL 9 #define SHT_SHLIB 10 #define SHT_DYNSYM 11 #define SHT_LOPROC 0x70000000 #define SHT_HIPROC 0x7FFFFFFF #define SHT_LOUSER 0x80000000 #define SHT_HIUSER 0xFFFFFFFF struct SectionHeader { U32 NameOffset; U32 Type; U64 Flags; U64 Address; U64 Offset; U64 Size; U32 Link; U32 Info; U64 AddrAlign; U64 EntSize; void Read(std::istream& stream, bool elf64) { MYELF_READ(stream, this->NameOffset); MYELF_READ(stream, this->Type); MYELF_READ_DIFF(stream, this->Flags, U32, elf64); MYELF_READ_DIFF(stream, this->Address, U32, elf64); MYELF_READ_DIFF(stream, this->Offset, U32, elf64); MYELF_READ_DIFF(stream, this->Size, U32, elf64); MYELF_READ(stream, this->Link); MYELF_READ(stream, this->Info); MYELF_READ_DIFF(stream, this->AddrAlign, U32, elf64); MYELF_READ_DIFF(stream, this->EntSize, U32, elf64); } };
22.095238
57
0.713362
korreborg
e929255ab8732af5534eb27118457cf3a3a44b14
2,969
hpp
C++
higan/processor/r65816/registers.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
3
2016-03-23T01:17:36.000Z
2019-10-25T06:41:09.000Z
higan/processor/r65816/registers.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
higan/processor/r65816/registers.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
null
null
null
struct flag_t { bool n{0}; bool v{0}; bool m{0}; bool x{0}; bool d{0}; bool i{0}; bool z{0}; bool c{0}; inline operator unsigned() const { return (n << 7) + (v << 6) + (m << 5) + (x << 4) + (d << 3) + (i << 2) + (z << 1) + (c << 0); } inline auto operator=(uint8 data) -> unsigned { n = data & 0x80; v = data & 0x40; m = data & 0x20; x = data & 0x10; d = data & 0x08; i = data & 0x04; z = data & 0x02; c = data & 0x01; return data; } }; struct reg16_t { union { uint16 w = 0; struct { uint8 order_lsb2(l, h); }; }; inline operator unsigned() const { return w; } inline auto operator = (unsigned i) -> unsigned { return w = i; } inline auto operator |= (unsigned i) -> unsigned { return w |= i; } inline auto operator ^= (unsigned i) -> unsigned { return w ^= i; } inline auto operator &= (unsigned i) -> unsigned { return w &= i; } inline auto operator <<= (unsigned i) -> unsigned { return w <<= i; } inline auto operator >>= (unsigned i) -> unsigned { return w >>= i; } inline auto operator += (unsigned i) -> unsigned { return w += i; } inline auto operator -= (unsigned i) -> unsigned { return w -= i; } inline auto operator *= (unsigned i) -> unsigned { return w *= i; } inline auto operator /= (unsigned i) -> unsigned { return w /= i; } inline auto operator %= (unsigned i) -> unsigned { return w %= i; } }; struct reg24_t { union { uint32 d = 0; struct { uint16 order_lsb2(w, wh); }; struct { uint8 order_lsb4(l, h, b, bh); }; }; inline operator unsigned() const { return d; } inline auto operator = (unsigned i) -> unsigned { return d = uclip<24>(i); } inline auto operator |= (unsigned i) -> unsigned { return d = uclip<24>(d | i); } inline auto operator ^= (unsigned i) -> unsigned { return d = uclip<24>(d ^ i); } inline auto operator &= (unsigned i) -> unsigned { return d = uclip<24>(d & i); } inline auto operator <<= (unsigned i) -> unsigned { return d = uclip<24>(d << i); } inline auto operator >>= (unsigned i) -> unsigned { return d = uclip<24>(d >> i); } inline auto operator += (unsigned i) -> unsigned { return d = uclip<24>(d + i); } inline auto operator -= (unsigned i) -> unsigned { return d = uclip<24>(d - i); } inline auto operator *= (unsigned i) -> unsigned { return d = uclip<24>(d * i); } inline auto operator /= (unsigned i) -> unsigned { return d = uclip<24>(d / i); } inline auto operator %= (unsigned i) -> unsigned { return d = uclip<24>(d % i); } }; struct regs_t { reg24_t pc; reg16_t a; reg16_t x; reg16_t y; reg16_t z; //pseudo-register (zero register) reg16_t s; reg16_t d; flag_t p; uint8 db{0}; bool e{0}; bool irq{0}; //IRQ pin (0 = low, 1 = trigger) bool wai{0}; //raised during wai, cleared after interrupt triggered uint8 mdr{0}; //memory data register uint16 vector{0}; //interrupt vector address };
36.654321
85
0.575951
ameer-bauer
e93265f9f07efe2d169dd68bf147138c45361cdb
1,621
cpp
C++
src/account/GetApplicationSubscriptionHistoryResponse.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
5
2019-06-30T06:29:46.000Z
2021-12-17T12:41:23.000Z
src/account/GetApplicationSubscriptionHistoryResponse.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
2
2018-01-09T17:14:45.000Z
2020-03-23T00:16:50.000Z
src/account/GetApplicationSubscriptionHistoryResponse.cpp
Sherlock92/greentop
aa278d08babe02326b3ab85a6eafb858d780dec5
[ "MIT" ]
7
2015-09-13T18:40:58.000Z
2020-01-24T10:57:56.000Z
/** * Copyright 2017 Colin Doig. Distributed under the MIT license. */ #include "greentop/account/GetApplicationSubscriptionHistoryResponse.h" namespace greentop { namespace account { GetApplicationSubscriptionHistoryResponse::GetApplicationSubscriptionHistoryResponse() { } GetApplicationSubscriptionHistoryResponse::GetApplicationSubscriptionHistoryResponse(const std::vector<SubscriptionHistory>& subscriptionHistorys) : subscriptionHistorys(subscriptionHistorys) { } void GetApplicationSubscriptionHistoryResponse::fromJson(const Json::Value& json) { if (validateJson(json)) { for (unsigned i = 0; i < json.size(); ++i) { SubscriptionHistory subscriptionHistory; subscriptionHistory.fromJson(json[i]); subscriptionHistorys.push_back(subscriptionHistory); } } } Json::Value GetApplicationSubscriptionHistoryResponse::toJson() const { Json::Value json(Json::arrayValue); if (subscriptionHistorys.size() > 0) { for (unsigned i = 0; i < subscriptionHistorys.size(); ++i) { json.append(subscriptionHistorys[i].toJson()); } } return json; } bool GetApplicationSubscriptionHistoryResponse::isValid() const { return subscriptionHistorys.size() > 0; } const std::vector<SubscriptionHistory>& GetApplicationSubscriptionHistoryResponse::getSubscriptionHistorys() const { return subscriptionHistorys; } void GetApplicationSubscriptionHistoryResponse::setSubscriptionHistorys(const std::vector<SubscriptionHistory>& subscriptionHistorys) { this->subscriptionHistorys = subscriptionHistorys; } } }
31.784314
148
0.750771
Sherlock92
e932a041f73bb9bf4b667c23bde3a38241c66cf2
28,526
cc
C++
test/sema/test_analyzer.cc
ligangwang/m
8a470441305689f4107c1c8b54276ef8910609c5
[ "MIT" ]
9
2020-01-25T05:27:46.000Z
2022-01-24T02:40:50.000Z
test/sema/test_analyzer.cc
ligangwang/m
8a470441305689f4107c1c8b54276ef8910609c5
[ "MIT" ]
1
2020-06-01T00:06:12.000Z
2020-06-01T00:06:12.000Z
test/sema/test_analyzer.cc
ligangwang/m
8a470441305689f4107c1c8b54276ef8910609c5
[ "MIT" ]
1
2020-05-08T05:19:13.000Z
2020-05-08T05:19:13.000Z
/* * Copyright (C) 2020 Ligang Wang <[email protected]> * * Unit tests for type inference and semantic analsysis */ #include "codegen/codegen.h" #include "codegen/env.h" #include "parser/m_parser.h" #include "sema/analyzer.h" #include "sema/sema_context.h" #include "tutil.h" #include "gtest/gtest.h" #include <stdio.h> TEST(testAnalyzer, testIntVariable) { char test_code[] = "x = 11"; env *env = env_new(false); ast_node *block = parse_string(env->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("x", string_get(node->var->var_name)); ASSERT_EQ(VAR_NODE, node->node_type); ASSERT_EQ(TYPE_INT, node->var->init_value->type->type); ASSERT_EQ(KIND_OPER, node->type->kind); string type_str = to_string(node->type); ASSERT_STREQ("int", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testDoubleVariable) { char test_code[] = "x = 11.0"; env *env = env_new(false); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("x", string_get(node->var->var_name)); ASSERT_EQ(VAR_NODE, node->node_type); ASSERT_EQ(TYPE_DOUBLE, node->var->init_value->type->type); string type_str = to_string(node->type); ASSERT_STREQ("double", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testBoolVariable) { char test_code[] = "x = true"; env *env = env_new(false); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("x", string_get(node->var->var_name)); ASSERT_EQ(VAR_NODE, node->node_type); ASSERT_EQ(TYPE_BOOL, node->var->init_value->type->type); string type_str = to_string(node->type); ASSERT_STREQ("bool", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testCharVariable) { char test_code[] = "x = 'c'"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("x", string_get(node->var->var_name)); ASSERT_EQ(VAR_NODE, node->node_type); ASSERT_EQ(TYPE_CHAR, node->var->init_value->type->type); string type_str = to_string(node->type); ASSERT_STREQ("char", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testStringVariable) { char test_code[] = "x = \"hello world!\""; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("x", string_get(node->var->var_name)); ASSERT_EQ(VAR_NODE, node->node_type); ASSERT_EQ(TYPE_STRING, node->var->init_value->type->type); string type_str = to_string(node->type); ASSERT_STREQ("string", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testCallNode) { char test_code[] = "printf \"hello\""; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_EQ(CALL_NODE, node->node_type); ASSERT_EQ(TYPE_INT, node->type->type); string type_str = to_string(node->type); ASSERT_STREQ("int", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testDoubleIntLiteralError) { char test_code[] = "x = 11.0 + 10"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("x", string_get(node->var->var_name)); ASSERT_EQ(VAR_NODE, node->node_type); ASSERT_EQ(0, node->type); env_free(env); } TEST(testAnalyzer, testGreaterThan) { char test_code[] = R"( 11>10 )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); auto node = *(ast_node **)array_front(&block->block->nodes); emit_code(env, (ast_node *)block); ASSERT_EQ(BINARY_NODE, node->node_type); string type_str = to_string(node->type); ASSERT_STREQ("bool", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testIdentityFunc) { reset_id_name("a"); char test_code[] = "id x = x"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("id", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(2, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("a -> a", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testIntIntFunc) { char test_code[] = "f x = x + 10"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("f", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(2, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("int -> int", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testDoubleDoubleFunc) { char test_code[] = "f x = x + 10.0"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("f", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(2, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("double -> double", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testBoolFunc) { char test_code[] = "f x = !x"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("f", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(2, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("bool -> bool", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testMultiParamFunc) { char test_code[] = "avg x y = (x + y) / 2.0"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("avg", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(3, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("double * double -> double", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testRecursiveFunc) { char test_code[] = R"( factorial n = if n < 2 then n else n * factorial (n-1) )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("factorial", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(2, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("int -> int", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testForLoopFunc) { char test_code[] = R"( # using for loop loopprint n = for i in 0..n printf "%d" i )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("loopprint", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(2, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("int -> ()", string_get(&type_str)); ast_node *forn = *(ast_node **)array_front(&node->func->body->block->nodes); ASSERT_EQ(TYPE_INT, get_type(forn->forloop->step->type)); ASSERT_EQ(TYPE_INT, get_type(forn->forloop->start->type)); ASSERT_EQ(TYPE_BOOL, get_type(forn->forloop->end->type)); ASSERT_EQ(TYPE_INT, get_type(forn->forloop->body->type)); env_free(env); } TEST(testAnalyzer, testLocalVariableFunc) { char test_code[] = R"( # using for loop distance x1 y1 x2 y2 = xx = (x1-x2) * (x1-x2) yy = (y1-y2) * (y1-y2) sqrt (xx + yy) )"; reset_id_name("a"); env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("distance", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(5, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("double * double * double * double -> double", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testLocalStringFunc) { char test_code[] = R"( to_string () = x = "hello" y = x y )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("to_string", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(1, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("() -> string", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testVariadicFunc) { char test_code[] = R"( var_func ... = 0 )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("var_func", string_get(node->func->func_type->ft->name)); ASSERT_EQ(true, node->func->func_type->ft->is_variadic); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(2, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("... -> int", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testPrintfFunc) { char test_code[] = R"( printf "%d" 100 )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_EQ(CALL_NODE, node->node_type); string type_str = to_string(node->type); ASSERT_STREQ("int", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testStructLikeType) { char test_code[] = R"( type Point2D = x:double y:double )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_EQ(TYPE_NODE, node->node_type); string type_str = to_string(node->type); ASSERT_EQ(TYPE_EXT, node->type->type); ASSERT_STREQ("Point2D", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testFunctionTypeAnnotation) { char test_code[] = R"( print x:int = printf "%d" x )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("print", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(2, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("int -> int", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testFunctionTypeAnnotationWithParentheses) { char test_code[] = R"( prt (x:int) = printf "%d" x )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("prt", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(2, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("int -> int", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testFunctionTypeAnnotationWithReturnType) { char test_code[] = R"( prt (x:int):int = printf "%d" x )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); ASSERT_EQ(1, array_size(&block->block->nodes)); ASSERT_STREQ("prt", string_get(node->func->func_type->ft->name)); ASSERT_EQ(FUNCTION_NODE, node->node_type); auto var = (type_oper *)node->type; ASSERT_EQ(TYPE_FUNCTION, var->base.type); ASSERT_EQ(2, array_size(&var->args)); string type_str = to_string(node->type); ASSERT_STREQ("int -> int", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testVariableWithScope) { char test_code[] = R"( x = 10 getx()= x = 1.3 x getx() x )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); ASSERT_EQ(4, array_size(&block->block->nodes)); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); string type_str = to_string(node->type); ASSERT_STREQ("int", string_get(&type_str)); /*fun definition*/ node = *(ast_node **)array_get(&block->block->nodes, 1); type_str = to_string(node->type); ASSERT_STREQ("() -> double", string_get(&type_str)); node = *(ast_node **)array_get(&block->block->nodes, 2); ASSERT_EQ(CALL_NODE, node->node_type); type_str = to_string(node->type); ASSERT_STREQ("double", string_get(&type_str)); node = *(ast_node **)array_get(&block->block->nodes, 3); ASSERT_EQ(IDENT_NODE, node->node_type); type_str = to_string(node->type); ASSERT_STREQ("int", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testRedefinitionInTheSameScropeIsNotAllowed) { char test_code[] = R"( x = 10.0 x = 10 )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); ASSERT_EQ(2, array_size(&block->block->nodes)); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); string type_str = to_string(node->type); ASSERT_STREQ("double", string_get(&type_str)); /*fun definition*/ node = *(ast_node **)array_get(&block->block->nodes, 1); type_str = to_string(node->type); ASSERT_STREQ("type mismatch", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testStructTypeVariables) { char test_code[] = R"( type Point2D = x:double y:double xy:Point2D = 0.0 0.0 xy.x )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); ASSERT_EQ(3, array_size(&block->block->nodes)); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); string type_str = to_string(node->type); ASSERT_STREQ("Point2D", string_get(&type_str)); node = *(ast_node **)array_get(&block->block->nodes, 1); type_str = to_string(node->type); ASSERT_STREQ("Point2D", string_get(&type_str)); node = *(ast_node **)array_get(&block->block->nodes, 2); ASSERT_EQ(IDENT_NODE, node->node_type); struct ast_node *id_node = node; ASSERT_STREQ("xy.x", string_get(id_node->ident->name)); type_str = to_string(node->type); ASSERT_STREQ("double", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testStructTypeVariablesNewForm) { char test_code[] = R"( type Point2D = x:double y:double xy = Point2D 10.0 20.0 xy.x )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); ASSERT_EQ(3, array_size(&block->block->nodes)); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); string type_str = to_string(node->type); ASSERT_STREQ("Point2D", string_get(&type_str)); node = *(ast_node **)array_get(&block->block->nodes, 1); type_str = to_string(node->type); ASSERT_STREQ("Point2D", string_get(&type_str)); node = *(ast_node **)array_get(&block->block->nodes, 2); ASSERT_EQ(IDENT_NODE, node->node_type); struct ast_node *id_node = node; ASSERT_STREQ("xy.x", string_get(id_node->ident->name)); type_str = to_string(node->type); ASSERT_STREQ("double", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testStructTypeLocalVariables) { char test_code[] = R"( type Point2D = x:double y:double getx()= xy:Point2D = 10.0 0.0 xy.x getx() )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); ASSERT_EQ(3, array_size(&block->block->nodes)); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); string type_str = to_string(node->type); ASSERT_STREQ("Point2D", string_get(&type_str)); /*fun definition*/ node = *(ast_node **)array_get(&block->block->nodes, 1); type_str = to_string(node->type); ASSERT_STREQ("() -> double", string_get(&type_str)); node = *(ast_node **)array_get(&block->block->nodes, 2); ASSERT_EQ(CALL_NODE, node->node_type); type_str = to_string(node->type); ASSERT_STREQ("double", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testStructTypeLocalVariablesNewForm) { char test_code[] = R"( type Point2D = x:double y:double getx()= xy = Point2D 10.0 0.0 xy.x getx() )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); ASSERT_EQ(3, array_size(&block->block->nodes)); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); string type_str = to_string(node->type); ASSERT_STREQ("Point2D", string_get(&type_str)); /*fun definition*/ node = *(ast_node **)array_get(&block->block->nodes, 1); type_str = to_string(node->type); ASSERT_STREQ("() -> double", string_get(&type_str)); node = *(ast_node **)array_get(&block->block->nodes, 2); ASSERT_EQ(CALL_NODE, node->node_type); type_str = to_string(node->type); ASSERT_STREQ("double", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testStructTypeReturn) { char test_code[] = R"( type Point2D = x:double y:double getx()= xy:Point2D = 10.0 0.0 xy z = getx() )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); ASSERT_EQ(3, array_size(&block->block->nodes)); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); string type_str = to_string(node->type); ASSERT_STREQ("Point2D", string_get(&type_str)); /*fun definition*/ node = *(ast_node **)array_get(&block->block->nodes, 1); type_str = to_string(node->type); ASSERT_STREQ("() -> Point2D", string_get(&type_str)); /*variable node*/ node = *(ast_node **)array_get(&block->block->nodes, 2); ASSERT_EQ(VAR_NODE, node->node_type); struct ast_node *var = node; /*initial value is a call expression*/ ASSERT_EQ(CALL_NODE, var->var->init_value->node_type); type_str = to_string(var->var->init_value->type); ASSERT_STREQ("Point2D", string_get(&type_str)); type_str = to_string(var->type); ASSERT_STREQ("Point2D", string_get(&type_str)); /*verify variable xy in inner function is out of scope*/ symbol xy = to_symbol("xy"); ASSERT_EQ(false, has_symbol(&env->cg->sema_context->decl_2_typexps, xy)); env_free(env); } TEST(testAnalyzer, testStructTypeReturnNewForm) { char test_code[] = R"( type Point2D = x:double y:double getx()= xy = Point2D 10.0 0.0 xy z = getx() )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); ASSERT_EQ(3, array_size(&block->block->nodes)); emit_code(env, (ast_node *)block); auto node = *(ast_node **)array_front(&block->block->nodes); string type_str = to_string(node->type); ASSERT_STREQ("Point2D", string_get(&type_str)); /*fun definition*/ node = *(ast_node **)array_get(&block->block->nodes, 1); type_str = to_string(node->type); ASSERT_STREQ("() -> Point2D", string_get(&type_str)); /*variable node*/ node = *(ast_node **)array_get(&block->block->nodes, 2); ASSERT_EQ(VAR_NODE, node->node_type); struct ast_node *var = node; /*initial value is a call expression*/ ASSERT_EQ(CALL_NODE, var->var->init_value->node_type); type_str = to_string(var->var->init_value->type); ASSERT_STREQ("Point2D", string_get(&type_str)); type_str = to_string(var->type); ASSERT_STREQ("Point2D", string_get(&type_str)); /*verify variable xy in inner function is out of scope*/ symbol xy = to_symbol("xy"); ASSERT_EQ(false, has_symbol(&env->cg->sema_context->decl_2_typexps, xy)); env_free(env); } TEST(testAnalyzer, testStructTypeReturnNoNamed) { char test_code[] = R"( type Point2D = x:double y:double get_point() = Point2D 10.0 0.0 z() = get_point() )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); ASSERT_EQ(3, array_size(&block->block->nodes)); emit_code(env, (ast_node *)block); //1. type definition auto node = *(ast_node **)array_front(&block->block->nodes); string type_str = to_string(node->type); ASSERT_STREQ("Point2D", string_get(&type_str)); //2. function definition node = *(ast_node **)array_get(&block->block->nodes, 1); type_str = to_string(node->type); ASSERT_STREQ("() -> Point2D", string_get(&type_str)); //3. function definition again node = *(ast_node **)array_get(&block->block->nodes, 2); ASSERT_EQ(FUNCTION_NODE, node->node_type); type_str = to_string(node->type); ASSERT_STREQ("() -> Point2D", string_get(&type_str)); env_free(env); } TEST(testAnalyzer, testReturnValueFlag) { char test_code[] = R"( getx()= x = 10 y = x + 1 y )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); ASSERT_EQ(1, array_size(&block->block->nodes)); emit_code(env, (ast_node *)block); /*validate fun definition*/ auto node = *(ast_node **)array_get(&block->block->nodes, 0); auto type_str = to_string(node->type); ASSERT_STREQ("() -> int", string_get(&type_str)); /*validate inside functions*/ auto fun = (ast_node *)node; auto var_x = *(ast_node **)array_get(&fun->func->body->block->nodes, 0); auto var_y = *(ast_node **)array_get(&fun->func->body->block->nodes, 1); ASSERT_EQ(false, var_x->is_ret); ASSERT_EQ(true, var_y->is_ret); env_free(env); } TEST(testAnalyzer, testReturnExpression) { char test_code[] = R"( getx()= x = 10 x + 1 )"; env *env = env_new(false); create_ir_module(env->cg, "test"); ast_node *block = parse_string(env->cg->sema_context->parser, "test", test_code); ASSERT_EQ(1, array_size(&block->block->nodes)); emit_code(env, (ast_node *)block); /*validate fun definition*/ auto node = *(ast_node **)array_get(&block->block->nodes, 0); auto type_str = to_string(node->type); ASSERT_STREQ("() -> int", string_get(&type_str)); /*validate inside functions*/ auto fun = (ast_node *)node; auto var_x = *(ast_node **)array_get(&fun->func->body->block->nodes, 0); auto exp = *(ast_node **)array_get(&fun->func->body->block->nodes, 1); ASSERT_EQ(false, var_x->is_ret); ASSERT_EQ(BINARY_NODE, exp->node_type); env_free(env); }
36.154626
87
0.660836
ligangwang
e946a0e063efa142ad15381004e7d41e78a2bee0
1,111
cpp
C++
src/Engine/map/MapAltitude.cpp
turesnake/tprPixelGames
6b5471a072a1a8b423834ab04ff03e64df215d5e
[ "BSD-3-Clause" ]
591
2020-03-12T05:10:33.000Z
2022-03-30T13:41:59.000Z
src/Engine/map/MapAltitude.cpp
turesnake/tprPixelGames
6b5471a072a1a8b423834ab04ff03e64df215d5e
[ "BSD-3-Clause" ]
4
2020-04-06T01:55:06.000Z
2020-05-02T04:28:04.000Z
src/Engine/map/MapAltitude.cpp
turesnake/tprPixelGames
6b5471a072a1a8b423834ab04ff03e64df215d5e
[ "BSD-3-Clause" ]
112
2020-04-05T23:55:36.000Z
2022-03-17T11:58:02.000Z
/* * ====================== MapAltitude.cpp ======================= * -- tpr -- * CREATE -- 2019.03.11 * MODIFY -- * ---------------------------------------------------------- */ #include "pch.h" #include "MapAltitude.h" void MapAltitude::init( double altiVal_from_gpgpu_ ){ tprAssert( (altiVal_from_gpgpu_>=-100.0) && (altiVal_from_gpgpu_<=100.0) ); this->val = static_cast<int>(floor(altiVal_from_gpgpu_)); //------------------// // lvl //------------------// int tmpLvl {}; double waterStep { 7.0 }; //- 水下梯度,tmp... double landStep { 14.0 }; //- 陆地梯度,tmp... if( this->val < 0 ){ //- under water tmpLvl = static_cast<int>( floor(altiVal_from_gpgpu_/waterStep) ); if( tmpLvl < -5 ){ //- 抹平 水域底部 tmpLvl = -5; } }else{ //- land tmpLvl = static_cast<int>( floor(altiVal_from_gpgpu_/landStep) ); if( tmpLvl > 2 ){ //- 抹平 陆地高区 tmpLvl = 2; } } this->lvl = tmpLvl; }
29.236842
79
0.414941
turesnake
e94c305c2b3cd0447ccdfb89a80fa1faf09529a2
10,273
cpp
C++
MandarinInstrInfo.cpp
WheretIB/llvm-mandarin
073fd12ba433e531a05a211439bb23405196811a
[ "MIT" ]
null
null
null
MandarinInstrInfo.cpp
WheretIB/llvm-mandarin
073fd12ba433e531a05a211439bb23405196811a
[ "MIT" ]
null
null
null
MandarinInstrInfo.cpp
WheretIB/llvm-mandarin
073fd12ba433e531a05a211439bb23405196811a
[ "MIT" ]
null
null
null
//===-- MandarinInstrInfo.cpp - Mandarin Instruction Information ----------------===// // // Vyacheslav Egorov // // This file is distributed under the MIT License // //===----------------------------------------------------------------------===// // // This file contains the Mandarin implementation of the TargetInstrInfo class. // //===----------------------------------------------------------------------===// #include "MandarinInstrInfo.h" #include "Mandarin.h" #include "MandarinMachineFunctionInfo.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineMemOperand.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/TargetRegistry.h" #define GET_INSTRINFO_CTOR_DTOR #include "MandarinGenInstrInfo.inc" using namespace llvm; // Pin the vtable to this file. void MandarinInstrInfo::anchor() {} MandarinInstrInfo::MandarinInstrInfo(MandarinSubtarget &ST) : MandarinGenInstrInfo(MD::ADJCALLSTACKDOWN, MD::ADJCALLSTACKUP), RI(ST), Subtarget(ST) { } /// isLoadFromStackSlot - If the specified machine instruction is a direct /// load from a stack slot, return the virtual or physical register number of /// the destination along with the FrameIndex of the loaded stack slot. If /// not, return 0. This predicate must return 0 if the instruction has /// any side effects other than loading from the stack slot. unsigned MandarinInstrInfo::isLoadFromStackSlot(const MachineInstr *MI, int &FrameIndex) const { MI->dump(); /*if (MI->getOpcode() == MD::LOADri || MI->getOpcode() == SP::LDXri || MI->getOpcode() == SP::LDFri || MI->getOpcode() == SP::LDDFri || MI->getOpcode() == SP::LDQFri) { if (MI->getOperand(1).isFI() && MI->getOperand(2).isImm() && MI->getOperand(2).getImm() == 0) { FrameIndex = MI->getOperand(1).getIndex(); return MI->getOperand(0).getReg(); } }*/ return 0; } /// isStoreToStackSlot - If the specified machine instruction is a direct /// store to a stack slot, return the virtual or physical register number of /// the source reg along with the FrameIndex of the loaded stack slot. If /// not, return 0. This predicate must return 0 if the instruction has /// any side effects other than storing to the stack slot. unsigned MandarinInstrInfo::isStoreToStackSlot(const MachineInstr *MI, int &FrameIndex) const { MI->dump(); /*if (MI->getOpcode() == SP::STri || MI->getOpcode() == SP::STXri || MI->getOpcode() == SP::STFri || MI->getOpcode() == SP::STDFri || MI->getOpcode() == SP::STQFri) { if (MI->getOperand(0).isFI() && MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0) { FrameIndex = MI->getOperand(0).getIndex(); return MI->getOperand(2).getReg(); } }*/ return 0; } bool MandarinInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB, SmallVectorImpl<MachineOperand> &Cond, bool AllowModify) const { MachineBasicBlock::iterator I = MBB.end(); while (I != MBB.begin()) { --I; if (I->isDebugValue()) continue; // When we see a non-terminator, we are done. if (!isUnpredicatedTerminator(I)) break; // Terminator is not a branch. if (!I->isBranch()) return true; // Cannot handle indirect branches. if (I->getOpcode() == MD::JMPr || I->getOpcode() == MD::JCCr) return true; // Handle unconditional branches. if (I->getOpcode() == MD::JMPi) { if (!AllowModify) { TBB = I->getOperand(0).getMBB(); continue; } // If the block has any instructions after a JMP, delete them. while (llvm::next(I) != MBB.end()) llvm::next(I)->eraseFromParent(); Cond.clear(); FBB = 0; // Delete the JMP if it's equivalent to a fall-through. if (MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) { TBB = 0; I->eraseFromParent(); I = MBB.end(); continue; } // TBB is used to indicate the unconditinal destination. TBB = I->getOperand(0).getMBB(); continue; } MDCC::CondCodes BranchCode = static_cast<MDCC::CondCodes>(I->getOperand(1).getImm()); if (BranchCode == MDCC::COND_INVALID) return true; // Can't handle weird stuff. // Working from the bottom, handle the first conditional branch. if (Cond.empty()) { FBB = TBB; TBB = I->getOperand(0).getMBB(); Cond.push_back(MachineOperand::CreateImm(BranchCode)); continue; } // Handle subsequent conditional branches. Only handle the case where all // conditional branches branch to the same destination. assert(Cond.size() == 1); assert(TBB); // Only handle the case where all conditional branches branch to // the same destination. if (TBB != I->getOperand(0).getMBB()) return true; MDCC::CondCodes OldBranchCode = (MDCC::CondCodes)Cond[0].getImm(); // If the conditions are the same, we can leave them alone. if (OldBranchCode == BranchCode) continue; return true; } return false; } unsigned MandarinInstrInfo::InsertBranch(MachineBasicBlock &MBB,MachineBasicBlock *TBB, MachineBasicBlock *FBB, const SmallVectorImpl<MachineOperand> &Cond, DebugLoc DL) const { assert(TBB && "InsertBranch must not be told to insert a fallthrough"); assert((Cond.size() == 1 || Cond.size() == 0) && "Mandarin branch conditions should have one component!"); if (Cond.empty()) { assert(!FBB && "Unconditional branch with multiple successors!"); BuildMI(&MBB, DL, get(MD::JMPi)).addMBB(TBB); return 1; } // Conditional branch unsigned Count = 0; BuildMI(&MBB, DL, get(MD::JCCi)).addMBB(TBB).addImm(Cond[0].getImm()); ++Count; if (FBB) { // Two-way Conditional branch. Insert the second branch. BuildMI(&MBB, DL, get(MD::JMPi)).addMBB(FBB); ++Count; } return Count; } unsigned MandarinInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const { MachineBasicBlock::iterator I = MBB.end(); unsigned Count = 0; while (I != MBB.begin()) { --I; if (I->isDebugValue()) continue; if (I->getOpcode() != MD::JMPi && I->getOpcode() != MD::JCCi && I->getOpcode() != MD::JMPr && I->getOpcode() != MD::JCCr) break; // Not a branch // Remove the branch. I->eraseFromParent(); I = MBB.end(); ++Count; } return Count; } void MandarinInstrInfo::copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, DebugLoc DL, unsigned DestReg, unsigned SrcReg, bool KillSrc) const { if(MD::GenericRegsRegClass.contains(DestReg, SrcReg)) { BuildMI(MBB, I, DL, get(MD::MOVrr), DestReg).addReg(SrcReg, getKillRegState(KillSrc)); } else if(MD::DoubleRegsRegClass.contains(DestReg, SrcReg) ) { BuildMI(MBB, I, DL, get(MD::MOV2rr), DestReg).addReg(SrcReg, getKillRegState(KillSrc)); } else if(MD::DoubleRegsRegClass.contains(DestReg) && (SrcReg == MD::R0 || SrcReg == MD::R2)) { printf("Registers are already there\n"); } else if(MD::QuadRegsRegClass.contains(DestReg, SrcReg)) { BuildMI(MBB, I, DL, get(MD::MOV4rr), DestReg).addReg(SrcReg, getKillRegState(KillSrc)); } else if(MD::QuadRegsRegClass.contains(DestReg) && SrcReg == MD::R0) { printf("Registers are already there\n"); } else { llvm_unreachable("Impossible reg-to-reg copy"); } } /// storeRegToStackSlot - Store the specified register of the given register /// class to the specified stack frame index. The store instruction is to be /// added to the given machine basic block before the specified machine /// instruction. If isKill is true, the register operand is the last use and /// must be marked kill. void MandarinInstrInfo:: storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg, bool isKill, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const { DebugLoc DL; if (MI != MBB.end()) DL = MI->getDebugLoc(); MachineFunction *MF = MBB.getParent(); const MachineFrameInfo &MFI = *MF->getFrameInfo(); MachineMemOperand *MMO = MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIndex), MachineMemOperand::MOStore, MFI.getObjectSize(FrameIndex), MFI.getObjectAlignment(FrameIndex)); if (RC == &MD::GenericRegsRegClass) { BuildMI(MBB, MI, DL, get(MD::STORErr)) .addFrameIndex(FrameIndex).addImm(0) .addReg(SrcReg, getKillRegState(isKill)).addMemOperand(MMO); }else{ llvm_unreachable("Cannot store this register to stack slot!"); } } /// loadRegFromStackSlot - Load the specified register of the given register /// class from the specified stack frame index. The load instruction is to be /// added to the given machine basic block before the specified machine /// instruction. void MandarinInstrInfo:: loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg, int FrameIndex, const TargetRegisterClass *RC, const TargetRegisterInfo *TRI) const { DebugLoc DL; if (MI != MBB.end()) DL = MI->getDebugLoc(); MachineFunction &MF = *MBB.getParent(); MachineFrameInfo &MFI = *MF.getFrameInfo(); MachineMemOperand *MMO = MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIndex), MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIndex), MFI.getObjectAlignment(FrameIndex)); if (RC == &MD::GenericRegsRegClass) { BuildMI(MBB, MI, DL, get(MD::LOADrr), DestReg) .addFrameIndex(FrameIndex).addImm(0).addMemOperand(MMO); }else{ llvm_unreachable("Cannot store this register to stack slot!"); } }
32.003115
92
0.632727
WheretIB
e94ec877a7f3cc056a9555adfffecd019977ac2b
1,093
cpp
C++
src/Horn.cpp
mauriciocele/fast-rotor-estimation
1ee3f5a4aaee83f66e8ced209c2891b6e2045856
[ "MIT" ]
2
2020-07-28T15:34:57.000Z
2021-09-24T06:04:03.000Z
src/Horn.cpp
mauriciocele/fast-rotor-estimation
1ee3f5a4aaee83f66e8ced209c2891b6e2045856
[ "MIT" ]
null
null
null
src/Horn.cpp
mauriciocele/fast-rotor-estimation
1ee3f5a4aaee83f66e8ced209c2891b6e2045856
[ "MIT" ]
null
null
null
#include "Horn.h" #include <Eigen/Eigenvalues> using Eigen::Vector3d; using Eigen::Vector4d; using Eigen::Matrix3d; using Eigen::Matrix4d; using Eigen::Quaterniond; using std::vector; Quaterniond Horn(const vector<Vector3d>& P, const vector<Vector3d>& Q, const vector<double>& w) { Matrix3d M; Matrix4d N; const size_t n = P.size(); M.setZero(); for (size_t j = 0; j < n; ++j) { M += w[j] * P[j] * Q[j].transpose(); } // on-diagonal elements N(0, 0) = M(0, 0) + M(1, 1) + M(2, 2); N(1, 1) = M(0, 0) - M(1, 1) - M(2, 2); N(2, 2) = -M(0, 0) + M(1, 1) - M(2, 2); N(3, 3) = -M(0, 0) - M(1, 1) + M(2, 2); // off-diagonal elements N(0, 1) = N(1, 0) = M(1, 2) - M(2, 1); N(0, 2) = N(2, 0) = M(2, 0) - M(0, 2); N(0, 3) = N(3, 0) = M(0, 1) - M(1, 0); N(1, 2) = N(2, 1) = M(0, 1) + M(1, 0); N(1, 3) = N(3, 1) = M(2, 0) + M(0, 2); N(2, 3) = N(3, 2) = M(1, 2) + M(2, 1); Eigen::SelfAdjointEigenSolver<Matrix4d> eigen(N); Vector4d V = eigen.eigenvectors().col(3); Quaterniond quaternion(V(0), V(1), V(2), V(3)); return quaternion; }
26.02381
96
0.513266
mauriciocele
e952343c13a600e55880909a6c7f042ae515207b
9,426
cc
C++
android_ar/app/src/main/cpp/game_renderer.cc
oseiskar/3dtris
16f60c10b8496db1a584c0eaf55cc9959bffab3a
[ "Apache-2.0" ]
4
2018-07-06T21:03:00.000Z
2022-02-10T10:17:21.000Z
android_ar/app/src/main/cpp/game_renderer.cc
oseiskar/3dtris
16f60c10b8496db1a584c0eaf55cc9959bffab3a
[ "Apache-2.0" ]
null
null
null
android_ar/app/src/main/cpp/game_renderer.cc
oseiskar/3dtris
16f60c10b8496db1a584c0eaf55cc9959bffab3a
[ "Apache-2.0" ]
2
2021-08-04T05:49:30.000Z
2022-02-26T12:19:45.000Z
/* * Copyright 2017 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Modifications copyright (C) Otto Seiskari 2018 */ #include "game_renderer.h" #include "util.h" #include <array> namespace { const glm::vec4 kLightDirection(0.5f, 1.0f, 2.0f, 0.0f); // Shader material lighting "pateremrs" [sic] // ... just wondering how sleep-deprived the Google interns who wrote the original // shader were after the ARKit release :P constexpr float AMBIENT = 0.0f; constexpr float DIFFUSE = 3.5f; constexpr float SPECULAR = 1.0f; constexpr float SPECULAR_POWER = 6.0f; constexpr char kVertexShader[] = R"( uniform mat4 u_ModelView; uniform mat4 u_ModelViewProjection; attribute vec4 a_Position; attribute vec3 a_Normal; attribute vec2 a_TexCoord; varying vec3 v_ViewPosition; varying vec3 v_ViewNormal; varying vec2 v_TexCoord; void main() { v_ViewPosition = (u_ModelView * a_Position).xyz; v_ViewNormal = normalize((u_ModelView * vec4(a_Normal, 0.0)).xyz); v_TexCoord = a_TexCoord; gl_Position = u_ModelViewProjection * a_Position; })"; constexpr char kFragmentShader[] = R"( precision mediump float; uniform vec4 u_LightingParameters; uniform vec4 u_MaterialParameters; uniform vec3 u_DiffuseColor; varying vec3 v_ViewPosition; varying vec3 v_ViewNormal; varying vec2 v_TexCoord; void main() { // We support approximate sRGB gamma. const float kGamma = 0.4545454; const float kInverseGamma = 2.2; const float EDGE_WIDTH = 0.02; const float EDGE_BRIGHTNESS = 0.3; // Unpack lighting and material parameters for better naming. vec3 viewLightDirection = u_LightingParameters.xyz; float lightIntensity = u_LightingParameters.w; float materialAmbient = u_MaterialParameters.x; float materialDiffuse = u_MaterialParameters.y; float materialSpecular = u_MaterialParameters.z; float materialSpecularPower = u_MaterialParameters.w; // Normalize varying parameters, because they are linearly interpolated in // the vertex shader. vec3 viewFragmentDirection = normalize(v_ViewPosition); vec3 viewNormal = normalize(v_ViewNormal); vec4 objectColor = vec4(u_DiffuseColor, 1.0); objectColor.rgb = pow(objectColor.rgb, vec3(kInverseGamma)); // Ambient light is unaffected by the light intensity. float ambient = materialAmbient; // Approximate a hemisphere light (not a harsh directional light). float diffuse = lightIntensity * materialDiffuse * 0.5 * (dot(viewNormal, viewLightDirection) + 1.0); vec2 edgeVec = abs((v_TexCoord - 0.5)*2.0); float edgeness = max(edgeVec.x, edgeVec.y); if (edgeness > 1.0 - EDGE_WIDTH) objectColor.rgb = objectColor.rgb * EDGE_BRIGHTNESS; // Compute specular light. vec3 reflectedLightDirection = reflect(viewLightDirection, viewNormal); float specularStrength = max(0.0, dot(viewFragmentDirection, reflectedLightDirection)); float specular = lightIntensity * materialSpecular * pow(specularStrength, materialSpecularPower); // Apply SRGB gamma before writing the fragment color. gl_FragColor.a = objectColor.a; gl_FragColor.rgb = pow(objectColor.rgb * (ambient + diffuse) + specular, vec3(kGamma)); } )"; constexpr float yIsUpInsteadOfZEl[16] = { 1, 0, 0, 0, 0, 0,-1, 0, 0, 1, 0, 0, 0, 0, 0, 1 }; constexpr int32_t kBlockColorRgbaSize = 16; constexpr std::array<uint32_t, kBlockColorRgbaSize> kBlockColorRgba = {{ 0xFFFFFFFF, 0xF44336FF, 0xE91E63FF, 0x9C27B0FF, 0x673AB7FF, 0x3F51B5FF, 0x2196F3FF, 0x03A9F4FF, 0x00BCD4FF, 0x009688FF, 0x4CAF50FF, 0x8BC34AFF, 0xCDDC39FF, 0xFFEB3BFF, 0xFFC107FF, 0xFF9800FF }}; constexpr float COLOR_LIGHTNESS = 1.0; inline glm::vec3 GetBlockColor(int i) { const int32_t colorRgba = kBlockColorRgba[i % kBlockColorRgbaSize]; return glm::vec3(((colorRgba >> 24) & 0xff) / 255.0f, ((colorRgba >> 16) & 0xff) / 255.0f, ((colorRgba >> 8) & 0xff) / 255.0f) * COLOR_LIGHTNESS; } } // namespace GameRenderer::Model GameRenderer::blocksToModel(const std::vector<Block>& blocks, Pos3d dims, float game_scale) const { Model m = Model(); int index_offset = 0; for (Block block : blocks) { float pos[3] = { block.pos.x + 0.5f - dims.x*0.5f, block.pos.y + 0.5f - dims.y*0.5f, block.pos.z + 0.5f }; for (int vertex_index=0; vertex_index < cube_.vertices.size() / 3; ++vertex_index) { for (int coord = 0; coord < 3; ++coord) { m.vertices.push_back((cube_.vertices[vertex_index*3+coord]+pos[coord])*game_scale); } } for (int index : cube_.indices) { m.indices.push_back(index + index_offset); } index_offset += cube_.indices.size(); // copy others unmodified m.uvs.insert(m.uvs.end(), cube_.uvs.begin(), cube_.uvs.end()); m.normals.insert(m.normals.end(), cube_.normals.begin(), cube_.normals.end()); } return m; } const glm::mat4 GAME_MODEL_TRANSFORM = glm::make_mat4(yIsUpInsteadOfZEl); void GameRenderer::InitializeGlContent(AAssetManager* asset_manager) { shader_program_ = util::CreateProgram(kVertexShader, kFragmentShader); if (!shader_program_) { LOGE("Could not create program."); } uniform_mvp_mat_ = glGetUniformLocation(shader_program_, "u_ModelViewProjection"); uniform_mv_mat_ = glGetUniformLocation(shader_program_, "u_ModelView"); uniform_lighting_param_ = glGetUniformLocation(shader_program_, "u_LightingParameters"); uniform_material_param_ = glGetUniformLocation(shader_program_, "u_MaterialParameters"); uniform_diffuse_color_ = glGetUniformLocation(shader_program_, "u_DiffuseColor"); attri_vertices_ = glGetAttribLocation(shader_program_, "a_Position"); attri_uvs_ = glGetAttribLocation(shader_program_, "a_TexCoord"); attri_normals_ = glGetAttribLocation(shader_program_, "a_Normal"); util::LoadObjFile(asset_manager, "cube.obj", &cube_.vertices, &cube_.normals, &cube_.uvs, &cube_.indices); util::CheckGlError("obj_renderer::InitializeGlContent()"); // initialize colors material_colors_.clear(); scene_by_material_.clear(); const int nMaterials = kBlockColorRgbaSize; const int randomOffset = std::rand(); for (int i = 0; i < nMaterials; ++i) { material_colors_.push_back(GetBlockColor(i + randomOffset)); scene_by_material_.push_back(Model()); } } void GameRenderer::update(const Game& game, float game_scale) { const int nMaterials = material_colors_.size(); std::vector< std::vector<Block> > blocks_by_material(nMaterials); for (Block block : game.getAllBlocks()) { const int materialId = block.pieceId % nMaterials; blocks_by_material[materialId].push_back(block); } for (int i = 0; i < nMaterials; ++i) { scene_by_material_[i] = blocksToModel(blocks_by_material[i], game.getDimensions(), game_scale); } } void GameRenderer::Draw(const glm::mat4& projection_mat, const glm::mat4& view_mat, const glm::mat4& model_mat, float light_intensity) const { if (!shader_program_) { LOGE("shader_program is null."); return; } glUseProgram(shader_program_); glm::mat4 mvp_mat = projection_mat * view_mat * model_mat * GAME_MODEL_TRANSFORM; glm::mat4 mv_mat = view_mat * model_mat; glm::vec4 view_light_direction = glm::normalize(mv_mat * kLightDirection); glUniform4f(uniform_lighting_param_, view_light_direction[0], view_light_direction[1], view_light_direction[2], light_intensity); glUniform4f(uniform_material_param_, AMBIENT, DIFFUSE, SPECULAR, SPECULAR_POWER); glUniformMatrix4fv(uniform_mvp_mat_, 1, GL_FALSE, glm::value_ptr(mvp_mat)); glUniformMatrix4fv(uniform_mv_mat_, 1, GL_FALSE, glm::value_ptr(mv_mat)); for (int i = 0; i < scene_by_material_.size(); ++i) { const Model& model = scene_by_material_[i]; if (model.vertices.size() == 0) { continue; } const glm::vec3 color = material_colors_[i] * light_intensity; glUniform3f(uniform_diffuse_color_, color.x, color.y, color.z); glEnableVertexAttribArray(attri_vertices_); glVertexAttribPointer(attri_vertices_, 3, GL_FLOAT, GL_FALSE, 0, model.vertices.data()); glEnableVertexAttribArray(attri_normals_); glVertexAttribPointer(attri_normals_, 3, GL_FLOAT, GL_FALSE, 0, model.normals.data()); glEnableVertexAttribArray(attri_uvs_); glVertexAttribPointer(attri_uvs_, 2, GL_FLOAT, GL_FALSE, 0, model.uvs.data()); glDrawElements(GL_TRIANGLES, model.indices.size(), GL_UNSIGNED_SHORT, model.indices.data()); glDisableVertexAttribArray(attri_vertices_); glDisableVertexAttribArray(attri_uvs_); glDisableVertexAttribArray(attri_normals_); } glUseProgram(0); util::CheckGlError("obj_renderer::Draw()"); }
33.190141
108
0.711436
oseiskar
e95f4d29ee1c0054f8a378bc5fab1b1655df7316
1,811
cpp
C++
LeetCode/Problems/Algorithms/#662_MaximumWidthOfBinaryTree_sol2_bfs.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#662_MaximumWidthOfBinaryTree_sol2_bfs.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#662_MaximumWidthOfBinaryTree_sol2_bfs.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int widthOfBinaryTree(TreeNode* root) { int max_width = 0; queue<pair<TreeNode*, int>> q; if(root != NULL){ q.push({root, 1}); } while(!q.empty()){ if(q.size() == 1){ // use this trick to avoid overflow q.front().second = 1; } // min and max pos of the current level int min_pos = q.front().second; int max_pos = q.front().second; // check only the nodes from the current level for(int nodes_cnt = q.size(); nodes_cnt > 0; --nodes_cnt){ TreeNode* node = q.front().first; int pos = q.front().second; q.pop(); // update min and max pos of the current level min_pos = min(pos, min_pos); max_pos = max(pos, max_pos); // add nodes for the next level if(node->left != NULL){ q.push({node->left, 2 * pos}); } if(node->right != NULL){ q.push({node->right, 2 * pos + 1}); } } max_width = max(max_pos - min_pos + 1, max_width); } return max_width; } };
32.339286
94
0.429045
Tudor67
e9604b41c710292d935908af771b4d184a785ff8
11,423
cpp
C++
Source/Model/CSceneAppMediaEngine.cpp
StevoGTA/SceneApp
a24337bb749d13411b5f78460b8a7915024cbeb7
[ "MIT" ]
null
null
null
Source/Model/CSceneAppMediaEngine.cpp
StevoGTA/SceneApp
a24337bb749d13411b5f78460b8a7915024cbeb7
[ "MIT" ]
null
null
null
Source/Model/CSceneAppMediaEngine.cpp
StevoGTA/SceneApp
a24337bb749d13411b5f78460b8a7915024cbeb7
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------------------------------------------------- // CSceneAppMediaEngine.cpp ©2020 Stevo Brock All rights reserved. //---------------------------------------------------------------------------------------------------------------------- #include "CSceneAppMediaEngine.h" #include "CAudioDecoder.h" #include "CDictionary.h" #include "CFilesystemPath.h" #include "CMediaSourceRegistry.h" #include "CVideoDecoder.h" #if defined(TARGET_OS_IOS) || defined(TARGET_OS_MACOS) || defined(TARGET_OS_TVOS) #include "CCoreAudioAudioConverter.h" #elif defined(TARGET_OS_WINDOWS) #include "CSecretRabbitCodeAudioConverter.h" #endif //---------------------------------------------------------------------------------------------------------------------- // MARK: CSceneAppMediaPlayer class CSceneAppMediaPlayer : public CMediaPlayer { public: CSceneAppMediaPlayer(CSRSWMessageQueues& messageQueues, const CMediaPlayer::Info& info, const CString& resourceFilename, TReferenceDictionary<CSceneAppMediaPlayer>& sceneAppMediaPlayerMap) : CMediaPlayer(messageQueues, info), mResourceFilename(resourceFilename), mSceneAppMediaPlayerMap(sceneAppMediaPlayerMap), mReferenceCount(0) {} void addReference() { mReferenceCount++; } void removeReference() { // Check if last reference if (--mReferenceCount == 0) { // Going away now mSceneAppMediaPlayerMap.remove(mResourceFilename); CSceneAppMediaPlayer* THIS = this; Delete(THIS); } } CString mResourceFilename; TReferenceDictionary<CSceneAppMediaPlayer>& mSceneAppMediaPlayerMap; UInt32 mReferenceCount; }; //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- // MARK: - CSceneAppMediaPlayerReference class CSceneAppMediaPlayerReference : public CMediaPlayer { public: CSceneAppMediaPlayerReference(CSRSWMessageQueues& messageQueues, const CMediaPlayer::Info& info, CSceneAppMediaPlayer& sceneAppMediaPlayer) : CMediaPlayer(messageQueues, info), mSceneAppMediaPlayer(sceneAppMediaPlayer) { mSceneAppMediaPlayer.addReference(); } ~CSceneAppMediaPlayerReference() { mSceneAppMediaPlayer.removeReference(); } void setupComplete() { mSceneAppMediaPlayer.setupComplete(); } I<CAudioPlayer> newAudioPlayer(const CString& identifier, UInt32 trackIndex) { return mSceneAppMediaPlayer.newAudioPlayer(identifier, trackIndex); } void setAudioGain(Float32 audioGain) { mSceneAppMediaPlayer.setAudioGain(audioGain); } I<CVideoFrameStore> newVideoFrameStore(const CString& identifier, UInt32 trackIndex) { return mSceneAppMediaPlayer.newVideoFrameStore(identifier, trackIndex); } void setLoopCount(OV<UInt32> loopCount = OV<UInt32>()) { mSceneAppMediaPlayer.setLoopCount(loopCount); } void play() { mSceneAppMediaPlayer.play(); } void pause() { mSceneAppMediaPlayer.pause(); } bool isPlaying() const { return mSceneAppMediaPlayer.isPlaying(); } void reset() { mSceneAppMediaPlayer.reset(); } CSceneAppMediaPlayer& mSceneAppMediaPlayer; }; //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- // MARK: - CSceneAppMediaEngineInternals class CSceneAppMediaEngineInternals { public: CSceneAppMediaEngineInternals(CSRSWMessageQueues& messageQueues, const SSceneAppResourceLoading& sceneAppResourceLoading) : mMessageQueues(messageQueues), mSSceneAppResourceLoading(sceneAppResourceLoading) {} CSRSWMessageQueues& mMessageQueues; SSceneAppResourceLoading mSSceneAppResourceLoading; TReferenceDictionary<CSceneAppMediaPlayer> mSceneAppMediaPlayerMap; }; //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- // MARK: - CSceneAppMediaEngine // MARK: Lifecycle methods //---------------------------------------------------------------------------------------------------------------------- CSceneAppMediaEngine::CSceneAppMediaEngine(CSRSWMessageQueues& messageQueues, const SSceneAppResourceLoading& sceneAppResourceLoading) : CMediaEngine() //---------------------------------------------------------------------------------------------------------------------- { mInternals = new CSceneAppMediaEngineInternals(messageQueues, sceneAppResourceLoading); } //---------------------------------------------------------------------------------------------------------------------- CSceneAppMediaEngine::~CSceneAppMediaEngine() //---------------------------------------------------------------------------------------------------------------------- { Delete(mInternals); } // MARK: Instance methods //---------------------------------------------------------------------------------------------------------------------- OI<CMediaPlayer> CSceneAppMediaEngine::getMediaPlayer(const CAudioInfo& audioInfo, const CMediaPlayer::Info& info) //---------------------------------------------------------------------------------------------------------------------- { // Setup const CString& resourceFilename = audioInfo.getResourceFilename(); // CAudioInfo::Options audioInfoOptions = audioInfo.getOptions(); // Look for existing media player const OR<CSceneAppMediaPlayer> sceneAppMediaPlayerReference = mInternals->mSceneAppMediaPlayerMap[resourceFilename]; if (sceneAppMediaPlayerReference.hasReference()) // Have reference return OI<CMediaPlayer>( new CSceneAppMediaPlayerReference(mInternals->mMessageQueues, info, *sceneAppMediaPlayerReference)); // Query audio tracks I<CSeekableDataSource> seekableDataSource = mInternals->mSSceneAppResourceLoading .createSeekableDataSource(resourceFilename); CString extension = CFilesystemPath(resourceFilename).getExtension(); TIResult<CMediaSourceRegistry::IdentifyInfo> identifyInfo = CMediaSourceRegistry::mShared.identify( seekableDataSource, extension, SMediaSource::kComposeDecodeInfo); const CMediaTrackInfos& mediaTrackInfos = identifyInfo.getValue().getMediaTrackInfos(); const TArray<CMediaTrackInfos::AudioTrackInfo>& audioTrackInfos = mediaTrackInfos.getAudioTrackInfos(); // Setup Media Player CSceneAppMediaPlayer* sceneAppMediaPlayer = new CSceneAppMediaPlayer(mInternals->mMessageQueues, info, resourceFilename, mInternals->mSceneAppMediaPlayerMap); for (CArray::ItemIndex i = 0; i < audioTrackInfos.getCount(); i++) { // Setup I<CAudioSource> audioSource = getAudioSource(audioTrackInfos[i]); I<CAudioPlayer> audioPlayer = sceneAppMediaPlayer->newAudioPlayer(resourceFilename, i); // Connect ConnectResult connectResult = connect((I<CAudioProcessor>&) audioSource, (I<CAudioProcessor>&) audioPlayer, composeAudioProcessingFormat(*audioSource, *audioPlayer)); if (!connectResult.isSuccess()) { // Cleanup Delete(sceneAppMediaPlayer); return OI<CMediaPlayer>(); } } // Finish setup sceneAppMediaPlayer->setAudioGain(audioInfo.getGain()); sceneAppMediaPlayer->setLoopCount(audioInfo.getLoopCount()); sceneAppMediaPlayer->setupComplete(); // Success mInternals->mSceneAppMediaPlayerMap.set(resourceFilename, *sceneAppMediaPlayer); return OI<CMediaPlayer>(new CSceneAppMediaPlayerReference(mInternals->mMessageQueues, info, *sceneAppMediaPlayer)); } //---------------------------------------------------------------------------------------------------------------------- OI<CMediaPlayer> CSceneAppMediaEngine::getMediaPlayer(const VideoInfo& videoInfo, CVideoFrame::Compatibility compatibility, const CMediaPlayer::Info& info) //---------------------------------------------------------------------------------------------------------------------- { // Setup const CString& filename = videoInfo.mFilename; // Query tracks I<CSeekableDataSource> seekableDataSource = mInternals->mSSceneAppResourceLoading .createSeekableDataSource(filename); CString extension = CFilesystemPath(filename).getExtension(); TIResult<CMediaSourceRegistry::IdentifyInfo> identifyInfo = CMediaSourceRegistry::mShared.identify( seekableDataSource, extension, SMediaSource::kComposeDecodeInfo); const CMediaTrackInfos& mediaTrackInfos = identifyInfo.getValue().getMediaTrackInfos(); const TArray<CMediaTrackInfos::AudioTrackInfo>& audioTrackInfos = mediaTrackInfos.getAudioTrackInfos(); const TArray<CMediaTrackInfos::VideoTrackInfo>& videoTrackInfos = mediaTrackInfos.getVideoTrackInfos(); // Setup Media Player CSceneAppMediaPlayer* sceneAppMediaPlayer = new CSceneAppMediaPlayer(mInternals->mMessageQueues, info, filename, mInternals->mSceneAppMediaPlayerMap); for (CArray::ItemIndex i = 0; i < audioTrackInfos.getCount(); i++) { // Setup I<CAudioSource> audioSource = getAudioSource(audioTrackInfos[i]); I<CAudioPlayer> audioPlayer = sceneAppMediaPlayer->newAudioPlayer(filename, i); // Connect ConnectResult connectResult = connect((I<CAudioProcessor>&) audioSource, (I<CAudioProcessor>&) audioPlayer, composeAudioProcessingFormat(*audioSource, *audioPlayer)); if (!connectResult.isSuccess()) { // Cleanup Delete(sceneAppMediaPlayer); return OI<CMediaPlayer>(); } } for (CArray::ItemIndex i = 0; i < videoTrackInfos.getCount(); i++) { // Setup I<CVideoSource> videoSource = getVideoSource(videoTrackInfos[i], compatibility); I<CVideoFrameStore> videoFrameStore = sceneAppMediaPlayer->newVideoFrameStore(filename, i); // Connect OI<SError> error = videoFrameStore->connectInput((const I<CVideoProcessor>&) videoSource); if (error.hasInstance()) { // Cleanup Delete(sceneAppMediaPlayer); return OI<CMediaPlayer>(); } } // Finish setup sceneAppMediaPlayer->setupComplete(); // Success mInternals->mSceneAppMediaPlayerMap.set(filename, *sceneAppMediaPlayer); return OI<CMediaPlayer>(new CSceneAppMediaPlayerReference(mInternals->mMessageQueues, info, *sceneAppMediaPlayer)); } // MARK: Subclass methods //---------------------------------------------------------------------------------------------------------------------- I<CAudioConverter> CSceneAppMediaEngine::createAudioConverter() const //---------------------------------------------------------------------------------------------------------------------- { #if defined(TARGET_OS_IOS) || defined(TARGET_OS_MACOS) || defined(TARGET_OS_TVOS) // Apple return I<CAudioConverter>(new CCoreAudioAudioConverter()); #elif defined(TARGET_OS_WINDOWS) // Windows return I<CAudioConverter>(new CSecretRabbitCodeAudioConverter()); #endif }
42.151292
120
0.594327
StevoGTA
e964a248419155561dad97b26eed0340ad045b78
134
cpp
C++
persistence/backend.cpp
czpwpq/hotel
2e003b019cf6b21349228740a8dae6c639945510
[ "MIT" ]
7
2017-04-05T20:06:30.000Z
2022-01-01T00:14:42.000Z
persistence/backend.cpp
czpwpq/hotel
2e003b019cf6b21349228740a8dae6c639945510
[ "MIT" ]
1
2017-01-06T13:47:45.000Z
2017-01-06T13:49:47.000Z
persistence/backend.cpp
decden/hotel
1d7d16ad0a97c9a24f8e54b9b180fcd3166d0c89
[ "MIT" ]
4
2017-04-05T20:06:31.000Z
2020-10-29T14:50:12.000Z
#include "persistence/backend.h" namespace persistence { Backend::Backend() {} Backend::~Backend() {} } // namespace persistence
16.75
32
0.701493
czpwpq
e96739bf6e4bc7f698b1de5c069b552058138a1f
309
cpp
C++
SignalTester/playsoundfile/playfile.cpp
GeertRoks/DSP_theory
508e6b52261460c7d06caffa02cab66b38d87e88
[ "MIT" ]
null
null
null
SignalTester/playsoundfile/playfile.cpp
GeertRoks/DSP_theory
508e6b52261460c7d06caffa02cab66b38d87e88
[ "MIT" ]
null
null
null
SignalTester/playsoundfile/playfile.cpp
GeertRoks/DSP_theory
508e6b52261460c7d06caffa02cab66b38d87e88
[ "MIT" ]
null
null
null
#include "playfile.hpp" Playfile::Playfile() { } Playfile::Playfile(std::string file) { } std::vector<double> Playfile::getSamples(const unsigned int num_samples) { std::vector<double> file = {}; for (unsigned int i = 0; i < num_samples; i++) { file.push_back(sample0[i]); } return file; }
17.166667
74
0.653722
GeertRoks
e96cb2a50dc79efaf5825c78e77700732319be4c
2,265
cpp
C++
tests/util/uint_types_test.cpp
patflick/dpt
5b300500c97f41d1d24c4e660af2d4499ad40520
[ "BSD-2-Clause" ]
7
2017-03-23T05:19:53.000Z
2021-02-26T14:25:08.000Z
tests/util/uint_types_test.cpp
patflick/dpt
5b300500c97f41d1d24c4e660af2d4499ad40520
[ "BSD-2-Clause" ]
2
2019-04-04T02:24:06.000Z
2019-04-04T02:57:08.000Z
tests/util/uint_types_test.cpp
patflick/dpt
5b300500c97f41d1d24c4e660af2d4499ad40520
[ "BSD-2-Clause" ]
2
2019-04-03T20:09:47.000Z
2021-10-30T16:06:47.000Z
/******************************************************************************* * tests/util/uint_types_test.cpp * * Part of dpt - Distributed Patricia Trie * * Copyright (C) 2013 Timo Bingmann <[email protected]> * * Copied from: * > tests/common/uint_types_test.cpp * > * > Class representing a 40-bit or 48-bit unsigned integer encoded in five or * > six bytes. * > Part of Project Thrill - http://project-thrill.org * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <gtest/gtest.h> #include <limits> #include <dpt/util/uint_types.hpp> // forced instantiation template class dpt::UIntPair<uint8_t>; template class dpt::UIntPair<uint16_t>; template <typename uint> void dotest(unsigned int nbytes) { // simple initialize uint a = 42; // check sizeof (again) ASSERT_EQ(sizeof(a), nbytes); // count up 1024 and down again uint b = 0xFFFFFF00; uint b_save = b; uint64_t b64 = b; for (uint32_t i = 0; i < 1024; ++i) { ASSERT_EQ(b.u64(), b64); ASSERT_EQ(b.ull(), b64); ASSERT_NE(b, a); ++b, ++b64; } ASSERT_NE(b, b_save); for (uint32_t i = 0; i < 1024; ++i) { ASSERT_EQ(b.u64(), b64); ASSERT_EQ(b.ull(), b64); ASSERT_NE(b, a); --b, --b64; } ASSERT_EQ(b.u64(), b64); ASSERT_EQ(b.ull(), b64); ASSERT_EQ(b, b_save); // check min and max value ASSERT_LE(uint::min(), a); ASSERT_GE(uint::max(), a); ASSERT_LT(std::numeric_limits<uint>::min(), a); ASSERT_GT(std::numeric_limits<uint>::max(), a); // check simple math a = 42; a = a + a; ASSERT_EQ(a, uint(84)); ASSERT_EQ(a.ull(), uint(84)); a += uint(0xFFFFFF00); ASSERT_EQ(a.ull(), 0xFFFFFF54llu); a += uint(0xFFFFFF00); ASSERT_EQ(a.ull(), 0x1FFFFFE54llu); a -= uint(0xFFFFFF00); ASSERT_EQ(a.ull(), 0xFFFFFF54llu); a -= uint(0xFFFFFF00); ASSERT_EQ(a.ull(), uint(84)); } TEST(UIntPair, Uint40) { dotest<dpt::uint40>(5); } TEST(UIntPair, Uint48) { dotest<dpt::uint48>(6); } /******************************************************************************/
23.112245
80
0.535541
patflick
e971b1083ac5316aa29749b05674ff5cf40ad582
1,880
cpp
C++
code/5/5_pre2_4_bombard.cpp
kdh9949/snups-scpc2020
7a3266ea6ba618e5ae066f156f404689d5e270b6
[ "MIT" ]
6
2020-07-14T01:46:39.000Z
2021-06-15T06:08:28.000Z
code/5/5_pre2_4_bombard.cpp
kdh9949/snups-scpc2020
7a3266ea6ba618e5ae066f156f404689d5e270b6
[ "MIT" ]
null
null
null
code/5/5_pre2_4_bombard.cpp
kdh9949/snups-scpc2020
7a3266ea6ba618e5ae066f156f404689d5e270b6
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; using pil = pair<int, ll>; using pli = pair<ll, int>; using pll = pair<ll, ll>; using vint = vector<int>; using vll = vector<ll>; using vld = vector<ld>; using vpii = vector<pii>; using vpil = vector<pil>; using vpli = vector<pli>; using vpll = vector<pll>; #define x first #define y second #define all(v) v.begin(),v.end() void solve() { int n, m; cin >> n >> m; vector<string> b(n + 2); b[0] = b[n + 1] = string("0", m + 2); for(int i = 1; i <= n; i++) { cin >> b[i]; b[i] = "0" + b[i] + "0"; } vpii ans; auto cnt = [&](int x, int y) { if(x <= 0 || y <= 0) return -1; int r = 0; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) if(b[x + i][y + j] == '1') r++; return r; }; auto bomb = [&](int x, int y) { ans.emplace_back(x, y); for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) b[x + i][y + j] = '0'; }; for(int i = 1; i <= n - 3; i++) { for(int j = 1; j <= m - 3; j++) { if(b[i][j] == '1') { int c[3] = {cnt(i, j - 2), cnt(i, j - 1), cnt(i, j)}; int mx = max({c[0], c[1], c[2]}); if(mx == c[0]) bomb(i, j - 2); else if(mx == c[1]) bomb(i, j - 1); else bomb(i, j); } } } for(int i = 1; i <= n - 3; i++) { if(b[i][m - 2] + b[i][m - 1] + b[i][m] > 3 * '0') bomb(i, m - 2); } for(int i = 1; i <= m - 3; i++) { if(b[n - 2][i] + b[n - 1][i] + b[n][i] > 3 * '0') bomb(n - 2, i); } if(cnt(n - 2, m - 2)) bomb(n - 2, m - 2); cout << ans.size() << '\n'; for(pii &p : ans) cout << p.x << ' ' << p.y << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); int tc; cin >> tc; for(int i = 1; i <= tc; i++) { cout << "Case #" << i << '\n'; solve(); } return 0; }
22.650602
69
0.435106
kdh9949
e97b04f1c26a1cac1113ce8c27355b665709f46c
1,034
cpp
C++
Plugins/SkillEditor2D/Source/SkillEditor2D/Private/Editor/Preview/SkillEditorPreviewClient.cpp
UnderGround-orchestra-band/SuperRogue
65a520ac6ccf859c5994e429ffe915e9ff6f1028
[ "MIT" ]
1
2021-12-18T13:50:51.000Z
2021-12-18T13:50:51.000Z
Plugins/SkillEditor2D/Source/SkillEditor2D/Private/Editor/Preview/SkillEditorPreviewClient.cpp
UnderGround-orchestra-band/SuperRogue
65a520ac6ccf859c5994e429ffe915e9ff6f1028
[ "MIT" ]
1
2021-11-30T08:09:46.000Z
2021-11-30T08:09:46.000Z
Plugins/SkillEditor2D/Source/SkillEditor2D/Private/Editor/Preview/SkillEditorPreviewClient.cpp
UnderGround-orchestra-band/SuperRogue
65a520ac6ccf859c5994e429ffe915e9ff6f1028
[ "MIT" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "SkillEditorPreviewClient.h" void SkillEditorPreviewClient::Draw(FViewport* InViewport, FCanvas* Canvas) { FEditorViewportClient::Draw(InViewport, Canvas); } void SkillEditorPreviewClient::Tick(float DeltaSeconds) { FEditorViewportClient::Tick(DeltaSeconds); if(DeltaSeconds>0.f) { PreviewScene->GetWorld()->Tick(LEVELTICK_All,DeltaSeconds); } } UWorld* SkillEditorPreviewClient::GetWorld() const { if(PreviewScene!=nullptr) return PreviewScene->GetWorld(); return GWorld; } SkillEditorPreviewClient::SkillEditorPreviewClient(FEditorModeTools* InModeTools, FPreviewScene* InPreviewScene, const TWeakPtr<SEditorViewport>& InEditorViewportWidget ): FEditorViewportClient(InModeTools,InPreviewScene,InEditorViewportWidget) { SetViewLocation(FVector(100,100,100)); } SkillEditorPreviewClient::~SkillEditorPreviewClient() { }
25.85
109
0.727273
UnderGround-orchestra-band
e97e242c15b3b9cc5ec0a0027dd2eca45893abb7
17,718
cpp
C++
Overdrive/render/shaderprogram.cpp
png85/Overdrive
e763827546354c7c75395ab1a82949a685ecb880
[ "MIT" ]
41
2015-02-21T08:54:00.000Z
2021-05-11T16:01:29.000Z
Overdrive/render/shaderprogram.cpp
png85/Overdrive
e763827546354c7c75395ab1a82949a685ecb880
[ "MIT" ]
1
2018-05-14T10:02:09.000Z
2018-05-14T10:02:09.000Z
Overdrive/render/shaderprogram.cpp
png85/Overdrive
e763827546354c7c75395ab1a82949a685ecb880
[ "MIT" ]
10
2015-10-07T05:44:08.000Z
2020-12-01T09:00:01.000Z
#include "stdafx.h" #include "shaderprogram.h" #include "shaderAttribute.h" #include "shaderUniform.h" #include "../core/logger.h" #include <fstream> namespace overdrive { namespace render { namespace { int getShaderIndex(eShaderType type) { switch (type) { case eShaderType::VERTEX: return 0; case eShaderType::FRAGMENT: return 1; case eShaderType::GEOMETRY: return 2; case eShaderType::TESSELATION_CONTROL: return 3; case eShaderType::TESSELATION_EVAL: return 4; case eShaderType::COMPUTE: return 5; default: throw ShaderException("Unsupported shader type"); } } } ShaderProgram::ShaderProgram(): mHandle(0), mIsLinked(false) { } ShaderProgram::~ShaderProgram() { if (mHandle) { for (const auto& shader : mShaders) if (shader) glDetachShader(mHandle, shader->getHandle()); glDeleteProgram(mHandle); } } GLuint ShaderProgram::getHandle() const { return mHandle; } void ShaderProgram::attachShader(const std::string& source, eShaderType type) { if (mHandle == 0) { mHandle = glCreateProgram(); if (mHandle == 0) { gLogError << "Failed to create shader program"; throw ShaderException("Failed to create shader program"); } } int idx = getShaderIndex(type); if (mShaders[idx]) { gLogWarning << "Duplicate shader type provided; overwriting previous shader"; glDetachShader(mHandle, mShaders[idx]->getHandle()); } mShaders[idx] = std::make_unique<Shader>(type); mShaders[idx]->compile(source); glAttachShader(mHandle, mShaders[idx]->getHandle()); } void ShaderProgram::loadShader(const boost::filesystem::path& p, eShaderType type) { using namespace boost::filesystem; if (!exists(p)) { gLogError << "File not found: " << p; throw ShaderException("File not found"); } if (!is_regular_file(p)) { gLogError << "Not a regular file: " << p; throw ShaderException("Not a regular file"); } std::ifstream ifs(p.c_str()); if (!ifs.good()) { gLogError << "Could not open file: " << p; throw ShaderException("Could not open file"); } std::string content( (std::istreambuf_iterator<char>(ifs)), // <~ Most Vexing Parse... hence the extra () std::istreambuf_iterator<char>() ); attachShader(content, type); } void ShaderProgram::link() { if (mIsLinked) { gLogWarning << "Shader program already linked"; return; } if (mHandle == 0) { gLogError << "No program handle available, cannot link"; return; } glLinkProgram(mHandle); GLint result; glGetProgramiv(mHandle, GL_LINK_STATUS, &result); if (result == GL_FALSE) { // something went wrong, extract and log the error message GLint messageLength = 0; glGetProgramiv(mHandle, GL_INFO_LOG_LENGTH, &messageLength); if (messageLength > 0) { auto message = std::make_unique<char[]>(messageLength); GLsizei bytesWritten = 0; glGetProgramInfoLog( mHandle, messageLength, &bytesWritten, message.get() ); gLogError << message.get(); return; } } mIsLinked = true; #ifdef OVERDRIVE_DEBUG validate(); #endif gatherUniforms(); gatherAttributes(); } bool ShaderProgram::isLinked() const { return mIsLinked; } void ShaderProgram::validate() { if (!isLinked()) { gLogWarning << "Cannot validate a shader program that is not linked yet"; return; } glValidateProgram(mHandle); GLint result; glGetProgramiv(mHandle, GL_LINK_STATUS, &result); if (result == GL_FALSE) { // something went wrong, extract and log the error message GLint messageLength = 0; glGetProgramiv( mHandle, GL_INFO_LOG_LENGTH, &messageLength ); if (messageLength > 0) { auto message = std::make_unique<char[]>(messageLength); GLsizei bytesWritten = 0; glGetProgramInfoLog( mHandle, messageLength, &bytesWritten, message.get() ); gLogError << message.get(); } } } void ShaderProgram::bind() { assert(mHandle); glUseProgram(mHandle); } void ShaderProgram::unbind() { glUseProgram(0); } void ShaderProgram::listUniforms() const { // [NOTE] perhaps sort the names alphabetically? gLogDebug << " ---- Active Uniforms ---- "; gLogDebug << "Number of uniforms: " << mUniforms.size(); unsigned int i = 0; for (const auto& item : mUniforms) gLog << i++ << ":\t" << item.first << " " << item.second; gLogDebug << " ------------------------- "; } void ShaderProgram::listAttributes() const { // [NOTE] perhapse sort the attributes alphabetically? gLogDebug << " ---- Active Attributes ---- "; gLogDebug << " Number of attributes: " << mAttributes.size(); unsigned int i = 0; for (const auto& item : mAttributes) gLog << i++ << ":\t" << item.second; gLogDebug << " ------------------------- "; } Shader* ShaderProgram::getShader(eShaderType type) const { return mShaders[getShaderIndex(type)].get(); } /* void ShaderProgram::bindAttributeLocation(GLuint id, const std::string& name) { } void ShaderProgram::bindFragDataLocation(GLuint id, const std::string& name) { } */ GLint ShaderProgram::getUniformLocation(const std::string& name) const { auto it = mUniforms.find(name); if (it == mUniforms.end()) throw ShaderException(std::string("Cannot locate uniform: ") + name); return it->second.mLocation; } const ShaderUniform& ShaderProgram::getUniformData(const std::string& name) const { auto it = mUniforms.find(name); if (it == mUniforms.end()) throw ShaderException(std::string("Cannot locate uniform: ") + name); return it->second; } GLint ShaderProgram::getAttributeLocation(const std::string& name) const { auto it = mAttributes.find(name); if (it == mAttributes.end()) throw ShaderException(std::string("Cannot locate attribute: ") + name); return it->second.getLocation(); } const ShaderAttribute& ShaderProgram::getAttributeData(const std::string& name) const { auto it = mAttributes.find(name); if (it == mAttributes.end()) throw ShaderException(std::string("Cannot locate attribute: ") + name); return it->second; } // http://docs.gl/gl4/glGetProgramInterface // http://docs.gl/gl4/glGetProgramResource void ShaderProgram::gatherUniforms() { using std::pair; using std::string; typedef pair<string, ShaderUniform> UniformPair; GLint numUniforms = 0; glGetProgramInterfaceiv(mHandle, GL_UNIFORM, GL_ACTIVE_RESOURCES, &numUniforms); // [NOTE] this must correspond to the constructor in ShaderUniform! GLenum properties[] = { GL_NAME_LENGTH, GL_TYPE, GL_LOCATION, GL_ARRAY_SIZE, GL_ARRAY_STRIDE, GL_MATRIX_STRIDE, GL_OFFSET, GL_BLOCK_INDEX, GL_ATOMIC_COUNTER_BUFFER_INDEX, GL_IS_ROW_MAJOR, GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_REFERENCED_BY_GEOMETRY_SHADER, GL_REFERENCED_BY_TESS_CONTROL_SHADER, GL_REFERENCED_BY_TESS_EVALUATION_SHADER, GL_REFERENCED_BY_COMPUTE_SHADER }; const size_t numProperties = sizeof(properties) / sizeof(properties[0]); for (GLint i = 0; i < numUniforms; ++i) { GLint results[numProperties]; glGetProgramResourceiv( mHandle, GL_UNIFORM, i, numProperties, properties, numProperties, nullptr, results ); GLint nameLength = results[0]; std::unique_ptr<GLchar[]> uniformName(new GLchar[nameLength]); glGetProgramResourceName( mHandle, GL_UNIFORM, i, nameLength, nullptr, uniformName.get() ); mUniforms.insert(UniformPair( uniformName.get(), ShaderUniform(uniformName.get(), results) )); } } // http://docs.gl/gl4/glGetProgramInterface // http://docs.gl/gl4/glGetProgramResource void ShaderProgram::gatherAttributes() { using std::pair; using std::string; typedef pair<string, ShaderAttribute> AttributePair; GLint numAttributes = 0; glGetProgramInterfaceiv(mHandle, GL_PROGRAM_INPUT, GL_ACTIVE_RESOURCES, &numAttributes); // [NOTE] this must correspond to the constructor in ShaderAttribute! GLenum properties[] = { GL_NAME_LENGTH, GL_TYPE, GL_LOCATION, GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_REFERENCED_BY_GEOMETRY_SHADER, GL_REFERENCED_BY_TESS_CONTROL_SHADER, GL_REFERENCED_BY_TESS_EVALUATION_SHADER, GL_REFERENCED_BY_COMPUTE_SHADER, GL_IS_PER_PATCH, GL_LOCATION_COMPONENT }; const size_t numProperties = sizeof(properties) / sizeof(properties[0]); for (GLint i = 0; i < numAttributes; ++i) { GLint results[numProperties]; glGetProgramResourceiv( mHandle, GL_PROGRAM_INPUT, i, numProperties, properties, numProperties, nullptr, results ); GLint nameSize = results[0]; std::unique_ptr<GLchar[]> attributeName(new GLchar[nameSize]); glGetProgramResourceName( mHandle, GL_PROGRAM_INPUT, i, nameSize, nullptr, attributeName.get() ); mAttributes.insert(AttributePair( attributeName.get(), ShaderAttribute(attributeName.get(), results) )); } } void ShaderProgram::setUniform(GLint location, GLfloat x) { glUniform1f(location, x); } void ShaderProgram::setUniform(GLint location, GLfloat x, GLfloat y) { glUniform2f(location, x, y); } void ShaderProgram::setUniform(GLint location, GLfloat x, GLfloat y, GLfloat z) { glUniform3f(location, x, y, z); } void ShaderProgram::setUniform(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { glUniform4f(location, x, y, z, w); } void ShaderProgram::setUniform(GLint location, const glm::vec2& v) { glUniform2f(location, v.x, v.y); } void ShaderProgram::setUniform(GLint location, const glm::vec3& v) { glUniform3f(location, v.x, v.y, v.z); } void ShaderProgram::setUniform(GLint location, const glm::vec4& v) { glUniform4f(location, v.x, v.y, v.z, v.w); } void ShaderProgram::setUniform(GLint location, GLdouble x) { glUniform1d(location, x); } void ShaderProgram::setUniform(GLint location, GLdouble x, GLdouble y) { glUniform2d(location, x, y); } void ShaderProgram::setUniform(GLint location, GLdouble x, GLdouble y, GLdouble z) { glUniform3d(location, x, y, z); } void ShaderProgram::setUniform(GLint location, GLdouble x, GLdouble y, GLdouble z, GLdouble w) { glUniform4d(location, x, y, z, w); } void ShaderProgram::setUniform(GLint location, const glm::dvec2& v) { glUniform2d(location, v.x, v.y); } void ShaderProgram::setUniform(GLint location, const glm::dvec3& v) { glUniform3d(location, v.x, v.y, v.z); } void ShaderProgram::setUniform(GLint location, const glm::dvec4& v) { glUniform4d(location, v.x, v.y, v.z, v.w); } void ShaderProgram::setUniform(GLint location, GLint x) { glUniform1i(location, x); } void ShaderProgram::setUniform(GLint location, GLint x, GLint y) { glUniform2i(location, x, y); } void ShaderProgram::setUniform(GLint location, GLint x, GLint y, GLint z) { glUniform3i(location, x, y, z); } void ShaderProgram::setUniform(GLint location, GLint x, GLint y, GLint z, GLint w) { glUniform4i(location, x, y, z, w); } void ShaderProgram::setUniform(GLint location, const glm::ivec2& v) { glUniform2i(location, v.x, v.y); } void ShaderProgram::setUniform(GLint location, const glm::ivec3& v) { glUniform3i(location, v.x, v.y, v.z); } void ShaderProgram::setUniform(GLint location, const glm::ivec4& v) { glUniform4i(location, v.x, v.y, v.z, v.w); } void ShaderProgram::setUniform(GLint location, GLuint x) { glUniform1ui(location, x); } void ShaderProgram::setUniform(GLint location, GLuint x, GLuint y) { glUniform2ui(location, x, y); } void ShaderProgram::setUniform(GLint location, GLuint x, GLuint y, GLuint z) { glUniform3ui(location, x, y, z); } void ShaderProgram::setUniform(GLint location, GLuint x, GLuint y, GLuint z, GLuint w) { glUniform4ui(location, x, y, z, w); } void ShaderProgram::setUniform(GLint location, const glm::uvec2& v) { glUniform2ui(location, v.x, v.y); } void ShaderProgram::setUniform(GLint location, const glm::uvec3& v) { glUniform3ui(location, v.x, v.y, v.z); } void ShaderProgram::setUniform(GLint location, const glm::uvec4& v) { glUniform4ui(location, v.x, v.y, v.z, v.w); } void ShaderProgram::setUniform(GLint location, GLboolean x) { glUniform1i(location, x); } void ShaderProgram::setUniform(GLint location, GLboolean x, GLboolean y) { glUniform2i(location, x, y); } void ShaderProgram::setUniform(GLint location, GLboolean x, GLboolean y, GLboolean z) { glUniform3i(location, x, y, z); } void ShaderProgram::setUniform(GLint location, GLboolean x, GLboolean y, GLboolean z, GLboolean w) { glUniform4i(location, x, y, z, w); } void ShaderProgram::setUniform(GLint location, const glm::bvec2& v) { glUniform2i(location, v.x, v.y); } void ShaderProgram::setUniform(GLint location, const glm::bvec3& v) { glUniform3i(location, v.x, v.y, v.z); } void ShaderProgram::setUniform(GLint location, const glm::bvec4& v) { glUniform4i(location, v.x, v.y, v.z, v.w); } void ShaderProgram::setUniform(GLint location, const glm::mat2& m) { glUniformMatrix2fv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::mat3& m) { glUniformMatrix3fv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::mat4& m) { glUniformMatrix4fv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::mat2x3& m) { glUniformMatrix2x3fv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::mat2x4& m) { glUniformMatrix2x4fv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::mat3x2& m) { glUniformMatrix3x2fv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::mat3x4& m) { glUniformMatrix3x4fv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::mat4x2& m) { glUniformMatrix4x2fv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::mat4x3& m) { glUniformMatrix4x3fv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::dmat2& m) { glUniformMatrix2dv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::dmat3& m) { glUniformMatrix3dv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::dmat4& m) { glUniformMatrix4dv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::dmat2x3& m) { glUniformMatrix2x3dv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::dmat2x4& m) { glUniformMatrix2x4dv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::dmat3x2& m) { glUniformMatrix3x2dv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::dmat3x4& m) { glUniformMatrix3x4dv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::dmat4x2& m) { glUniformMatrix4x2dv(location, 1, GL_FALSE, &m[0][0]); } void ShaderProgram::setUniform(GLint location, const glm::dmat4x3& m) { glUniformMatrix4x3dv(location, 1, GL_FALSE, &m[0][0]); } std::ostream& operator << (std::ostream& os, const ShaderProgram& program) { os << "Shader program: " << program.getHandle() << "\n"; if (program.isLinked()) { program.listAttributes(); program.listUniforms(); } /* auto vtx = program.getShader(eShaderType::VERTEX); auto frag = program.getShader(eShaderType::FRAGMENT); auto geom = program.getShader(eShaderType::GEOMETRY); auto tess_ctrl = program.getShader(eShaderType::TESSELATION_CONTROL); auto tess_eval = program.getShader(eShaderType::TESSELATION_EVAL); auto compute = program.getShader(eShaderType::COMPUTE); if (vtx) os << "\nVertex shader:\n" << vtx->getSource(); if (frag) os << "\nFragment shader:\n" << frag->getSource(); if (geom) os << "\nGeometry shader:\n" << geom->getSource(); if (tess_ctrl) os << "\nTesselation control:\n" << tess_ctrl->getSource(); if (tess_eval) os << "\nTesselation evaluation:\n" << tess_eval->getSource(); if (compute) os << "\nCompute shader:\n" << compute->getSource(); */ return os; } } }
26.968037
103
0.642454
png85
e980b12a489a4e89883a9d7920f0541f45d6ff5d
870
cpp
C++
src/breadboard/node_signature.cpp
Coolgamer0403/breadboard
45537cea0d6cdee70ed91d86cc6114465c351325
[ "Apache-2.0" ]
138
2015-11-19T05:00:41.000Z
2021-12-13T14:26:34.000Z
src/breadboard/node_signature.cpp
Coolgamer0403/breadboard
45537cea0d6cdee70ed91d86cc6114465c351325
[ "Apache-2.0" ]
3
2015-11-20T01:25:44.000Z
2019-09-21T11:45:12.000Z
src/breadboard/node_signature.cpp
Coolgamer0403/breadboard
45537cea0d6cdee70ed91d86cc6114465c351325
[ "Apache-2.0" ]
27
2015-11-28T02:47:02.000Z
2021-10-15T11:17:20.000Z
// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "breadboard/node_signature.h" namespace breadboard { BaseNode* NodeSignature::Constructor() const { return constructor_(); } void NodeSignature::Destructor(BaseNode* base_node) const { return destructor_(base_node); } } // namespace breadboard
33.461538
75
0.752874
Coolgamer0403
e98355928269503f85125b2b2affb2ef3c9bbbcf
2,137
cc
C++
tests/catch/unit/device/hipDeviceGetLimit.cc
neon60/HIP
586165ebc281eb9461898a5b2abbc74595f5d97d
[ "MIT" ]
null
null
null
tests/catch/unit/device/hipDeviceGetLimit.cc
neon60/HIP
586165ebc281eb9461898a5b2abbc74595f5d97d
[ "MIT" ]
null
null
null
tests/catch/unit/device/hipDeviceGetLimit.cc
neon60/HIP
586165ebc281eb9461898a5b2abbc74595f5d97d
[ "MIT" ]
null
null
null
/* Copyright (c) 2021-Present Advanced Micro Devices, Inc. All rights reserved. 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 WARRANNTY OF ANY KIND, EXPRESS OR IMPLIED, INNCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANNY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER INN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR INN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * Conformance test for checking functionality of * hipError_t hipDeviceGetLimit(size_t* pValue, enum hipLimit_t limit); */ #include <hip_test_common.hh> /** * hipDeviceGetLimit tests * Scenario1: Validates if pValue = nullptr returns hip error code. * Scenario2: Validates if *pValue > 0 is returned for limit = hipLimitMallocHeapSize. * Scenario3: Validates if error code is returned for limit = Invalid Flag = 0xff. */ TEST_CASE("Unit_hipDeviceGetLimit_NegTst") { size_t Value = 0; // Scenario1 SECTION("NULL check") { REQUIRE_FALSE(hipDeviceGetLimit(nullptr, hipLimitMallocHeapSize) == hipSuccess); } // Scenario3 SECTION("Invalid Input Flag") { REQUIRE_FALSE(hipDeviceGetLimit(&Value, static_cast<hipLimit_t>(0xff)) == hipSuccess); } } TEST_CASE("Unit_hipDeviceGetLimit_CheckValidityOfOutputVal") { size_t Value = 0; // Scenario2 REQUIRE(hipDeviceGetLimit(&Value, hipLimitMallocHeapSize) == hipSuccess); REQUIRE_FALSE(Value <= 0); }
41.096154
86
0.759008
neon60
e984dc80cc35a62fdb73bb71feeca42ebae1a025
15,164
cpp
C++
Blizzlike/ArcEmu/C++/WorldPvPScripts/ZoneHellfirePeninsula.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/ArcEmu/C++/WorldPvPScripts/ZoneHellfirePeninsula.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/ArcEmu/C++/WorldPvPScripts/ZoneHellfirePeninsula.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/** * Summit MMORPG Server Software * Copyright (c) 2008 Summit Server Team * See COPYING for license details. */ #include "StdAfx.h" // Some customizable defines. // Maybe move these to config? #define BANNER_RANGE 900 #define UPDATE_PERIOD 5000 #define CAPTURE_RATE 20 // Towers enum Towers { TOWER_STADIUM, TOWER_OVERLOOK, TOWER_BROKENHILL, TOWER_COUNT, }; // Tower GameObject Ids #define TOWER_WEST 182173 #define TOWER_NORTH 182174 #define TOWER_SOUTH 182175 // Buff Ids #define HELLFIRE_SUPERORITY_ALLIANCE 32071 #define HELLFIRE_SUPERORITY_HORDE 32049 // Owners of the towers, used for save/restore int32 g_towerOwners[TOWER_COUNT] = { -1, -1, -1 }; // global variables uint32 g_hordeTowers = 0; uint32 g_allianceTowers = 0; int32 g_superiorTeam = -1; // SUPERIORITY // Fields to update visual view of the client map static const uint32 g_hordeStateFields[3] = { WORLDSTATE_HELLFIRE_STADIUM_HORDE, WORLDSTATE_HELLFIRE_OVERLOOK_HORDE, WORLDSTATE_HELLFIRE_BROKENHILL_HORDE }; static const uint32 g_allianceStateFields[3] = { WORLDSTATE_HELLFIRE_STADIUM_ALLIANCE, WORLDSTATE_HELLFIRE_OVERLOOK_ALLIANCE, WORLDSTATE_HELLFIRE_BROKENHILL_ALLIANCE }; static const uint32 g_neutralStateFields[3] = { WORLDSTATE_HELLFIRE_STADIUM_NEUTRAL, WORLDSTATE_HELLFIRE_OVERLOOK_NEUTRAL, WORLDSTATE_HELLFIRE_BROKENHILL_NEUTRAL }; // updates clients visual counter, and adds the buffs to players if needed HEARTHSTONE_INLINE void UpdateTowerCount(shared_ptr<MapMgr> mgr) { if(!mgr) return; mgr->GetStateManager().UpdateWorldState(WORLDSTATE_HELLFIRE_ALLIANCE_TOWERS_CONTROLLED, g_allianceTowers); mgr->GetStateManager().UpdateWorldState(WORLDSTATE_HELLFIRE_HORDE_TOWERS_CONTROLLED, g_hordeTowers); if(g_superiorTeam == 0 && g_allianceTowers != 3) { mgr->RemovePositiveAuraFromPlayers(0, HELLFIRE_SUPERORITY_ALLIANCE); g_superiorTeam = -1; } if(g_superiorTeam == 1 && g_hordeTowers != 3) { mgr->RemovePositiveAuraFromPlayers(1, HELLFIRE_SUPERORITY_HORDE); g_superiorTeam = -1; } if(g_allianceTowers == 3 && g_superiorTeam != 0) { g_superiorTeam = 0; mgr->CastSpellOnPlayers(0, HELLFIRE_SUPERORITY_ALLIANCE); } if(g_hordeTowers == 3 && g_superiorTeam != 1) { g_superiorTeam = 1; mgr->CastSpellOnPlayers(1, HELLFIRE_SUPERORITY_HORDE); } } enum BannerStatus { BANNER_STATUS_NEUTRAL = 0, BANNER_STATUS_ALLIANCE = 1, BANNER_STATUS_HORDE = 2, }; class HellfirePeninsulaBannerAI : public GameObjectAIScript { map<uint32, uint32> StoredPlayers; uint32 Status; const char* ControlPointName; uint32 towerid; uint32 m_bannerStatus; public: GameObjectPointer pBanner; HellfirePeninsulaBannerAI(GameObjectPointer go) : GameObjectAIScript(go) { m_bannerStatus = BANNER_STATUS_NEUTRAL; Status = 50; switch(go->GetEntry()) { case TOWER_WEST: ControlPointName = "The Stadium"; towerid = TOWER_STADIUM; break; case TOWER_NORTH: ControlPointName = "The Overlook"; towerid = TOWER_OVERLOOK; break; case TOWER_SOUTH: ControlPointName = "Broken Hill"; towerid = TOWER_BROKENHILL; break; default: ControlPointName = "Unknown"; break; } } void AIUpdate() { uint32 plrcounts[2] = { 0, 0 }; // details: // loop through inrange players, for new ones, send the enable CP worldstate. // the value of the map is a timestamp of the last update, to avoid cpu time wasted // doing lookups of objects that have already been updated unordered_set<PlayerPointer>::iterator itr = _gameobject->GetInRangePlayerSetBegin(); unordered_set<PlayerPointer>::iterator itrend = _gameobject->GetInRangePlayerSetEnd(); map<uint32, uint32>::iterator it2, it3; uint32 timeptr = (uint32)UNIXTIME; bool in_range; bool is_valid; PlayerPointer plr = NULLPLR; for(; itr != itrend; ++itr) { if(!(*itr)->IsPvPFlagged() || (*itr)->InStealth()) is_valid = false; else is_valid = true; in_range = (_gameobject->GetDistance2dSq((*itr)) <= BANNER_RANGE) ? true : false; it2 = StoredPlayers.find((*itr)->GetLowGUID()); if(it2 == StoredPlayers.end()) { // new player :) if(in_range) { (*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_DISPLAY, 1); (*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_VALUE, Status); StoredPlayers.insert(make_pair((*itr)->GetLowGUID(), timeptr)); if(is_valid) plrcounts[(*itr)->GetTeam()]++; } } else { // oldie if(!in_range) { (*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_DISPLAY, 0); StoredPlayers.erase(it2); } else { (*itr)->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_VALUE, Status); it2->second = timeptr; if(is_valid) plrcounts[(*itr)->GetTeam()]++; } } } // handle stuff for the last tick if(Status == 100 && m_bannerStatus != BANNER_STATUS_ALLIANCE) { m_bannerStatus = BANNER_STATUS_ALLIANCE; SetArtKit(); // send message to everyone in the zone, has been captured by the Alliance _gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00%s has been taken by the Alliance!|r", ControlPointName); // tower update g_allianceTowers++; UpdateTowerCount(_gameobject->GetMapMgr()); // state update _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 0); _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_allianceStateFields[towerid], 1); // woot g_towerOwners[towerid] = 1; UpdateInDB(); } else if(Status == 0 && m_bannerStatus != BANNER_STATUS_HORDE) { m_bannerStatus = BANNER_STATUS_HORDE; SetArtKit(); // send message to everyone in the zone, has been captured by the Horde _gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00%s has been taken by the Horde!|r", ControlPointName); // tower update g_hordeTowers++; UpdateTowerCount(_gameobject->GetMapMgr()); // state update _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 0); _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_hordeStateFields[towerid], 1); // woot g_towerOwners[towerid] = 0; UpdateInDB(); } else if(m_bannerStatus != BANNER_STATUS_NEUTRAL) { // if the difference for the faction is >50, change to neutral if(m_bannerStatus == BANNER_STATUS_ALLIANCE && Status <= 50) { // send message: The Alliance has lost control of point xxx m_bannerStatus = BANNER_STATUS_NEUTRAL; SetArtKit(); g_allianceTowers--; UpdateTowerCount(_gameobject->GetMapMgr()); _gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00The Alliance have lost control of %s!|r", ControlPointName); // state update _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_allianceStateFields[towerid], 0); _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 1); // woot g_towerOwners[towerid] = -1; UpdateInDB(); } else if(m_bannerStatus == BANNER_STATUS_HORDE && Status >= 50) { // send message: The Alliance has lost control of point xxx m_bannerStatus = BANNER_STATUS_NEUTRAL; SetArtKit(); g_hordeTowers--; UpdateTowerCount(_gameobject->GetMapMgr()); _gameobject->GetMapMgr()->SendPvPCaptureMessage(ZONE_HELLFIRE_PENINSULA, ZONE_HELLFIRE_PENINSULA, "|cffffff00The Horde have lost control of %s!|r", ControlPointName); // state update _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_hordeStateFields[towerid], 0); _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 1); // woot g_towerOwners[towerid] = -1; UpdateInDB(); } } // send any out of range players the disable flag for(it2 = StoredPlayers.begin(); it2 != StoredPlayers.end();) { it3 = it2; ++it2; if(it3->second != timeptr) { plr = _gameobject->GetMapMgr()->GetPlayer(it3->first); // they WILL be out of range at this point. this is guaranteed. means they left the set rly quickly. if(plr != NULL) plr->SendWorldStateUpdate(WORLDSTATE_HELLFIRE_PVP_CAPTURE_BAR_DISPLAY, 0); StoredPlayers.erase(it3); } } // work out current status for next tick uint32 delta; if(plrcounts[0] > plrcounts[1]) { delta = plrcounts[0] - plrcounts[1]; delta *= CAPTURE_RATE; // cap it at 25 so the banner always gets removed. if(delta > 25) delta = 25; Status += delta; if(Status >= 100) Status = 100; } else if(plrcounts[1] > plrcounts[0]) { delta = plrcounts[1] - plrcounts[0]; delta *= CAPTURE_RATE; // cap it at 25 so the banner always gets removed. if(delta > 25) delta = 25; if(delta > Status) Status = 0; else Status -= delta; } } void SetArtKit() { // big towers static const uint32 artkits_towers[3][3] = { { 69, 67, 68 }, { 63, 62, 61 }, { 66, 65, 64 }, }; // flag poles static const uint32 artkits_flagpole[3] = { 3, 2, 1 }; // set away - we don't know the artkits anymore :((( //_gameobject->SetUInt32Value(GAMEOBJECT_ARTKIT, artkits_flagpole[m_bannerStatus]); //pBanner->SetUInt32Value(GAMEOBJECT_ARTKIT, artkits_towers[towerid][m_bannerStatus]); } void OnSpawn() { m_bannerStatus = BANNER_STATUS_NEUTRAL; // preloaded data, do we have any? if(g_towerOwners[towerid] == 1) { m_bannerStatus = BANNER_STATUS_HORDE; Status = 0; // state update _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_hordeStateFields[towerid], 1); _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 0); // countz g_hordeTowers++; UpdateTowerCount(_gameobject->GetMapMgr()); SetArtKit(); } else if(g_towerOwners[towerid] == 0) { m_bannerStatus = BANNER_STATUS_ALLIANCE; Status = 100; // state update _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_allianceStateFields[towerid], 1); _gameobject->GetMapMgr()->GetStateManager().UpdateWorldState(g_neutralStateFields[towerid], 0); // countz g_allianceTowers++; UpdateTowerCount(_gameobject->GetMapMgr()); SetArtKit(); } // start the event timer RegisterAIUpdateEvent(UPDATE_PERIOD); } ////////////////////////////////////////////////////////////////////////// // Save Data To DB ////////////////////////////////////////////////////////////////////////// void UpdateInDB() { static const char* fieldnames[TOWER_COUNT] = { "hellfire-stadium-status", "hellfire-overlook-status", "hellfire-brokenhill-status" }; const char* msg = "-1"; if(Status == 100) msg = "0"; else msg = "1"; WorldStateManager::SetPersistantSetting(fieldnames[towerid], msg); } }; ////////////////////////////////////////////////////////////////////////// // Zone Hook ////////////////////////////////////////////////////////////////////////// void ZoneHook(PlayerPointer plr, uint32 Zone, uint32 OldZone) { static uint32 spellids[2] = { HELLFIRE_SUPERORITY_ALLIANCE, HELLFIRE_SUPERORITY_HORDE }; if(Zone == ZONE_HELLFIRE_PENINSULA) { if(g_superiorTeam == plr->GetTeam()) plr->CastSpell(plr, dbcSpell.LookupEntry(spellids[plr->GetTeam()]), true); } else if(OldZone == ZONE_HELLFIRE_PENINSULA) { if(g_superiorTeam == plr->GetTeam()) plr->RemovePositiveAura(spellids[plr->GetTeam()]); } } ////////////////////////////////////////////////////////////////////////// // Object Spawn Data ////////////////////////////////////////////////////////////////////////// struct sgodata { uint32 entry; float posx; float posy; float posz; float facing; float orientation[4]; uint32 state; uint32 flags; uint32 faction; float scale; uint32 is_banner; }; void SpawnObjects(shared_ptr<MapMgr> pmgr) { if(!pmgr || pmgr->GetMapId() != 530) return; const static sgodata godata[] = { { 182173, -290.016f, 3702.42f, 56.6729f, 0.0349066f, 0, 0, 0.0174524f, 0.999848f, 1, 32, 0, 1 }, // stadium { 182174, -184.889f, 3476.93f, 38.205f, -0.0174535f, 0, 0, 0.00872664f, -0.999962f, 1, 32, 0, 1 }, // overlook { 182175, -471.462f, 3451.09f, 34.6432f, 0.174533f, 0, 0, 0.0871557f, 0.996195f, 1, 32, 0, 1 }, // brokenhill { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, }; const static sgodata godata_banner[] = { { 183515, -289.61f, 3696.83f, 75.9447f, 3.12414f, 0, 0, 0.999962f, 0.00872656f, 1, 32, 1375, 1 }, // stadium { 182525, -187.887f, 3459.38f, 60.0403f, -3.12414f, 0, 0, 0.999962f, -0.00872653f, 1, 32, 1375, 1 }, // overlook { 183514, -467.078f, 3528.17f, 64.7121f, 3.14159f, 0, 0, 1, -4.37114E-8f, 1, 32, 1375, 1 }, // brokenhill { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, }; uint32 i; const sgodata* p, *p2; for(i = 0; i < 3; ++i) { p = &godata[i]; p2 = &godata_banner[i]; GameObjectPointer pGo = pmgr->GetInterface()->SpawnGameObject(p->entry, p->posx, p->posy, p->posz, p->facing, false, 0, 0); if(pGo == NULL) continue; GameObjectPointer pGo2 = pmgr->GetInterface()->SpawnGameObject(p2->entry, p2->posx, p2->posy, p2->posz, p2->facing, false, 0, 0); if(pGo2 == NULL) continue; pGo->SetByte(GAMEOBJECT_BYTES_1, GAMEOBJECT_BYTES_STATE, p->state); pGo2->SetByte(GAMEOBJECT_BYTES_1, GAMEOBJECT_BYTES_STATE, p2->state); pGo->SetUInt32Value(GAMEOBJECT_FLAGS, p->flags); pGo2->SetUInt32Value(GAMEOBJECT_FLAGS, p2->flags); pGo->SetUInt32Value(GAMEOBJECT_FACTION, p->faction); pGo2->SetUInt32Value(GAMEOBJECT_FACTION, p2->faction); for(uint32 j = 0; j < 4; ++j) { pGo->SetFloatValue(GAMEOBJECT_ROTATION + j, p->orientation[j]); pGo2->SetFloatValue(GAMEOBJECT_ROTATION + j, p2->orientation[j]); } // now make his script pGo->SetScript(new HellfirePeninsulaBannerAI(pGo)); ((HellfirePeninsulaBannerAI*)pGo->GetScript())->pBanner = pGo2; pGo->PushToWorld(pmgr); pGo2->PushToWorld(pmgr); pGo->GetScript()->OnSpawn(); printf("Spawned gameobject entry %u for world pvp on hellfire.\n", p->entry); } } void SetupPvPHellfirePeninsula(ScriptMgr* mgr) { // register instance hooker mgr->register_hook(SERVER_HOOK_EVENT_ON_ZONE, (void*)&ZoneHook); mgr->register_hook(SERVER_HOOK_EVENT_ON_CONTINENT_CREATE, (void*)&SpawnObjects); // load data const string tstadium = WorldStateManager::GetPersistantSetting("hellfire-stadium-status", "-1"); const string toverlook = WorldStateManager::GetPersistantSetting("hellfire-overlook-status", "-1"); const string tbrokenhill = WorldStateManager::GetPersistantSetting("hellfire-brokenhill-status", "-1"); g_towerOwners[TOWER_STADIUM] = atoi(tstadium.c_str()); g_towerOwners[TOWER_OVERLOOK] = atoi(toverlook.c_str()); g_towerOwners[TOWER_BROKENHILL] = atoi(tbrokenhill.c_str()); }
30.027723
174
0.672975
499453466
e985dab5ed0bb48e420189b274a354d982507df7
3,477
hpp
C++
src/entry_node.hpp
BrightTux/model_server
cdbeb464c78b161e5706490fc18b0a8cf16138fb
[ "Apache-2.0" ]
234
2020-04-24T22:09:49.000Z
2022-03-30T10:40:04.000Z
src/entry_node.hpp
BrightTux/model_server
cdbeb464c78b161e5706490fc18b0a8cf16138fb
[ "Apache-2.0" ]
199
2020-04-29T08:43:21.000Z
2022-03-29T09:05:52.000Z
src/entry_node.hpp
BrightTux/model_server
cdbeb464c78b161e5706490fc18b0a8cf16138fb
[ "Apache-2.0" ]
80
2020-04-29T14:54:41.000Z
2022-03-30T14:50:29.000Z
//***************************************************************************** // Copyright 2020 Intel Corporation // // 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. //***************************************************************************** #pragma once #include <memory> #include <optional> #include <string> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wall" #include "tensorflow_serving/apis/prediction_service.grpc.pb.h" #pragma GCC diagnostic pop #include "logging.hpp" #include "node.hpp" #include "tensorinfo.hpp" namespace ovms { const std::string ENTRY_NODE_NAME = "request"; class EntryNode : public Node { const tensorflow::serving::PredictRequest* request; const tensor_map_t inputsInfo; public: EntryNode(const tensorflow::serving::PredictRequest* request, const tensor_map_t& inputsInfo, std::optional<uint32_t> demultiplyCount = std::nullopt) : Node(ENTRY_NODE_NAME, demultiplyCount), request(request), inputsInfo(inputsInfo) {} Status execute(session_key_t sessionId, PipelineEventQueue& notifyEndQueue) override; Status fetchResults(NodeSession& nodeSession, SessionResults& nodeSessionOutputs) override; protected: Status fetchResults(BlobMap& outputs); Status createShardedBlob(InferenceEngine::Blob::Ptr& dividedBlob, const InferenceEngine::TensorDesc& dividedBlobDesc, InferenceEngine::Blob::Ptr blob, size_t i, size_t step, const NodeSessionMetadata& metadata, const std::string blobName) override; public: // Entry nodes have no dependency void addDependency(Node&, const Aliases&) override { throw std::logic_error("This node cannot have dependency"); } Status isInputBinary(const std::string& name, bool& isBinary) const; const Status validateNumberOfInputs(const tensorflow::serving::PredictRequest* request, const size_t expectedNumberOfInputs); const Status checkIfShapeValuesNegative(const tensorflow::TensorProto& requestInput); const Status validateNumberOfBinaryInputShapeDimensions(const tensorflow::TensorProto& requestInput); const bool checkBinaryInputBatchSizeMismatch(const ovms::TensorInfo& networkInput, const tensorflow::TensorProto& requestInput); const Status validatePrecision(const ovms::TensorInfo& networkInput, const tensorflow::TensorProto& requestInput); const Status validateNumberOfShapeDimensions(const ovms::TensorInfo& networkInput, const tensorflow::TensorProto& requestInput); const bool checkBatchSizeMismatch(const ovms::TensorInfo& networkInput, const tensorflow::TensorProto& requestInput); const bool checkShapeMismatch(const ovms::TensorInfo& networkInput, const tensorflow::TensorProto& requestInput); const Status validateTensorContentSize(const ovms::TensorInfo& networkInput, const tensorflow::TensorProto& requestInput); const Status validate(); }; } // namespace ovms
38.208791
252
0.724475
BrightTux
e985df3717495afbf993ed59fe2ec49ffdcd2273
1,542
cpp
C++
test/gcc/harden.cpp
triton/cc-wrapper
4be147e091897efc080691567034127dfafd75b9
[ "Apache-2.0" ]
1
2018-09-27T05:08:35.000Z
2018-09-27T05:08:35.000Z
test/gcc/harden.cpp
triton/cc-wrapper
4be147e091897efc080691567034127dfafd75b9
[ "Apache-2.0" ]
null
null
null
test/gcc/harden.cpp
triton/cc-wrapper
4be147e091897efc080691567034127dfafd75b9
[ "Apache-2.0" ]
3
2017-12-24T22:07:05.000Z
2020-11-26T01:20:16.000Z
#include <catch2/catch.hpp> #include <gcc/harden.hpp> namespace cc_wrapper { namespace gcc { namespace harden { TEST_CASE("Enabled flags", "[isValidFlag]") { Env env; env.position_independent = true; env.optimize = true; CHECK(isValidFlag("-Wl,-rpath", env)); CHECK(isValidFlag("-c", env)); CHECK(isValidFlag("-o", env)); CHECK(isValidFlag("main.o", env)); CHECK(!isValidFlag("-fPIC", env)); CHECK(!isValidFlag("-fpic", env)); CHECK(!isValidFlag("-fPIE", env)); CHECK(!isValidFlag("-no-pie", env)); CHECK(!isValidFlag("-pie", env)); CHECK(!isValidFlag("-O0", env)); CHECK(!isValidFlag("-Ofast", env)); CHECK(!isValidFlag("-Os", env)); CHECK(isValidFlag("-O3", env)); CHECK(!isValidFlag("-march=native", env)); CHECK(!isValidFlag("-mtune=native", env)); } TEST_CASE("Disabled Flags", "[isValidFlag]") { Env env; env.position_independent = false; env.optimize = false; CHECK(isValidFlag("-Wl,-rpath", env)); CHECK(isValidFlag("-c", env)); CHECK(isValidFlag("-o", env)); CHECK(isValidFlag("main.o", env)); CHECK(isValidFlag("-fPIC", env)); CHECK(isValidFlag("-fpic", env)); CHECK(isValidFlag("-fPIE", env)); CHECK(isValidFlag("-no-pie", env)); CHECK(isValidFlag("-pie", env)); CHECK(isValidFlag("-O0", env)); CHECK(isValidFlag("-Ofast", env)); CHECK(isValidFlag("-Os", env)); CHECK(isValidFlag("-O3", env)); CHECK(!isValidFlag("-march=native", env)); CHECK(!isValidFlag("-mtune=native", env)); } } // namespace harden } // namespace gcc } // namespace cc_wrapper
27.535714
46
0.64786
triton
e986e6e516b91e5a862174b3c1cfefcddd86ebfd
625
cpp
C++
ims/src/v2/model/BatchAddOrDeleteTagsResponse.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
ims/src/v2/model/BatchAddOrDeleteTagsResponse.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
ims/src/v2/model/BatchAddOrDeleteTagsResponse.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/ims/v2/model/BatchAddOrDeleteTagsResponse.h" namespace HuaweiCloud { namespace Sdk { namespace Ims { namespace V2 { namespace Model { BatchAddOrDeleteTagsResponse::BatchAddOrDeleteTagsResponse() { } BatchAddOrDeleteTagsResponse::~BatchAddOrDeleteTagsResponse() = default; void BatchAddOrDeleteTagsResponse::validate() { } web::json::value BatchAddOrDeleteTagsResponse::toJson() const { web::json::value val = web::json::value::object(); return val; } bool BatchAddOrDeleteTagsResponse::fromJson(const web::json::value& val) { bool ok = true; return ok; } } } } } }
13.297872
72
0.7296
yangzhaofeng
e99118ff9f0ba42e66e1309f734c6140d8c1e89c
481
hpp
C++
Engine/src/Engpch.hpp
Niels04/Engine
2bc0f8d65ffb0f29035edc16958c60826da7f535
[ "Apache-2.0" ]
null
null
null
Engine/src/Engpch.hpp
Niels04/Engine
2bc0f8d65ffb0f29035edc16958c60826da7f535
[ "Apache-2.0" ]
null
null
null
Engine/src/Engpch.hpp
Niels04/Engine
2bc0f8d65ffb0f29035edc16958c60826da7f535
[ "Apache-2.0" ]
null
null
null
#pragma once #include <iostream> #include <utility> #include <functional> #include <memory> #include <algorithm> #include <string> #include <vector> #include <map> #include <unordered_map> #include <unordered_set> #include <sstream> #include <fstream> #include <charconv> #include <stdarg.h> #include "Engine/Log.hpp" #include "Engine/datatypes/include.hpp" #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #ifdef ENG_PLATFORM_WINDOWS #include <windows.h> #endif
18.5
39
0.752599
Niels04
e9911a14829fb3f0971ba2f42b74ada70355319b
542
cpp
C++
dmoj/ecoo/13r1p1-take-a-number.cpp
ruar18/competitive-programming
f264675fab92bf27dce184dd65eb81e302381f96
[ "MIT" ]
null
null
null
dmoj/ecoo/13r1p1-take-a-number.cpp
ruar18/competitive-programming
f264675fab92bf27dce184dd65eb81e302381f96
[ "MIT" ]
null
null
null
dmoj/ecoo/13r1p1-take-a-number.cpp
ruar18/competitive-programming
f264675fab92bf27dce184dd65eb81e302381f96
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int N; cin >> N; string a; cin >> a; int late = 0, served = 0, nextN = N; while(a != "EOF") { if(a == "TAKE") { nextN = nextN == 999? 1 : nextN+1; late++; } else if(a == "SERVE") { served++; } else if(a == "CLOSE") { printf("%d %d %d\n", late, late-served, nextN); late = served = 0; } cin >> a; } return 0; }
17.483871
59
0.369004
ruar18
e994016064ae4dbd0beb089a5c48321369715214
5,975
cpp
C++
src/chapter_12_networking_and_services/imap_connection.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
src/chapter_12_networking_and_services/imap_connection.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
src/chapter_12_networking_and_services/imap_connection.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
#include "Chapter12_NetworkingAndServices/ImapConnection.h" #include "curlcpp/master/include/curl_easy.h" #include <algorithm> // transform #include <boost/algorithm/string.hpp> #include <iostream> // cout #include <iterator> // back_inserter #include <optional> #include <regex> // regex_match, smatch, sregex_iterator #include <sstream> // istringstream, ostringstream #include <string> // getline, stoull #include <string_view> #include <unordered_map> #include <vector> namespace rtc::imap { void imap_connection::setup_easy(curl::curl_easy& easy) const { easy.add<CURLOPT_PORT>(email_server_port); easy.add<CURLOPT_USERNAME>(username_.c_str()); easy.add<CURLOPT_PASSWORD>(password_.c_str()); easy.add<CURLOPT_USE_SSL>(CURLUSESSL_ALL); easy.add<CURLOPT_SSL_VERIFYPEER>(0L); easy.add<CURLOPT_SSL_VERIFYHOST>(0L); easy.add<CURLOPT_USERAGENT>("libcurl-agent/1.0"); } [[nodiscard]] auto imap_connection::parse_get_mailbox_folders_response(const std::string& response) const -> std::vector<std::string> { std::vector<std::string> ret{}; std::istringstream iss{ response }; std::string line{}; std::smatch matches{}; const std::regex pattern{ R"(\* LIST \([^\)]+\) \"[^"]+\" \"([^\\]+)\".*)" }; while (std::getline(iss, line)) { boost::algorithm::trim_right(line); if (std::regex_match(line, matches, pattern)) { ret.push_back(matches[1]); } } return ret; } [[nodiscard]] auto imap_connection::parse_get_unread_email_ids_response(std::string response) const -> std::vector<std::size_t> { std::vector<std::size_t> ret{}; std::smatch matches{}; boost::algorithm::trim_right(response); const std::regex response_pattern{ R"(\* SEARCH(?: \d+)+)" }; if (std::regex_match(response, matches, response_pattern)) { const std::regex id_pattern{ R"(\d+)" }; std::transform( std::sregex_iterator{ std::cbegin(response), std::cend(response), id_pattern }, std::sregex_iterator{}, std::back_inserter(ret), [](const std::smatch match) { return static_cast<size_t>(std::stoull(match.str())); } ); } return ret; } [[nodiscard]] auto imap_connection::parse_email_subject(const std::string& email) const -> std::optional<std::string> { std::optional<std::string> ret{}; std::istringstream iss{ email }; std::string line{}; std::smatch matches{}; const std::regex pattern{ R"(^Subject: .*$)" }; while (std::getline(iss, line)) { boost::algorithm::trim_right(line); if (std::regex_match(line, matches, pattern)) { ret = matches[0].str(); break; } } return ret; } imap_connection::imap_connection(email_server_provider_t provider, std::string_view username, std::string_view password) : provider_{ provider } , url_{ email_server_provider_to_url.at(provider_) } , username_{ username } , password_{ password } {} [[nodiscard]] auto imap_connection::get_mailbox_folders() const -> std::optional<std::vector<std::string>> { std::optional<std::vector<std::string>> ret{}; try { std::ostringstream oss{}; curl::curl_ios<std::ostringstream> writer{ oss }; curl::curl_easy easy{ writer }; setup_easy(easy); easy.add<CURLOPT_URL>(url_.c_str()); easy.perform(); ret = parse_get_mailbox_folders_response(oss.str()); } catch (const curl::curl_easy_exception& ex) { std::cout << "\tError: " << ex.what() << "\n"; } return ret; } [[nodiscard]] auto imap_connection::get_unread_email_ids(std::string_view folder) const -> std::optional<std::vector<size_t>> { std::optional<std::vector<size_t>> ret{}; try { std::ostringstream oss{}; curl::curl_ios<std::ostringstream> writer{ oss }; curl::curl_easy easy{ writer }; setup_easy(easy); std::ostringstream url_oss{}; url_oss << url_ << "/" << folder.data() << "/"; easy.add<CURLOPT_URL>(url_oss.str().c_str()); easy.add<CURLOPT_CUSTOMREQUEST>("SEARCH UNSEEN"); easy.perform(); ret = parse_get_unread_email_ids_response(oss.str()); } catch (const curl::curl_easy_exception& ex) { std::cout << "\tError: " << ex.what() << "\n"; } return ret; } [[nodiscard]] auto imap_connection::get_email(std::string_view folder, size_t id) const -> std::optional<std::string> { std::optional<std::string> ret{}; try { std::ostringstream oss{}; curl::curl_ios<std::ostringstream> writer{ oss }; curl::curl_easy easy{ writer }; setup_easy(easy); std::ostringstream url_oss{}; url_oss << url_ << "/" << folder.data() << "/;UID=" << id; easy.add<CURLOPT_URL>(url_oss.str().c_str()); easy.perform(); ret = oss.str(); } catch (const curl::curl_easy_exception& ex) { std::cout << "\tError: " << ex.what() << "\n"; } return ret; } [[nodiscard]] auto imap_connection::get_email_subject(std::string_view folder, size_t id) const -> std::optional<std::string> { std::optional<std::string> ret{}; auto email_opt{ get_email(folder, id) }; if (email_opt.has_value()) { ret = parse_email_subject(email_opt.value()); } return ret; } } // namespace rtc::imap
34.142857
137
0.567029
rturrado
e994fce4832b5e16f91fafc14f68612e7a2e253d
1,500
cpp
C++
GameModel.cpp
zubrim/monty_hall_problem
6e6dbdf4cddad4c84b81bd250fcfccc5d44bf35c
[ "MIT" ]
null
null
null
GameModel.cpp
zubrim/monty_hall_problem
6e6dbdf4cddad4c84b81bd250fcfccc5d44bf35c
[ "MIT" ]
null
null
null
GameModel.cpp
zubrim/monty_hall_problem
6e6dbdf4cddad4c84b81bd250fcfccc5d44bf35c
[ "MIT" ]
null
null
null
#include "GameModel.h" GameModel::GameModel() : gameEngine_(GameEngine()){ } GameModel::~GameModel(){} void GameModel::changeStateTo(GameEngineState state) { switch (state) { case GameEngineState::READY: gameEngine_.reset(); break; case GameEngineState::DOOR_ELIMINATED: gameEngine_.eliminateDoor(); break; case GameEngineState::QUIT: gameEngine_.quit(); break; } gameEngine_.print(); notifyUpdate(); } void GameModel::changeStateTo(GameEngineState state, int index) { switch (state) { case GameEngineState::FIRST_TRY_DONE: gameEngine_.doFirstTry(index); break; case GameEngineState::SECOND_TRY_DONE: gameEngine_.doSecondTry(index); break; } gameEngine_.print(); notifyUpdate(); } GameEngineState GameModel::getState() { return gameEngine_.getState(); } int GameModel::getNumberOfDoors() { return gameEngine_.getNumberOfDoors(); } std::string GameModel::getDoorContentText(int index) { switch (gameEngine_.getDoorContentByIndex(index)) { case Prize::CAR : return "CAR"; case Prize::GOAT : return "GOAT"; default: return "ERROR"; } }; std::string GameModel::getDoorStateText(int index) { switch (gameEngine_.getDoorStateByIndex(index)) { case DoorState::INITIAL: return "CLOSED"; case DoorState::PICKED: return "PICKED"; case DoorState::ELIMINATED: return "ELIMINATED"; default: return "ERROR"; } }; DoorState GameModel::getDoorState(int index) { return gameEngine_.getDoorStateByIndex(index); }; bool GameModel::isCarWon() { return gameEngine_.isCarWon(); }
25.423729
96
0.752
zubrim
e99992d4399dec01b531f4f57c1d46846f3305a6
401
hpp
C++
src/supermarx/data/karluser.hpp
Supermarx/common
bb1aaaef4486d6c1089193824fde4533de150b4d
[ "MIT" ]
null
null
null
src/supermarx/data/karluser.hpp
Supermarx/common
bb1aaaef4486d6c1089193824fde4533de150b4d
[ "MIT" ]
null
null
null
src/supermarx/data/karluser.hpp
Supermarx/common
bb1aaaef4486d6c1089193824fde4533de150b4d
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <supermarx/token.hpp> #include <boost/fusion/include/adapt_struct.hpp> namespace supermarx { namespace data { struct karluser { std::string name; token password_salt; token password_hashed; }; } } BOOST_FUSION_ADAPT_STRUCT( supermarx::data::karluser, (std::string, name) (supermarx::token, password_salt) (supermarx::token, password_hashed) )
13.366667
48
0.743142
Supermarx
e999dfe4c99873548ae45fe6a597d0375102cb71
252
cpp
C++
Maths/7_lcm.cpp
Simran2000-jpg/CPP-Programming
cad4f362252f8bde4afadf455ddd67a85aa70dba
[ "MIT" ]
30
2020-09-30T19:16:04.000Z
2022-02-20T14:28:13.000Z
Maths/7_lcm.cpp
Simran2000-jpg/CPP-Programming
cad4f362252f8bde4afadf455ddd67a85aa70dba
[ "MIT" ]
168
2020-09-30T19:52:42.000Z
2021-10-22T03:55:57.000Z
Maths/7_lcm.cpp
Simran2000-jpg/CPP-Programming
cad4f362252f8bde4afadf455ddd67a85aa70dba
[ "MIT" ]
123
2020-09-30T19:16:12.000Z
2021-11-12T18:49:18.000Z
// LCM of two numbers a and b is equal to (a*b)/gcd(a,b); #include <iostream> #include <algorithm> using namespace std; int lcm(int a, int b){ return a * b/(__gcd(a,b)); } int main(){ int a,b; cin>>a>>b; cout<<lcm(a,b)<<endl; }
14.823529
57
0.56746
Simran2000-jpg
e99fdfc22ec9dff53c79b8ec87e1d3dd07c00867
2,799
cxx
C++
source/code/core/tasks/private/task_thread_pool_win32.cxx
iceshard-engine/engine
4f2092af8d2d389ea72addc729d0c2c8d944c95c
[ "BSD-3-Clause-Clear" ]
39
2019-08-17T09:08:51.000Z
2022-02-13T10:14:19.000Z
source/code/core/tasks/private/task_thread_pool_win32.cxx
iceshard-engine/engine
4f2092af8d2d389ea72addc729d0c2c8d944c95c
[ "BSD-3-Clause-Clear" ]
63
2020-05-22T16:09:30.000Z
2022-01-21T14:24:05.000Z
source/code/core/tasks/private/task_thread_pool_win32.cxx
iceshard-engine/engine
4f2092af8d2d389ea72addc729d0c2c8d944c95c
[ "BSD-3-Clause-Clear" ]
null
null
null
#include <ice/task_thread_pool.hxx> #include <ice/os/windows.hxx> #if ISP_WINDOWS namespace ice { namespace detail { void threadpool_coroutine_work_callback( PTP_CALLBACK_INSTANCE instance, PVOID context, PTP_WORK work ) noexcept { ice::detail::ScheduleOperationData const* operation_data = reinterpret_cast<ice::detail::ScheduleOperationData*>(context); operation_data->_coroutine.resume(); CloseThreadpoolWork(work); } } // namespace detail class IceTaskThreadPool : public ice::TaskThreadPool { public: IceTaskThreadPool(ice::u32 thread_count) noexcept : _thread_count{ thread_count } , _native_threadpool{ } , _native_tp_callback{ } , _native_tp_group_cleanup{ } { _native_threadpool = CreateThreadpool(nullptr); SetThreadpoolThreadMinimum(_native_threadpool, ice::min(_thread_count, 2u)); SetThreadpoolThreadMaximum(_native_threadpool, _thread_count); InitializeThreadpoolEnvironment(&_native_tp_callback); SetThreadpoolCallbackPool(&_native_tp_callback, _native_threadpool); _native_tp_group_cleanup = CreateThreadpoolCleanupGroup(); SetThreadpoolCallbackCleanupGroup(&_native_tp_callback, _native_tp_group_cleanup, nullptr); } ~IceTaskThreadPool() noexcept override { //CloseThreadpoolTimer(_native_tp_timer); CloseThreadpoolCleanupGroupMembers(_native_tp_group_cleanup, true, nullptr); CloseThreadpoolCleanupGroup(_native_tp_group_cleanup); CloseThreadpool(_native_threadpool); } void schedule_internal( ScheduleOperation* op, ScheduleOperation::DataMemberType data_member ) noexcept override { ice::detail::ScheduleOperationData& data = op->*data_member; SubmitThreadpoolWork( CreateThreadpoolWork( detail::threadpool_coroutine_work_callback, &data, &_native_tp_callback ) ); } private: ice::u32 const _thread_count; PTP_POOL _native_threadpool; TP_CALLBACK_ENVIRON _native_tp_callback; PTP_CLEANUP_GROUP _native_tp_group_cleanup; std::atomic<ice::detail::ScheduleOperationData*> _head = nullptr; }; auto create_simple_threadpool( ice::Allocator& alloc, ice::u32 thread_count ) noexcept -> ice::UniquePtr<ice::TaskThreadPool> { return ice::make_unique<ice::TaskThreadPool, ice::IceTaskThreadPool>(alloc, thread_count); } } // namespace ice #endif
31.806818
134
0.642372
iceshard-engine
e9a0d3bba2720cb3bc93ac1ad81121afb5dc90bd
1,518
cpp
C++
Algorithm/Problem48/main.cpp
et16kr/ModernCppChallengeStudy
089cbfa2ef43f81001c986b569c4122793fcd268
[ "MIT" ]
null
null
null
Algorithm/Problem48/main.cpp
et16kr/ModernCppChallengeStudy
089cbfa2ef43f81001c986b569c4122793fcd268
[ "MIT" ]
null
null
null
Algorithm/Problem48/main.cpp
et16kr/ModernCppChallengeStudy
089cbfa2ef43f81001c986b569c4122793fcd268
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; void quickSort( int arr[], int left, int right ) { int i = left, j = right; int pivot = arr[(left + right) / 2]; int temp; do { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i<= j) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; } } while (i<= j); /* recursion */ if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } struct node { int num; int count; }; void solve( int * start, int size ) { int max = 1; node * num = new node [size]; int idx = 0; quickSort( start, 0, size - 1); num[idx].num = start[0]; num[idx].count = 1; for(int i = 1 ; i < size ; i++) { if ( num[idx].num == start[i] ) { num[idx].count++; if( num[idx].count > max ) { max = num[idx].count; } } else { num[++idx].num = start[i]; num[idx].count = 1; } } for(int i = 0 ; i <= idx ; i++ ) { if ( num[i].count == max ) { cout << "{" << num[i].num << ", " << num[i].count << "}" << endl; } } } int main(int argc, char* argv[]) { int arr[] = {1,1,3,5,8,13,3,5,8,8,5}; solve(arr,11); return 0; }
18.071429
77
0.387352
et16kr
e9a4cb96c8f548432507409740524c201692143a
3,144
hpp
C++
src/pca9685/pca9685.hpp
daniel-blake/piio-server
fc0d9306343518c865c9bd1fb96fd70b693aaab1
[ "MIT" ]
null
null
null
src/pca9685/pca9685.hpp
daniel-blake/piio-server
fc0d9306343518c865c9bd1fb96fd70b693aaab1
[ "MIT" ]
null
null
null
src/pca9685/pca9685.hpp
daniel-blake/piio-server
fc0d9306343518c865c9bd1fb96fd70b693aaab1
[ "MIT" ]
null
null
null
#ifndef __PCA9685_H_ #define __PCA9685_H_ #include "../exception/baseexceptions.hpp" #include "../thread/thread.hpp" #include <stdint.h> /*! \file MCP23017 interface functions. Header file. */ /************************************ * * * MAIN CLASS * * * *************************************/ class Pca9685 : Thread { public: // Structure for IO Configuration //! \typedef Pca9685Config Structure containing hardware configuration for the MCP23017 class Pca9685Config { friend class Pca9685; // Allow public: enum OutNotEnabledMode { OutputLow = 0, OutputHigh = 1, OutputHighZ = 2 }; enum OutputDriveType { OpenDrain = 0, TotemPole = 1}; public: // Mode2 bool Invert; /*!< Invert output logic state, Default: false*/ bool OutputChangeOnAck; /*!< Change outputs on Ack instead of stop command, Default: false */ OutputDriveType OutputDrive; /*!< Type of output driver, Default: TotemPole*/ OutNotEnabledMode OutNotEnabled; /*!< Status of ouputs when /OE = 1, Default: OutputLow */ // Mode1 bool ExtClk; // Prescale uint32_t OscillatorClock; uint16_t Frequency; Pca9685Config(); uint8_t getMode1(); /*!< parse into usable uint8_t */ uint8_t getMode2(); /*!< parse into usable uint8_t */ uint8_t getPrescaler(); /*!< parse into usable uint8_t prescaler value */ uint16_t getActualFrequency(); /*!< return actual frequency used */ void setMode1(uint8_t); /*!< parse from read uint8_t */ void setMode2(uint8_t);/*!< parse from read uint8_t */ private: // Allow this only to be set by friend class Pca9685 // Mode1 bool Restart; bool AutoIncrement; bool Sleep; // Mode 2 bool Sub1; bool Sub2; bool Sub3; bool AllCall; double round(double number); }; private: uint8_t adr; // I2C Address of the IO expander chip int fp; // File pointer for the I2C connection Pca9685Config config; // Initial configuration of the chip uint8_t tryI2CRead8 (uint8_t reg); void tryI2CWrite8(uint8_t reg, uint8_t value); void tryI2CMaskedWrite8(uint8_t reg, uint8_t value, uint8_t mask); uint16_t tryI2CRead16(uint8_t reg); void tryI2CWrite16(uint8_t reg, uint16_t value); void tryI2CMaskedWrite16(uint8_t reg, uint16_t value, uint16_t mask); void muteI2CMaskedWrite16(uint8_t reg, uint16_t value, uint16_t mask); public: //! Open a new connection to the PCA9685 device, and initialize it. /*! \param adr The I2C address of the IC to connect to \param config Configuration for the IC */ Pca9685( uint8_t adr, Pca9685Config config); ~Pca9685(); /************************************ * * * REGULAR I/O FUNCTIONS * * * ************************************/ //! Set set new void setValue(uint8_t pin, uint16_t off, uint16_t on); //! Get current on time of the PWM uint16_t getOnValue(uint8_t pin); //! Get current off time of the PWM uint16_t getOffValue(uint8_t pin); }; #endif
28.071429
95
0.619275
daniel-blake
e9a7d2df484de4d8079fc656362f8832b5e21645
5,432
cpp
C++
SDK/ARKSurvivalEvolved_ProjSpaceDolphinChargedLaser0_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_ProjSpaceDolphinChargedLaser0_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_ProjSpaceDolphinChargedLaser0_functions.cpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_ProjSpaceDolphinChargedLaser0_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.GetExtraTriggerExplosionOffsetForTarget // () // Parameters: // float Return (Parm, OutParm, ZeroConstructor, IsPlainOldData) void AProjSpaceDolphinChargedLaser0_C::GetExtraTriggerExplosionOffsetForTarget(float* Return) { static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.GetExtraTriggerExplosionOffsetForTarget"); AProjSpaceDolphinChargedLaser0_C_GetExtraTriggerExplosionOffsetForTarget_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Return != nullptr) *Return = params.Return; } // Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveDestroyed // () void AProjSpaceDolphinChargedLaser0_C::ReceiveDestroyed() { static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveDestroyed"); AProjSpaceDolphinChargedLaser0_C_ReceiveDestroyed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.OnExplode // () // Parameters: // struct FHitResult Result (Parm, OutParm, ReferenceParm) void AProjSpaceDolphinChargedLaser0_C::OnExplode(struct FHitResult* Result) { static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.OnExplode"); AProjSpaceDolphinChargedLaser0_C_OnExplode_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (Result != nullptr) *Result = params.Result; } // Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.BPIgnoreRadialDamageVictim // () // Parameters: // class AActor** Victim (Parm, ZeroConstructor, IsPlainOldData) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) bool AProjSpaceDolphinChargedLaser0_C::BPIgnoreRadialDamageVictim(class AActor** Victim) { static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.BPIgnoreRadialDamageVictim"); AProjSpaceDolphinChargedLaser0_C_BPIgnoreRadialDamageVictim_Params params; params.Victim = Victim; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.UserConstructionScript // () void AProjSpaceDolphinChargedLaser0_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.UserConstructionScript"); AProjSpaceDolphinChargedLaser0_C_UserConstructionScript_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveTick // () // Parameters: // float* DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData) void AProjSpaceDolphinChargedLaser0_C::ReceiveTick(float* DeltaSeconds) { static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveTick"); AProjSpaceDolphinChargedLaser0_C_ReceiveTick_Params params; params.DeltaSeconds = DeltaSeconds; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveBeginPlay // () void AProjSpaceDolphinChargedLaser0_C::ReceiveBeginPlay() { static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ReceiveBeginPlay"); AProjSpaceDolphinChargedLaser0_C_ReceiveBeginPlay_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ExecuteUbergraph_ProjSpaceDolphinChargedLaser0 // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void AProjSpaceDolphinChargedLaser0_C::ExecuteUbergraph_ProjSpaceDolphinChargedLaser0(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function ProjSpaceDolphinChargedLaser0.ProjSpaceDolphinChargedLaser0_C.ExecuteUbergraph_ProjSpaceDolphinChargedLaser0"); AProjSpaceDolphinChargedLaser0_C_ExecuteUbergraph_ProjSpaceDolphinChargedLaser0_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
30.516854
170
0.761782
2bite
e9be7fc767e8537d66c0aa0b4fc2a22efeb9ad38
2,911
hpp
C++
src/cpu/cpu.hpp
Tunacan427/FishOS
86a173e8c423e96e70dfc624b5738e1313b0b130
[ "MIT" ]
null
null
null
src/cpu/cpu.hpp
Tunacan427/FishOS
86a173e8c423e96e70dfc624b5738e1313b0b130
[ "MIT" ]
null
null
null
src/cpu/cpu.hpp
Tunacan427/FishOS
86a173e8c423e96e70dfc624b5738e1313b0b130
[ "MIT" ]
null
null
null
#pragma once #include <kstd/types.hpp> #include <panic.hpp> namespace cpu { static inline void cli() { asm volatile("cli"); } static inline void sti() { asm volatile("sti"); } static inline void cpuid(u32 leaf, u32 subleaf, u32 *eax, u32 *ebx, u32 *ecx, u32 *edx) { asm volatile("cpuid" : "=a" (*eax), "=b" (*ebx), "=c" (*ecx), "=d" (*edx) : "a" (leaf), "c" (subleaf)); } static inline u64 read_msr(u32 msr) { volatile u32 lo, hi; asm volatile("rdmsr" : "=a" (lo), "=d" (hi) : "c" (msr)); return ((u64)hi << 32) | lo; } static inline void write_msr(u32 msr, u64 val) { volatile u32 lo = val & 0xFFFFFFFF; volatile u32 hi = val >> 32; asm volatile("wrmsr" : : "a" (lo), "d" (hi), "c" (msr)); } static inline void write_cr3(u64 cr3) { asm volatile("mov %0, %%cr3" : : "r" (cr3)); } static inline void write_cr4(u64 cr4) { asm volatile("mov %0, %%cr4" : : "r" (cr4)); } static inline u64 read_cr4() { volatile u64 cr4; asm volatile("mov %%cr4, %0" : "=r" (cr4)); return cr4; } static inline u64 read_cr2() { volatile u64 cr2; asm volatile("mov %%cr2, %0" : "=r" (cr2)); return cr2; } static inline void invlpg(void *m) { asm volatile("invlpg (%0)" : : "r" (m) : "memory"); } template<kstd::Integral T> static inline T bswap(T val) { volatile T result; asm volatile("bswap %0" : "=r" (result) : "r" (val)); return result; } template<kstd::Integral T> static inline void out(const u16 port, const T val) { panic("cpu::out must be used with u8, u16, or u32"); } template<> inline void out<u8>(const u16 port, const u8 val) { asm volatile("outb %0, %1" : : "a" (val), "Nd" (port)); } template<> inline void out<u16>(const u16 port, const u16 val) { asm volatile("outw %0, %1" : : "a" (val), "Nd" (port)); } template<> inline void out<u32>(const u16 port, const u32 val) { asm volatile("outl %0, %1" : : "a" (val), "Nd" (port)); } template<kstd::Integral T> static inline T in(const u16 port) { panic("cpu::in must be used with u8, u16, or u32"); } template<> inline u8 in<u8>(const u16 port) { volatile u8 ret; asm volatile("inb %1, %0" : "=a" (ret) : "Nd" (port)); return ret; } template<> inline u16 in<u16>(const u16 port) { volatile u16 ret; asm volatile("inw %1, %0" : "=a" (ret) : "Nd" (port)); return ret; } template<> inline u32 in<u32>(const u16 port) { volatile u32 ret; asm volatile("inl %1, %0" : "=a" (ret) : "Nd" (port)); return ret; } static inline void io_wait() { out<u8>(0x80, 0); } }
26.463636
111
0.512195
Tunacan427
e9c44d780609a6b5ea7a921e72bf1d3dab9d2620
5,333
cc
C++
src/AMOS/msgtest.cc
sagrudd/amos
47643a1d238bff83421892cb74daaf6fff8d9548
[ "Artistic-1.0" ]
10
2015-03-20T18:25:56.000Z
2020-06-02T22:00:08.000Z
src/AMOS/msgtest.cc
sagrudd/amos
47643a1d238bff83421892cb74daaf6fff8d9548
[ "Artistic-1.0" ]
5
2015-05-14T17:51:20.000Z
2020-07-19T04:17:47.000Z
src/AMOS/msgtest.cc
sagrudd/amos
47643a1d238bff83421892cb74daaf6fff8d9548
[ "Artistic-1.0" ]
10
2015-05-17T16:01:23.000Z
2020-05-20T08:13:43.000Z
#include "foundation_AMOS.hh" #include <fstream> #include <ctime> using namespace std; using namespace AMOS; #define ITERS 500000 int main (int argc, char ** argv) { Message_t msg; Read_t red; Contig_t ctg; double loopa = 0; double loopb = 0; clock_t clocka, clockb; vector<Tile_t> tlevec; Tile_t tle; tle . source = 33396; tle . offset = 512; tle . range = Range_t (12,832); tle . gaps . push_back (12); tle . gaps . push_back (30); tle . gaps . push_back (337); tle . gaps . push_back (508); tle . gaps . push_back (514); tle . gaps . push_back (789); for ( int j = 0; j < 200; j ++ ) tlevec . push_back (tle); try { red . setIID (1); red . setEID ("str2"); red . setComment ("GBRAA01TF"); red . setSequence ("CCTTTGTGCTGGAAGGTGAATGCGGTGCGGCTGGTAACGGGCCGCGCGGGCGCAATCGGCGTCGTGATGGGCCGCAACAGCGAGTTTCACTTTGCCGAATTCATGCGCGGCATGGCCGAACGGCTGGGGCAGGACGAAGTGGACATTCTCGTCAGCCCCACCTCGCCGACCGGCAATGACGACGAGGTGCAGCTTTGTCACCGGCTGGCAACGAGCGGACGGGTGGATGCCGTTATCGTCACTTCCCCCAGGCCGAATGATGAACGCATCCGCATGTTGCACAAGCTCGGCATGCCGTTTCTGGTCCACGGGCGTTCGCAGATCGACATTCCCCATGCATGGCTTGATATCGACAATGAGAGCGCGGTCTATCATTCCACCGCACATCTGCTCGATCTTGGCCACAAGCGGATTGCGATGATCAACGGGCGCCATGGCTTCACCTTCTCGCTGCACCGCGACGCTGGCTATCGTAAGGCGCTTGAAAGCCGGGGAATCGACTTTGATCCCGACCTGGTGGAACATGGCGATTTCACCGATGAAATCGGCTATTGCCTCGCCCGCAAGCTTCTGGAACGCAATCCACGTCCAACGGCATTCGTCGCAGGCTCCATGATGACCGCGCTCGGCATCTACCGTGCCGCCCGCTCCTTCGGCCTTACGATCGGCAAGGATATTTCCGTCATCGCCCATGACGACGTGATCTCGTTCCTCAGCGCCGGTAATATGGGTGCCGTCGCTGACTGCGACACGCTCTTCAATGCGCGCGGCTGGCAAGCGATGCGCCGACCTTTTGATGGATATCCTCGATGGGCGCGCGCCCACCGAAATCCA", "9878<?JQONBB77:=EGMPDOHRNSTSTSTRSSSREMRSSRSSRSQSSLQLLLLMPPPRRSSSRRRRSSSRSSSRRSRRRRSRIJJJONLTTTTRRROLLLLLLTTTTTTTRRRRPPPSRRSTTTRSRRRSPOLOOLOSSSSRSSRSRPRPPPSPSTSTSQSQTRURSSSSSTTTTRRRSRRSRSSSURRRRSWSSRRRSSTSRRTTTTTTTTTPPSRPPSTTTTRSRUSSSSUSPPPPRSQRTTTTSSSRRRRRTRRSTRTTTRTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTPSPPPPPRRRTTTTTRSSSSRRSRRSTSTTTTTTTTRTTRSSSTRSRSRRSSSTTTRSSRSSSUSSQSSRSSSSRRRRRSRRTRTSRTSURTTTTTRSSSSSSTRTRRRSSRSSRTSPSPPPRTRRSSRRSTRRRSSRRRRTTTRRRUSRSSSTRSSSSRRLLLLOLNOTTTSRRRRSSSTTTTTTTTTTTWRRPPPPPPSTTTTWPPMSTPTTTTTTTTSTSRSRSSTTRSSSSTTTTTTTTPPPPKPPSRSSSTSSSSTSSRRSSSTTTTTRRSSTTSSRSSSSSTTTTTTTTTTTRTTTSRSSSSSTTTTRRRSSPPSPPPTTTTSRRPORSRPPPPLPPSSSSTTSSRSSSRPPNSSQRTTTTTSSPKKGMNPSSQSSRSSSSQLLIL?HSTQPSSPLRSQSSRSUQSMRSSUPRLLPGEPPSNMRPTYRRQPMMGGPMLQE?CENRNCRSLQRNTTKTKLQTXSRSRTTPRQXISRCONK<?IDTPPPDDIR?B<LALBDL@;LQQLCH?E=@IC<9F9?I;9;=8"); red . setFragment (1); red . setClearRange (Range_t(16,823)); red . setVectorClearRange (Range_t(16,823)); red . setQualityClearRange (Range_t(16,823)); ctg . setIID (1); ctg . setEID ("str2"); ctg . setComment ("big contig"); ctg . setSequence ("CCTTTGTGCTGGAAGGTGAATGCGGTGCGGCTGGTAACGGGCCGCGCGGGCGCAATCGGCGTCGTGATGGGCCGCAACAGCGAGTTTCACTTTGCCGAATTCATGCGCGGCATGGCCGAACGGCTGGGGCAGGACGAAGTGGACATTCTCGTCAGCCCCACCTCGCCGACCGGCAATGACGACGAGGTGCAGCTTTGTCACCGGCTGGCAACGAGCGGACGGGTGGATGCCGTTATCGTCACTTCCCCCAGGCCGAATGATGAACGCATCCGCATGTTGCACAAGCTCGGCATGCCGTTTCTGGTCCACGGGCGTTCGCAGATCGACATTCCCCATGCATGGCTTGATATCGACAATGAGAGCGCGGTCTATCATTCCACCGCACATCTGCTCGATCTTGGCCACAAGCGGATTGCGATGATCAACGGGCGCCATGGCTTCACCTTCTCGCTGCACCGCGACGCTGGCTATCGTAAGGCGCTTGAAAGCCGGGGAATCGACTTTGATCCCGACCTGGTGGAACATGGCGATTTCACCGATGAAATCGGCTATTGCCTCGCCCGCAAGCTTCTGGAACGCAATCCACGTCCAACGGCATTCGTCGCAGGCTCCATGATGACCGCGCTCGGCATCTACCGTGCCGCCCGCTCCTTCGGCCTTACGATCGGCAAGGATATTTCCGTCATCGCCCATGACGACGTGATCTCGTTCCTCAGCGCCGGTAATATGGGTGCCGTCGCTGACTGCGACACGCTCTTCAATGCGCGCGGCTGGCAAGCGATGCGCCGACCTTTTGATGGATATCCTCGATGGGCGCGCGCCCACCGAAATCCA", "9878<?JQONBB77:=EGMPDOHRNSTSTSTRSSSREMRSSRSSRSQSSLQLLLLMPPPRRSSSRRRRSSSRSSSRRSRRRRSRIJJJONLTTTTRRROLLLLLLTTTTTTTRRRRPPPSRRSTTTRSRRRSPOLOOLOSSSSRSSRSRPRPPPSPSTSTSQSQTRURSSSSSTTTTRRRSRRSRSSSURRRRSWSSRRRSSTSRRTTTTTTTTTPPSRPPSTTTTRSRUSSSSUSPPPPRSQRTTTTSSSRRRRRTRRSTRTTTRTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTPSPPPPPRRRTTTTTRSSSSRRSRRSTSTTTTTTTTRTTRSSSTRSRSRRSSSTTTRSSRSSSUSSQSSRSSSSRRRRRSRRTRTSRTSURTTTTTRSSSSSSTRTRRRSSRSSRTSPSPPPRTRRSSRRSTRRRSSRRRRTTTRRRUSRSSSTRSSSSRRLLLLOLNOTTTSRRRRSSSTTTTTTTTTTTWRRPPPPPPSTTTTWPPMSTPTTTTTTTTSTSRSRSSTTRSSSSTTTTTTTTPPPPKPPSRSSSTSSSSTSSRRSSSTTTTTRRSSTTSSRSSSSSTTTTTTTTTTTRTTTSRSSSSSTTTTRRRSSPPSPPPTTTTSRRPORSRPPPPLPPSSSSTTSSRSSSRPPNSSQRTTTTTSSPKKGMNPSSQSSRSSSSQLLIL?HSTQPSSPLRSQSSRSUQSMRSSUPRLLPGEPPSNMRPTYRRQPMMGGPMLQE?CENRNCRSLQRNTTKTKLQTXSRSRTTPRQXISRCONK<?IDTPPPDDIR?B<LALBDL@;LQQLCH?E=@IC<9F9?I;9;=8"); ctg . setReadTiling (tlevec); clocka = clock( ); for ( int i = 0; i < ITERS; i ++ ) red . writeMessage (msg); clockb = clock( ); loopa = (double)(clockb - clocka); clocka = clock( ); for ( int i = 0; i < ITERS; i ++ ) red . readMessage (msg); clockb = clock( ); loopb = (double)(clockb - clocka); msg . setField ("eid", "hello"); msg . setField ("bla", "foo"); msg . write (cerr); Message_t::const_iterator mi; cerr << "\nField List\n"; for ( mi = msg . begin( ); mi != msg . end( ); ++ mi ) cerr << Decode (mi -> first) << endl; cerr << endl << "loopa: " << (double)loopa / CLOCKS_PER_SEC << " sec.\n" << "loopb: " << (double)loopb / CLOCKS_PER_SEC << " sec.\n" << "granu: " << CLOCKS_PER_SEC << " of a sec.\n"; } catch (Exception_t & e) { cerr << "ERROR: exception\n" << e; } return 0; }
59.921348
845
0.824864
sagrudd
8397256bd2d0a925f0e6c1a29152e1582cd95868
761
cpp
C++
stacks/Recursion/Factorial1.cpp
InamulRehman/DataStructures_and_Algorithms_Cplusplus
7fb5ca3e9313ef302c7ce9bac3bb9ec9016ab906
[ "MIT" ]
null
null
null
stacks/Recursion/Factorial1.cpp
InamulRehman/DataStructures_and_Algorithms_Cplusplus
7fb5ca3e9313ef302c7ce9bac3bb9ec9016ab906
[ "MIT" ]
null
null
null
stacks/Recursion/Factorial1.cpp
InamulRehman/DataStructures_and_Algorithms_Cplusplus
7fb5ca3e9313ef302c7ce9bac3bb9ec9016ab906
[ "MIT" ]
null
null
null
// calculating factorial using loop #include <iostream> using namespace std; class factorial { private: int fac; public: // function to calculate factorial int fact (int val) { fac = 1; if (val == 0) { return fac; } else { for(int i = fac; i <= val; i++ ) { fac = fac * i; } return fac; } } }; int main () { factorial obj; int val , result; cout << "Enter value to calculate factorial: "<< flush; cin >> val ; result = obj.fact(val); cout << "Factorial of " << val << " is " << result; return 0; }
15.530612
59
0.412615
InamulRehman
8398274554f23e9cb7aa54ac70e963a4059f5510
1,620
cpp
C++
src/ThreadPool.cpp
CaptainUnitaco/Clustered-Deferred-shading-in-Vulkan
08803777a20a010015958af8bd841147fc6b7fd6
[ "MIT" ]
3
2020-06-24T07:13:59.000Z
2020-10-22T03:49:15.000Z
src/ThreadPool.cpp
CaptainUnitaco/Clustered-Deferred-shading-in-Vulkan
08803777a20a010015958af8bd841147fc6b7fd6
[ "MIT" ]
null
null
null
src/ThreadPool.cpp
CaptainUnitaco/Clustered-Deferred-shading-in-Vulkan
08803777a20a010015958af8bd841147fc6b7fd6
[ "MIT" ]
null
null
null
/** * @file 'ThreadPool.cpp' * @brief Implementation of thread pool design pattern * @copyright The MIT license * @author Matej Karas */ #include "ThreadPool.h" Thread::Thread(size_t id) : mID(id) { mThread = std::thread(&Thread::run, this); } Thread::~Thread() { mDestroy = true; if (mThread.joinable()) { { std::lock_guard<std::mutex> lock(mWorkMutex); mWorkCondition.notify_one(); } mThread.join(); } } void Thread::run() { while(true) { { std::unique_lock<std::mutex> lock(mWorkMutex); mWorkCondition.wait(lock, [this]() { return mWork != nullptr || mDestroy; }); if (mDestroy) break; auto work = std::move(mWork); work(mID); } { std::lock_guard<std::mutex> lock(mWorkMutex); mFinished = true; mWorkCondition.notify_one(); } } } void Thread::addWork(ThreadFuncPtr work) { std::lock_guard<std::mutex> lock(mWorkMutex); mWork = std::move(work); mWorkCondition.notify_one(); } void Thread::wait() { std::unique_lock<std::mutex> lock(mWorkMutex); mWorkCondition.wait(lock, [this]() { return mFinished; }); mFinished = false; } ThreadPool::ThreadPool() { for (size_t i = 0; i < std::thread::hardware_concurrency(); i++) mThreads.emplace_back(std::make_unique<Thread>(i)); } void ThreadPool::addWorkMultiplex(const ThreadFuncPtr& work) { for (auto& thread : mThreads) thread->addWork(work); } void ThreadPool::addWork(std::vector<ThreadFuncPtr>&& work) { for (size_t i = 0; i < work.size(); i++) mThreads[i % mThreads.size()]->addWork(work[i]); } void ThreadPool::wait() { for (auto& thread : mThreads) thread->wait(); }
17.802198
80
0.656173
CaptainUnitaco
839c75e18a6aeab381fee29142df80c268967d3b
4,977
cpp
C++
ID3v2/source/ID3v2-Version.cpp
macmade/ID3v2
be8022a5ee94197a58710a55931aea7d89ae3f71
[ "MIT" ]
2
2018-12-15T22:30:58.000Z
2019-11-24T21:25:02.000Z
ID3v2/source/ID3v2-Version.cpp
macmade/ID3v2
be8022a5ee94197a58710a55931aea7d89ae3f71
[ "MIT" ]
null
null
null
ID3v2/source/ID3v2-Version.cpp
macmade/ID3v2
be8022a5ee94197a58710a55931aea7d89ae3f71
[ "MIT" ]
1
2018-01-22T13:09:06.000Z
2018-01-22T13:09:06.000Z
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2014 Jean-David Gadina - www.xs-labs.com / www.digidna.net * * 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. ******************************************************************************/ /*! * @header ID3v2-Tag.cpp * @copyright (c) 2014 - Jean-David Gadina - www.xs-labs.com / www.digidna.net * @abstract ID3v2 version */ #include <ID3v2.h> #include <sstream> namespace ID3v2 { class Version::IMPL { public: IMPL( void ); unsigned int major; unsigned int minor; unsigned int revision; }; Version::Version( unsigned int major, unsigned int minor, unsigned int revision ): impl( new IMPL ) { this->impl->major = major; this->impl->minor = minor; this->impl->revision = revision; } Version::Version( const Version & version ): impl( new IMPL ) { this->impl->major = version.impl->major; this->impl->minor = version.impl->minor; this->impl->revision = version.impl->revision; } Version::~Version( void ) { delete this->impl; } Version & Version::operator =( const Version & version ) { this->impl->major = version.impl->major; this->impl->minor = version.impl->minor; this->impl->revision = version.impl->revision; return *( this ); } bool Version::operator ==( const Version & version ) const { return this->GetMajor() == version.GetMajor() && this->GetMinor() == version.GetMinor() && this->GetRevision() == version.GetRevision(); } bool Version::operator !=( const Version & version ) const { return ( this->operator ==( version ) ) ? false : true; } bool Version::operator >=( const Version & version ) const { if( this->operator ==( version ) ) { return true; } return this->operator >( version ); } bool Version::operator <=( const Version & version ) const { if( this->operator ==( version ) ) { return true; } return this->operator <( version ); } bool Version::operator >( const Version & version ) const { if( this->GetMajor() > version.GetMajor() ) { return true; } if( this->GetMinor() > version.GetMinor() ) { return true; } if( this->GetRevision() > version.GetRevision() ) { return true; } return false; } bool Version::operator <( const Version & version ) const { if( this->GetMajor() < version.GetMajor() ) { return true; } if( this->GetMinor() < version.GetMinor() ) { return true; } if( this->GetRevision() < version.GetRevision() ) { return true; } return false; } std::string Version::GetStringValue( void ) const { std::stringstream ss; ss << this->impl->major; ss << "."; ss << this->impl->minor; ss << "."; ss << this->impl->revision; return ss.str(); } unsigned int Version::GetMajor( void ) const { return this->impl->major; } unsigned int Version::GetMinor( void ) const { return this->impl->minor; } unsigned int Version::GetRevision( void ) const { return this->impl->revision; } Version::IMPL::IMPL( void ) { this->major = 0; this->minor = 0; this->revision = 0; } }
27.65
144
0.53486
macmade
83a08cbb6a38c6b2cfbb6753f79b8600bc12c77e
1,737
cpp
C++
src/Receiver.cpp
NassimEzz/Projet_2A_SeriousGameAlgorithme
588eda6049d732f5908e2c0876b7363c9ff1fee3
[ "Unlicense", "MIT" ]
null
null
null
src/Receiver.cpp
NassimEzz/Projet_2A_SeriousGameAlgorithme
588eda6049d732f5908e2c0876b7363c9ff1fee3
[ "Unlicense", "MIT" ]
null
null
null
src/Receiver.cpp
NassimEzz/Projet_2A_SeriousGameAlgorithme
588eda6049d732f5908e2c0876b7363c9ff1fee3
[ "Unlicense", "MIT" ]
null
null
null
#include "Receiver.h" #include "Utils.h" Receiver::Receiver(const Point &position, const PictureInformer &emptyReceiverInformer, const std::string &wrongAnswerPicture, const std::string &lockedReceiverPicture) { _emptyReceiverPicture = emptyReceiverInformer.picturePath; _wrongAnswerPicture = wrongAnswerPicture; _lockedReceiverPicture = lockedReceiverPicture; _rect = {position.x, position.y, emptyReceiverInformer.getPictureWidth(), emptyReceiverInformer.getPictureHeight()}; _uniqIDDrag = 0; } void Receiver::drawMe(Window *window, bool isRCorrect) const { if (!isRCorrect) { window->drawPng(_rect.x, _rect.y, _wrongAnswerPicture); } else if (_uniqIDDrag != 0) { window->drawPng(_rect.x, _rect.y, _lockedReceiverPicture); } else { window->drawPng(_rect.x, _rect.y, _emptyReceiverPicture); } } bool Receiver::isAvailable(long dragUniqueId, int x, int y) { return ((isEmpty()) || (dragUniqueId == _uniqIDDrag)) && (_rect.isInRectangle(x, y)); } void Receiver::setReceiverContent(DraggableRectangle *instruction, unsigned int x, unsigned int y) { if (_rect.isInRectangle((int) x, (int) y)) { instruction->setMeInReceiver(_rect.x, _rect.y); _uniqIDDrag = instruction->getUniqueID(); _logicIDDrag = instruction->getLogicID(); } } bool Receiver::isOutOfReceiver(long dragUniqueId, unsigned int x, unsigned int y) { return (!(_rect.isInRectangle((int) x, (int) y)) && (dragUniqueId == _uniqIDDrag)); } int Receiver::getCurrentDragLogicID() const { return _logicIDDrag; } bool Receiver::isEmpty() const { return _uniqIDDrag == 0; } void Receiver::resetDrag() { _logicIDDrag = 0; _uniqIDDrag = 0; }
33.403846
120
0.699482
NassimEzz
83b2054ffda44c4fe78d01b862a24bde1ec71f02
3,821
cpp
C++
source/ContratException.cpp
fantome3/test1
6b28cbbe87110baa68ef22ed7aeba13f538fcaef
[ "MIT" ]
null
null
null
source/ContratException.cpp
fantome3/test1
6b28cbbe87110baa68ef22ed7aeba13f538fcaef
[ "MIT" ]
null
null
null
source/ContratException.cpp
fantome3/test1
6b28cbbe87110baa68ef22ed7aeba13f538fcaef
[ "MIT" ]
null
null
null
/** * \file ContratException.cpp * \brief Implantation de la classe ContratException et de ses héritiers * \author administrateur * \date 16 janvier 2014 * \version révisée balises Doxygen C++ normes H2014 */ #include "ContratException.h" #include <sstream> using namespace std; /** * \brief Constructeur de la classe de base ContratException * \param p_fichP chaîne de caractères représentant le fichier source dans lequel a eu lieu l'erreur * \param p_prmLigne un entier représentant la ligne où a eu lieu l'erreur * \param p_msgP Message décrivant l'erreur * \param p_exprP Test logique qui a échoué */ ContratException::ContratException(std::string p_fichP, unsigned int p_prmLigne, std::string p_exprP, std::string p_msgP) : logic_error(p_msgP), m_expression(p_exprP), m_fichier(p_fichP), m_ligne(p_prmLigne) { } /** * \brief Construit le texte complet relié à l'exception de contrat * \return une chaîne de caractères correspondant à l'exception */ std::string ContratException::reqTexteException() const { // --- Prépare le message ostringstream os; os << "Message : " << what() << endl; os << "Fichier : " << m_fichier << endl; os << "Ligne : " << m_ligne << endl; os << "Test : " << m_expression << endl; return os.str(); } /** * \brief Constructeur de la classe AssertionException \n * Le constructeur public AssertionException(...)initialise * sa classe de base ContratException. On n'a pas d'attribut local. Cette * classe est intéressante pour son TYPE lors du traitement des exceptions. * \param p_fichP chaîne de caractères représentant le fichier source dans lequel a eu lieu l'erreur * \param p_prmLigne un entier représentant la ligne où a eu lieu l'erreur * \param p_exprP Test logique qui a échoué * */ AssertionException::AssertionException(std::string p_fichP, unsigned int p_prmLigne, std::string p_exprP) : ContratException(p_fichP, p_prmLigne, p_exprP, "ERREUR D'ASSERTION") { } /** * \brief Constructeur de la classe PreconditionException en initialisant la classe de base ContratException. * La classe représente l'erreur de précondition dans la théorie du contrat. * \param p_fichP chaîne de caractères représentant le fichier source dans lequel a eu lieu l'erreur * \param p_prmLigne un entier représentant la ligne où a eu lieu l'erreur * \param p_exprP Test logique qui a échoué */ PreconditionException::PreconditionException(std::string p_fichP, unsigned int p_prmLigne, std::string p_exprP) : ContratException(p_fichP, p_prmLigne, p_exprP, "ERREUR DE PRECONDITION") { } /** * \brief Constructeur de la classe PostconditionException en initialisant la classe de base ContratException. * La classe représente des erreurs de postcondition dans la théorie du contrat. * \param p_fichP chaîne de caractères représentant le fichier source dans lequel a eu lieu l'erreur * \param p_prmLigne un entier représentant la ligne où a eu lieu l'erreur * \param p_exprP Test logique qui a échoué */ PostconditionException::PostconditionException(std::string p_fichP, unsigned int p_prmLigne, std::string p_exprP) : ContratException(p_fichP, p_prmLigne, p_exprP, "ERREUR DE POSTCONDITION") { } /** * \brief Constructeur de la classe InvariantException en initialisant la classe de base ContratException. * La classe représente des erreurs d'invariant dans la théorie du contrat. * \param p_fichP chaîne de caractères représentant le fichier source dans lequel a eu lieu l'erreur * \param p_prmLigne un entier représentant la ligne où a eu lieu l'erreur * \param p_exprP Test logique qui a échoué */ InvariantException::InvariantException(std::string p_fichP, unsigned int p_prmLigne, std::string p_exprP) : ContratException(p_fichP, p_prmLigne, p_exprP, "ERREUR D'INVARIANT") { }
41.086022
110
0.751636
fantome3
83b2ab4de7b7d92fb74840afe2843d4df7585395
290
cpp
C++
2000/60/2066.cpp
actium/timus
6231d9e7fd325cae36daf5ee2ec7e61381f04003
[ "Unlicense" ]
null
null
null
2000/60/2066.cpp
actium/timus
6231d9e7fd325cae36daf5ee2ec7e61381f04003
[ "Unlicense" ]
null
null
null
2000/60/2066.cpp
actium/timus
6231d9e7fd325cae36daf5ee2ec7e61381f04003
[ "Unlicense" ]
null
null
null
#include <algorithm> #include <iostream> int main() { int a, b, c; std::cin >> a >> b >> c; if (a > b) std::swap(a, b); if (b > c) std::swap(b, c); if (a > b) std::swap(a, b); std::cout << std::min({ a*b*c, a+b*c, a-b*c, a+b+c, a-b-c }) << '\n'; return 0; }
17.058824
73
0.441379
actium
83b8f3a485f00073195f9764c1e4982926097be8
2,992
hpp
C++
rap_kvv.hpp
linkdata/crap
1062cc4b42ae2a3dc4e7d61c19f2102f1557e180
[ "MIT" ]
null
null
null
rap_kvv.hpp
linkdata/crap
1062cc4b42ae2a3dc4e7d61c19f2102f1557e180
[ "MIT" ]
null
null
null
rap_kvv.hpp
linkdata/crap
1062cc4b42ae2a3dc4e7d61c19f2102f1557e180
[ "MIT" ]
null
null
null
#ifndef RAP_KVV_HPP #define RAP_KVV_HPP #include "rap.hpp" #include "rap_frame.h" #include "rap_reader.hpp" #include "rap_text.hpp" #include "rap_writer.hpp" #include <cassert> #include <cstdint> #include <string> #include <vector> namespace rap { class kvv { public: kvv() {} kvv(const kvv& other) : data_(other.data_) { } kvv(reader& r) { for (;;) { text key(r.read_text()); if (key.is_null()) break; data_.push_back(key); for (;;) { text val(r.read_text()); data_.push_back(val); if (val.is_null()) break; } } } size_t size() const { return data_.size(); } text at(size_t n) const { return data_.at(n); } size_t find(const char* key) const { size_t i = 0; while (i < data_.size()) { if (data_.at(i).is_null()) break; if (data_.at(i) == key) return i + 1; while (!data_.at(i).is_null()) ++i; } return 0; } const rap::writer& operator>>(const rap::writer& w) const { for (size_t i = 0; i < size(); ++i) w << at(i); w << text(); return w; } protected: std::vector<text> data_; }; class query : public kvv { public: query() : kvv() { } query(reader& r) : kvv(r) { } void render(string_t& out) const { char prefix = '?'; for (size_t i = 0; i < size(); ++i) { text key(at(i)); if (key.is_null()) break; for (;;) { if (++i >= size()) break; text val(at(i)); if (val.is_null()) break; out += prefix; key.render(out); prefix = '&'; if (!val.empty()) { out += '='; val.render(out); } } } } }; class headers : public kvv { public: headers() : kvv() { } headers(reader& r) : kvv(r) { } void render(string_t& out) const { for (size_t i = 0; i < size(); ++i) { text key(at(i)); if (key.is_null()) break; for (;;) { if (++i >= size()) break; text val(at(i)); if (val.is_null()) break; if (!val.empty()) { key.render(out); out += ": "; val.render(out); out += '\n'; } } } } }; inline const rap::writer& operator<<(const rap::writer& w, const rap::kvv& kvv) { return kvv >> w; } } // namespace rap #endif // RAP_KVV_HPP
20.353741
61
0.389372
linkdata
83b905ae548cea507540063f5574333cca9bc799
909
cpp
C++
IssueTest/test.cpp
vvck/QXlsx
281fcb41ec186167ee3bbbe57572746f3c9c09be
[ "MIT" ]
547
2019-01-14T18:38:08.000Z
2022-03-31T07:30:00.000Z
IssueTest/test.cpp
vvck/QXlsx
281fcb41ec186167ee3bbbe57572746f3c9c09be
[ "MIT" ]
136
2019-01-07T05:44:21.000Z
2022-03-29T08:41:18.000Z
IssueTest/test.cpp
vvck/QXlsx
281fcb41ec186167ee3bbbe57572746f3c9c09be
[ "MIT" ]
201
2019-03-02T09:59:02.000Z
2022-03-25T17:43:13.000Z
// test.cpp #include <QtGlobal> #include <QCoreApplication> #include <QtCore> #include <QVector> #include <QVariant> #include <QDebug> #include <QDir> #include <QColor> #include <QImage> #include <QRgb> #include <QRandomGenerator> #include <iostream> using namespace std; #include "xlsxdocument.h" #include "xlsxchartsheet.h" #include "xlsxcellrange.h" #include "xlsxchart.h" #include "xlsxrichstring.h" #include "xlsxworkbook.h" int test162( QVector<QVariant> params ); int test( QVector<QVariant> params ) { qDebug() << "[debug] current path : " << QDir::currentPath(); return test162( params ); } int test162( QVector<QVariant> params ) { using namespace QXlsx; Document xlsx; xlsx.saveAs("image1.xlsx"); Document xlsx2("image1.xlsx"); qDebug() << "xlsx2" ; qDebug() << " image count : " << xlsx.getImageCount(); xlsx2.saveAs("image2.xlsx"); return 0; }
18.55102
65
0.678768
vvck
83b9107f67fe4998cb60ce665677862afc9de7cb
1,943
cpp
C++
vision/src/detect/motion_simple.cpp
robotalks/analytics
fede843601cba39370e77804a78bb704b32414f1
[ "MIT" ]
null
null
null
vision/src/detect/motion_simple.cpp
robotalks/analytics
fede843601cba39370e77804a78bb704b32414f1
[ "MIT" ]
null
null
null
vision/src/detect/motion_simple.cpp
robotalks/analytics
fede843601cba39370e77804a78bb704b32414f1
[ "MIT" ]
null
null
null
#include <vector> #include "vision/detect/motion.h" namespace vision { using namespace std; using namespace cv; SimpleMotionDetector::SimpleMotionDetector(const Size &blurSize, double areaMin, double threshold) : m_blurSize(blurSize), m_areaMin(areaMin), m_threshold(threshold) { } void SimpleMotionDetector::detect(const Mat& image, DetectedObjectList& objects) { Mat gray; cvtColor(image, gray, CV_BGR2GRAY); GaussianBlur(gray, gray, m_blurSize, 0); if (m_prev.empty()) { m_prev = gray; return; } Mat thresh; absdiff(m_prev, gray, thresh); m_prev = gray; threshold(thresh, thresh, m_threshold, 255, THRESH_BINARY); dilate(thresh, thresh, Mat()); vector<vector<Point>> contours; findContours(thresh.clone(), contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); for (auto& c : contours) { if (contourArea(c) >= m_areaMin) { objects.push_back(DetectedObject(boundingRect(c), "motion")); } } } void SimpleMotionDetector::reg(App* app, const ::std::string& name) { app->options().add_options() ("motion-min-area", "minimum motion area", cxxopts::value<double>()) ("motion-blur", "size of gaussian blur", cxxopts::value<int>()) ("motion-threshold", "threshold for diff", cxxopts::value<double>()) ; app->pipeline()->addFactory(name, [app] { auto blurSize = app->opt("motion-blur").as<int>(); if (blurSize <= 0) { blurSize = 11; } auto threshold = app->opt("motion-threshold").as<double>(); if (threshold <= 0) { threshold = 25; } return new SimpleMotionDetector( Size(blurSize, blurSize), app->opt("motion-min-area").as<double>(), threshold); }); } void SimpleMotionDetector::reg(App* app, ::cv::Scalar color, const ::std::string& name) { reg(app, name); app->objectColor("motion", color); } }
29.439394
98
0.630468
robotalks
83be419f9aceb2831ae6e5dc1ea825a8b084692b
888
hh
C++
advent/utils/timer.hh
tamaroth/AdventOfCode2017
0c0f93590068b6b8fa6ed7f5d53c9fecede632bb
[ "MIT" ]
2
2017-12-01T09:18:03.000Z
2017-12-13T12:59:40.000Z
advent/utils/timer.hh
tamaroth/AdventOfCode2017
0c0f93590068b6b8fa6ed7f5d53c9fecede632bb
[ "MIT" ]
null
null
null
advent/utils/timer.hh
tamaroth/AdventOfCode2017
0c0f93590068b6b8fa6ed7f5d53c9fecede632bb
[ "MIT" ]
null
null
null
/// @file /// /// Time measuring. /// #pragma once #include <chrono> #include <iostream> #include <string> #include <sstream> namespace advent { using ms = std::chrono::milliseconds; using us = std::chrono::microseconds; template<typename Timepoint> std::string duration_to_string(Timepoint start, Timepoint end) { std::ostringstream os; if (auto elapsed = std::chrono::duration_cast<ms>(end-start); elapsed.count()) { os << elapsed.count() << "ms."; } else { os << std::chrono::duration_cast<us>(end-start).count() << "µs.";; } return os.str(); } template<typename Block, typename ...Args> void measure_execution_time(std::string_view task, Block block) { auto start = std::chrono::high_resolution_clock::now(); block(); auto end = std::chrono::high_resolution_clock::now(); std::cout << task << "executed in " << duration_to_string(start, end) << std::endl; } }
23.368421
85
0.682432
tamaroth
83caaaa81636c1efbbdb0c8fdaa3d6b9e215e601
14,599
cpp
C++
VarCalc/GdaParser.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
VarCalc/GdaParser.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
VarCalc/GdaParser.cpp
chenyoujie/GeoDa
87504344512bd0da2ccadfb160ecd1e918a52f06
[ "BSL-1.0" ]
null
null
null
/** * GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved * * This file is part of GeoDa. * * GeoDa is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GeoDa is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <limits> #include <math.h> #include "../logger.h" #include "GdaParser.h" GdaParser::GdaParser() : data_table(0), w_man_int(0) { } bool GdaParser::eval(const std::vector<GdaTokenDetails>& tokens_, std::map<wxString, GdaFVSmtPtr>* data_table_, WeightsManInterface* w_man_int_) { tokens = tokens_; data_table = data_table_; w_man_int = w_man_int_; tok_i = 0; bool success = false; eval_toks.clear(); try { error_msg = ""; eval_val = expression(); success = true; } catch (GdaParserException e) { error_msg = e.what(); } catch (GdaFVException e) { error_msg = e.what(); } catch (std::exception e) { error_msg = e.what(); } return success; } GdaFVSmtPtr GdaParser::expression() { return logical_xor_expr(); } GdaFVSmtPtr GdaParser::logical_xor_expr() { using namespace std; GdaFVSmtPtr left = logical_or_expr(); for (;;) { if (curr_token() == Gda::XOR) { inc_token(); // consume XOR GdaFVSmtPtr right = logical_or_expr(); left->ApplyBinarySelf(&Gda::logical_xor, *right); } else { return left; } } } GdaFVSmtPtr GdaParser::logical_or_expr() { using namespace std; GdaFVSmtPtr left = logical_and_expr(); for (;;) { if (curr_token() == Gda::OR) { inc_token(); // consume OR GdaFVSmtPtr right = logical_and_expr(); left->ApplyBinarySelf(&Gda::logical_or, *right); } else { return left; } } } GdaFVSmtPtr GdaParser::logical_and_expr() { using namespace std; GdaFVSmtPtr left = logical_not_expr(); for (;;) { if (curr_token() == Gda::AND) { inc_token(); // consume AND GdaFVSmtPtr right = logical_not_expr(); left->ApplyBinarySelf(&Gda::logical_and, *right); } else { return left; } } } GdaFVSmtPtr GdaParser::logical_not_expr() { if (curr_token() == Gda::NOT) { inc_token(); // consume NOT GdaFVSmtPtr p(expression()); p->ApplyUniSelf(&Gda::logical_not); return p; } return comp_expr(); } GdaFVSmtPtr GdaParser::comp_expr() { GdaFVSmtPtr left = add_expr(); for (;;) { if (curr_token() == Gda::LT) { inc_token(); // consume < GdaFVSmtPtr right = add_expr(); left->ApplyBinarySelf(&Gda::lt, *right); } else if (curr_token() == Gda::LE) { inc_token(); // consume <= GdaFVSmtPtr right = add_expr(); left->ApplyBinarySelf(&Gda::le, *right); } else if (curr_token() == Gda::GT) { inc_token(); // consume > GdaFVSmtPtr right = add_expr(); left->ApplyBinarySelf(&Gda::gt, *right); } else if (curr_token() == Gda::GE) { inc_token(); // consume >= GdaFVSmtPtr right = add_expr(); left->ApplyBinarySelf(&Gda::ge, *right); } else if (curr_token() == Gda::EQ) { inc_token(); // consume = GdaFVSmtPtr right = add_expr(); left->ApplyBinarySelf(&Gda::eq, *right); } else if (curr_token() == Gda::NE) { inc_token(); // consume <> GdaFVSmtPtr right = add_expr(); left->ApplyBinarySelf(&Gda::ne, *right); } else { return left; } } } GdaFVSmtPtr GdaParser::add_expr() { using namespace std; GdaFVSmtPtr left = mult_expr(); for (;;) { if (curr_token() == Gda::PLUS) { inc_token(); // consume '+' GdaFVSmtPtr right = mult_expr(); wxString ss; ss << "GdaParser + op: operand " << (*left).ToStr(); ss << ", operand " << (*right).ToStr(); (*left) += (*right); } else if (curr_token() == Gda::MINUS) { inc_token(); // consume '-' (*left) -= (*mult_expr()); } else { return left; } } } GdaFVSmtPtr GdaParser::mult_expr() { GdaFVSmtPtr left = pow_expr(); for (;;) { if (curr_token() == Gda::MUL) { inc_token(); // consume '*' (*left) *= (*pow_expr()); } else if (curr_token() == Gda::DIV) { inc_token(); // consume '/' (*left) /= (*pow_expr()); } else { return left; } } } GdaFVSmtPtr GdaParser::pow_expr() { GdaFVSmtPtr left = func_expr(); if (curr_token() == Gda::POW) { inc_token(); // consume '^' GdaFVSmtPtr right = expression(); (*left) ^= (*right); return left; } else { return left; } } GdaFVSmtPtr GdaParser::func_expr() { if (curr_token() != Gda::NAME || (curr_token() == Gda::NAME && next_token() != Gda::LP)) { return primary(); } wxString func_name = curr_tok_str_val(); mark_curr_token_func(); inc_token(); // consume NAME token inc_token(); // consume '(' if (curr_token() == Gda::RP) { inc_token(); // consume ')' // return 0-ary function NAME () value LOG(func_name); if (func_name.CmpNoCase("rook") == 0 || func_name.CmpNoCase("queen") == 0) { throw GdaParserException("automatic weights creation " "not yet supported"); if (!w_man_int) { throw GdaParserException("no weights available."); } WeightsMetaInfo wmi; if (func_name.CmpNoCase("rook") == 0) { wmi.SetToRook(""); } else { wmi.SetToQueen(""); } boost::uuids::uuid u = w_man_int->RequestWeights(wmi); GdaFVSmtPtr p(new GdaFlexValue(u)); return p; } throw GdaParserException("unknown function \"" + func_name + "\""); } GdaFVSmtPtr arg1(expression()); // evaluate first argument if (curr_token() == Gda::RP) { inc_token(); // consume ')' // evaluate unary function NAME ( arg1 ) LOG(func_name); if (func_name.CmpNoCase("sqrt") == 0) { arg1->ApplyUniSelf(&sqrt); } else if (func_name.CmpNoCase("cos") == 0) { arg1->ApplyUniSelf(&cos); } else if (func_name.CmpNoCase("sin") == 0) { arg1->ApplyUniSelf(&sin); } else if (func_name.CmpNoCase("tan") == 0) { arg1->ApplyUniSelf(&tan); } else if (func_name.CmpNoCase("acos") == 0) { arg1->ApplyUniSelf(&acos); } else if (func_name.CmpNoCase("asin") == 0) { arg1->ApplyUniSelf(&asin); } else if (func_name.CmpNoCase("atan") == 0) { arg1->ApplyUniSelf(&atan); } else if (func_name.CmpNoCase("abs") == 0 || func_name.CmpNoCase("fabs") == 0) { arg1->ApplyUniSelf(&fabs); } else if (func_name.CmpNoCase("ceil") == 0) { arg1->ApplyUniSelf(&ceil); } else if (func_name.CmpNoCase("floor") == 0) { arg1->ApplyUniSelf(&floor); } else if (func_name.CmpNoCase("round") == 0) { arg1->Round(); } else if (func_name.CmpNoCase("log") == 0 || func_name.CmpNoCase("ln") == 0) { arg1->ApplyUniSelf(&log); } else if (func_name.CmpNoCase("log10") == 0) { arg1->ApplyUniSelf(&log10); } else if (func_name.CmpNoCase("sum") == 0) { arg1->Sum(); } else if (func_name.CmpNoCase("mean") == 0 || func_name.CmpNoCase("avg") == 0) { arg1->Mean(); } else if (func_name.CmpNoCase("sum") == 0) { arg1->Sum(); } else if (func_name.CmpNoCase("stddev") == 0) { arg1->StdDev(); } else if (func_name.CmpNoCase("dev_fr_mean") == 0) { arg1->DevFromMean(); } else if (func_name.CmpNoCase("standardize") == 0) { arg1->Standardize(); } else if (func_name.CmpNoCase("shuffle") == 0) { arg1->Shuffle(); } else if (func_name.CmpNoCase("rot_down") == 0) { arg1->Rotate(-1); } else if (func_name.CmpNoCase("rot_up") == 0) { arg1->Rotate(1); } else if (func_name.CmpNoCase("unif_dist") == 0) { arg1->UniformDist(); } else if (func_name.CmpNoCase("norm_dist") == 0) { arg1->GaussianDist(0,1); } else if (func_name.CmpNoCase("enumerate") == 0) { arg1->Enumerate(1, 1); } else if (func_name.CmpNoCase("max") == 0) { arg1->Max(); } else if (func_name.CmpNoCase("min") == 0) { arg1->Min(); } else if (func_name.CmpNoCase("is_defined") == 0) { arg1->ApplyUniSelf(&Gda::is_defined); } else if (func_name.CmpNoCase("is_finite") == 0) { arg1->ApplyUniSelf(&Gda::is_finite); } else if (func_name.CmpNoCase("is_nan") == 0) { arg1->ApplyUniSelf(&Gda::is_nan); } else if (func_name.CmpNoCase("is_pos_inf") == 0) { arg1->ApplyUniSelf(&Gda::is_pos_inf); } else if (func_name.CmpNoCase("is_neg_inf") == 0) { arg1->ApplyUniSelf(&Gda::is_neg_inf); } else if (func_name.CmpNoCase("is_inf") == 0) { arg1->ApplyUniSelf(&Gda::is_inf); } else if (func_name.CmpNoCase("counts") == 0) { if (!w_man_int) { throw GdaParserException("no weights available."); } if (!arg1->IsWeights()) { throw GdaParserException("first argument of counts must be weights"); } std::vector<long> counts; if (!w_man_int->GetCounts(arg1->GetWUuid(), counts)) { throw GdaParserException("could not find neighbor counts"); } GdaFVSmtPtr p(new GdaFlexValue(counts)); return p; } else { throw GdaParserException("unknown function \"" + func_name + "\""); } return arg1; } if (curr_token() != Gda::COMMA) { throw GdaParserException("',' or ')' expected"); } inc_token(); // consume ',' GdaFVSmtPtr arg2(expression()); // evaluate second argument if (curr_token() == Gda::RP) { inc_token(); // consume ')' // evaluate binary function NAME ( arg1 , arg2 ) LOG(func_name); if (func_name.CmpNoCase("pow") == 0) { arg1->ApplyBinarySelf(&pow, *arg2); } else if (func_name.CmpNoCase("lag") == 0) { if (!w_man_int) { throw GdaParserException("no weights available."); } if (!arg1->IsWeights()) { throw GdaParserException("first argument of lag must be weights."); } if (!arg2->IsData()) { throw GdaParserException("second argument of lag must be data."); } if (!w_man_int->WeightsExists(arg1->GetWUuid())) { throw GdaParserException("invalid weights."); } LOG(arg1->ToStr()); GdaFVSmtPtr p(new GdaFlexValue()); if (!w_man_int->Lag(arg1->GetWUuid(), *arg2, *p)) { throw GdaParserException("error computing spatial lag"); } return p; } else { throw GdaParserException("unknown function \"" + func_name + "\""); } return arg1; } if (curr_token() != Gda::COMMA) { throw GdaParserException("',' or ')' expected"); } inc_token(); // consume ',' GdaFVSmtPtr arg3(expression()); // evaluate third argument if (curr_token() == Gda::RP) { // mark as function token. inc_token(); // consume ')' // evaluate binary function NAME ( arg1 , arg2, arg3 ) LOG(func_name); if (func_name.CmpNoCase("enumerate") == 0 || func_name.CmpNoCase("norm_dist") == 0) { if (arg2->GetObs() != 1 || arg2->GetTms() != 1) { throw GdaParserException("second argument of " + func_name + " must be a constant."); } if (arg3->GetObs() != 1 || arg3->GetTms() != 1) { throw GdaParserException("third argument of " + func_name + " must be a constant."); } } if (func_name.CmpNoCase("enumerate") == 0) { arg1->Enumerate(arg2->GetDouble(), arg3->GetDouble()); } else if (func_name.CmpNoCase("norm_dist") == 0) { double sd = arg3->GetDouble(); if (sd-sd != 0 || sd < 0) { // x-x == 0 is a reliable test for double being finite throw GdaParserException("third argument of " + func_name + " must be a non-negative finite real."); } arg1->GaussianDist(arg2->GetDouble(), sd); } else { throw GdaParserException("unknown function \"" + func_name + "\""); } return arg1; } throw GdaParserException("')' expected"); } GdaFVSmtPtr GdaParser::primary() { if (curr_token() == Gda::STRING) { GdaFVSmtPtr p(new GdaFlexValue(curr_tok_str_val())); inc_token(); // consume STRING token return p; } if (curr_token() == Gda::NUMBER) { GdaFVSmtPtr p(new GdaFlexValue(curr_tok_num_val())); //double v = curr_tok_num_val(); inc_token(); // consume NUMBER token return p; } else if (curr_token() == Gda::NAME) { wxString key(curr_tok_str_val()); //if (next_token() == Gda::ASSIGN) { // (*data_table)[key] = expression(true); //} // check for existence in data_table and in weights if w_man_int exists if (data_table->find(key) == data_table->end() && (!w_man_int || (w_man_int && w_man_int->FindIdByTitle(key).is_nil()))) { mark_curr_token_ident(); mark_curr_token_problem(); inc_token(); throw GdaParserException(key + " not a known identifier"); } mark_curr_token_ident(); inc_token(); // consume NAME token if (data_table->find(key) != data_table->end()) { GdaFVSmtPtr p(new GdaFlexValue((*(*data_table)[key]))); return p; } else { GdaFVSmtPtr p(new GdaFlexValue(w_man_int->FindIdByTitle(key))); return p; } } else if (curr_token() == Gda::MINUS) { // unary minus inc_token(); // consume '-' GdaFVSmtPtr p(primary()); p->NegateSelf(); return p; } else if (curr_token() == Gda::LP) { inc_token(); // consume '(' GdaFVSmtPtr e(expression()); if (curr_token() != Gda::RP) { throw GdaParserException("')' expected"); } inc_token(); // consume ')' return e; } throw GdaParserException("primary expected"); } Gda::TokenEnum GdaParser::curr_token() { if (tok_i >= tokens.size()) return Gda::END; return tokens[tok_i].token; } double GdaParser::curr_tok_num_val() { if (tok_i >= tokens.size() || curr_token() != Gda::NUMBER) return 0; return tokens[tok_i].number_value; } wxString GdaParser::curr_tok_str_val() { if (tok_i >= tokens.size() || (curr_token() != Gda::NAME && curr_token() != Gda::STRING)) return ""; return tokens[tok_i].string_value; } Gda::TokenEnum GdaParser::next_token() { int ii = tok_i + 1; if (ii >= tokens.size()) return Gda::END; return tokens[ii].token; } void GdaParser::inc_token() { if (tok_i < tokens.size()) { eval_toks.push_back(tokens[tok_i]); } ++tok_i; } void GdaParser::mark_curr_token_func() { if (tok_i < tokens.size()) { tokens[tok_i].is_func = true; tokens[tok_i].is_ident = false; } } void GdaParser::mark_curr_token_ident() { if (tok_i < tokens.size()) { tokens[tok_i].is_func = false; tokens[tok_i].is_ident = true; } } void GdaParser::mark_curr_token_problem() { if (tok_i < tokens.size()) tokens[tok_i].problem_token = true; } void GdaParser::exception_if_not_data(const GdaFVSmtPtr x) { if (!x->IsData()) { throw GdaParserException("parser expected data expression"); } } void GdaParser::exception_if_not_weights(const GdaFVSmtPtr x) { if (!x->IsWeights()) { throw GdaParserException("parser expected weights expression"); } }
27.545283
73
0.635728
chenyoujie
83d284ff83da1c52a3e20d49c50879f0340a3e11
192
cpp
C++
src/JSEUIMenuLeafImpl.cpp
imzcy/JavaScriptExecutable
723a13f433aafad84faa609f62955ce826063c66
[ "MIT" ]
3
2015-03-18T03:12:27.000Z
2020-11-19T10:40:12.000Z
src/JSEUIMenuLeafImpl.cpp
imzcy/JavaScriptExecutable
723a13f433aafad84faa609f62955ce826063c66
[ "MIT" ]
null
null
null
src/JSEUIMenuLeafImpl.cpp
imzcy/JavaScriptExecutable
723a13f433aafad84faa609f62955ce826063c66
[ "MIT" ]
null
null
null
#include "JSEUIMenuLeafImpl.h" namespace JSE { namespace UI { JSEUIMenuLeafImpl::JSEUIMenuLeafImpl(QWidget *parent) : QAction(parent) { } JSEUIMenuLeafImpl::~JSEUIMenuLeafImpl() {} }}
13.714286
53
0.739583
imzcy
83d4bd29208359d57a0680654dc43ad268cfb655
1,936
hpp
C++
game_files/game_order/game_order.hpp
sakumo7/zpr
7b9cdbec1ff8d8179a96bb6e1e88f54ee84d138e
[ "MIT" ]
null
null
null
game_files/game_order/game_order.hpp
sakumo7/zpr
7b9cdbec1ff8d8179a96bb6e1e88f54ee84d138e
[ "MIT" ]
null
null
null
game_files/game_order/game_order.hpp
sakumo7/zpr
7b9cdbec1ff8d8179a96bb6e1e88f54ee84d138e
[ "MIT" ]
null
null
null
#ifndef GAME_ORDER_HPP #define GAME_ORDER_HPP #include "../typedefs.hpp" #include <vector> #include <memory> #include "../game_engine/game_engine.hpp" typedef std::unique_ptr<std::vector<unsigned int>> ship_vector_uptr; class GameOrder{ public: virtual std::string toString() const=0; virtual int type() const = 0; }; class MoveOrder : public GameOrder{ public: enum {type_id = 1}; MoveOrder():start_point_id_(0), destination_id_(0) {ship_id_vector_ = std::make_unique<std::vector<unsigned int>>();} MoveOrder(unsigned int start_point_id, unsigned int destination_id, const std::vector<unsigned int>& ship_id_vector): start_point_id_(start_point_id), destination_id_(destination_id){ship_id_vector_ = std::make_unique<std::vector<unsigned int>> (ship_id_vector);} MoveOrder(std::string data); std::string toString() const; unsigned int getStartPoint() const {return start_point_id_;} unsigned int getDestination() const {return destination_id_;} const ship_vector_uptr& getShipVector() const {return ship_id_vector_;} int type() const{return MoveOrder::type_id;} private: unsigned int start_point_id_; unsigned int destination_id_; ship_vector_uptr ship_id_vector_; }; class BuildOrder : public GameOrder{ public: BuildOrder(unsigned int point_id = 0): point_id_(point_id){} BuildOrder(std::string data); enum {type_id= 2}; unsigned int getPointId() const {return point_id_;} std::string toString() const; int type() const {return BuildOrder::type_id;} private: unsigned int point_id_; }; class CreateShipOrder: public GameOrder{ public: enum {type_id=3}; CreateShipOrder(unsigned int point_id = 0): point_id_(point_id){} std::string toString() const; CreateShipOrder(std::string data); unsigned int getPointId() const {return point_id_;} int type() const {return CreateShipOrder::type_id;} private: unsigned int point_id_; }; #endif //GAME_ORDER_HPP
31.225806
146
0.75
sakumo7
83d987d24bfb176ca10c8132e11da65f1009d534
2,715
cpp
C++
session-manager/common/call/CallInGetUserSession.cpp
Syamsuri227/FreeRDS
933f43a9f2dfd254d825e6687c8ca536ec2bf569
[ "Apache-2.0" ]
14
2015-02-17T15:43:46.000Z
2022-02-17T07:11:46.000Z
session-manager/common/call/CallInGetUserSession.cpp
Syamsuri227/FreeRDS
933f43a9f2dfd254d825e6687c8ca536ec2bf569
[ "Apache-2.0" ]
4
2015-03-22T10:26:38.000Z
2020-07-07T13:35:56.000Z
session-manager/common/call/CallInGetUserSession.cpp
Syamsuri227/FreeRDS
933f43a9f2dfd254d825e6687c8ca536ec2bf569
[ "Apache-2.0" ]
58
2015-04-08T02:24:17.000Z
2022-03-29T15:59:15.000Z
/** * Class for rpc call GetUserSession (freerds to session manager) * * Copyright 2013 Thinstuff Technologies GmbH * Copyright 2013 DI (FH) Martin Haimberger <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "CallInGetUserSession.h" #include <appcontext/ApplicationContext.h> using freerds::icp::GetUserSessionRequest; using freerds::icp::GetUserSessionResponse; namespace freerds{ namespace sessionmanager{ namespace call{ CallInGetUserSession::CallInGetUserSession() { }; CallInGetUserSession::~CallInGetUserSession() { }; unsigned long CallInGetUserSession::getCallType() { return freerds::icp::GetUserSession; }; int CallInGetUserSession::decodeRequest() { // decode protocol buffers GetUserSessionRequest req; if (!req.ParseFromString(mEncodedRequest)) { // failed to parse mResult = 1;// will report error with answer return -1; } mUserName = req.username(); if (req.has_domainname()) { mDomainName = req.domainname(); } return 0; }; int CallInGetUserSession::encodeResponse() { // encode protocol buffers GetUserSessionResponse resp; // stup do stuff here resp.set_sessionid(mSessionID); resp.set_serviceendpoint(mPipeName); if (!resp.SerializeToString(&mEncodedResponse)) { // failed to serialize mResult = 1; return -1; } return 0; }; int CallInGetUserSession::doStuff() { std::string pipeName; sessionNS::Session * currentSession = APP_CONTEXT.getSessionStore()->createSession(); currentSession->setUserName(mUserName); currentSession->setDomain(mDomainName); if (!currentSession->generateUserToken()) { mResult = 1;// will report error with answer return 1; } if (!currentSession->generateEnvBlockAndModify() ){ mResult = 1;// will report error with answer return 1; } currentSession->setModuleName("x11module"); if (!currentSession->startModule(pipeName)) { mResult = 1;// will report error with answer return 1; } mSessionID = currentSession->getSessionID(); mPipeName = pipeName; return 0; } } } }
24.908257
88
0.710497
Syamsuri227
83dbec132ac763ab5b591eecaf876cad502393b0
2,108
cpp
C++
MemSpy/MemSpy/Sources/CommandLine.cpp
piskunovdenis/MemSpy
84c4994a5c3a0f7a9379f64609a6eff4a3d7985f
[ "MIT" ]
null
null
null
MemSpy/MemSpy/Sources/CommandLine.cpp
piskunovdenis/MemSpy
84c4994a5c3a0f7a9379f64609a6eff4a3d7985f
[ "MIT" ]
null
null
null
MemSpy/MemSpy/Sources/CommandLine.cpp
piskunovdenis/MemSpy
84c4994a5c3a0f7a9379f64609a6eff4a3d7985f
[ "MIT" ]
null
null
null
#include <algorithm> #include <windows.h> #include <stdexcept> #include "CommandLine.hpp" #include "WideString.hpp" namespace memspy { const std::vector<wchar_t> CommandLine::kParamSeparators = { L'-', L'/' }; const std::vector<wchar_t> CommandLine::kNameValueSeparators = { L':', L'=' }; CommandLine::CommandLine(int argc, _TCHAR* argv[]) : m_Arguments(argv + 1, argv + argc) { } bool CommandLine::FindParam(const std::wstring& searchingParamName) const { if (!searchingParamName.empty()) { for (const auto& i : m_Arguments) { std::wstring paramName; std::wstring paramValue; ParseParam(i, paramName, paramValue); if (memspy::WideString::Compare(paramName, searchingParamName) || memspy::WideString::Compare(L"-" + paramName, searchingParamName) || memspy::WideString::Compare(L"/" + paramName, searchingParamName)) { return true; } } } return false; } std::wstring CommandLine::GetParamValue(const std::wstring& searchingParamName) const { if (!searchingParamName.empty()) { for (const auto& i : m_Arguments) { std::wstring paramName; std::wstring paramValue; ParseParam(i, paramName, paramValue); if (memspy::WideString::Compare(paramName, searchingParamName)) { return paramValue; } } } return L""; } void CommandLine::ParseParam(const std::wstring& param, std::wstring& rParamName, std::wstring& rParamValue) const { rParamName = L""; rParamValue = L""; if (param.empty()) return; for (auto i : kParamSeparators) { if (param[0] == i) { rParamName = param.substr(1, param.length()); break; } } size_t firstSeparatorPos{ std::wstring::npos }; for (auto i : kNameValueSeparators) { size_t separatorPos = rParamName.find(i); if (separatorPos != std::wstring::npos) { firstSeparatorPos = min(separatorPos, firstSeparatorPos); } } if (firstSeparatorPos != std::wstring::npos) { rParamValue = rParamName.substr(firstSeparatorPos + 1, std::wstring::npos); } rParamName = rParamName.substr(0, firstSeparatorPos); } }
23.685393
115
0.666034
piskunovdenis
83dc85e75596c3bcee21afa8ca606de437c7467a
4,045
cpp
C++
src/blocksigner.cpp
jazy510/XSN
6ea74506573c6253c2ce933aafce9ad8b2d95659
[ "MIT" ]
1
2021-04-04T20:38:41.000Z
2021-04-04T20:38:41.000Z
src/blocksigner.cpp
jazy510/XSN
6ea74506573c6253c2ce933aafce9ad8b2d95659
[ "MIT" ]
null
null
null
src/blocksigner.cpp
jazy510/XSN
6ea74506573c6253c2ce933aafce9ad8b2d95659
[ "MIT" ]
null
null
null
#include "blocksigner.h" #include "tpos/tposutils.h" #include "tpos/activemerchantnode.h" #include "keystore.h" #include "primitives/block.h" #include "utilstrencodings.h" CBlockSigner::CBlockSigner(CBlock &block, const CKeyStore &keystore, const TPoSContract &contract) : refBlock(block), refKeystore(keystore), refContract(contract) { } bool CBlockSigner::SignBlock() { std::vector<std::vector<unsigned char>> vSolutions; txnouttype whichType; CKey keySecret; if(refBlock.IsProofOfStake()) { const CTxOut& txout = refBlock.vtx[1].vout[1]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if(refBlock.IsTPoSBlock()) { CKeyID merchantKeyID; if(!refContract.merchantAddress.GetKeyID(merchantKeyID)) return error("CBlockSigner::SignBlock() : merchant address is not P2PKH, critical error, can't accept."); if(merchantKeyID != activeMerchantnode.pubKeyMerchantnode.GetID()) return error("CBlockSigner::SignBlock() : contract address is different from merchantnode address, won't sign."); keySecret = activeMerchantnode.keyMerchantnode; } else { CKeyID keyID; if (whichType == TX_PUBKEYHASH) { keyID = CKeyID(uint160(vSolutions[0])); } else if(whichType == TX_PUBKEY) { keyID = CPubKey(vSolutions[0]).GetID(); } if (!refKeystore.GetKey(keyID, keySecret)) return false; } } else { const CTxOut& txout = refBlock.vtx[0].vout[0]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; CKeyID keyID; if (whichType == TX_PUBKEYHASH) { keyID = CKeyID(uint160(vSolutions[0])); } else if(whichType == TX_PUBKEY) { keyID = CPubKey(vSolutions[0]).GetID(); } if (!refKeystore.GetKey(keyID, keySecret)) return false; } return keySecret.SignCompact(refBlock.IsTPoSBlock() ? refBlock.GetTPoSHash() : refBlock.GetHash(), refBlock.vchBlockSig); } bool CBlockSigner::CheckBlockSignature() const { if(refBlock.IsProofOfWork()) return true; if(refBlock.vchBlockSig.empty()) return false; std::vector<std::vector<unsigned char>> vSolutions; txnouttype whichType; const CTxOut& txout = refBlock.vtx[1].vout[1]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; CKeyID signatureKeyID; CPubKey recoveredKey; auto hashMessage = refBlock.IsTPoSBlock() ? refBlock.GetTPoSHash() : refBlock.GetHash(); if(!recoveredKey.RecoverCompact(hashMessage, refBlock.vchBlockSig)) return error("CBlockSigner::CheckBlockSignature() : failed to recover public key from signature"); if(refBlock.IsProofOfStake()) { if(refBlock.IsTPoSBlock()) { if(!refContract.merchantAddress.GetKeyID(signatureKeyID)) return error("CBlockSigner::CheckBlockSignature() : merchant address is not P2PKH, critical error, can't accept."); } else { if (whichType == TX_PUBKEYHASH) { signatureKeyID = CKeyID(uint160(vSolutions[0])); } else if(whichType == TX_PUBKEY) { signatureKeyID = CPubKey(vSolutions[0]).GetID(); } } } else { const CTxOut& txout = refBlock.vtx[0].vout[0]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEYHASH) { signatureKeyID = CKeyID(uint160(vSolutions[0])); } else if(whichType == TX_PUBKEY) { signatureKeyID = CPubKey(vSolutions[0]).GetID(); } } return recoveredKey.GetID() == signatureKeyID; }
27.705479
131
0.595797
jazy510