hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
36108101864ac34d81ba74b20544631749d40515
4,059
cpp
C++
cpp/chinesePostman/chinesePostman.cpp
indy256/codelibrary-sandbox
fd49b2de1cf578084f222a087a472f0760a4fa4d
[ "Unlicense" ]
6
2018-04-20T22:58:22.000Z
2021-03-25T13:09:57.000Z
cpp/chinesePostman/chinesePostman.cpp
indy256/codelibrary-sandbox
fd49b2de1cf578084f222a087a472f0760a4fa4d
[ "Unlicense" ]
null
null
null
cpp/chinesePostman/chinesePostman.cpp
indy256/codelibrary-sandbox
fd49b2de1cf578084f222a087a472f0760a4fa4d
[ "Unlicense" ]
2
2018-06-05T18:30:17.000Z
2018-11-14T16:56:19.000Z
#include <cmath> #include <string> #include <vector> #include <map> #include <set> #include <cstring> #include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <utility> #include <queue> #include <functional> #include <cstdlib> #include <climits> #include <sstream> #include <cctype> #include <complex> #include <numeric> #include <cassert> using namespace std; int d[60][60]; const long long OO = 1000000000000000LL; typedef vector<int> VI; typedef vector<long long> VD; /* returns the maximum weight perfect matching on a complete bipartite graph */ /* matching[i] contains the 0-based number of the second set that has been matched to i */ /* runtime: O(V^3) */ long long MaxWeightPerfectMatching( vector<VD> &val, VI &matching ) { int n = val.size(); vector< int > matched( n, -1 ); matching.assign( n, -1 ); vector< long long > l1( n, OO ), l2( n, -OO ); for( int k = 0; k < n; k++ ) { vector< int > s( n, 0 ), t( n, 0 ); vector< long long > slick( n, OO ); vector< int > pred( n ); for( int i = 0; i < n; i++ ) // unmatched nodes -> S if( matching[i] < 0 ) { for( int j = 0; j < n; j++ ) slick[j] <?= l1[i] + l2[j] - val[i][j]; s[i] = 1; } int j_min = -1; while( j_min == -1 ) { long long slick_min = OO; for( int j = 0; j < n; j++ ) if( !t[j] && ( slick[j] < slick_min ) ) slick_min = slick[j], j_min = j; assert(j_min>=0); for( int i = 0; i < n; i++ ) { // update labels if( s[i] ) l1[i] -= slick_min; if( t[i] ) l2[i] += slick_min; else slick[i] -= slick_min; if( s[i] && l1[i] + l2[j_min] == val[i][j_min] ) pred[j_min] = i; } if( matched[ j_min ] >= 0 ) { // matching exists already t[j_min] = 1, s[matched[j_min]] = 1; for( int j = 0; j < n; j++ ) // update slick slick[j]<?=l1[matched[j_min]]+l2[j]-val[matched[j_min]][j]; j_min = -1; } } while( j_min >= 0 ) { int i = pred[j_min], j = j_min; j_min = matching[i]; matching[i] = j, matched[j] = i; } } long long weight = 0; for( int i = 0; i < n; i++ ) weight += val[i][matching[i]]; return weight; } char needvisit[60]; char visit[60]; int n; void dfs(int cur) { if (visit[cur]) return; visit[cur] = 1; for (int i=0; i<n; ++i) if (d[cur][i]) dfs(i); } class SnowPlow { public: int solve(vector <string> roads) { n = roads.size(); int indeg[60] = {0}, outdeg[60] = {0}; int res = 0; for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) { if (roads[i][j] > '0') { d[i][j] = 1; needvisit[i] = needvisit[j] = 1; } else d[i][j] = 0; indeg[j] += roads[i][j]-'0'; outdeg[i] += roads[i][j]-'0'; res += roads[i][j] - '0'; } dfs(0); for (int i=0; i<n; ++i) if (!visit[i] && needvisit[i]) return -1; for (int i=0; i<n; ++i) for (int j=0; j<n; ++j) { if (!d[j][i]) continue; for (int k=0; k<n; ++k) { if (!d[i][k]) continue; if (d[j][k] == 0 || d[j][k] < d[j][i] + d[i][k]) d[j][k] = d[j][i] + d[i][k]; } } vector<int> left, right; for (int i=0; i<n; ++i) { while(indeg[i] < outdeg[i]) { right.push_back(i); ++indeg[i]; } while(outdeg[i] < indeg[i]) { left.push_back(i); ++outdeg[i]; } } assert(left.size() == right.size()); vector<VD> val(left.size(), VD(right.size(), -OO)); for (int i=0; i<(int)left.size(); ++i) for (int j=0; j<(int)right.size(); ++j) if (d[left[i]][right[j]] > 0) val[i][j] = -d[left[i]][right[j]]; VI matching; long long tres = -MaxWeightPerfectMatching(val, matching); if (tres >= OO) return -1; return res + tres; } };
27.80137
91
0.476472
indy256
361562e0e8986078bfb3d2ab5006396b2e907940
279
cpp
C++
src/Z/Z119.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
src/Z/Z119.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
src/Z/Z119.cpp
wlhcode/lscct
7fd112a9d1851ddcf41886d3084381a52e84a3ce
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define ll long long using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(0); long double c,d,e,f,g; cin>>c>>d>>e>>f>>g; cout<<setprecision(0)<<fixed<<(0.75+0.25*(c+d+e+f+g))*(2000*c+2500*d+3000*e+3500*f+4000*g)<<endl; return 0; }
21.461538
98
0.637993
wlhcode
36182b2be400f2c21efb859ed5c4b448c3cd8acb
5,551
cpp
C++
src/utils.cpp
typcn/LeanClub
a10b8adc927e7977ac89fe09223d34d7a7a6ac33
[ "MIT" ]
263
2015-05-07T16:26:18.000Z
2022-03-14T13:34:25.000Z
src/utils.cpp
UnreliableBuilder/C-LeanClub
a10b8adc927e7977ac89fe09223d34d7a7a6ac33
[ "MIT" ]
16
2015-05-28T10:53:24.000Z
2016-01-27T08:54:30.000Z
src/utils.cpp
UnreliableBuilder/C-LeanClub
a10b8adc927e7977ac89fe09223d34d7a7a6ac33
[ "MIT" ]
61
2015-05-21T07:51:08.000Z
2022-01-28T11:52:42.000Z
// // utils.cpp // leanclub // // Created by TYPCN on 2015/5/1. // // #include "utils.h" #include "config.h" #include "restclient/restclient.h" #include "oauth/md5.h" #include "redis3m/include/redis3m/redis3m.hpp" #include <fstream> #include <boost/filesystem.hpp> #include <boost/thread/thread.hpp> #include <boost/random/random_device.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <boost/date_time/posix_time/posix_time.hpp> using namespace redis3m; simple_pool::ptr_t pool; simple_pool::ptr_t WritePool; int online = -1; void InitRedisPool(){ pool = simple_pool::create(REDIS_READ_IP); WritePool = simple_pool::create(REDIS_MASTER_IP); } std::string randomStr(int len){ std::string chars("ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"); boost::random::random_device rng; boost::random::uniform_int_distribution<> index_dist(0, chars.size() - 1); std::string str; for(int i = 0; i < len; ++i) { str = str + chars[index_dist(rng)]; } return str; } bool string_is_valid(const std::string &str) { return find_if(str.begin(), str.end(), [](char c) { return !(isalnum(c)); }) == str.end(); } char easytolower(char in){ if(in<='Z' && in>='A') return in-('Z'-'z'); return in; } std::string GetGravatar(std::string email){ std::string data = email; std::transform(data.begin(), data.end(), data.begin(), easytolower); return GRAVATAR_BASE_URL + md5(data) + "?d=identicon"; } std::string cookie_expries_time(time_t timestamp){ std::ostringstream ss; ss.exceptions(std::ios_base::failbit); boost::posix_time::ptime ptime = boost::posix_time::from_time_t(timestamp); boost::posix_time::time_facet *facet = new boost::posix_time::time_facet("%a, %d-%b-%Y %T GMT"); ss.imbue(std::locale(std::locale::classic(), facet)); ss.str(""); ss << ptime; return ss.str(); } std::string SetSession(std::string content){ std::string sessionID = randomStr(SESSION_COOKIE_LENGTH); connection::ptr_t c = WritePool->get(); c->run(command("SET")("SESS" + sessionID)(content)); WritePool->put(c); std::string expries = cookie_expries_time(time(0) + (SESSION_COOKIE_EXPRIES)); return "LBSESSIONID=" + sessionID + "; expires="+ expries + "; path=/; domain=" SESSION_COOKIE_DOMAIN "; HttpOnly; Secure"; } std::string GetSession(std::string cookie){ size_t loc = cookie.find("LBSESSIONID="); if(loc == std::string::npos){ return ""; }else{ std::string sessid = cookie.substr(loc + 12,SESSION_COOKIE_LENGTH); connection::ptr_t c = pool->get(); std::string session = c->run(command("GET")("SESS" + sessid)).str(); pool->put(c); return session; } } bool createFolder(std::string path){ boost::filesystem::path dir = boost::filesystem::system_complete(path); if(!boost::filesystem::exists(dir)){ return boost::filesystem::create_directory(dir); } return true; } std::string getFileExt(std::string data){ if(data.find("image/jpeg") != std::string::npos){ return ".jpg"; }else if(data.find("image/png") != std::string::npos){ return ".png"; }else if(data.find("image/gif") != std::string::npos){ return ".gif"; }else if(data.find("image/jpg") != std::string::npos){ return ".jpg"; }else if(data.find("image/webp") != std::string::npos){ return ".webp"; }else if(data.find("image/x-ms-bmp") != std::string::npos){ return ".bmp"; }else if(data.find("image/tif") != std::string::npos){ return ".tif"; }else if(data.find("image/svg+xml") != std::string::npos){ return ".svg"; }else{ return ""; } } std::string SavePostFile(std::string postdata,std::string uid){ int start = postdata.find("\r\n\r\n") + 4; int end = postdata.rfind("\r\n-"); if (start != std::string::npos && end != std::string::npos ){ std::string fileMeta = postdata.substr(0,200); std::string fileData = postdata.substr(start,end-start); if(fileData.length() > 50){ if(!createFolder("../attachments/" + uid)) return "create folder failed"; std::string filename = std::to_string(time(0)) + randomStr(6) + getFileExt(fileMeta); std::ofstream ofile("../attachments/" + uid + "/" + filename, std::ios::binary); ofile.write(fileData.c_str(),fileData.length()); ofile.close(); return uid + "/" + filename; } } return "error"; } void UpdateOnlineCount(){ while(1){ RestClient::response onlineinfo = RestClient::get("https://script.google.com/macros/s/AKfycbxQ0XJpdE669DlvQ9vSWGFp1iIoQsoqEnUBW_0K2sMaZ5lxazI/exec",false); if(onlineinfo.code == 200){ online = std::stoi(onlineinfo.body); if(online == 0){ online = 1; } }else{ online = -1; } boost::this_thread::sleep(boost::posix_time::seconds(300)); } } void InitOnlineCount(){ boost::thread t(&UpdateOnlineCount); t.detach(); } int GetOnlineCount(){ return online; } std::string ReplaceAll(std::string str, const std::string& from, const std::string& to) { size_t start_pos = 0; while((start_pos = str.find(from, start_pos)) != std::string::npos) { str.replace(start_pos, from.length(), to); start_pos += to.length(); // Handles case where 'to' is a substring of 'from' } return str; }
30.168478
163
0.615925
typcn
361c596d6d29a03461adeb08507ad930003bf0c4
2,729
hpp
C++
source/modus_core/scene/SceneTree.hpp
Gurman8r/modus
5c97a89f77c1c5733793dddc20c5ce4afe1fd134
[ "MIT" ]
null
null
null
source/modus_core/scene/SceneTree.hpp
Gurman8r/modus
5c97a89f77c1c5733793dddc20c5ce4afe1fd134
[ "MIT" ]
null
null
null
source/modus_core/scene/SceneTree.hpp
Gurman8r/modus
5c97a89f77c1c5733793dddc20c5ce4afe1fd134
[ "MIT" ]
null
null
null
#ifndef _ML_SCENE_TREE_HPP_ #define _ML_SCENE_TREE_HPP_ #include <modus_core/detail/Duration.hpp> #include <modus_core/detail/Matrix.hpp> #include <modus_core/scene/Node.hpp> #include <modus_core/system/EventSystem.hpp> #include <entt/entt.hpp> namespace ml { struct entity; struct ML_CORE_API scene_tree : non_copyable, trackable { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ public: using allocator_type = typename pmr::polymorphic_allocator<byte>; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ public: virtual ~scene_tree() noexcept override; scene_tree(string const & name, allocator_type alloc = {}) noexcept : m_name{ name.empty() ? "New Scene" : name, alloc } , m_reg {} , m_root{ _ML make_ref<node>(name, this, nullptr, alloc) } { } scene_tree(scene_tree && other, allocator_type alloc = {}) noexcept : m_name{ alloc } , m_reg {} , m_root{} { this->swap(std::move(other)); } scene_tree & operator=(scene_tree && other) noexcept { this->swap(std::move(other)); return (*this); } void swap(scene_tree & other) noexcept { if (this != std::addressof(other)) { std::swap(m_name, other.m_name); std::swap(m_reg, other.m_reg); std::swap(m_root, other.m_root); } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ public: ML_NODISCARD auto get_name() const noexcept -> string const & { return m_name; } ML_NODISCARD auto get_reg() noexcept -> entt::registry & { return m_reg; } ML_NODISCARD auto get_reg() const noexcept -> entt::registry const & { return m_reg; } ML_NODISCARD auto get_root() noexcept -> ref<node> & { return m_root; } ML_NODISCARD auto get_root() const noexcept -> ref<node> const & { return m_root; } void set_name(string const & name) noexcept { if (m_name != name) { m_name = name; } } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ public: void on_runtime_update(duration dt); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ protected: template <class T> void on_component_added(entity &, T &) {} /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ private: friend node; friend entity; string m_name ; // name entt::registry m_reg ; // registry ref<node> m_root ; // root node /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ }; } namespace ml { inline void from_json(json const & j, scene_tree & v) noexcept {} inline void to_json(json & j, scene_tree const & v) noexcept {} } #endif // !_ML_SCENE_TREE_HPP_
26.495146
88
0.532063
Gurman8r
361ec44caafd0e83f64d1e20577f767f9476eeab
1,249
cxx
C++
Applications/ColadaApp/StylePlugins/qColadaStylePlugin.cxx
TierraColada/Colada
c9d7ca30bfb5ec523722b35921c1e9e6a11a7914
[ "MIT" ]
null
null
null
Applications/ColadaApp/StylePlugins/qColadaStylePlugin.cxx
TierraColada/Colada
c9d7ca30bfb5ec523722b35921c1e9e6a11a7914
[ "MIT" ]
null
null
null
Applications/ColadaApp/StylePlugins/qColadaStylePlugin.cxx
TierraColada/Colada
c9d7ca30bfb5ec523722b35921c1e9e6a11a7914
[ "MIT" ]
null
null
null
// Colada includes #include "qColadaStylePlugin.h" #include "qColadaStyle.h" #include "qColadaDarkStyle.h" #include "qColadaLightStyle.h" // Qt includes #include <QStringList> #include <QStyle> // -------------------------------------------------------------------------- // qColadaStylePlugin methods //----------------------------------------------------------------------------- qColadaStylePlugin::qColadaStylePlugin() = default; //----------------------------------------------------------------------------- qColadaStylePlugin::~qColadaStylePlugin() = default; //----------------------------------------------------------------------------- QStyle* qColadaStylePlugin::create( const QString & key ) { if (key.compare("Colada", Qt::CaseInsensitive) == 0) { return new qColadaStyle(); } if (key.compare("Light Colada", Qt::CaseInsensitive) == 0) { return new qColadaLightStyle(); } if (key.compare("Dark Colada", Qt::CaseInsensitive) == 0) { return new qColadaDarkStyle(); } return nullptr; } //----------------------------------------------------------------------------- QStringList qColadaStylePlugin::keys() const { return QStringList() << "Colada" << "Light Colada" << "Dark Colada"; }
27.755556
79
0.472378
TierraColada
36215f8da755f7b074b410a6aa1ec73d18ffeef9
1,946
cc
C++
routines/test/latms.cc
luiscarbonell/nlapack
99d17f92f8f9bada17a89f72e8cc55486d848102
[ "MIT" ]
1
2019-05-24T21:31:59.000Z
2019-05-24T21:31:59.000Z
routines/test/latms.cc
luiscarbonell/nlapack
99d17f92f8f9bada17a89f72e8cc55486d848102
[ "MIT" ]
null
null
null
routines/test/latms.cc
luiscarbonell/nlapack
99d17f92f8f9bada17a89f72e8cc55486d848102
[ "MIT" ]
null
null
null
#include "routines.h" void dlatms(const v8::FunctionCallbackInfo<v8::Value>& info) { lapack_int m = info[0]->Uint32Value(); lapack_int n = info[1]->Uint32Value(); char dist = info[2]->Uint32Value(); lapack_int *iseed = reinterpret_cast<lapack_int*>(GET_CONTENTS(info[3].As<v8::Int32Array>())); char sym = info[4]->Uint32Value(); double *d = reinterpret_cast<double*>(GET_CONTENTS(info[5].As<v8::Float64Array>())); lapack_int mode = info[6]->Uint32Value(); double cond = info[7]->NumberValue(); double dmax = info[8]->NumberValue(); lapack_int kl = info[9]->Uint32Value(); lapack_int ku = info[10]->Uint32Value(); char pack = info[11]->Uint32Value(); double *a = reinterpret_cast<double*>(GET_CONTENTS(info[12].As<v8::Float64Array>())); lapack_int lda = info[13]->Uint32Value(); lapack_int i = LAPACKE_dlatms(LAPACK_ROW_MAJOR, m, n, dist, iseed, sym, d, mode, cond, dmax, kl, ku, pack, a, lda); info.GetReturnValue().Set( v8::Number::New(info.GetIsolate(), i) ); } void slatms(const v8::FunctionCallbackInfo<v8::Value>& info) { lapack_int m = info[0]->Uint32Value(); lapack_int n = info[1]->Uint32Value(); char dist = info[2]->Uint32Value(); lapack_int *iseed = reinterpret_cast<lapack_int*>(GET_CONTENTS(info[3].As<v8::Int32Array>())); char sym = info[4]->Uint32Value(); float *d = reinterpret_cast<float*>(GET_CONTENTS(info[5].As<v8::Float32Array>())); lapack_int mode = info[6]->Uint32Value(); float cond = info[7]->NumberValue(); float dmax = info[8]->NumberValue(); lapack_int kl = info[9]->Uint32Value(); lapack_int ku = info[10]->Uint32Value(); char pack = info[11]->Uint32Value(); float *a = reinterpret_cast<float*>(GET_CONTENTS(info[12].As<v8::Float32Array>())); lapack_int lda = info[13]->Uint32Value(); lapack_int i = LAPACKE_slatms(LAPACK_ROW_MAJOR, m, n, dist, iseed, sym, d, mode, cond, dmax, kl, ku, pack, a, lda); info.GetReturnValue().Set( v8::Number::New(info.GetIsolate(), i) ); }
40.541667
116
0.690647
luiscarbonell
362923b666a155565d1ac1073f28e047f628ff76
729
cpp
C++
class/friend_2clases.cpp
AAI1234S/cpp
b0037406694712e647ad55c01f5d73764e5a54b3
[ "MIT" ]
null
null
null
class/friend_2clases.cpp
AAI1234S/cpp
b0037406694712e647ad55c01f5d73764e5a54b3
[ "MIT" ]
null
null
null
class/friend_2clases.cpp
AAI1234S/cpp
b0037406694712e647ad55c01f5d73764e5a54b3
[ "MIT" ]
null
null
null
#include<iostream> class NUM2; //class forward declaration class NUM1 { int num1; public: void add_data() { std::cout<<"Enter the num:"<<std::endl; std::cin>>num1; } private: friend void sum(NUM1 , NUM2); //friend function declration to communicate with another class }; class NUM2 { int num2; public: void add_data(); private: friend void sum(NUM1, NUM2); }; void NUM2::add_data() { std::cout<<"Enter the num2:"<<std::endl; std::cin>>num2; } void sum(NUM1 ob1, NUM2 ob2) //friend function defination { std::cout<<ob1.num1<<" +"<<ob2.num2<<"="<<ob1.num1+ob2.num2; } int main() { NUM1 obj1; NUM2 obj2; obj1.add_data(); obj2.add_data(); sum(obj1, obj2); //friend function calling return 0; }
15.510638
96
0.654321
AAI1234S
3629ad56b2919990b6ddd86188e3f75626c2c7e8
659
hpp
C++
SDK/ARKSurvivalEvolved_E_EnforcerClimbingState_structs.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_E_EnforcerClimbingState_structs.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_E_EnforcerClimbingState_structs.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Basic.hpp" namespace sdk { //--------------------------------------------------------------------------- //Enums //--------------------------------------------------------------------------- // UserDefinedEnum E_EnforcerClimbingState.E_EnforcerClimbingState enum class E_EnforcerClimbingState : uint8_t { E_EnforcerClimbingState__NewEnumerator2 = 0, E_EnforcerClimbingState__NewEnumerator0 = 1, E_EnforcerClimbingState__NewEnumerator1 = 2, E_EnforcerClimbingState__E_MAX = 3 }; } #ifdef _MSC_VER #pragma pack(pop) #endif
19.969697
77
0.611533
2bite
362a30c2e786ff27c2b5e78f710402d6ef090f93
1,437
hpp
C++
src/continuousfusion.hpp
jhultman/continuous-fusion
1df1cc1488965fd5f101d66d1ca916a430d1dfd6
[ "MIT" ]
25
2019-06-19T11:55:53.000Z
2022-02-28T07:56:38.000Z
src/continuousfusion.hpp
jhultman/continuous-fusion
1df1cc1488965fd5f101d66d1ca916a430d1dfd6
[ "MIT" ]
1
2020-11-17T06:46:26.000Z
2021-11-04T11:49:38.000Z
src/continuousfusion.hpp
jhultman/continuous-fusion
1df1cc1488965fd5f101d66d1ca916a430d1dfd6
[ "MIT" ]
4
2020-07-16T01:59:47.000Z
2022-02-28T06:41:14.000Z
#ifndef CONTINUOUSFUSION_HPP #define CONTINUOUSFUSION_HPP #include <vector> #include <sensor_msgs/Image.h> #include <pcl_ros/point_cloud.h> #include <pcl/point_types.h> #include <image_transport/image_transport.h> #include <message_filters/synchronizer.h> #include <message_filters/subscriber.h> #include <message_filters/sync_policies/approximate_time.h> #include <opencv2/opencv.hpp> #include <opencv2/core/eigen.hpp> #include <Eigen/Dense> typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, sensor_msgs::PointCloud2> KittiSyncPolicy; class ContinuousFusion { private: cv::Mat _PRT; ros::NodeHandle _nh; image_transport::ImageTransport _xport; image_transport::Publisher _publisher; message_filters::Subscriber<sensor_msgs::Image> _imageSub; message_filters::Subscriber<sensor_msgs::PointCloud2> _veloSub; message_filters::Synchronizer<KittiSyncPolicy> _sync; Eigen::MatrixXf pcl2ToEigen(pcl::PCLPointCloud2 cloud); pcl::PCLPointCloud2 rosMsgToPcl2(const sensor_msgs::PointCloud2ConstPtr& cloudPtr); cv::Mat rosMsgToCvMat(const sensor_msgs::PointCloud2ConstPtr& cloudPtr); void publishBevImage(cv::Mat bevImage); public: ContinuousFusion(cv::Mat PRT); void callback( const sensor_msgs::ImageConstPtr& imageIn, const sensor_msgs::PointCloud2ConstPtr& veloIn); }; #endif
35.925
118
0.746695
jhultman
362d21123b1ecce9329dbbaf7bc42b566e924cbc
17,691
cpp
C++
01_Develop/libXMFFmpeg/Source/libavcodec/tiffenc.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
01_Develop/libXMFFmpeg/Source/libavcodec/tiffenc.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
01_Develop/libXMFFmpeg/Source/libavcodec/tiffenc.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* * TIFF image encoder * Copyright (c) 2007 Bartlomiej Wolowiec * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * TIFF image encoder * @author Bartlomiej Wolowiec */ #include "XMFFmpeg/libavutil/log.h" #include "XMFFmpeg/libavutil/opt.h" #include "internal.h" #if CONFIG_ZLIB #include <XMZlib/zlib.h> #endif #include "XMFFmpeg/libavutil/opt.h" #include "bytestream.h" #include "tiff.h" #include "rle.h" #include "lzw.h" #include "put_bits.h" #define TIFF_MAX_ENTRY 32 /** sizes of various TIFF field types (string size = 1)*/ static const uint8_t type_sizes2[6] = { 0, 1, 1, 2, 4, 8 }; typedef struct TiffEncoderContext { AVClass *av_class; ///< for private options AVCodecContext *avctx; AVFrame picture; int width; ///< picture width int height; ///< picture height unsigned int bpp; ///< bits per pixel int compr; ///< compression level int bpp_tab_size; ///< bpp_tab size int photometric_interpretation; ///< photometric interpretation int strips; ///< number of strips int rps; ///< row per strip uint8_t entries[TIFF_MAX_ENTRY*12]; ///< entires in header int num_entries; ///< number of entires uint8_t **buf; ///< actual position in buffer uint8_t *buf_start; ///< pointer to first byte in buffer int buf_size; ///< buffer size uint16_t subsampling[2]; ///< YUV subsampling factors struct LZWEncodeState *lzws; ///< LZW Encode state uint32_t dpi; ///< image resolution in DPI } TiffEncoderContext; /** * Check free space in buffer * @param s Tiff context * @param need Needed bytes * @return 0 - ok, 1 - no free space */ inline static int check_size(TiffEncoderContext * s, uint64_t need) { if (s->buf_size < *s->buf - s->buf_start + need) { *s->buf = s->buf_start + s->buf_size + 1; av_log(s->avctx, AV_LOG_ERROR, "Buffer is too small\n"); return 1; } return 0; } /** * Put n values to buffer * * @param p Pointer to pointer to output buffer * @param n Number of values * @param val Pointer to values * @param type Type of values * @param flip =0 - normal copy, >0 - flip */ static void tnput(uint8_t ** p, int n, const uint8_t * val, enum TiffTypes type, int flip) { int i; #if HAVE_BIGENDIAN flip ^= ((int[]) {0, 0, 0, 1, 3, 3})[type]; #endif for (i = 0; i < n * type_sizes2[type]; i++) *(*p)++ = val[i ^ flip]; } /** * Add entry to directory in tiff header. * @param s Tiff context * @param tag Tag that identifies the entry * @param type Entry type * @param count The number of values * @param ptr_val Pointer to values */ static void add_entry(TiffEncoderContext * s, enum TiffTags tag, enum TiffTypes type, int count, const void *ptr_val) { uint8_t *entries_ptr = s->entries + 12 * s->num_entries; assert(s->num_entries < TIFF_MAX_ENTRY); bytestream_put_le16(&entries_ptr, tag); bytestream_put_le16(&entries_ptr, type); bytestream_put_le32(&entries_ptr, count); if (type_sizes[type] * count <= 4) { tnput(&entries_ptr, count, (const uint8_t *)ptr_val, type, 0); } else { bytestream_put_le32(&entries_ptr, *s->buf - s->buf_start); check_size(s, count * type_sizes2[type]); tnput(s->buf, count, (const uint8_t *)ptr_val, type, 0); } s->num_entries++; } static void add_entry1(TiffEncoderContext * s, enum TiffTags tag, enum TiffTypes type, int val){ uint16_t w = val; uint32_t dw= val; add_entry(s, tag, type, 1, type == TIFF_SHORT ? (void *)&w : (void *)&dw); } /** * Encode one strip in tiff file * * @param s Tiff context * @param src Input buffer * @param dst Output buffer * @param n Size of input buffer * @param compr Compression method * @return Number of output bytes. If an output error is encountered, -1 returned */ static int encode_strip(TiffEncoderContext * s, const int8_t * src, uint8_t * dst, int n, int compr) { switch (compr) { #if CONFIG_ZLIB case TIFF_DEFLATE: case TIFF_ADOBE_DEFLATE: { unsigned long zlen = s->buf_size - (*s->buf - s->buf_start); if (compress(dst, (z_uLongf *)&zlen, (const z_Bytef *)src, n) != Z_OK) { av_log(s->avctx, AV_LOG_ERROR, "Compressing failed\n"); return -1; } return zlen; } #endif case TIFF_RAW: if (check_size(s, n)) return -1; memcpy(dst, src, n); return n; case TIFF_PACKBITS: return ff_rle_encode(dst, s->buf_size - (*s->buf - s->buf_start), (const uint8_t *)src, 1, n, 2, 0xff, -1, 0); case TIFF_LZW: return ff_lzw_encode(s->lzws, (const uint8_t *)src, n); default: return -1; } } static void pack_yuv(TiffEncoderContext * s, uint8_t * dst, int lnum) { AVFrame *p = &s->picture; int i, j, k; int w = (s->width - 1) / s->subsampling[0] + 1; uint8_t *pu = &p->data[1][lnum / s->subsampling[1] * p->linesize[1]]; uint8_t *pv = &p->data[2][lnum / s->subsampling[1] * p->linesize[2]]; for (i = 0; i < w; i++){ for (j = 0; j < s->subsampling[1]; j++) for (k = 0; k < s->subsampling[0]; k++) *dst++ = p->data[0][(lnum + j) * p->linesize[0] + i * s->subsampling[0] + k]; *dst++ = *pu++; *dst++ = *pv++; } } static int encode_frame(AVCodecContext * avctx, unsigned char *buf, int buf_size, void *data) { TiffEncoderContext *s = (TiffEncoderContext *)avctx->priv_data; AVFrame *pict = (AVFrame *)data; AVFrame *const p = (AVFrame *) & s->picture; int i; int n; uint8_t *ptr = buf; uint8_t *offset; uint32_t strips; uint32_t *strip_sizes = NULL; uint32_t *strip_offsets = NULL; int bytes_per_row; uint32_t res[2] = { s->dpi, 1 }; // image resolution (72/1) uint16_t bpp_tab[] = { 8, 8, 8, 8 }; int ret = -1; int is_yuv = 0; uint8_t *yuv_line = NULL; int shift_h, shift_v; s->avctx = avctx; s->buf_start = buf; s->buf = &ptr; s->buf_size = buf_size; *p = *pict; p->pict_type = AV_PICTURE_TYPE_I; p->key_frame = 1; avctx->coded_frame= &s->picture; #if FF_API_TIFFENC_COMPLEVEL if (avctx->compression_level != FF_COMPRESSION_DEFAULT) av_log(avctx, AV_LOG_WARNING, "Using compression_level to set compression " "algorithm is deprecated. Please use the compression_algo private " "option instead.\n"); if (avctx->compression_level == 0) { s->compr = TIFF_RAW; } else if(avctx->compression_level == 2) { s->compr = TIFF_LZW; #if CONFIG_ZLIB } else if ((avctx->compression_level >= 3)) { s->compr = TIFF_DEFLATE; #endif } #endif s->width = avctx->width; s->height = avctx->height; s->subsampling[0] = 1; s->subsampling[1] = 1; switch (avctx->pix_fmt) { case PIX_FMT_RGBA64LE: s->bpp = 64; s->photometric_interpretation = 2; bpp_tab[0] = 16; bpp_tab[1] = 16; bpp_tab[2] = 16; bpp_tab[3] = 16; break; case PIX_FMT_RGB48LE: s->bpp = 48; s->photometric_interpretation = 2; bpp_tab[0] = 16; bpp_tab[1] = 16; bpp_tab[2] = 16; bpp_tab[3] = 16; break; case PIX_FMT_RGBA: s->bpp = 32; s->photometric_interpretation = 2; break; case PIX_FMT_RGB24: s->bpp = 24; s->photometric_interpretation = 2; break; case PIX_FMT_GRAY8: s->bpp = 8; s->photometric_interpretation = 1; break; case PIX_FMT_PAL8: s->bpp = 8; s->photometric_interpretation = 3; break; case PIX_FMT_MONOBLACK: case PIX_FMT_MONOWHITE: s->bpp = 1; s->photometric_interpretation = avctx->pix_fmt == PIX_FMT_MONOBLACK; bpp_tab[0] = 1; break; case PIX_FMT_YUV420P: case PIX_FMT_YUV422P: case PIX_FMT_YUV444P: case PIX_FMT_YUV410P: case PIX_FMT_YUV411P: s->photometric_interpretation = 6; avcodec_get_chroma_sub_sample(avctx->pix_fmt, &shift_h, &shift_v); s->bpp = 8 + (16 >> (shift_h + shift_v)); s->subsampling[0] = 1 << shift_h; s->subsampling[1] = 1 << shift_v; s->bpp_tab_size = 3; is_yuv = 1; break; default: av_log(s->avctx, AV_LOG_ERROR, "This colors format is not supported\n"); return -1; } if (!is_yuv) s->bpp_tab_size = (s->bpp >= 48) ? ((s->bpp + 7) >> 4):((s->bpp + 7) >> 3); if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE || s->compr == TIFF_LZW) //best choose for DEFLATE s->rps = s->height; else s->rps = FFMAX(8192 / (((s->width * s->bpp) >> 3) + 1), 1); // suggest size of strip s->rps = ((s->rps - 1) / s->subsampling[1] + 1) * s->subsampling[1]; // round rps up strips = (s->height - 1) / s->rps + 1; if (check_size(s, 8)) goto fail; // write header bytestream_put_le16(&ptr, 0x4949); bytestream_put_le16(&ptr, 42); offset = ptr; bytestream_put_le32(&ptr, 0); strip_sizes = (uint32_t *)av_mallocz(sizeof(*strip_sizes) * strips); strip_offsets = (uint32_t *)av_mallocz(sizeof(*strip_offsets) * strips); bytes_per_row = (((s->width - 1)/s->subsampling[0] + 1) * s->bpp * s->subsampling[0] * s->subsampling[1] + 7) >> 3; if (is_yuv){ yuv_line = (uint8_t *)av_malloc(bytes_per_row); if (yuv_line == NULL){ av_log(s->avctx, AV_LOG_ERROR, "Not enough memory\n"); goto fail; } } #if CONFIG_ZLIB if (s->compr == TIFF_DEFLATE || s->compr == TIFF_ADOBE_DEFLATE) { uint8_t *zbuf; int zlen, zn; int j; zlen = bytes_per_row * s->rps; zbuf = (uint8_t *)av_malloc(zlen); strip_offsets[0] = ptr - buf; zn = 0; for (j = 0; j < s->rps; j++) { if (is_yuv){ pack_yuv(s, yuv_line, j); memcpy(zbuf + zn, yuv_line, bytes_per_row); j += s->subsampling[1] - 1; } else memcpy(zbuf + j * bytes_per_row, p->data[0] + j * p->linesize[0], bytes_per_row); zn += bytes_per_row; } n = encode_strip(s, (const int8_t *)zbuf, ptr, zn, s->compr); av_free(zbuf); if (n<0) { av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n"); goto fail; } ptr += n; strip_sizes[0] = ptr - buf - strip_offsets[0]; } else #endif { if(s->compr == TIFF_LZW) s->lzws = (LZWEncodeState *)av_malloc(ff_lzw_encode_state_size); for (i = 0; i < s->height; i++) { if (strip_sizes[i / s->rps] == 0) { if(s->compr == TIFF_LZW){ ff_lzw_encode_init(s->lzws, ptr, s->buf_size - (*s->buf - s->buf_start), 12, FF_LZW_TIFF, put_bits); } strip_offsets[i / s->rps] = ptr - buf; } if (is_yuv){ pack_yuv(s, yuv_line, i); n = encode_strip(s, (const int8_t *)yuv_line, ptr, bytes_per_row, s->compr); i += s->subsampling[1] - 1; } else n = encode_strip(s, (const int8_t *)(p->data[0] + i * p->linesize[0]), ptr, bytes_per_row, s->compr); if (n < 0) { av_log(s->avctx, AV_LOG_ERROR, "Encode strip failed\n"); goto fail; } strip_sizes[i / s->rps] += n; ptr += n; if(s->compr == TIFF_LZW && (i==s->height-1 || i%s->rps == s->rps-1)){ int ret; ret = ff_lzw_encode_flush(s->lzws, flush_put_bits); strip_sizes[(i / s->rps )] += ret ; ptr += ret; } } if(s->compr == TIFF_LZW) av_free(s->lzws); } s->num_entries = 0; add_entry1(s,TIFF_SUBFILE, TIFF_LONG, 0); add_entry1(s,TIFF_WIDTH, TIFF_LONG, s->width); add_entry1(s,TIFF_HEIGHT, TIFF_LONG, s->height); if (s->bpp_tab_size) add_entry(s, TIFF_BPP, TIFF_SHORT, s->bpp_tab_size, bpp_tab); add_entry1(s,TIFF_COMPR, TIFF_SHORT, s->compr); add_entry1(s,TIFF_INVERT, TIFF_SHORT, s->photometric_interpretation); add_entry(s, TIFF_STRIP_OFFS, TIFF_LONG, strips, strip_offsets); if (s->bpp_tab_size) add_entry1(s,TIFF_SAMPLES_PER_PIXEL, TIFF_SHORT, s->bpp_tab_size); add_entry1(s,TIFF_ROWSPERSTRIP, TIFF_LONG, s->rps); add_entry(s, TIFF_STRIP_SIZE, TIFF_LONG, strips, strip_sizes); add_entry(s, TIFF_XRES, TIFF_RATIONAL, 1, res); add_entry(s, TIFF_YRES, TIFF_RATIONAL, 1, res); add_entry1(s,TIFF_RES_UNIT, TIFF_SHORT, 2); if(!(avctx->flags & CODEC_FLAG_BITEXACT)) add_entry(s, TIFF_SOFTWARE_NAME, TIFF_STRING, strlen(LIBAVCODEC_IDENT) + 1, LIBAVCODEC_IDENT); if (avctx->pix_fmt == PIX_FMT_PAL8) { uint16_t pal[256 * 3]; for (i = 0; i < 256; i++) { uint32_t rgb = *(uint32_t *) (p->data[1] + i * 4); pal[i] = ((rgb >> 16) & 0xff) * 257; pal[i + 256] = ((rgb >> 8 ) & 0xff) * 257; pal[i + 512] = ( rgb & 0xff) * 257; } add_entry(s, TIFF_PAL, TIFF_SHORT, 256 * 3, pal); } if (is_yuv){ /** according to CCIR Recommendation 601.1 */ uint32_t refbw[12] = {15, 1, 235, 1, 128, 1, 240, 1, 128, 1, 240, 1}; add_entry(s, TIFF_YCBCR_SUBSAMPLING, TIFF_SHORT, 2, s->subsampling); add_entry(s, TIFF_REFERENCE_BW, TIFF_RATIONAL, 6, refbw); } bytestream_put_le32(&offset, ptr - buf); // write offset to dir if (check_size(s, 6 + s->num_entries * 12)) goto fail; bytestream_put_le16(&ptr, s->num_entries); // write tag count bytestream_put_buffer(&ptr, s->entries, s->num_entries * 12); bytestream_put_le32(&ptr, 0); ret = ptr - buf; fail: av_free(strip_sizes); av_free(strip_offsets); av_free(yuv_line); return ret; } #define OFFSET(x) offsetof(TiffEncoderContext, x) #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM static const AVOption options[] = { {"dpi", "set the image resolution (in dpi)", OFFSET(dpi), AV_OPT_TYPE_INT, 72, NULL, 1, 0x10000, AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_ENCODING_PARAM}, { "compression_algo", NULL, OFFSET(compr), AV_OPT_TYPE_INT, TIFF_PACKBITS, NULL, TIFF_RAW, TIFF_DEFLATE, VE, "compression_algo" }, { "packbits", NULL, 0, AV_OPT_TYPE_CONST, TIFF_PACKBITS, NULL, 0, 0, VE, "compression_algo" }, { "raw", NULL, 0, AV_OPT_TYPE_CONST, TIFF_RAW , NULL, 0, 0, VE, "compression_algo" }, { "lzw", NULL, 0, AV_OPT_TYPE_CONST, TIFF_LZW , NULL, 0, 0, VE, "compression_algo" }, #if CONFIG_ZLIB { "deflate", NULL, 0, AV_OPT_TYPE_CONST, TIFF_DEFLATE , NULL, 0, 0, VE, "compression_algo" }, #endif { NULL }, }; static const AVClass tiffenc_class = { /*.class_name = */ "TIFF encoder", /*.item_name = */ av_default_item_name, /*.option = */ options, /*.version = */ LIBAVUTIL_VERSION_INT, }; static const enum PixelFormat _ff_tiff_encoder[] = { PIX_FMT_RGB24, PIX_FMT_PAL8, PIX_FMT_GRAY8, PIX_FMT_MONOBLACK, PIX_FMT_MONOWHITE, PIX_FMT_YUV420P, PIX_FMT_YUV422P, PIX_FMT_YUV444P, PIX_FMT_YUV410P, PIX_FMT_YUV411P, PIX_FMT_RGB48LE, PIX_FMT_RGBA, PIX_FMT_RGBA64LE, PIX_FMT_NONE }; AVCodec ff_tiff_encoder = { /*.name = */ "tiff", /*.type = */ AVMEDIA_TYPE_VIDEO, /*.id = */ CODEC_ID_TIFF, /*.priv_data_size = */ sizeof(TiffEncoderContext), /*.init = */ 0, /*.encode = */ encode_frame, /*.close = */ 0, /*.decode = */ 0, /*.capabilities = */ 0, /*.next = */ 0, /*.flush = */ 0, /*.supported_framerates = */ 0, /*.pix_fmts = */ _ff_tiff_encoder, /*.long_name = */ NULL_IF_CONFIG_SMALL("TIFF image"), /*.supported_samplerates= */ 0, /*.sample_fmts = */ 0, /*.channel_layouts = */ 0, /*.max_lowres = */ 0, /*.priv_class = */ &tiffenc_class, };
33.56926
153
0.562602
mcodegeeks
1566dfe1662d7236050250c509af08ad25e2522f
863
cpp
C++
QtMario_Youtube-master/Mario_Updated/notebox.cpp
Rossterrrr/Qt
3e5c2934ce19675390d2ad6d513a14964d8cbe50
[ "MIT" ]
3
2019-09-02T05:17:08.000Z
2021-01-07T11:21:34.000Z
notebox.cpp
hadimousavi79/Super_Mario
89e0656de26b561d3713c6265c8a4f8695e25d9b
[ "MIT" ]
null
null
null
notebox.cpp
hadimousavi79/Super_Mario
89e0656de26b561d3713c6265c8a4f8695e25d9b
[ "MIT" ]
null
null
null
/* * Author: equati0n * Date: December 2016 */ #include "notebox.h" #include <QPainter> NoteBox::NoteBox(int length,QGraphicsItem *parent): QGraphicsItem(parent) ,mCurrentFrame(), mLength(length) { setFlag(ItemClipsToShape); mPixmap10 = QPixmap(":images/notebox.png"); } void NoteBox::nextFrame(){ mCurrentFrame += 65; if (mCurrentFrame >= 518 ) { mCurrentFrame = 0; } } QRectF NoteBox::boundingRect() const { return QRectF(0,0,63* mLength,63); } void NoteBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); Q_UNUSED(option); for(int i = 0; i < 63*mLength; ++i) { painter->drawPixmap(i*63,0, mPixmap10, mCurrentFrame, 0,63, 63); } setTransformOriginPoint(boundingRect().center()); } int NoteBox::type() const { return Type; }
19.177778
97
0.658169
Rossterrrr
156adb3eac6c007bd195d54680eb056a2296f8a6
2,100
cpp
C++
source/src/algorithms.cpp
ndoxx/wcore
8b24519e9a01b0397ba2959507e1e12ea3a3aa44
[ "Apache-2.0" ]
null
null
null
source/src/algorithms.cpp
ndoxx/wcore
8b24519e9a01b0397ba2959507e1e12ea3a3aa44
[ "Apache-2.0" ]
null
null
null
source/src/algorithms.cpp
ndoxx/wcore
8b24519e9a01b0397ba2959507e1e12ea3a3aa44
[ "Apache-2.0" ]
null
null
null
#include "algorithms.h" #include "math3d.h" namespace wcore { namespace math { // Previous power of 2 of x uint32_t pp2(uint32_t x) { x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return x - (x >> 1); } // Next power of 2 of x uint32_t np2(uint32_t x) { --x; x |= x >> 1; x |= x >> 2; x |= x >> 4; x |= x >> 8; x |= x >> 16; return ++x; } void compute_extent(const std::vector<math::vec3>& vertices, std::array<float,6>& extent) { extent[0] = std::numeric_limits<float>::max(); extent[1] = -std::numeric_limits<float>::max(); extent[2] = std::numeric_limits<float>::max(); extent[3] = -std::numeric_limits<float>::max(); extent[4] = std::numeric_limits<float>::max(); extent[5] = -std::numeric_limits<float>::max(); for(uint32_t ii=0; ii<vertices.size(); ++ii) { // OBB vertices const vec3& vertex = vertices[ii]; extent[0] = fmin(extent[0], vertex.x()); extent[1] = fmax(extent[1], vertex.x()); extent[2] = fmin(extent[2], vertex.y()); extent[3] = fmax(extent[3], vertex.y()); extent[4] = fmin(extent[4], vertex.z()); extent[5] = fmax(extent[5], vertex.z()); } } void compute_extent(const std::array<math::vec3, 8>& vertices, std::array<float,6>& extent) { extent[0] = std::numeric_limits<float>::max(); extent[1] = -std::numeric_limits<float>::max(); extent[2] = std::numeric_limits<float>::max(); extent[3] = -std::numeric_limits<float>::max(); extent[4] = std::numeric_limits<float>::max(); extent[5] = -std::numeric_limits<float>::max(); for(uint32_t ii=0; ii<8; ++ii) { // OBB vertices const vec3& vertex = vertices[ii]; extent[0] = fmin(extent[0], vertex.x()); extent[1] = fmax(extent[1], vertex.x()); extent[2] = fmin(extent[2], vertex.y()); extent[3] = fmax(extent[3], vertex.y()); extent[4] = fmin(extent[4], vertex.z()); extent[5] = fmax(extent[5], vertex.z()); } } } // namespace math } // namespace wcore
26.25
91
0.547619
ndoxx
156af671e5fbe397cd16d620101b8b320fd176c4
23,409
cxx
C++
main/bridges/source/cpp_uno/msvc_win64_x86-64/except.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/bridges/source/cpp_uno/msvc_win64_x86-64/except.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/bridges/source/cpp_uno/msvc_win64_x86-64/except.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_bridges.hxx" #pragma warning( disable : 4237 ) #include <hash_map> #include <sal/config.h> #include <malloc.h> #include <typeinfo.h> #include <signal.h> #include "rtl/alloc.h" #include "rtl/strbuf.hxx" #include "rtl/ustrbuf.hxx" #include "com/sun/star/uno/Any.hxx" #include "mscx.hxx" #pragma pack(push, 8) using namespace ::com::sun::star::uno; using namespace ::std; using namespace ::osl; using namespace ::rtl; namespace CPPU_CURRENT_NAMESPACE { //================================================================================================== static inline OUString toUNOname( OUString const & rRTTIname ) throw () { OUStringBuffer aRet( 64 ); OUString aStr( rRTTIname.copy( 4, rRTTIname.getLength()-4-2 ) ); // filter .?AUzzz@yyy@xxx@@ sal_Int32 nPos = aStr.getLength(); while (nPos > 0) { sal_Int32 n = aStr.lastIndexOf( '@', nPos ); aRet.append( aStr.copy( n +1, nPos -n -1 ) ); if (n >= 0) { aRet.append( (sal_Unicode)'.' ); } nPos = n; } return aRet.makeStringAndClear(); } //================================================================================================== static inline OUString toRTTIname( OUString const & rUNOname ) throw () { OUStringBuffer aRet( 64 ); aRet.appendAscii( RTL_CONSTASCII_STRINGPARAM(".?AV") ); // class ".?AV"; struct ".?AU" sal_Int32 nPos = rUNOname.getLength(); while (nPos > 0) { sal_Int32 n = rUNOname.lastIndexOf( '.', nPos ); aRet.append( rUNOname.copy( n +1, nPos -n -1 ) ); aRet.append( (sal_Unicode)'@' ); nPos = n; } aRet.append( (sal_Unicode)'@' ); return aRet.makeStringAndClear(); } //################################################################################################## //#### RTTI simulation ############################################################################# //################################################################################################## typedef hash_map< OUString, void *, OUStringHash, equal_to< OUString > > t_string2PtrMap; //================================================================================================== class RTTInfos { Mutex _aMutex; t_string2PtrMap _allRTTI; static OUString toRawName( OUString const & rUNOname ) throw (); public: type_info * getRTTI( OUString const & rUNOname ) throw (); RTTInfos(); ~RTTInfos(); }; //================================================================================================== class __type_info { friend type_info * RTTInfos::getRTTI( OUString const & ) throw (); friend int mscx_filterCppException( LPEXCEPTION_POINTERS, uno_Any *, uno_Mapping * ); public: virtual ~__type_info() throw (); inline __type_info( void * m_vtable, const char * m_d_name ) throw () : _m_vtable( m_vtable ) , _m_name( NULL ) { ::strcpy( _m_d_name, m_d_name ); } // #100211# - checked size_t length() const { return sizeof(__type_info) + strlen(_m_d_name); } private: void * _m_vtable; char * _m_name; // cached copy of unmangled name, NULL initially char _m_d_name[1]; // mangled name }; //__________________________________________________________________________________________________ __type_info::~__type_info() throw () { } //__________________________________________________________________________________________________ type_info * RTTInfos::getRTTI( OUString const & rUNOname ) throw () { // a must be OSL_ENSURE( sizeof(__type_info) == sizeof(type_info), "### type info structure size differ!" ); MutexGuard aGuard( _aMutex ); t_string2PtrMap::const_iterator const iFind( _allRTTI.find( rUNOname ) ); // check if type is already available if (iFind == _allRTTI.end()) { // insert new type_info OString aRawName( OUStringToOString( toRTTIname( rUNOname ), RTL_TEXTENCODING_ASCII_US ) ); __type_info * pRTTI = new( ::rtl_allocateMemory( sizeof(__type_info) + aRawName.getLength() ) ) __type_info( NULL, aRawName.getStr() ); // put into map pair< t_string2PtrMap::iterator, bool > insertion( _allRTTI.insert( t_string2PtrMap::value_type( rUNOname, pRTTI ) ) ); OSL_ENSURE( insertion.second, "### rtti insertion failed?!" ); return (type_info *)pRTTI; } else { return (type_info *)iFind->second; } } //__________________________________________________________________________________________________ RTTInfos::RTTInfos() throw () { } //__________________________________________________________________________________________________ RTTInfos::~RTTInfos() throw () { #if OSL_DEBUG_LEVEL > 1 OSL_TRACE( "> freeing generated RTTI infos... <\n" ); #endif MutexGuard aGuard( _aMutex ); for ( t_string2PtrMap::const_iterator iPos( _allRTTI.begin() ); iPos != _allRTTI.end(); ++iPos ) { __type_info * pType = (__type_info *)iPos->second; pType->~__type_info(); // obsolete, but good style... ::rtl_freeMemory( pType ); } } //################################################################################################## //#### Exception raising ########################################################################### //################################################################################################## //================================================================================================== static void * __copyConstruct( void * pExcThis, void * pSource, typelib_TypeDescription *pTypeDescr ) throw () { ::uno_copyData( pExcThis, pSource, pTypeDescr, cpp_acquire ); return pExcThis; } //================================================================================================== static void * __destruct( void * pExcThis, typelib_TypeDescription *pTypeDescr ) throw () { ::uno_destructData( pExcThis, pTypeDescr, cpp_release ); return pExcThis; } //================================================================================================== int const codeSnippetSize = 32; void copyConstructCodeSnippet( unsigned char * code, typelib_TypeDescription * pTypeDescr ) throw () { unsigned char * p = code; // mov r8, pTypeDescr *p++ = 0x49; *p++ = 0xb8; *p++ = ((sal_uIntPtr)(pTypeDescr)) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 8) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 16) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 24) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 32) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 40) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 48) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 56) & 0xff; // mov r9, __copyConstruct *p++ = 0x49; *p++ = 0xb9; *p++ = ((sal_uIntPtr)(&__copyConstruct)) & 0xff; *p++ = (((sal_uIntPtr)(&__copyConstruct)) >> 8) & 0xff; *p++ = (((sal_uIntPtr)(&__copyConstruct)) >> 16) & 0xff; *p++ = (((sal_uIntPtr)(&__copyConstruct)) >> 24) & 0xff; *p++ = (((sal_uIntPtr)(&__copyConstruct)) >> 32) & 0xff; *p++ = (((sal_uIntPtr)(&__copyConstruct)) >> 40) & 0xff; *p++ = (((sal_uIntPtr)(&__copyConstruct)) >> 48) & 0xff; *p++ = (((sal_uIntPtr)(&__copyConstruct)) >> 56) & 0xff; // jmp r9 *p++ = 0x41; *p++ = 0xff; *p++ = 0xe1; OSL_ASSERT(p - code <= codeSnippetSize); } //================================================================================================== void destructCodeSnippet( unsigned char * code, typelib_TypeDescription * pTypeDescr ) throw () { unsigned char * p = code; // mov rdx, pTypeDescr *p++ = 0x48; *p++ = 0xba; *p++ = ((sal_uIntPtr)(pTypeDescr)) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 8) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 16) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 24) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 32) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 40) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 48) & 0xff; *p++ = (((sal_uIntPtr)(pTypeDescr)) >> 56) & 0xff; // mov r9, __destruct *p++ = 0x49; *p++ = 0xb9; *p++ = ((sal_uIntPtr)(&__destruct)) & 0xff; *p++ = (((sal_uIntPtr)(&__destruct)) >> 8) & 0xff; *p++ = (((sal_uIntPtr)(&__destruct)) >> 16) & 0xff; *p++ = (((sal_uIntPtr)(&__destruct)) >> 24) & 0xff; *p++ = (((sal_uIntPtr)(&__destruct)) >> 32) & 0xff; *p++ = (((sal_uIntPtr)(&__destruct)) >> 40) & 0xff; *p++ = (((sal_uIntPtr)(&__destruct)) >> 48) & 0xff; *p++ = (((sal_uIntPtr)(&__destruct)) >> 56) & 0xff; // jmp r9 *p++ = 0x41; *p++ = 0xff; *p++ = 0xe1; OSL_ASSERT(p - code <= codeSnippetSize); } //================================================================================================== static size_t align16(size_t size) { return ((size + 15) >> 4) << 4; } //================================================================================================== // Known as "catchabletype" in https://github.com/icestudent/ontl/blob/master/ntl/nt/exception.hxx struct ExceptionType { sal_Int32 _n0; sal_uInt32 _pTypeInfo; // type_info *, RVA on Win64 sal_Int32 _n1, _n2, _n3; // pointer to member descriptor, 12 bytes. sal_uInt32 _n4; sal_uInt32 _pCopyCtor; // RVA on Win64 sal_Int32 _n5; static void initialize( unsigned char *p, sal_uInt32 typeInfoRVA, typelib_TypeDescription * pTypeDescr, sal_uInt32 copyConstructorRVA ) throw () { ExceptionType *e = (ExceptionType*)p; e->_n0 = 0; e->_pTypeInfo = typeInfoRVA; e->_n1 = 0; e->_n2 = -1; e->_n3 = 0; e->_n4 = pTypeDescr->nSize; e->_pCopyCtor = copyConstructorRVA; e->_n5 = 0; } }; //================================================================================================== // Known as "throwinfo" in https://github.com/icestudent/ontl/blob/master/ntl/nt/exception.hxx struct RaiseInfo { // Microsoft's fields: sal_uInt32 _n0; sal_uInt32 _pDtor; // RVA on Win64 sal_uInt32 _n2; sal_uInt32 _types; // void *, RVA on Win64 // Our additional fields: typelib_TypeDescription * pTypeDescr; unsigned char *baseAddress; // The RVAs are relative to this field RaiseInfo( typelib_TypeDescription * pTypeDescr ) throw (); ~RaiseInfo() throw (); }; //__________________________________________________________________________________________________ RaiseInfo::RaiseInfo( typelib_TypeDescription * pTypeDescr ) throw () : _n0( 0 ) , _n2( 0 ) { // a must be OSL_ENSURE( sizeof(sal_Int32) == sizeof(ExceptionType *), "### pointer size differs from sal_Int32!" ); ::typelib_typedescription_acquire( pTypeDescr ); this->pTypeDescr = pTypeDescr; typelib_CompoundTypeDescription * pCompTypeDescr; size_t bytesNeeded = codeSnippetSize; // destructCodeSnippet for _pDtor sal_uInt32 typeCount = 0; for ( pCompTypeDescr = (typelib_CompoundTypeDescription*)pTypeDescr; pCompTypeDescr; pCompTypeDescr = pCompTypeDescr->pBaseTypeDescription ) { ++typeCount; bytesNeeded += align16( sizeof( ExceptionType ) ); __type_info *typeInfo = (__type_info*) mscx_getRTTI( ((typelib_TypeDescription *)pCompTypeDescr)->pTypeName ); bytesNeeded += align16( typeInfo->length() ); bytesNeeded += codeSnippetSize; // copyConstructCodeSnippet for its _pCopyCtor } // type info count accompanied by RVAs of type info ptrs: type, base type, base base type, ... bytesNeeded += align16( sizeof( sal_uInt32 ) + (typeCount * sizeof( sal_uInt32 )) ); unsigned char *p = (unsigned char*) ::rtl_allocateMemory( bytesNeeded ); DWORD old_protect; #if OSL_DEBUG_LEVEL > 0 BOOL success = #endif VirtualProtect( p, bytesNeeded, PAGE_EXECUTE_READWRITE, &old_protect ); OSL_ENSURE( success, "VirtualProtect() failed!" ); baseAddress = p; destructCodeSnippet( p, pTypeDescr ); _pDtor = (sal_uInt32)(p - baseAddress); p += codeSnippetSize; sal_uInt32 *types = (sal_uInt32*)p; _types = (sal_uInt32)(p - baseAddress); p += align16( sizeof( sal_uInt32 ) + (typeCount * sizeof( sal_uInt32 )) ); types[0] = typeCount; int next = 1; for ( pCompTypeDescr = (typelib_CompoundTypeDescription*)pTypeDescr; pCompTypeDescr; pCompTypeDescr = pCompTypeDescr->pBaseTypeDescription ) { __type_info *typeInfo = (__type_info*) mscx_getRTTI( ((typelib_TypeDescription *)pCompTypeDescr)->pTypeName ); memcpy(p, typeInfo, typeInfo->length() ); sal_uInt32 typeInfoRVA = (sal_uInt32)(p - baseAddress); p += align16( typeInfo->length() ); copyConstructCodeSnippet( p, (typelib_TypeDescription *)pCompTypeDescr ); sal_uInt32 copyConstructorRVA = (sal_uInt32)(p - baseAddress); p += codeSnippetSize; ExceptionType::initialize( p, typeInfoRVA, (typelib_TypeDescription *)pCompTypeDescr, copyConstructorRVA ); types[next++] = (sal_uInt32)(p - baseAddress); p += align16( sizeof(ExceptionType) ); } OSL_ASSERT(p - baseAddress <= bytesNeeded); } //__________________________________________________________________________________________________ RaiseInfo::~RaiseInfo() throw () { ::rtl_freeMemory( baseAddress ); ::typelib_typedescription_release( pTypeDescr ); } //================================================================================================== class ExceptionInfos { Mutex _aMutex; t_string2PtrMap _allRaiseInfos; public: static RaiseInfo * getRaiseInfo( typelib_TypeDescription * pTypeDescr ) throw (); ExceptionInfos() throw (); ~ExceptionInfos() throw (); }; //__________________________________________________________________________________________________ ExceptionInfos::ExceptionInfos() throw () { } //__________________________________________________________________________________________________ ExceptionInfos::~ExceptionInfos() throw () { #if OSL_DEBUG_LEVEL > 1 OSL_TRACE( "> freeing exception infos... <\n" ); #endif MutexGuard aGuard( _aMutex ); for ( t_string2PtrMap::const_iterator iPos( _allRaiseInfos.begin() ); iPos != _allRaiseInfos.end(); ++iPos ) { delete (RaiseInfo *)iPos->second; } } //__________________________________________________________________________________________________ RaiseInfo * ExceptionInfos::getRaiseInfo( typelib_TypeDescription * pTypeDescr ) throw () { static ExceptionInfos * s_pInfos = 0; if (! s_pInfos) { MutexGuard aGuard( Mutex::getGlobalMutex() ); if (! s_pInfos) { #ifdef LEAK_STATIC_DATA s_pInfos = new ExceptionInfos(); #else static ExceptionInfos s_allExceptionInfos; s_pInfos = &s_allExceptionInfos; #endif } } OSL_ASSERT( pTypeDescr && (pTypeDescr->eTypeClass == typelib_TypeClass_STRUCT || pTypeDescr->eTypeClass == typelib_TypeClass_EXCEPTION) ); void * pRaiseInfo; OUString const & rTypeName = *reinterpret_cast< OUString * >( &pTypeDescr->pTypeName ); MutexGuard aGuard( s_pInfos->_aMutex ); t_string2PtrMap::const_iterator const iFind( s_pInfos->_allRaiseInfos.find( rTypeName ) ); if (iFind == s_pInfos->_allRaiseInfos.end()) { pRaiseInfo = new RaiseInfo( pTypeDescr ); // put into map pair< t_string2PtrMap::iterator, bool > insertion( s_pInfos->_allRaiseInfos.insert( t_string2PtrMap::value_type( rTypeName, pRaiseInfo ) ) ); OSL_ENSURE( insertion.second, "### raise info insertion failed?!" ); } else { // reuse existing info pRaiseInfo = iFind->second; } return (RaiseInfo*) pRaiseInfo; } //################################################################################################## //#### exported #################################################################################### //################################################################################################## //################################################################################################## type_info * mscx_getRTTI( OUString const & rUNOname ) { static RTTInfos * s_pRTTIs = 0; if (! s_pRTTIs) { MutexGuard aGuard( Mutex::getGlobalMutex() ); if (! s_pRTTIs) { #ifdef LEAK_STATIC_DATA s_pRTTIs = new RTTInfos(); #else static RTTInfos s_aRTTIs; s_pRTTIs = &s_aRTTIs; #endif } } return s_pRTTIs->getRTTI( rUNOname ); } //################################################################################################## void mscx_raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp ) { // no ctor/dtor in here: this leads to dtors called twice upon RaiseException()! // thus this obj file will be compiled without opt, so no inling of // ExceptionInfos::getRaiseInfo() // construct cpp exception object typelib_TypeDescription * pTypeDescr = 0; TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType ); void * pCppExc = alloca( pTypeDescr->nSize ); ::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp ); // a must be OSL_ENSURE( sizeof(sal_Int32) == sizeof(void *), "### pointer size differs from sal_Int32!" ); RaiseInfo *raiseInfo = ExceptionInfos::getRaiseInfo( pTypeDescr ); ULONG_PTR arFilterArgs[4]; arFilterArgs[0] = MSVC_magic_number; arFilterArgs[1] = (ULONG_PTR)pCppExc; arFilterArgs[2] = (ULONG_PTR)raiseInfo; arFilterArgs[3] = (ULONG_PTR)raiseInfo->baseAddress; // destruct uno exception ::uno_any_destruct( pUnoExc, 0 ); TYPELIB_DANGER_RELEASE( pTypeDescr ); // last point to release anything not affected by stack unwinding RaiseException( MSVC_ExceptionCode, EXCEPTION_NONCONTINUABLE, 4, arFilterArgs ); } //############################################################################## int mscx_filterCppException( EXCEPTION_POINTERS * pPointers, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno ) { if (pPointers == 0) return EXCEPTION_CONTINUE_SEARCH; EXCEPTION_RECORD * pRecord = pPointers->ExceptionRecord; // handle only C++ exceptions: if (pRecord == 0 || pRecord->ExceptionCode != MSVC_ExceptionCode) return EXCEPTION_CONTINUE_SEARCH; #if _MSC_VER < 1300 // MSVC -6 bool rethrow = (pRecord->NumberParameters < 3 || pRecord->ExceptionInformation[ 2 ] == 0); #else bool rethrow = __CxxDetectRethrow( &pRecord ); OSL_ASSERT( pRecord == pPointers->ExceptionRecord ); #endif if (rethrow && pRecord == pPointers->ExceptionRecord) { // hack to get msvcrt internal _curexception field: pRecord = *reinterpret_cast< EXCEPTION_RECORD ** >( reinterpret_cast< char * >( __pxcptinfoptrs() ) + // as long as we don't demand msvcr source as build prerequisite // (->platform sdk), we have to code those offsets here. // // crt\src\mtdll.h: // offsetof (_tiddata, _curexception) - // offsetof (_tiddata, _tpxcptinfoptrs): 48 ); } // rethrow: handle only C++ exceptions: if (pRecord == 0 || pRecord->ExceptionCode != MSVC_ExceptionCode) return EXCEPTION_CONTINUE_SEARCH; if (pRecord->NumberParameters == 4 && // pRecord->ExceptionInformation[ 0 ] == MSVC_magic_number && pRecord->ExceptionInformation[ 1 ] != 0 && pRecord->ExceptionInformation[ 2 ] != 0 && pRecord->ExceptionInformation[ 3 ] != 0) { unsigned char *baseAddress = (unsigned char*) pRecord->ExceptionInformation[ 3 ]; sal_uInt32 * types = (sal_uInt32*)(baseAddress + reinterpret_cast< RaiseInfo * >( pRecord->ExceptionInformation[ 2 ] )->_types ); if (types != 0 && (sal_uInt32)(types[0]) > 0) // count { ExceptionType * pType = reinterpret_cast< ExceptionType * >( baseAddress + types[ 1 ] ); if (pType != 0 && pType->_pTypeInfo != 0) { OUString aRTTIname( OStringToOUString( reinterpret_cast< __type_info * >( baseAddress + pType->_pTypeInfo )->_m_d_name, RTL_TEXTENCODING_ASCII_US ) ); OUString aUNOname( toUNOname( aRTTIname ) ); typelib_TypeDescription * pExcTypeDescr = 0; typelib_typedescription_getByName( &pExcTypeDescr, aUNOname.pData ); if (pExcTypeDescr == 0) { OUStringBuffer buf; buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "[mscx_uno bridge error] UNO type of " "C++ exception unknown: \"") ); buf.append( aUNOname ); buf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "\", RTTI-name=\"") ); buf.append( aRTTIname ); buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("\"!") ); RuntimeException exc( buf.makeStringAndClear(), Reference< XInterface >() ); uno_type_any_constructAndConvert( pUnoExc, &exc, ::getCppuType( &exc ).getTypeLibType(), pCpp2Uno ); #if _MSC_VER < 1400 // msvcr80.dll cleans up, different from former msvcrs // if (! rethrow): // though this unknown exception leaks now, no user-defined // exception is ever thrown through the binary C-UNO dispatcher // call stack. #endif } else { // construct uno exception any uno_any_constructAndConvert( pUnoExc, (void *) pRecord->ExceptionInformation[1], pExcTypeDescr, pCpp2Uno ); #if _MSC_VER < 1400 // msvcr80.dll cleans up, different from former msvcrs if (! rethrow) { uno_destructData( (void *) pRecord->ExceptionInformation[1], pExcTypeDescr, cpp_release ); } #endif typelib_typedescription_release( pExcTypeDescr ); } return EXCEPTION_EXECUTE_HANDLER; } } } // though this unknown exception leaks now, no user-defined exception // is ever thrown through the binary C-UNO dispatcher call stack. RuntimeException exc( OUString( RTL_CONSTASCII_USTRINGPARAM( "[mscx_uno bridge error] unexpected " "C++ exception occurred!") ), Reference< XInterface >() ); uno_type_any_constructAndConvert( pUnoExc, &exc, ::getCppuType( &exc ).getTypeLibType(), pCpp2Uno ); return EXCEPTION_EXECUTE_HANDLER; } } #pragma pack(pop)
35.254518
145
0.588235
Grosskopf
1571fa5458aec8ea81539c697fc84c17befef09d
905
cc
C++
cc/tree/connect.cc
pchengma/acm
8bbbfa68b56580fcf503fab5409dd4a34ef804f2
[ "Apache-2.0" ]
1
2021-05-22T04:39:31.000Z
2021-05-22T04:39:31.000Z
cc/tree/connect.cc
pchengma/acm
8bbbfa68b56580fcf503fab5409dd4a34ef804f2
[ "Apache-2.0" ]
null
null
null
cc/tree/connect.cc
pchengma/acm
8bbbfa68b56580fcf503fab5409dd4a34ef804f2
[ "Apache-2.0" ]
null
null
null
// LeetCode: 116. Populating Next Right Pointers in Each Node (Medium) /* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() : val(0), left(NULL), right(NULL), next(NULL) {} Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {} }; */ class Solution { public: Node *connect(Node *root) { Node *prev = root, *curr; while (prev) { curr = prev; while (curr && curr->left) { curr->left->next = curr->right; if (curr->next) { curr->right->next = curr->next->left; } curr = curr->next; } prev = prev->left; } return root; } };
23.815789
70
0.493923
pchengma
1576593238b3b2d7ecb2ff63a73d6d615b0b7b2a
2,240
cxx
C++
python/kwiver/vital/types/track.cxx
mwoehlke-kitware/kwiver
614a488bd2b7fe551ac75eec979766d882709791
[ "BSD-3-Clause" ]
176
2015-07-31T23:33:37.000Z
2022-03-21T23:42:44.000Z
python/kwiver/vital/types/track.cxx
mwoehlke-kitware/kwiver
614a488bd2b7fe551ac75eec979766d882709791
[ "BSD-3-Clause" ]
1,276
2015-05-03T01:21:27.000Z
2022-03-31T15:32:20.000Z
python/kwiver/vital/types/track.cxx
mwoehlke-kitware/kwiver
614a488bd2b7fe551ac75eec979766d882709791
[ "BSD-3-Clause" ]
85
2015-01-25T05:13:38.000Z
2022-01-14T14:59:37.000Z
// This file is part of KWIVER, and is distributed under the // OSI-approved BSD 3-Clause License. See top-level LICENSE file or // https://github.com/Kitware/kwiver/blob/master/LICENSE for details. #include <vital/types/track.h> #include <pybind11/operators.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py=pybind11; namespace kwiver { namespace vital { namespace python { py::object track_find_state(kwiver::vital::track &self, int64_t frame_id) { auto frame_itr = self.find(frame_id); if(frame_itr == self.end()) { throw py::index_error(); } return py::cast<std::shared_ptr<kwiver::vital::track_state>>(*frame_itr); } } } } using namespace kwiver::vital::python; PYBIND11_MODULE(track, m) { py::class_<kwiver::vital::track_state, std::shared_ptr<kwiver::vital::track_state>>(m, "TrackState") .def(py::init<int64_t>()) .def(py::self == py::self) .def_property("frame_id", &kwiver::vital::track_state::frame, &kwiver::vital::track_state::set_frame) ; py::class_<kwiver::vital::track, std::shared_ptr<kwiver::vital::track>>(m, "Track") .def(py::init([](int64_t id) { auto track = kwiver::vital::track::create(); track->set_id(id); return track; }), py::arg("id")=0) .def("all_frame_ids", &kwiver::vital::track::all_frame_ids) .def("append", [](kwiver::vital::track &self, std::shared_ptr<kwiver::vital::track_state> track_state) { return self.append(track_state); }) .def("append", [](kwiver::vital::track &self, kwiver::vital::track &track) { return self.append(track); }) .def("find_state", &track_find_state) .def("__iter__", [](const kwiver::vital::track &self) { return py::make_iterator(self.begin(), self.end()); }, py::keep_alive<0,1>()) .def("__len__", &kwiver::vital::track::size) .def("__getitem__", &track_find_state) .def_property("id", &kwiver::vital::track::id, &kwiver::vital::track::set_id) .def_property_readonly("size", &kwiver::vital::track::size) .def_property_readonly("is_empty", &kwiver::vital::track::empty) .def_property_readonly("first_frame", &kwiver::vital::track::first_frame) .def_property_readonly("last_frame", &kwiver::vital::track::last_frame) ; }
32
104
0.679464
mwoehlke-kitware
15784a63fedae043b1001697730c2da316722d26
2,549
cpp
C++
include/lookup.cpp
jermp/sshash
480f1da593e4550422ce8ead6540b24485897641
[ "MIT" ]
44
2022-01-13T18:53:51.000Z
2022-03-03T12:38:16.000Z
include/lookup.cpp
jermp/sshash
480f1da593e4550422ce8ead6540b24485897641
[ "MIT" ]
2
2022-01-19T22:48:36.000Z
2022-03-10T14:32:57.000Z
include/lookup.cpp
jermp/sshash
480f1da593e4550422ce8ead6540b24485897641
[ "MIT" ]
2
2022-01-14T13:35:14.000Z
2022-03-03T12:38:19.000Z
#pragma once namespace sshash { uint64_t dictionary::lookup_uint64_regular_parsing(uint64_t uint64_kmer) const { uint64_t minimizer = util::compute_minimizer(uint64_kmer, m_k, m_m, m_seed); uint64_t bucket_id = m_minimizers.lookup(minimizer); if (m_skew_index.empty()) return m_buckets.lookup(bucket_id, uint64_kmer, m_k, m_m); auto [begin, end] = m_buckets.locate_bucket(bucket_id); uint64_t num_super_kmers_in_bucket = end - begin; uint64_t log2_bucket_size = util::ceil_log2_uint32(num_super_kmers_in_bucket); if (log2_bucket_size > m_skew_index.min_log2) { uint64_t pos = m_skew_index.lookup(uint64_kmer, log2_bucket_size); /* It must hold pos < num_super_kmers_in_bucket for the kmer to exist. */ if (pos < num_super_kmers_in_bucket) { return m_buckets.lookup_in_super_kmer(begin + pos, uint64_kmer, m_k, m_m); } return constants::invalid; } return m_buckets.lookup(begin, end, uint64_kmer, m_k, m_m); } uint64_t dictionary::lookup_uint64_canonical_parsing(uint64_t uint64_kmer) const { uint64_t uint64_kmer_rc = util::compute_reverse_complement(uint64_kmer, m_k); uint64_t minimizer = util::compute_minimizer(uint64_kmer, m_k, m_m, m_seed); uint64_t minimizer_rc = util::compute_minimizer(uint64_kmer_rc, m_k, m_m, m_seed); uint64_t bucket_id = m_minimizers.lookup(std::min<uint64_t>(minimizer, minimizer_rc)); if (m_skew_index.empty()) { return m_buckets.lookup_canonical(bucket_id, uint64_kmer, uint64_kmer_rc, m_k, m_m); } auto [begin, end] = m_buckets.locate_bucket(bucket_id); uint64_t num_super_kmers_in_bucket = end - begin; uint64_t log2_bucket_size = util::ceil_log2_uint32(num_super_kmers_in_bucket); if (log2_bucket_size > m_skew_index.min_log2) { uint64_t pos = m_skew_index.lookup(uint64_kmer, log2_bucket_size); if (pos < num_super_kmers_in_bucket) { uint64_t kmer_id = m_buckets.lookup_in_super_kmer(begin + pos, uint64_kmer, m_k, m_m); if (kmer_id != constants::invalid) return kmer_id; } uint64_t pos_rc = m_skew_index.lookup(uint64_kmer_rc, log2_bucket_size); if (pos_rc < num_super_kmers_in_bucket) { uint64_t kmer_id = m_buckets.lookup_in_super_kmer(begin + pos_rc, uint64_kmer_rc, m_k, m_m); return kmer_id; } return constants::invalid; } return m_buckets.lookup_canonical(begin, end, uint64_kmer, uint64_kmer_rc, m_k, m_m); } } // namespace sshash
45.517857
98
0.717144
jermp
1578c32fefb79e85a0c5c7168be7b33053392c90
731
cpp
C++
src/YesNoAskerDialog.cpp
timre13/list-maker
ebedbfcefa626af98f746c16fd46f6dafa81d70b
[ "BSD-2-Clause" ]
null
null
null
src/YesNoAskerDialog.cpp
timre13/list-maker
ebedbfcefa626af98f746c16fd46f6dafa81d70b
[ "BSD-2-Clause" ]
null
null
null
src/YesNoAskerDialog.cpp
timre13/list-maker
ebedbfcefa626af98f746c16fd46f6dafa81d70b
[ "BSD-2-Clause" ]
null
null
null
#include "YesNoAskerDialog.h" YesNoAskerDialog::YesNoAskerDialog(const Glib::ustring &question, Gtk::ResponseType defaultButton/*=Gtk::ResponseType::RESPONSE_YES*/) : m_textLabel{std::make_unique<Gtk::Label>()} { get_vbox()->add(*m_textLabel); m_textLabel->set_text(question); add_button("Yes", Gtk::ResponseType::RESPONSE_YES); add_button("No", Gtk::ResponseType::RESPONSE_NO); set_default_response(defaultButton); show_all_children(); } bool askYesNo(const Glib::ustring &question, Gtk::ResponseType defaultButton/*=Gtk::ResponseType::RESPONSE_YES*/) { auto dialog{std::make_unique<YesNoAskerDialog>(question, defaultButton)}; return dialog->run() == Gtk::ResponseType::RESPONSE_YES; }
31.782609
134
0.737346
timre13
157978a127f42892396c050c73c757c334608391
11,926
cpp
C++
Qt-GL-Simple-Scene-master/libgizmo/save/GizmoTransformRenderDX9.cpp
nacsa/Retopology
03c009462db3d73dbb73ea543952d421ecc1416e
[ "Apache-2.0" ]
107
2015-04-24T08:09:32.000Z
2022-02-21T16:57:18.000Z
Qt-GL-Simple-Scene-master/libgizmo/save/GizmoTransformRenderDX9.cpp
nacsa/Retopology
03c009462db3d73dbb73ea543952d421ecc1416e
[ "Apache-2.0" ]
1
2019-04-24T07:44:27.000Z
2019-05-14T09:18:53.000Z
Qt-GL-Simple-Scene-master/libgizmo/save/GizmoTransformRenderDX9.cpp
nacsa/Retopology
03c009462db3d73dbb73ea543952d421ecc1416e
[ "Apache-2.0" ]
34
2015-03-15T14:50:12.000Z
2022-01-23T07:18:05.000Z
/////////////////////////////////////////////////////////////////////////////////////////////////// // Zenith Engine // File Name : GizmoTransform.h // Creation : 12/07/2007 // Author : Cedric Guillemet // Description : // /////////////////////////////////////////////////////////////////////////////////////////////////// // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // /////////////////////////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "GizmoTransformRender.h" #include <D3D9.h> #ifdef WIN32 typedef struct { float x; float y; float z; tulong diffuse; } PSM_LVERTEX; IDirect3DVertexDeclaration9* GGizmoVertDecl = NULL; #endif void InitDecl() { #ifdef WIN32 if (!GGizmoVertDecl) { D3DVERTEXELEMENT9 decl1[] = { { 0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 }, { 0, 12, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 }, D3DDECL_END() }; GDD->GetD3D9Device()->CreateVertexDeclaration( decl1, &GGizmoVertDecl ); } GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_FALSE); GDD->GetD3D9Device()->SetTexture(0,NULL); GDD->GetD3D9Device()->SetTexture(1,NULL); GDD->GetD3D9Device()->SetTexture(2,NULL); GDD->GetD3D9Device()->SetTexture(3,NULL); GDD->GetD3D9Device()->SetTexture(4,NULL); GDD->GetD3D9Device()->SetTexture(5,NULL); GDD->GetD3D9Device()->SetTexture(6,NULL); GDD->GetD3D9Device()->SetTexture(7,NULL); GDD->GetD3D9Device()->SetRenderState(D3DRS_COLORVERTEX , true); //GDD->GetD3D9Device()->SetRenderState(D3DRS_LIGHTING , true); GDD->GetD3D9Device()->SetRenderState(D3DRS_AMBIENT , 0xFFFFFFFF); GDD->GetD3D9Device()->SetVertexShader(NULL); GDD->GetD3D9Device()->SetPixelShader(NULL); #endif } void CGizmoTransformRender::DrawCircle(const tvector3 &orig,float r,float g,float b, const tvector3 &vtx, const tvector3 &vty) { #ifdef WIN32 InitDecl(); PSM_LVERTEX svVts[51]; for (int i = 0; i <= 50 ; i++) { tvector3 vt; vt = vtx * cos((2*ZPI/50)*i); vt += vty * sin((2*ZPI/50)*i); vt += orig; svVts[i].diffuse = 0xFF000000 + (int(r*255.0f) << 16) + (int(g*255.0f) << 8) + (int(b*255.0f)); svVts[i].x = vt.x; svVts[i].y = vt.y; svVts[i].z = vt.z; } IDirect3DDevice9 *pDev = GDD->GetD3D9Device(); GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl); GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINESTRIP , 50, svVts, sizeof(PSM_LVERTEX)); GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE); #endif } void CGizmoTransformRender::DrawCircleHalf(const tvector3 &orig,float r,float g,float b,const tvector3 &vtx, const tvector3 &vty, tplane &camPlan) { #ifdef WIN32 InitDecl(); int inc = 0; PSM_LVERTEX svVts[51]; for (int i = 0; i < 30 ; i++) { tvector3 vt; vt = vtx * cos((ZPI/30)*i); vt += vty * sin((ZPI/30)*i); vt +=orig; if (camPlan.DotNormal(vt)) { svVts[inc].diffuse = 0xFF000000 + (int(r*255.0f) << 16) + (int(g*255.0f) << 8) + (int(b*255.0f)); svVts[inc].x = vt.x; svVts[inc].y = vt.y; svVts[inc].z = vt.z; inc ++; } } IDirect3DDevice9 *pDev = GDD->GetD3D9Device(); GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl); GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINESTRIP , inc-1, svVts, sizeof(PSM_LVERTEX)); GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE); #endif } void CGizmoTransformRender::DrawAxis(const tvector3 &orig, const tvector3 &axis, const tvector3 &vtx, const tvector3 &vty, float fct,float fct2, const tvector4 &col) { #ifdef WIN32 InitDecl(); PSM_LVERTEX svVts[100]; int inc = 0; IDirect3DDevice9 *pDev = GDD->GetD3D9Device(); svVts[0].x = orig.x; svVts[0].y = orig.y; svVts[0].z = orig.z; svVts[0].diffuse = 0xFF000000 + (int(col.x*255.0f) << 16) + (int(col.y*255.0f) << 8) + (int(col.z*255.0f)); svVts[1].x = orig.x + axis.x; svVts[1].y = orig.y + axis.y; svVts[1].z = orig.z + axis.z; svVts[1].diffuse = svVts[0].diffuse; GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl); GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINELIST , 1, svVts, sizeof(PSM_LVERTEX)); //glBegin(GL_TRIANGLE_FAN); for (int i=0;i<=30;i++) { tvector3 pt; pt = vtx * cos(((2*ZPI)/30.0f)*i)*fct; pt+= vty * sin(((2*ZPI)/30.0f)*i)*fct; pt+=axis*fct2; pt+=orig; //glVertex3fv(&pt.x); svVts[inc].x = pt.x; svVts[inc].y = pt.y; svVts[inc].z = pt.z; svVts[inc++].diffuse = svVts[0].diffuse; pt = vtx * cos(((2*ZPI)/30.0f)*(i+1))*fct; pt+= vty * sin(((2*ZPI)/30.0f)*(i+1))*fct; pt+=axis*fct2; pt+=orig; //glVertex3fv(&pt.x); svVts[inc].x = pt.x; svVts[inc].y = pt.y; svVts[inc].z = pt.z; svVts[inc++].diffuse = svVts[0].diffuse; //glVertex3f(orig.x+axis.x,orig.y+axis.y,orig.z+axis.z); svVts[inc].x = orig.x+axis.x; svVts[inc].y = orig.y+axis.y; svVts[inc].z = orig.z+axis.z; svVts[inc++].diffuse = svVts[0].diffuse; } //glEnd(); GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl); GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_TRIANGLEFAN , 91, svVts, sizeof(PSM_LVERTEX)); GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE); #endif } void CGizmoTransformRender::DrawCamem(const tvector3& orig,const tvector3& vtx,const tvector3& vty,float ng) { #ifdef WIN32 InitDecl(); IDirect3DDevice9 *pDev = GDD->GetD3D9Device(); GDD->GetD3D9Device()->SetRenderState(D3DRS_SRCBLEND , D3DBLEND_SRCALPHA); GDD->GetD3D9Device()->SetRenderState(D3DRS_DESTBLEND , D3DBLEND_INVSRCALPHA); GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE ); PSM_LVERTEX svVts[52]; svVts[0].x = orig.x; svVts[0].y = orig.y; svVts[0].z = orig.z; svVts[0].diffuse = 0x80FFFF00; for (int i = 0 ; i <= 50 ; i++) { tvector3 vt; vt = vtx * cos(((ng)/50)*i); vt += vty * sin(((ng)/50)*i); vt+=orig; //glVertex3f(vt.x,vt.y,vt.z); svVts[i+1].x = vt.x; svVts[i+1].y = vt.y; svVts[i+1].z = vt.z; svVts[i+1].diffuse = svVts[0].diffuse; } GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl); GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_TRIANGLEFAN , 50, svVts, sizeof(PSM_LVERTEX)); GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); for (int i = 0 ; i < 52 ; i++) svVts[i].diffuse = 0xFFFFFF33; GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl); GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINESTRIP , 50, svVts, sizeof(PSM_LVERTEX)); GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE , D3DCULL_CCW ); GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE); #endif } void CGizmoTransformRender::DrawQuad(const tvector3& orig, float size, bool bSelected, const tvector3& axisU, const tvector3 &axisV) { #ifdef WIN32 InitDecl(); IDirect3DDevice9 *pDev = GDD->GetD3D9Device(); GDD->GetD3D9Device()->SetRenderState(D3DRS_SRCBLEND , D3DBLEND_SRCALPHA); GDD->GetD3D9Device()->SetRenderState(D3DRS_DESTBLEND , D3DBLEND_INVSRCALPHA); GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE , D3DCULL_NONE ); PSM_LVERTEX svVts[5]; svVts[0].x = orig.x; svVts[0].y = orig.y; svVts[0].z = orig.z; svVts[1].x = orig.x + (axisU.x * size); svVts[1].y = orig.y + (axisU.y * size); svVts[1].z = orig.z + (axisU.z * size); svVts[2].x = orig.x + (axisV.x * size); svVts[2].y = orig.y + (axisV.y * size); svVts[2].z = orig.z + (axisV.z * size); svVts[3].x = orig.x + (axisU.x + axisV.x)*size; svVts[3].y = orig.y + (axisU.y + axisV.y)*size; svVts[3].z = orig.z + (axisU.z + axisV.z)*size; svVts[4].x = orig.x; svVts[4].y = orig.y; svVts[4].z = orig.z; if (!bSelected) svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0x80FFFF00; else svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xA0FFFFFF; GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl); GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP , 2, svVts, sizeof(PSM_LVERTEX)); if (!bSelected) svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xFFFFFF30; else svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xA0FFFF90; svVts[3].x = orig.x + (axisV.x * size); svVts[3].y = orig.y + (axisV.y * size); svVts[3].z = orig.z + (axisV.z * size); svVts[2].x = orig.x + (axisU.x + axisV.x)*size; svVts[2].y = orig.y + (axisU.y + axisV.y)*size; svVts[2].z = orig.z + (axisU.z + axisV.z)*size; GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl); GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINESTRIP , 4, svVts, sizeof(PSM_LVERTEX)); GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE , D3DCULL_CCW ); GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE); #endif } void CGizmoTransformRender::DrawTri(const tvector3& orig, float size, bool bSelected, const tvector3& axisU, const tvector3& axisV) { #ifdef WIN32 InitDecl(); IDirect3DDevice9 *pDev = GDD->GetD3D9Device(); GDD->GetD3D9Device()->SetRenderState(D3DRS_SRCBLEND , D3DBLEND_SRCALPHA); GDD->GetD3D9Device()->SetRenderState(D3DRS_DESTBLEND , D3DBLEND_INVSRCALPHA); GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE , D3DCULL_NONE ); tvector3 pts[3]; pts[0] = orig; pts[1] = (axisU ); pts[2] = (axisV ); pts[1]*=size; pts[2]*=size; pts[1]+=orig; pts[2]+=orig; PSM_LVERTEX svVts[4]; svVts[0].x = pts[0].x; svVts[0].y = pts[0].y; svVts[0].z = pts[0].z; svVts[1].x = pts[1].x; svVts[1].y = pts[1].y; svVts[1].z = pts[1].z; svVts[2].x = pts[2].x; svVts[2].y = pts[2].y; svVts[2].z = pts[2].z; svVts[3].x = pts[0].x; svVts[3].y = pts[0].y; svVts[3].z = pts[0].z; if (!bSelected) svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0x80FFFF00; else svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xA0FFFFFF; GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl); GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_TRIANGLELIST , 1, svVts, sizeof(PSM_LVERTEX)); if (!bSelected) svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xFFFFFF30; else svVts[0].diffuse = svVts[1].diffuse = svVts[2].diffuse = svVts[3].diffuse = svVts[4].diffuse = 0xA0FFFF90; GDD->GetD3D9Device()->SetVertexDeclaration(GGizmoVertDecl); GDD->GetD3D9Device()->DrawPrimitiveUP(D3DPT_LINESTRIP , 3, svVts, sizeof(PSM_LVERTEX)); GDD->GetD3D9Device()->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); GDD->GetD3D9Device()->SetRenderState(D3DRS_CULLMODE , D3DCULL_CCW ); GDD->GetD3D9Device()->SetRenderState(D3DRS_ZENABLE , D3DZB_TRUE); #endif }
34.368876
165
0.633909
nacsa
1579fe0fefe2671a307901bd63be785d42e902e0
18,664
cpp
C++
src/ui/qt5/mainwindow.cpp
chenyvehtung/Agenda
9e35c67b692bfcc9c4af31a5a4d43ba97e6f0f7a
[ "MIT" ]
3
2016-10-20T08:19:45.000Z
2017-06-18T04:34:53.000Z
src/ui/qt5/mainwindow.cpp
donydchen/Agenda
9e35c67b692bfcc9c4af31a5a4d43ba97e6f0f7a
[ "MIT" ]
null
null
null
src/ui/qt5/mainwindow.cpp
donydchen/Agenda
9e35c67b692bfcc9c4af31a5a4d43ba97e6f0f7a
[ "MIT" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" #include "loginwindow.h" #include <QMessageBox> #include <QStandardItemModel> #include <Qt> #include <QAction> #include <QIcon> using std::string; using std::list; MainWindow::MainWindow(QWidget *parent) : ui(new Ui::MainWindow), QMainWindow(parent) { ui->setupUi(this); //set table view to be uneditable ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers); //display current time in status bar curTime = new QLabel(" SYSTEM TIME: " + QTime::currentTime().toString("hh:mm:ss"), ui->statusBar); curTime->setFixedWidth(300); startTimer(1000); initToolbar(); setFixedSize(size()); QIcon::setThemeName("ubuntu-mono-dark"); } void MainWindow::updateWin(string username, string password, AgendaService *agendaService) { // update property userName_ = username; userPassword_ = password; agendaService_ = agendaService; btnStatus = BtnStatus::Query; // update window title and toolbar text string buffer; buffer = "Logout User \"" + userName_ + "\""; ui->actionLogout->setText(buffer.c_str()); buffer = "Delete User \"" + userName_ + "\""; ui->actionDelete->setText(buffer.c_str()); buffer = "Agenda (" + agendaService_->getServiceName() + ") : " + userName_; setWindowTitle(buffer.c_str()); //set up the homepage buffer = "Welcome " + userName_; ui->wel_label->setText(buffer.c_str()); showPage(PageType::HomePage); } /* * Add button to toolbar */ void MainWindow::initToolbar() { //ui->toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); QString curPath = QCoreApplication::applicationDirPath(); // home QAction *tbHome = ui->toolBar->addAction(QIcon(curPath + "/resources/user-home.gif"), "Home"); connect(tbHome, SIGNAL(triggered()), this, SLOT(on_actionHome_triggered())); ui->toolBar->addSeparator(); // list all user QAction *tbList = ui->toolBar->addAction(QIcon(curPath + "/resources/go-down.gif"), "List Users"); connect(tbList, SIGNAL(triggered()), this, SLOT(on_actionList_triggered())); // create meeting QAction *tbCreate = ui->toolBar->addAction(QIcon(curPath + "/resources/document-new.gif"), "Create Meeting"); connect(tbCreate, SIGNAL(triggered()), this, SLOT(on_actionCreate_A_Meeting_triggered())); // delete meeting QAction *tbDel = ui->toolBar->addAction(QIcon(curPath + "/resources/edit-delete.gif"), "Delete Meeting"); connect(tbDel, SIGNAL(triggered()), this, SLOT(on_actionDelete_A_Meeting_triggered())); // search meeting QAction *tbSearch = ui->toolBar->addAction(QIcon(curPath + "/resources/edit-find.gif"), "Search Meeting"); connect(tbSearch, SIGNAL(triggered()), this, SLOT(on_actionQuery_Meeting_By_Title_triggered())); ui->toolBar->addSeparator(); // log out QAction *tbLogout = ui->toolBar->addAction(QIcon(curPath + "/resources/system-log-out.gif"), "Log Out"); connect(tbLogout, SIGNAL(triggered()), this, SLOT(on_actionLogout_triggered())); } MainWindow::~MainWindow() { //agendaService_->quitAgenda(); delete ui; delete curTime; } /** * @brief MainWindow::on_actionHome_triggered * go to homepage */ void MainWindow::on_actionHome_triggered() { showPage(PageType::HomePage); } void MainWindow::on_actionLogout_triggered() { string content = "Do you really want to logout " + userName_ + "?"; int ans = QMessageBox::question(NULL, "Logout User", content.c_str(), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ans == QMessageBox::Yes) { emit mainWinClose(); hide(); } } void MainWindow::on_actionDelete_triggered() { string content = "Do you really want to delete " + userName_ + "?"; int ans = QMessageBox::question(NULL, "Delete User", content.c_str(), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ans == QMessageBox::Yes) { if (agendaService_->deleteUser(userName_, userPassword_)) { content = "Successfully delete user " + userName_ + "<br>Click OK to continue..."; QMessageBox::information(NULL, "Delete Succeed", content.c_str(), QMessageBox::Ok); emit mainWinClose(); hide(); } else { content = "Fail to delete user " + userName_; QMessageBox::warning(NULL, "Delete Failed", content.c_str()); } } } void MainWindow::on_actionExit_triggered() { //agendaService_->quitAgenda(); qApp->closeAllWindows(); } /** * @brief MainWindow::on_actionList_triggered * to list all user in Agenda */ void MainWindow::on_actionList_triggered() { //ui->tableView->hide(); list<User> users = agendaService_->listAllUsers(); if (!users.empty()) { int rows = users.size(); QStandardItemModel *model = new QStandardItemModel(rows, 3, this); model->setHorizontalHeaderItem(0, new QStandardItem(QString("Name"))); model->setHorizontalHeaderItem(1, new QStandardItem(QString("Email"))); model->setHorizontalHeaderItem(2, new QStandardItem(QString("Phone"))); list<User>::iterator it; int i; for (i = 0, it = users.begin(); it != users.end(); ++i, ++it) { QStandardItem *nameItem = new QStandardItem(QString(it->getName().c_str())); QStandardItem *emailItem = new QStandardItem(QString(it->getEmail().c_str())); QStandardItem *phoneItem = new QStandardItem(QString(it->getPhone().c_str())); model->setItem(i, 0, nameItem); model->setItem(i, 1, emailItem); model->setItem(i, 2, phoneItem); } ui->tableView->setModel(model); // set table to be auto expended for (int c = 0; c < ui->tableView->horizontalHeader()->count(); ++c) { ui->tableView->horizontalHeader()->setSectionResizeMode( c, QHeaderView::Stretch); } showPage(PageType::TableView); } else { QMessageBox::information(NULL, "List User", "Sorry, no user exist!", QMessageBox::Ok); showPage(PageType::HomePage); } } /** * @brief MainWindow::on_actionList_All_Meetings_triggered * list all meetings */ void MainWindow::on_actionList_All_Meetings_triggered() { //ui->tableView->hide(); list<Meeting> meetings = agendaService_->listAllMeetings(userName_); if (!meetings.empty()) { printMeetings(meetings); } else { QMessageBox::information(NULL, "List Meetings", "Sorry, no meeting exist", QMessageBox::Ok); showPage(PageType::HomePage); } } /** * @brief MainWindow::on_actionList_All_Sponsor_Meetings_triggered * slot to find out all the sponsor meeting of the log in user */ void MainWindow::on_actionList_All_Sponsor_Meetings_triggered() { list<Meeting> meetings = agendaService_->listAllSponsorMeetings(userName_); if (!meetings.empty()) { printMeetings(meetings); } else { QMessageBox::information(NULL, "List Meetings", "Sorry, no sponsor meeting exist", QMessageBox::Ok); showPage(HomePage); } } /** * @brief MainWindow::on_actionList_All_Participant_Meetings_triggered * slot to find out all participator meetings of the log in user */ void MainWindow::on_actionList_All_Participant_Meetings_triggered() { //ui->tableView->hide(); list<Meeting> meetings = agendaService_->listAllParticipateMeetings(userName_); if (!meetings.empty()) { printMeetings(meetings); } else { QMessageBox::information(NULL, "List Meetings", "Sorry, no participate meeting exist", QMessageBox::Ok); showPage(PageType::HomePage); } } /** * @brief MainWindow::on_actionCreate_A_Meeting_triggered */ void MainWindow::on_actionCreate_A_Meeting_triggered() { // add users to participator combo box list<User> users = agendaService_->listAllUsers(); list<User>::iterator it; ui->parComboBox->clear(); for (it = users.begin(); it != users.end(); ++it) { string user = it->getName(); if (user != userName_) ui->parComboBox->addItem(QString::fromStdString(user)); } // set up date time picker yyyy-mm-dd/hh:mm ui->startDT->setCalendarPopup(true); ui->startDT->setDateTime(QDateTime::currentDateTime()); ui->startDT->setDisplayFormat("MMMM dd,yyyy hh:mm"); ui->endDT->setCalendarPopup(true); ui->endDT->setDateTime(QDateTime::currentDateTime()); ui->endDT->setDisplayFormat("MMMM dd,yyyy hh:mm"); // show the widget showPage(PageType::CreateMT); } /** * @brief MainWindow::on_crtMtBtn_clicked * create a meeting */ void MainWindow::on_crtMtBtn_clicked() { string title = ui->mtTitle->text().toUtf8().constData(); string participator = ui->parComboBox->currentText().toUtf8().constData(); string startTime = ui->startDT->dateTime().toString("yyyy-MM-dd/hh:mm").toUtf8().constData(); string endTime = ui->endDT->dateTime().toString("yyyy-MM-dd/hh:mm").toUtf8().constData(); if (agendaService_->createMeeting(userName_, title, participator, startTime, endTime)) { QMessageBox::information(NULL, "Create Meeting", "Successfully create a meeting!", QMessageBox::Ok); showPage(PageType::HomePage); } else { QMessageBox::critical(NULL, "Create Meeting", "Sorry, failed to create the meeeting!"); } } /** * @brief MainWindow::on_actionDelete_A_Meeting_triggered * delete a meeting accroding to the given name */ void MainWindow::on_actionDelete_A_Meeting_triggered() { showPage(PageType::SearchTitle); btnStatus = BtnStatus::Delete; } /** * @brief MainWindow::on_actionDelete_All_Meetings_triggered * Delete all the meeting connect to the log in user */ void MainWindow::on_actionDelete_All_Meetings_triggered() { int ans = QMessageBox::question(NULL, "Delete Meetings", "Do you really want to delete ALL the meetings?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ans == QMessageBox::Yes) { if (agendaService_->deleteAllMeetings(userName_)) { QMessageBox::information(NULL, "Delete Meetings", "Successfully deleted all the meeting!"); } else { QMessageBox::critical(NULL, "Delete Meetings", "Failed to delete all meetings:("); } } } /** * @brief MainWindow::on_actionQuery_Meeting_By_Title_triggered */ void MainWindow::on_actionQuery_Meeting_By_Title_triggered() { showPage(PageType::SearchTitle); btnStatus = BtnStatus::Query; } /** * @brief MainWindow::on_actionQuery_Meeting_By_Time_Interval_triggered * query meeting exist in the provided time interval */ void MainWindow::on_actionQuery_Meeting_By_Time_Interval_triggered() { // set up date time picker yyyy-mm-dd/hh:mm ui->startDT_2->setCalendarPopup(true); ui->startDT_2->setDateTime(QDateTime::currentDateTime()); ui->startDT_2->setDisplayFormat("MMMM dd,yyyy hh:mm"); ui->endDT_2->setCalendarPopup(true); ui->endDT_2->setDateTime(QDateTime::currentDateTime()); ui->endDT_2->setDisplayFormat("MMMM dd,yyyy hh:mm"); //show the time interval search widget showPage(PageType::SearchTime); } /** * @brief MainWindow::on_searchBtn_clicked * to search a meeting according to the title */ void MainWindow::on_searchBtn_clicked() { string title = ui->searchTitle->text().toUtf8().constData(); //search the meeting anyhow list<Meeting> meetings = agendaService_->meetingQuery(userName_, title); if (meetings.empty()) { QMessageBox::critical(NULL, "No Meeting", "Sorry but no such meeting"); } else { // if it is to delete a meeting by its title if (btnStatus == BtnStatus::Delete) { string content = "Do you really want to delete meeting \"" + title + "\"?"; int ans = QMessageBox::question(NULL, "Delete Meeting", content.c_str(), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ans == QMessageBox::Yes) { if (agendaService_->deleteMeeting(userName_, title)) { QMessageBox::information(NULL, "Delete Meeting", "Successfully delete the meetings!"); on_actionHome_triggered(); } else { QMessageBox::critical(NULL, "Delete Meeting", "Failed to delete the meeting!"); } } } //if it is to query a meeting by title else if (btnStatus == BtnStatus::Query) { //show the meeting in the tableView int rows = meetings.size(); QStandardItemModel *model = new QStandardItemModel(rows, 4, this); model->setHorizontalHeaderItem(0, new QStandardItem(QString("Sponsor"))); model->setHorizontalHeaderItem(1, new QStandardItem(QString("Participator"))); model->setHorizontalHeaderItem(2, new QStandardItem(QString("Start Time"))); model->setHorizontalHeaderItem(3, new QStandardItem(QString("End Time"))); list<Meeting>::iterator it; int i; for (i = 0, it = meetings.begin(); it != meetings.end(); ++i, ++it) { QStandardItem *sponsorItem = new QStandardItem(QString(it->getSponsor().c_str())); QStandardItem *partiItem = new QStandardItem(QString(it->getParticipator().c_str())); QStandardItem *startItem = new QStandardItem(QString(Date::dateToString(it->getStartDate()).c_str())); QStandardItem *endItem = new QStandardItem(QString(Date::dateToString(it->getEndDate()).c_str())); model->setItem(i, 0, sponsorItem); model->setItem(i, 1, partiItem); model->setItem(i, 2, startItem); model->setItem(i, 3, endItem); } ui->tableView->setModel(model); // set table to be auto expended for (int c = 0; c < ui->tableView->horizontalHeader()->count(); ++c) { ui->tableView->horizontalHeader()->setSectionResizeMode( c, QHeaderView::Stretch); } showPage(PageType::TableView); } else { //do nothing } } } /** * @brief MainWindow::on_searchBtn_2_clicked * to search meeting according to the provided time interval */ void MainWindow::on_searchBtn_2_clicked() { string startTime = ui->startDT_2->dateTime().toString("yyyy-MM-dd/hh:mm").toUtf8().constData(); string endTime = ui->endDT_2->dateTime().toString("yyyy-MM-dd/hh:mm").toUtf8().constData(); list<Meeting> meetings = agendaService_->meetingQuery(userName_, startTime, endTime); if (!meetings.empty()) { printMeetings(meetings); } else { string content = "Sorry, no meeting exist during <br>" + startTime + " ~ " + endTime; QMessageBox::warning(NULL, "Query Meetings", content.c_str()); } } void MainWindow::on_actionAbout_triggered() { QMessageBox::about(NULL, "Agenda", "Agenda is a simple app writen by Donald<br>1st Oct. 2016<br>May 2017: Update, add SQLite3 Backend"); } /** * @brief MainWindow::printMeetings * @param meetings * An assitant function to print the meetings */ void MainWindow::printMeetings(std::list<Meeting> meetings) { int rows = meetings.size(); QStandardItemModel *model = new QStandardItemModel(rows, 5, this); model->setHorizontalHeaderItem(0, new QStandardItem(QString("Title"))); model->setHorizontalHeaderItem(1, new QStandardItem(QString("Sponsor"))); model->setHorizontalHeaderItem(2, new QStandardItem(QString("Participator"))); model->setHorizontalHeaderItem(3, new QStandardItem(QString("Start Time"))); model->setHorizontalHeaderItem(4, new QStandardItem(QString("End Time"))); list<Meeting>::iterator it; int i; for (i = 0, it = meetings.begin(); it != meetings.end(); ++i, ++it) { QStandardItem *titleItem = new QStandardItem(QString(it->getTitle().c_str())); QStandardItem *sponsorItem = new QStandardItem(QString(it->getSponsor().c_str())); QStandardItem *partiItem = new QStandardItem(QString(it->getParticipator().c_str())); QStandardItem *startItem = new QStandardItem(QString(Date::dateToString(it->getStartDate()).c_str())); QStandardItem *endItem = new QStandardItem(QString(Date::dateToString(it->getEndDate()).c_str())); model->setItem(i, 0, titleItem); model->setItem(i, 1, sponsorItem); model->setItem(i, 2, partiItem); model->setItem(i, 3, startItem); model->setItem(i, 4, endItem); } ui->tableView->setModel(model); // set table to be auto expended for (int c = 0; c < ui->tableView->horizontalHeader()->count(); ++c) { ui->tableView->horizontalHeader()->setSectionResizeMode( c, QHeaderView::Stretch); } showPage(PageType::TableView); } /** * @brief MainWindow::showPage * Hide all other widget and show the widget according to the pageType */ void MainWindow::showPage(PageType pageType) { ui->tableView->hide(); ui->createmtwidget->hide(); ui->searchwidget->hide(); ui->searchwidget_2->hide(); ui->welcomewidget->hide(); ui->opTitle->hide(); switch(pageType) { case PageType::HomePage: ui->welcomewidget->show(); break; case PageType::TableView: ui->tableView->show(); break; case PageType::CreateMT: ui->opTitle->setText("Create Meeting"); ui->opTitle->show(); ui->createmtwidget->show(); break; case PageType::SearchTitle: ui->opTitle->setText("Search"); ui->opTitle->show(); ui->searchwidget->show(); break; case PageType::SearchTime: ui->opTitle->setText("Search"); ui->opTitle->show(); ui->searchwidget_2->show(); break; default: ui->welcomewidget->show(); } } /** * @brief MainWindow::timerEvent * @param event * update current time in status bar */ void MainWindow::timerEvent(QTimerEvent *) { curTime->setText(" SYSTEM TIME: " + QTime::currentTime().toString("hh:mm:ss")); }
35.686424
140
0.635502
chenyvehtung
157a2b6659db6262f316bce087c4dc65ac464e90
107
cpp
C++
SerPrunesALot/SerPrunesALot/Move.cpp
DennisSoemers/SerPrunesALot
34f0277fec58cf1f837df8f31ed14c62a945811c
[ "MIT" ]
null
null
null
SerPrunesALot/SerPrunesALot/Move.cpp
DennisSoemers/SerPrunesALot
34f0277fec58cf1f837df8f31ed14c62a945811c
[ "MIT" ]
null
null
null
SerPrunesALot/SerPrunesALot/Move.cpp
DennisSoemers/SerPrunesALot
34f0277fec58cf1f837df8f31ed14c62a945811c
[ "MIT" ]
null
null
null
#include "Move.h" Move::Move(int from, int to, bool captured) : from(from), to(to), captured(captured) {}
21.4
43
0.672897
DennisSoemers
157d5b03d796cd7fa1e41784e4274ff88acedb5b
4,954
cpp
C++
src/Sense.cpp
danielkaldheim/sense-library
25e2786618d0ed5171d283e66e4bad25a2295570
[ "MIT" ]
null
null
null
src/Sense.cpp
danielkaldheim/sense-library
25e2786618d0ed5171d283e66e4bad25a2295570
[ "MIT" ]
null
null
null
src/Sense.cpp
danielkaldheim/sense-library
25e2786618d0ed5171d283e66e4bad25a2295570
[ "MIT" ]
null
null
null
#include "Sense.h" Preferences preferences; Sense::~Sense() { // preferences.end(); } Sense::Sense() { preferences.begin(PREFERENCES_KEY, false); } bool Sense::begin(void) { preferences.begin(PREFERENCES_KEY, false); return true; } String Sense::getChipName() { uint64_t chipid = ESP.getEfuseMac(); char chipName[32]; sprintf(chipName, "-%04X", (uint16_t)(chipid >> 32)); return String(STR(PROJECT)) + chipName; } String Sense::getDeviceName() { return getString("deviceName", getChipName()); } void Sense::setDeviceName(String value) { putString("deviceName", value); } String Sense::getWiFiMac() { return WiFi.macAddress(); } String Sense::getLocalIp() { return WiFi.localIP().toString(); } String Sense::getWiFiSSID() { return getString("wifi-ssid", STR(WIFI_SSID)); } void Sense::setWiFiSSID(String value) { putString("wifi-ssid", value); } String Sense::getWiFiPwd() { return getString("wifi-pwd", STR(WIFI_SSID_PWD)); } void Sense::setWiFiPwd(String value) { putString("wifi-pwd", value); } String Sense::getDevice() { return getString("deviceId"); } void Sense::setDevice(String value) { putString("deviceId", value); } String Sense::getRoom() { return getString("roomId"); } void Sense::setRoom(String value) { putString("roomId", value); } String Sense::getFloor() { return getString("floor"); } void Sense::setFloor(String value) { putString("floor", value); } String Sense::getTenant() { return getString("tenantId"); } void Sense::setTenant(String value) { putString("tenantId", value); } String Sense::getMQTTTopic() { String tenantID = getTenant(); String deviceID = getDevice(); if (!tenantID.isEmpty() && !deviceID.isEmpty()) { return String(STR(PROJECT)) + "/" + deviceID + "/"; } uint64_t chipid = ESP.getEfuseMac(); char chipName[32]; sprintf(chipName, "/%04X/", (uint16_t)(chipid >> 32)); return getString("mqtt-topic", String(STR(PROJECT)) + chipName); } void Sense::setMQTTTopic(String value) { putString("mqtt-topic", value); } String Sense::getMQTTHost() { return getString("mqtt-host", STR(MQTT_HOST)); } void Sense::setMQTTHost(String value) { putString("mqtt-host", value); } uint16_t Sense::getMQTTPort() { preferences.begin(PREFERENCES_KEY, false); return preferences.getUShort("mqtt-port", 1883); } void Sense::setMQTTPort(uint16_t value) { preferences.begin(PREFERENCES_KEY, false); preferences.putUShort("mqtt-port", value); } String Sense::getMQTTUser() { return getString("mqtt-user", STR(MQTT_USER)); } void Sense::setMQTTUser(String value) { putString("mqtt-user", value); } String Sense::getMQTTPwd() { return getString("mqtt-pwd", STR(MQTT_PWD)); } void Sense::setMQTTPwd(String value) { putString("mqtt-pwd", value); } String Sense::getCrudusToken() { return getString("token"); } void Sense::setCrudusToken(String value) { putString("token", value); } float Sense::getCaliTemp() { return getFloat("cali-temp", 3.5f); } void Sense::setCaliTemp(float value) { putFloat("cali-temp", value); } bool Sense::checkIAQState(size_t maxLen) { preferences.begin(PREFERENCES_KEY, false); return preferences.getBytesLength("bsecState") == maxLen; } void Sense::getIAQState(uint8_t *state, size_t maxLen) { preferences.begin(PREFERENCES_KEY, false); preferences.getBytes("bsecState", state, maxLen); } void Sense::setIAQState(const void *bsecState, size_t maxLen) { preferences.begin(PREFERENCES_KEY, false); preferences.putBytes("bsecState", bsecState, maxLen); } void Sense::clearIAQState() { preferences.begin(PREFERENCES_KEY, false); preferences.remove("bsecState"); } Preferences *Sense::getPreferences() { preferences.begin(PREFERENCES_KEY, false); return &preferences; } String Sense::getString(const char *key, const String defaultValue) { preferences.begin(PREFERENCES_KEY, false); return preferences.getString(key, defaultValue); } uint32_t Sense::getUInt(const char *key, const uint32_t defaultValue) { preferences.begin(PREFERENCES_KEY, false); return preferences.getUInt(key, defaultValue); } float_t Sense::getFloat(const char *key, const float_t defaultValue) { preferences.begin(PREFERENCES_KEY, false); return preferences.getFloat(key, defaultValue); } size_t Sense::putString(const char *key, String value) { preferences.begin(PREFERENCES_KEY, false); return preferences.putString(key, value); } size_t Sense::putUInt(const char *key, uint32_t value) { preferences.begin(PREFERENCES_KEY, false); return preferences.putUInt(key, value); } size_t Sense::putFloat(const char *key, float_t value) { preferences.begin(PREFERENCES_KEY, false); return preferences.putFloat(key, value); } bool Sense::clearPreferences() { return preferences.clear(); }
18.69434
69
0.690553
danielkaldheim
157d5dd525cb3f4b5f98390236e2a121add34777
685
cc
C++
P9 Data Structure (tuples)/P84786.cc
miquelt9/Problemes-PRO1
1bd5214ce75129e9a027728b93ad8354ec993e41
[ "Apache-2.0" ]
2
2021-09-01T10:52:32.000Z
2021-11-09T09:19:57.000Z
P9 Data Structure (tuples)/P84786.cc
miquelt9/Problemes-PRO1
1bd5214ce75129e9a027728b93ad8354ec993e41
[ "Apache-2.0" ]
null
null
null
P9 Data Structure (tuples)/P84786.cc
miquelt9/Problemes-PRO1
1bd5214ce75129e9a027728b93ad8354ec993e41
[ "Apache-2.0" ]
1
2021-09-24T20:00:41.000Z
2021-09-24T20:00:41.000Z
#include <typeinfo> #include <iostream> #include <string> #include <cmath> using namespace std; struct Punt { double x, y; }; struct Cercle { Punt centre; double radi; }; double distancia(const Punt& a, const Punt& b){ double x = abs(a.x - b.x); double y = abs(a.y - b.y); double dist = sqrt(pow(x, 2) + pow(y, 2)); return dist; } void desplaca(Punt& p1, const Punt& p2){ p1.x += p2.x; p1.y += p2.y; } void escala(Cercle& c, double esc){ c.radi *= esc; } void desplaca(Cercle& c, const Punt& p){ c.centre.x += p.x; c.centre.y += p.y; } bool es_interior(const Punt& p, const Cercle& c){ if(distancia(p, c.centre) < c.radi) return true; return false; }
17.564103
50
0.620438
miquelt9
157dedc0ab16822309615dede51157455c5f3fd2
11,995
cc
C++
src/iocontrollers/pcie_controller.cc
werneazc/mcpat
fcd4d650709423f24bdad8d3cc302001e10e1f7d
[ "Intel" ]
1
2020-05-25T00:34:01.000Z
2020-05-25T00:34:01.000Z
src/iocontrollers/pcie_controller.cc
werneazc/mcpat
fcd4d650709423f24bdad8d3cc302001e10e1f7d
[ "Intel" ]
15
2020-05-24T23:33:03.000Z
2020-06-24T17:54:59.000Z
src/iocontrollers/pcie_controller.cc
werneazc/mcpat
fcd4d650709423f24bdad8d3cc302001e10e1f7d
[ "Intel" ]
2
2021-01-26T02:02:27.000Z
2021-03-07T12:24:56.000Z
/***************************************************************************** * McPAT * SOFTWARE LICENSE AGREEMENT * Copyright 2012 Hewlett-Packard Development Company, L.P. * 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 copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.” * * Author: * Andrew Smith ***************************************************************************/ #include "pcie_controller.h" #include "XML_Parse.h" #include "basic_circuit.h" #include "basic_components.h" #include "const.h" #include "io.h" #include "parameter.h" #include <algorithm> #include <assert.h> #include <cmath> #include <iostream> #include <string> /* * PCIeController() * Constructor, Initializes the member variables that are shared across * methods. */ PCIeController::PCIeController() { long_channel = false; power_gating = false; init_params = false; init_stats = false; } /* * computeArea() * Computes the component area based off of the input parameters in the XML. * Side Effects: * Sets the component area member to the calculated area. * Input: * None * Output: * None */ void PCIeController::computeArea() { double frontend_area = 0.0; double phy_area = 0.0; double ctrl_area = 0.0; double SerDer_area = 0.0; if (!init_params) { std::cerr << "[ PCIeController ] Error: must set params before calling " "computeArea()\n"; exit(1); } /* Assuming PCIe is bit-slice based architecture * This is the reason for /8 in both area and power calculation * to get per lane numbers */ local_result = init_interface(&ip); if (pciep.type == 0) // high performance NIU { // Area estimation based on average of die photo from Niagara 2 and Cadence // ChipEstimate @ 65nm. ctrl_area = (5.2 + 0.5) / 2 * (ip.F_sz_um / 0.065) * (ip.F_sz_um / 0.065); // Area estimation based on average of die photo from Niagara 2, and Cadence // ChipEstimate @ 65nm. frontend_area = (5.2 + 0.1) / 2 * (ip.F_sz_um / 0.065) * (ip.F_sz_um / 0.065); // Area estimation based on average of die photo from Niagara 2 and Cadence // ChipEstimate hard IP @65nm. SerDer is very hard to scale SerDer_area = (3.03 + 0.36) * (ip.F_sz_um / 0.065); //* (ip.F_sz_um/0.065); phy_area = frontend_area + SerDer_area; // total area } else { ctrl_area = 0.412 * (ip.F_sz_um / 0.065) * (ip.F_sz_um / 0.065); // Area estimation based on average of die photo from Niagara 2, and Cadence // ChipEstimate @ 65nm. SerDer_area = 0.36 * (ip.F_sz_um / 0.065) * (ip.F_sz_um / 0.065); // total area } area.set_area(((ctrl_area + (pciep.withPHY ? SerDer_area : 0)) / 8 * pciep.num_channels) * 1e6); } /* * computeStaticPower() * Computes the static power based off of the input parameters from the xml. * It calculates leakage power, * * TODO: Add Vdd such that the static power & dynamic power can reflect * changes in the chip power supply. * * Side Effects: * Sets the static power, leakage, and power gated leakage * Input: * None * Output: * None */ void PCIeController::computeStaticPower() { double frontend_dyn = 0.0; double ctrl_dyn = 0.0; double SerDer_dyn = 0.0; double frontend_gates = 0.0; double ctrl_gates = 0.0; double SerDer_gates = 0.0; double NMOS_sizing = 0.0; double PMOS_sizing = 0.0; double pmos_to_nmos_sizing_r = pmos_to_nmos_sz_ratio(); if (!init_params) { std::cerr << "[ PCIeController ] Error: must set params before calling " "computeStaticPower()\n"; exit(1); } if (pciep.type == 0) // high performance NIU { // Power // Cadence ChipEstimate using 65nm the controller includes everything: the // PHY, the data link and transaction layer ctrl_dyn = 3.75e-9 / 8 * g_tp.peri_global.Vdd / 1.1 * g_tp.peri_global.Vdd / 1.1 * (ip.F_sz_nm / 65.0); // //Cadence ChipEstimate using 65nm soft IP; // frontend_dyn = // 0.27e-9/8*g_tp.peri_global.Vdd/1.1*g_tp.peri_global.Vdd/1.1*(ip.F_sz_nm/65.0); // SerDer_dyn is power not energy, scaling from 10mw/Gb/s @90nm SerDer_dyn = 0.01 * 4 * (ip.F_sz_um / 0.09) * g_tp.peri_global.Vdd / 1.2 * g_tp.peri_global.Vdd / 1.2; // PCIe 2.0 max per lane speed is 4Gb/s SerDer_dyn /= pciep.clockRate; // covert to energy per clock cycle // power_t.readOp.dynamic = (ctrl_dyn)*pciep.num_channels; // Cadence ChipEstimate using 65nm ctrl_gates = 900000 / 8 * pciep.num_channels; // frontend_gates = 120000/8; // SerDer_gates = 200000/8; NMOS_sizing = 5 * g_tp.min_w_nmos_; PMOS_sizing = 5 * g_tp.min_w_nmos_ * pmos_to_nmos_sizing_r; } else { // Power // Cadence ChipEstimate using 65nm the controller includes everything: the // PHY, the data link and transaction layer ctrl_dyn = 2.21e-9 / 8 * g_tp.peri_global.Vdd / 1.1 * g_tp.peri_global.Vdd / 1.1 * (ip.F_sz_nm / 65.0); // //Cadence ChipEstimate using 65nm soft IP; // frontend_dyn = // 0.27e-9/8*g_tp.peri_global.Vdd/1.1*g_tp.peri_global.Vdd/1.1*(ip.F_sz_nm/65.0); // SerDer_dyn is power not energy, scaling from 10mw/Gb/s @90nm SerDer_dyn = 0.01 * 4 * (ip.F_sz_um / 0.09) * g_tp.peri_global.Vdd / 1.2 * g_tp.peri_global.Vdd / 1.2; // PCIe 2.0 max per lane speed is 4Gb/s SerDer_dyn /= pciep.clockRate; // covert to energy per clock cycle // Cadence ChipEstimate using 65nm ctrl_gates = 200000 / 8 * pciep.num_channels; // frontend_gates = 120000/8; SerDer_gates = 200000 / 8 * pciep.num_channels; NMOS_sizing = g_tp.min_w_nmos_; PMOS_sizing = g_tp.min_w_nmos_ * pmos_to_nmos_sizing_r; } power_t.readOp.dynamic = (ctrl_dyn + (pciep.withPHY ? SerDer_dyn : 0)) * pciep.num_channels; power_t.readOp.leakage = (ctrl_gates + (pciep.withPHY ? SerDer_gates : 0)) * cmos_Isub_leakage(NMOS_sizing, PMOS_sizing, 2, nand) * g_tp.peri_global.Vdd; // unit W double long_channel_device_reduction = longer_channel_device_reduction(Uncore_device); double pg_reduction = power_gating_leakage_reduction(false); power_t.readOp.longer_channel_leakage = power_t.readOp.leakage * long_channel_device_reduction; power_t.readOp.power_gated_leakage = power_t.readOp.leakage * pg_reduction; power_t.readOp.power_gated_with_long_channel_leakage = power_t.readOp.power_gated_leakage * long_channel_device_reduction; power_t.readOp.gate_leakage = (ctrl_gates + (pciep.withPHY ? SerDer_gates : 0)) * cmos_Ig_leakage(NMOS_sizing, PMOS_sizing, 2, nand) * g_tp.peri_global.Vdd; // unit W } /* * computeDynamicPower() * Compute both Peak Power and Runtime Power based on the stats of the input * xml. * Side Effects: * Sets the runtime power, and the peak dynamic power in the component * class * Input: * None * Output: * None */ void PCIeController::computeDynamicPower() { power = power_t; power.readOp.dynamic *= pciep.duty_cycle; rt_power = power_t; rt_power.readOp.dynamic *= pciep.perc_load; } /* * display(uint32_t, bool) * Display the Power, Area, and Timing results to the standard output * Side Effects: * None * Input: * indent - How far in to indent * enable - toggle printing * Output: * None */ void PCIeController::display(uint32_t indent, bool enable) { string indent_str(indent, ' '); string indent_str_next(indent + 2, ' '); if (enable) { cout << "PCIe:" << endl; cout << indent_str << "Area = " << area.get_area() * 1e-6 << " mm^2" << endl; cout << indent_str << "Peak Dynamic = " << power.readOp.dynamic * pciep.clockRate << " W" << endl; cout << indent_str << "Subthreshold Leakage = " << (long_channel ? power.readOp.longer_channel_leakage : power.readOp.leakage) << " W" << endl; if (power_gating) cout << indent_str << "Subthreshold Leakage with power gating = " << (long_channel ? power.readOp.power_gated_with_long_channel_leakage : power.readOp.power_gated_leakage) << " W" << endl; cout << indent_str << "Gate Leakage = " << power.readOp.gate_leakage << " W" << endl; cout << indent_str << "Runtime Dynamic = " << rt_power.readOp.dynamic * pciep.clockRate << " W" << endl; cout << endl; } else { } } /* * set_params(const ParseXML, InputParameter) * Sets the parts of the flash controller params that contribute to area and * static power. Must be called before computing area or static power. * Side Effects: * sets the interface_ip struct, and sets the params struct to the * "params" from the xml file. Also sets init_params to true. * Input: * *XML - Parsed XML * *interface_ip - Interface from McPAT used in Cacti Library * Output: * None */ void PCIeController::set_params(const ParseXML *XML, InputParameter *interface_ip) { ip = *interface_ip; pciep.clockRate = XML->sys.pcie.clockrate; pciep.clockRate *= 1e6; pciep.num_units = XML->sys.pcie.number_units; pciep.num_channels = XML->sys.pcie.num_channels; pciep.type = XML->sys.pcie.type; pciep.withPHY = XML->sys.pcie.withPHY; long_channel = XML->sys.longer_channel_device; power_gating = XML->sys.power_gating; if (XML->sys.pcie.vdd > 0) { ip.specific_hp_vdd = true; ip.specific_lop_vdd = true; ip.specific_lstp_vdd = true; ip.hp_Vdd = XML->sys.pcie.vdd; ip.lop_Vdd = XML->sys.pcie.vdd; ip.lstp_Vdd = XML->sys.pcie.vdd; } if (XML->sys.pcie.power_gating_vcc > -1) { ip.specific_vcc_min = true; ip.user_defined_vcc_min = XML->sys.pcie.power_gating_vcc; } init_params = true; } /* * set_stats(const ParseXML) * Sets the parts of the flash controller params that contribute to dynamic * power. * Side Effects: * Store duty cycle and and percentage load into fc params, sets * init_stats to true * Input: * *XML - Parsed XML * Output: * None */ void PCIeController::set_stats(const ParseXML *XML) { pciep.duty_cycle = XML->sys.pcie.duty_cycle; pciep.perc_load = XML->sys.pcie.total_load_perc; init_stats = true; }
36.681957
85
0.647853
werneazc
15819bd3a1465c23d9bef99abfece6f69e9ebb11
883
cpp
C++
src/Router/lookup_service/src/thread_safe_map.cpp
JungyeonYoon/MicroSuite
acc75468a3568bb9504841978b887a337eba889c
[ "BSD-3-Clause" ]
12
2019-03-06T13:17:50.000Z
2022-02-20T21:27:25.000Z
src/Router/lookup_service/src/thread_safe_map.cpp
DCchico/MicroSuite
b8651e0f5b74461393140135b917243a2e853f3d
[ "BSD-3-Clause" ]
null
null
null
src/Router/lookup_service/src/thread_safe_map.cpp
DCchico/MicroSuite
b8651e0f5b74461393140135b917243a2e853f3d
[ "BSD-3-Clause" ]
3
2019-06-08T01:46:55.000Z
2020-05-18T01:40:38.000Z
#include <iostream> #include <mutex> // For std::unique_lock #include <shared_mutex> #include <thread> #include <map> class ThreadSafeMap { public: ThreadSafeMap() = default; // Multiple threads/readers can read the counter's value at the same time. std::string Get(std::string key) { std::shared_lock<std::shared_mutex> lock(mutex_); try { map_.at(key); } catch( ... ) { return "nack"; } return map_[key]; } // Only one thread/writer can increment/write the counter's value. void Set(std::string key, std::string value) { std::unique_lock<std::shared_mutex> lock(mutex_); map_[key] = value; } private: mutable std::shared_mutex mutex_; std::map<std::string, std::string> map_; };
26.757576
82
0.554926
JungyeonYoon
158491f40e7d49938c0f5e062c97a940eeea8edc
4,012
cc
C++
source/blender/nodes/geometry/nodes/node_geo_mesh_primitive_cylinder.cc
recogni/blender
af830498016c01c4847f00b51246bc8e3c88f6f6
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-01-30T01:03:05.000Z
2020-01-30T01:03:05.000Z
source/blender/nodes/geometry/nodes/node_geo_mesh_primitive_cylinder.cc
recogni/blender
af830498016c01c4847f00b51246bc8e3c88f6f6
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/nodes/geometry/nodes/node_geo_mesh_primitive_cylinder.cc
recogni/blender
af830498016c01c4847f00b51246bc8e3c88f6f6
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "DNA_mesh_types.h" #include "DNA_meshdata_types.h" #include "BKE_mesh.h" #include "UI_interface.h" #include "UI_resources.h" #include "node_geometry_util.hh" static bNodeSocketTemplate geo_node_mesh_primitive_cylinder_in[] = { {SOCK_INT, N_("Vertices"), 32, 0.0f, 0.0f, 0.0f, 3, 4096}, {SOCK_FLOAT, N_("Radius"), 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, FLT_MAX, PROP_DISTANCE}, {SOCK_FLOAT, N_("Depth"), 2.0f, 0.0f, 0.0f, 0.0f, 0.0f, FLT_MAX, PROP_DISTANCE}, {SOCK_VECTOR, N_("Location"), 0.0f, 0.0f, 0.0f, 0.0f, -FLT_MAX, FLT_MAX, PROP_TRANSLATION}, {SOCK_VECTOR, N_("Rotation"), 0.0f, 0.0f, 0.0f, 0.0f, -FLT_MAX, FLT_MAX, PROP_EULER}, {-1, ""}, }; static bNodeSocketTemplate geo_node_mesh_primitive_cylinder_out[] = { {SOCK_GEOMETRY, N_("Geometry")}, {-1, ""}, }; static void geo_node_mesh_primitive_cylinder_layout(uiLayout *layout, bContext *UNUSED(C), PointerRNA *ptr) { uiLayoutSetPropSep(layout, true); uiLayoutSetPropDecorate(layout, false); uiItemR(layout, ptr, "fill_type", 0, nullptr, ICON_NONE); } static void geo_node_mesh_primitive_cylinder_init(bNodeTree *UNUSED(ntree), bNode *node) { NodeGeometryMeshCylinder *node_storage = (NodeGeometryMeshCylinder *)MEM_callocN( sizeof(NodeGeometryMeshCylinder), __func__); node_storage->fill_type = GEO_NODE_MESH_CIRCLE_FILL_NGON; node->storage = node_storage; } namespace blender::nodes { static void geo_node_mesh_primitive_cylinder_exec(GeoNodeExecParams params) { const bNode &node = params.node(); const NodeGeometryMeshCylinder &storage = *(const NodeGeometryMeshCylinder *)node.storage; const GeometryNodeMeshCircleFillType fill_type = (const GeometryNodeMeshCircleFillType) storage.fill_type; const int verts_num = params.extract_input<int>("Vertices"); if (verts_num < 3) { params.set_output("Geometry", GeometrySet()); return; } const float radius = params.extract_input<float>("Radius"); const float depth = params.extract_input<float>("Depth"); const float3 location = params.extract_input<float3>("Location"); const float3 rotation = params.extract_input<float3>("Rotation"); /* The cylinder is a special case of the cone mesh where the top and bottom radius are equal. */ Mesh *mesh = create_cylinder_or_cone_mesh( location, rotation, radius, radius, depth, verts_num, fill_type); params.set_output("Geometry", GeometrySet::create_with_mesh(mesh)); } } // namespace blender::nodes void register_node_type_geo_mesh_primitive_cylinder() { static bNodeType ntype; geo_node_type_base(&ntype, GEO_NODE_MESH_PRIMITIVE_CYLINDER, "Cylinder", NODE_CLASS_GEOMETRY, 0); node_type_socket_templates( &ntype, geo_node_mesh_primitive_cylinder_in, geo_node_mesh_primitive_cylinder_out); node_type_init(&ntype, geo_node_mesh_primitive_cylinder_init); node_type_storage( &ntype, "NodeGeometryMeshCylinder", node_free_standard_storage, node_copy_standard_storage); ntype.geometry_node_execute = blender::nodes::geo_node_mesh_primitive_cylinder_exec; ntype.draw_buttons = geo_node_mesh_primitive_cylinder_layout; nodeRegisterType(&ntype); }
38.576923
99
0.725075
recogni
1587e46ebf7719f8a1f74a1dbc9321fbf6956610
2,198
cpp
C++
2D Arrays/sum_of_matrix_Q_queries.cpp
jahnvisrivastava100/CompetitiveProgrammingQuestionBank
0d72884ea5e0eb674a503b81ab65e444f5175cf4
[ "MIT" ]
931
2020-04-18T11:57:30.000Z
2022-03-31T15:15:39.000Z
2D Arrays/sum_of_matrix_Q_queries.cpp
jahnvisrivastava100/CompetitiveProgrammingQuestionBank
0d72884ea5e0eb674a503b81ab65e444f5175cf4
[ "MIT" ]
661
2020-12-13T04:31:48.000Z
2022-03-15T19:11:54.000Z
2D Arrays/sum_of_matrix_Q_queries.cpp
Mayuri-cell/CompetitiveProgrammingQuestionBank
eca2257d7da5346f45bdd7a351cc95bde6ed5c7d
[ "MIT" ]
351
2020-08-10T06:49:21.000Z
2022-03-25T04:02:12.000Z
// Problem - Print the sum of all submatrices of the given matrix for Q queries. // The coordinates (start and end index) of the submatrix is given as queries // the problem is to find the sum of those submatrices for given queries. // Sample Input - 1 // 3 3 // 1 1 1 // 1 1 1 // 1 1 1 // 2 // 2 2 // 2 2 // 0 0 // 1 1 // Sample Output - 1 // 1 // 4 // Sample Input - 2 // 3 2 // 1 10 8 // -1 5 0 // 2 // 0 0 // 1 2 // 1 1 // 1 2 // Sample Output - 2 // 23 // 5 #include <iostream> #include <vector> using namespace std; vector <vector <int>> build_prefix_sum(vector <vector <int>> grid) { int n = grid.size() , m = grid[0].size(); vector <vector <int>> prefix_sum(n , vector <int> (m)); // Calculating the prefix sum of rows for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(j == 0) prefix_sum[i][j] = grid[i][j]; else prefix_sum[i][j] = prefix_sum[i][j - 1] + grid[i][j]; } } // Calculating the prefix sum of columns for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(i != 0) prefix_sum[i][j] += prefix_sum[i - 1][j]; } } return prefix_sum; } int submatrix_sum(vector <vector <int>> prefix , int tl1 , int tl2 , int br1 , int br2) { int n = prefix.size() , m = prefix[0].size(); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) cout << prefix[i][j] << " "; cout << endl; } int sum = 0; sum += (prefix[br1][br2]); if(tl1 > 0 && tl2 > 0) sum = sum - (prefix[br1][tl2 - 1] + prefix[tl1 - 1][br2]) + prefix[tl1 - 1][tl2 - 1]; else if(tl1 > 0) sum = sum - prefix[tl1 - 1][br2]; else sum = sum - prefix[br1][tl2 - 1]; return sum; } int main() { int n , m; cin >> n >> m; vector <vector <int>> grid(n , vector <int> (m)); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) cin >> grid[i][j]; } int q; cin >> q; vector <vector <int>> prefix_sum = build_prefix_sum(grid); for(int i = 0; i < q; i++) { int tl1 , tl2 , br1 , br2; cin >> tl1 >> tl2; cin >> br1 >> br2; int sum = submatrix_sum(prefix_sum , tl1 , tl2 , br1 , br2); cout << sum << endl; } return 0; }
18.165289
89
0.515469
jahnvisrivastava100
1588b394cb476cd9ee8462097d55ec36dd58ce9a
36,871
cpp
C++
private/shell/ext/netplwiz/ulistpg.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/ext/netplwiz/ulistpg.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/ext/netplwiz/ulistpg.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
/******************************************************** ulistpg.cpp User Manager user list property page History: 09/23/98: dsheldon created ********************************************************/ #include "stdafx.h" #include "resource.h" #include "ulistpg.h" #include "data.h" #include "unpage.h" #include "pwpage.h" #include "grppage.h" #include "netpage.h" #include "autolog.h" #include "usercom.h" #include "misc.h" // Help ID array static const DWORD rgHelpIds[] = { IDC_AUTOLOGON_CHECK, IDH_AUTOLOGON_CHECK, IDC_LISTTITLE_STATIC, IDH_USER_LIST, IDC_USER_LIST, IDH_USER_LIST, IDC_ADDUSER_BUTTON, IDH_ADDUSER_BUTTON, IDC_REMOVEUSER_BUTTON, IDH_REMOVEUSER_BUTTON, IDC_USERPROPERTIES_BUTTON, IDH_USERPROPERTIES_BUTTON, IDC_PASSWORD_STATIC, IDH_PASSWORD_BUTTON, IDC_CURRENTUSER_ICON, IDH_PASSWORD_BUTTON, IDC_PASSWORD_BUTTON, IDH_PASSWORD_BUTTON, IDC_PWGROUP_STATIC, (DWORD) -1, IDC_ULISTPG_TEXT, (DWORD) -1, IDC_USERLISTPAGE_ICON, (DWORD) -1, 0, 0 }; // Control ID arrays for enabling/disabling/moving static const UINT rgidDisableOnAutologon[] = { IDC_USER_LIST, IDC_ADDUSER_BUTTON, IDC_REMOVEUSER_BUTTON, IDC_USERPROPERTIES_BUTTON, IDC_PASSWORD_BUTTON }; static const UINT rgidDisableOnNoSelection[] = { IDC_REMOVEUSER_BUTTON, IDC_USERPROPERTIES_BUTTON, IDC_PASSWORD_BUTTON }; static const UINT rgidMoveOnNoAutologonCheck[] = { IDC_LISTTITLE_STATIC, IDC_USER_LIST, // IDC_ADDUSER_BUTTON, // IDC_e_BUTTON, // IDC_USERPROPERTIES_BUTTON, // IDC_PWGROUP_STATIC, // IDC_CURRENTUSER_ICON, // IDC_PASSWORD_STATIC, // IDC_PASSWORD_BUTTON }; CUserlistPropertyPage::~CUserlistPropertyPage() { if (m_himlLarge != NULL) ImageList_Destroy(m_himlLarge); } INT_PTR CUserlistPropertyPage::DialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { HANDLE_MSG(hwndDlg, WM_INITDIALOG, OnInitDialog); HANDLE_MSG(hwndDlg, WM_NOTIFY, OnNotify); HANDLE_MSG(hwndDlg, WM_COMMAND, OnCommand); HANDLE_MSG(hwndDlg, WM_SETCURSOR, OnSetCursor); case WM_HELP: return OnHelp(hwndDlg, (LPHELPINFO) lParam); case WM_CONTEXTMENU: return OnContextMenu((HWND) wParam); case WM_ADDUSERTOLIST: return SUCCEEDED(AddUserToListView(GetDlgItem(hwndDlg, IDC_USER_LIST), (CUserInfo*) lParam, (BOOL) wParam)); } return FALSE; } BOOL CUserlistPropertyPage::OnHelp(HWND hwnd, LPHELPINFO pHelpInfo) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::OnHelp"); WinHelp((HWND) pHelpInfo->hItemHandle, m_pData->GetHelpfilePath(), HELP_WM_HELP, (ULONG_PTR) (LPTSTR) rgHelpIds); TraceLeaveValue(TRUE); } BOOL CUserlistPropertyPage::OnContextMenu(HWND hwnd) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::OnContextMenu"); WinHelp(hwnd, m_pData->GetHelpfilePath(), HELP_CONTEXTMENU, (ULONG_PTR) (LPTSTR) rgHelpIds); TraceLeaveValue(TRUE); } BOOL CUserlistPropertyPage::OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::OnInitDialog"); HWND hwndList = GetDlgItem(hwnd, IDC_USER_LIST); InitializeListView(hwndList, m_pData->IsComputerInDomain()); m_pData->Initialize(hwnd); SetupList(hwnd); m_fAutologonCheckChanged = FALSE; TraceLeaveValue(TRUE); } BOOL CUserlistPropertyPage::OnListViewDeleteItem(HWND hwndList, int iItem) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::OnListViewDeleteItem"); LVITEM lvi = {0}; lvi.iItem = iItem; lvi.mask = LVIF_PARAM; ListView_GetItem(hwndList, &lvi); CUserInfo* pUserInfo = (CUserInfo*) lvi.lParam; if (NULL != pUserInfo) { delete pUserInfo; } TraceLeaveValue(TRUE); } BOOL CUserlistPropertyPage::OnNotify(HWND hwnd, int idCtrl, LPNMHDR pnmh) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::OnNotify"); BOOL fResult = TRUE; switch (pnmh->code) { case PSN_APPLY: { long applyEffect = OnApply(hwnd); SetWindowLongPtr(hwnd, DWLP_MSGRESULT, applyEffect); } break; case LVN_GETINFOTIP: fResult = OnGetInfoTip(pnmh->hwndFrom, (LPNMLVGETINFOTIP) pnmh); break; case LVN_ITEMCHANGED: fResult = OnListViewItemChanged(hwnd); break; case LVN_DELETEITEM: fResult = OnListViewDeleteItem(GetDlgItem(hwnd, IDC_USER_LIST), ((LPNMLISTVIEW) pnmh)->iItem); break; case NM_DBLCLK: LaunchUserProperties(hwnd); fResult = TRUE; break; case LVN_COLUMNCLICK: { int iColumn = ((LPNMLISTVIEW) pnmh)->iSubItem; // Want to work with 1-based columns so we can use zero as // a special value iColumn += 1; // If we aren't showing the domain column because we're in // non-domain mode, then map column 2 (group since we're not in // domain mode to column 3 since the callback always expects // the columns to be, "username", "domain", "group". if ((iColumn == 2) && (!m_pData->IsComputerInDomain())) { iColumn = 3; } if (m_iReverseColumnIfSelected == iColumn) { m_iReverseColumnIfSelected = 0; iColumn = -iColumn; } else { m_iReverseColumnIfSelected = iColumn; } ListView_SortItems(pnmh->hwndFrom, ListCompare, (LPARAM) iColumn); fResult = TRUE; } break; default: fResult = FALSE; break; } TraceLeaveValue(fResult); } BOOL CUserlistPropertyPage::OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::OnCommand"); switch (id) { case IDC_ADDUSER_BUTTON: if (m_pData->IsComputerInDomain()) { // Launch the wizard to add a network user to a local group LaunchAddNetUserWizard(hwnd); } else { // No domain; create a new local machine user LaunchNewUserWizard(hwnd); } TraceLeaveValue(TRUE); case IDC_REMOVEUSER_BUTTON: OnRemove(hwnd); TraceLeaveValue(TRUE); case IDC_AUTOLOGON_CHECK: m_fAutologonCheckChanged = TRUE; // We may need some user input to change the autologon state SetAutologonState(hwnd, BST_UNCHECKED == SendMessage(GetDlgItem(hwnd, IDC_AUTOLOGON_CHECK), BM_GETCHECK, 0, 0)); SetPageState(hwnd); break; case IDC_ADVANCED_BUTTON: { // Launch the MMC local user manager STARTUPINFO startupinfo = {0}; startupinfo.cb = sizeof (startupinfo); PROCESS_INFORMATION process_information; // Consider using env. vars and ExpandEnvironmentString here static const TCHAR szMMCCommandLineFormat[] = TEXT("mmc.exe /computer=%s %%systemroot%%\\system32\\lusrmgr.msc"); TCHAR szMMCCommandLine[MAX_PATH]; TCHAR szExpandedCommandLine[MAX_PATH]; wnsprintf(szMMCCommandLine, ARRAYSIZE(szMMCCommandLine), szMMCCommandLineFormat, m_pData->GetComputerName()); if (ExpandEnvironmentStrings(szMMCCommandLine, szExpandedCommandLine, ARRAYSIZE(szExpandedCommandLine)) > 0) { if (CreateProcess(NULL, szExpandedCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &startupinfo, &process_information)) { CloseHandle(process_information.hProcess); CloseHandle(process_information.hThread); } } } break; case IDC_PASSWORD_BUTTON: LaunchSetPasswordDialog(hwnd); break; case IDC_USERPROPERTIES_BUTTON: LaunchUserProperties(hwnd); break; } TraceLeaveValue(FALSE); } BOOL CUserlistPropertyPage::OnSetCursor(HWND hwnd, HWND hwndCursor, UINT codeHitTest, UINT msg) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::OnSetCursor"); BOOL fHandled = FALSE; // If the thread is filling, handle by setting the appstarting cursor if (m_pData->GetUserListLoader()->InitInProgress()) { fHandled = TRUE; SetCursor(LoadCursor(NULL, IDC_APPSTARTING)); } SetWindowLongPtr(hwnd, DWLP_MSGRESULT, fHandled); TraceLeaveValue(TRUE); } BOOL CUserlistPropertyPage::OnGetInfoTip(HWND hwndList, LPNMLVGETINFOTIP pGetInfoTip) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::OnGetInfoTip"); // Get the UserInfo structure for the selected item LVITEM lvi; lvi.mask = LVIF_PARAM; lvi.iItem = pGetInfoTip->iItem; lvi.iSubItem = 0; if ((lvi.iItem >= 0) && (ListView_GetItem(hwndList, &lvi))) { CUserInfo* pUserInfo = (CUserInfo*) lvi.lParam; TraceAssert(pUserInfo != NULL); // Ensure full name and comment are available pUserInfo->GetExtraUserInfo(); // Make a string containing our "Full Name: %s\nComment: %s" message if ((pUserInfo->m_szFullName[0] != TEXT('\0')) && (pUserInfo->m_szComment[0] != TEXT('\0'))) { // We have a full name and comment FormatMessageString(IDS_USR_TOOLTIPBOTH_FORMAT, pGetInfoTip->pszText, pGetInfoTip->cchTextMax, pUserInfo->m_szFullName, pUserInfo->m_szComment); } else if (pUserInfo->m_szFullName[0] != TEXT('\0')) { // We only have full name FormatMessageString(IDS_USR_TOOLTIPFULLNAME_FORMAT, pGetInfoTip->pszText, pGetInfoTip->cchTextMax, pUserInfo->m_szFullName); } else if (pUserInfo->m_szComment[0] != TEXT('\0')) { // We only have comment FormatMessageString(IDS_USR_TOOLTIPCOMMENT_FORMAT, pGetInfoTip->pszText, pGetInfoTip->cchTextMax, pUserInfo->m_szComment); } else { // We have no extra information - do nothing (show no tip) } } TraceLeaveValue(TRUE); } struct MYCOLINFO { int percentWidth; UINT idString; }; HRESULT CUserlistPropertyPage::InitializeListView(HWND hwndList, BOOL fShowDomain) { // Array of icon ids icons 0, 1, and 2 respectively static const UINT rgIcons[] = { IDI_USR_LOCALUSER_ICON, IDI_USR_DOMAINUSER_ICON, IDI_USR_GROUP_ICON }; // Array of relative column widths, for columns 0, 1, and 2 respectively static const MYCOLINFO rgColWidthsWithDomain[] = { {40, IDS_USR_NAME_COLUMN}, {30, IDS_USR_DOMAIN_COLUMN}, {30, IDS_USR_GROUP_COLUMN} }; static const MYCOLINFO rgColWidthsNoDomain[] = { {50, IDS_USR_NAME_COLUMN}, {50, IDS_USR_GROUP_COLUMN} }; TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::InitializeListView"); HRESULT hr = S_OK; // Create a listview with three columns RECT rect; GetClientRect(hwndList, &rect); // Width of our window minus width of a verticle scroll bar minus one for the // little bevel at the far right of the header. int cxListView = (rect.right - rect.left) - GetSystemMetrics(SM_CXVSCROLL) - 1; // Make our columns int i; int nColumns; const MYCOLINFO* pColInfo; if (fShowDomain) { nColumns = ARRAYSIZE(rgColWidthsWithDomain); pColInfo = rgColWidthsWithDomain; } else { nColumns = ARRAYSIZE(rgColWidthsNoDomain); pColInfo = rgColWidthsNoDomain; } LVCOLUMN lvc; lvc.mask = LVCF_TEXT | LVCF_SUBITEM | LVCF_WIDTH; for (i = 0; i < nColumns; i++) { TCHAR szText[MAX_PATH]; // Load this column's caption LoadString(g_hInstance, pColInfo[i].idString, szText, ARRAYSIZE(szText)); lvc.iSubItem = i; lvc.cx = (int) MulDiv(pColInfo[i].percentWidth, cxListView, 100); lvc.pszText = szText; ListView_InsertColumn(hwndList, i, &lvc); } UINT flags = ILC_MASK; if(IS_WINDOW_RTL_MIRRORED(hwndList)) { flags |= ILC_MIRROR; } // Create an image list for the listview HIMAGELIST himlSmall = ImageList_Create(GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), flags, 0, ARRAYSIZE(rgIcons)); // Large image lists for the "set password" group icon m_himlLarge = ImageList_Create(32, 32, flags, 0, ARRAYSIZE(rgIcons)); if (himlSmall && m_himlLarge) { // Add our icons to the image list for(i = 0; i < ARRAYSIZE(rgIcons); i ++) { HICON hIconSmall = (HICON) LoadImage(g_hInstance, MAKEINTRESOURCE(rgIcons[i]), IMAGE_ICON, 16, 16, 0); if (hIconSmall) { ImageList_AddIcon(himlSmall, hIconSmall); DestroyIcon(hIconSmall); } HICON hIconLarge = (HICON) LoadImage(g_hInstance, MAKEINTRESOURCE(rgIcons[i]), IMAGE_ICON, 32, 32, 0); if (hIconLarge) { ImageList_AddIcon(m_himlLarge, hIconLarge); DestroyIcon(hIconLarge); } } } ListView_SetImageList(hwndList, himlSmall, LVSIL_SMALL); // Set extended styles for the listview ListView_SetExtendedListViewStyleEx(hwndList, LVS_EX_LABELTIP | LVS_EX_FULLROWSELECT | LVS_EX_INFOTIP, LVS_EX_LABELTIP | LVS_EX_FULLROWSELECT | LVS_EX_INFOTIP); // Set some settings for our tooltips - stolen from defview.cpp code HWND hwndInfoTip = ListView_GetToolTips(hwndList); if (hwndInfoTip != NULL) { //make the tooltip window to be topmost window SetWindowPos(hwndInfoTip, HWND_TOPMOST, 0,0,0,0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); // increase the ShowTime (the delay before we show the tooltip) to 2 times the default value LRESULT uiShowTime = SendMessage(hwndInfoTip, TTM_GETDELAYTIME, TTDT_INITIAL, 0); SendMessage(hwndInfoTip, TTM_SETDELAYTIME, TTDT_INITIAL, uiShowTime * 2); } TraceLeaveResult(hr); } HRESULT CUserlistPropertyPage::AddUserToListView(HWND hwndList, CUserInfo* pUserInfo, BOOL fSelectUser /* = FALSE */) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::AddUserToListView"); HRESULT hr = S_OK; // Do the add LVITEM lvi; int iItem; lvi.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM; // Always select the first loaded user if (ListView_GetItemCount(hwndList) == 0) { fSelectUser = TRUE; } if (fSelectUser) { lvi.mask |= LVIF_STATE; lvi.state = lvi.stateMask = LVIS_SELECTED | LVIS_FOCUSED; } lvi.iItem = 0; lvi.iSubItem = 0; lvi.pszText = pUserInfo->m_szUsername; lvi.iImage = pUserInfo->m_userType; lvi.lParam = (LPARAM) pUserInfo; iItem = ListView_InsertItem(hwndList, &lvi); if (iItem >= 0) { if (fSelectUser) { // Make the item visible ListView_EnsureVisible(hwndList, iItem, FALSE); } // Success! Now add the subitems (domain, groups) lvi.iItem = iItem; lvi.mask = LVIF_TEXT; // Only add the domain field if the user is in a domain if (::IsComputerInDomain()) { lvi.iSubItem = 1; lvi.pszText = pUserInfo->m_szDomain; ListView_SetItem(hwndList, &lvi); // User is in a domain; group should be third column lvi.iSubItem = 2; } else { // User isn't in a domain, group should be second column lvi.iSubItem = 1; } // Add group regardless of whether user is in a domain lvi.pszText = pUserInfo->m_szGroups; ListView_SetItem(hwndList, &lvi); } TraceLeaveResult(hr); } HRESULT CUserlistPropertyPage::LaunchNewUserWizard(HWND hwndParent) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::LaunchNewUserWizard"); HRESULT hr = S_OK; static const int nPages = 3; int cPages = 0; HPROPSHEETPAGE rghPages[nPages]; // Create a new user record CUserInfo* pNewUser = new CUserInfo; if (pNewUser != NULL) { pNewUser->InitializeForNewUser(); pNewUser->m_userType = CUserInfo::LOCALUSER; PROPSHEETPAGE psp = {0}; // Common propsheetpage settings psp.dwSize = sizeof (psp); psp.hInstance = g_hInstance; psp.dwFlags = PSP_DEFAULT | PSP_HIDEHEADER; // Page 1: Username entry page psp.pszTemplate = MAKEINTRESOURCE(IDD_USR_USERNAME_WIZARD_PAGE); CUsernameWizardPage page1(pNewUser); page1.SetPropSheetPageMembers(&psp); rghPages[cPages++] = CreatePropertySheetPage(&psp); // Page 2: Password page psp.pszTemplate = MAKEINTRESOURCE(IDD_USR_PASSWORD_WIZARD_PAGE); CPasswordWizardPage page2(pNewUser); page2.SetPropSheetPageMembers(&psp); rghPages[cPages++] = CreatePropertySheetPage(&psp); // Page 3: Local group addition psp.pszTemplate = MAKEINTRESOURCE(IDD_USR_CHOOSEGROUP_WIZARD_PAGE); CGroupWizardPage page3(pNewUser, m_pData->GetGroupList()); page3.SetPropSheetPageMembers(&psp); rghPages[cPages++] = CreatePropertySheetPage(&psp); TraceAssert(cPages <= nPages); PROPSHEETHEADER psh = {0}; psh.dwSize = sizeof (psh); psh.dwFlags = PSH_NOCONTEXTHELP | PSH_WIZARD | PSH_WIZARD_LITE; psh.hwndParent = hwndParent; psh.hInstance = g_hInstance; psh.nPages = nPages; psh.phpage = rghPages; int iRetCode = (int)PropertySheet(&psh); if (iRetCode == IDOK) { AddUserToListView(GetDlgItem(hwndParent, IDC_USER_LIST), pNewUser, TRUE); } else { // User clicked cancel delete pNewUser; pNewUser = NULL; } } else { hr = E_OUTOFMEMORY; TraceMsg("CreateNewUserInfo() failed!"); DisplayFormatMessage(hwndParent, IDS_USR_NEWUSERWIZARD_CAPTION, IDS_USR_CREATE_MISC_ERROR, MB_OK | MB_ICONERROR); } if (FAILED(hr)) { if (pNewUser) { delete pNewUser; } } TraceLeaveResult(hr); } HRESULT CUserlistPropertyPage::LaunchAddNetUserWizard(HWND hwndParent) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::LaunchAddNetUserWizard"); HRESULT hr = S_OK; static const int nPages = 2; int cPages = 0; HPROPSHEETPAGE rghPages[nPages]; // Create a new user record CUserInfo* pNewUser = new CUserInfo; if (pNewUser != NULL) { pNewUser->InitializeForNewUser(); pNewUser->m_userType = CUserInfo::DOMAINUSER; PROPSHEETPAGE psp = {0}; // Common propsheetpage settings psp.dwSize = sizeof (psp); psp.hInstance = g_hInstance; psp.dwFlags = PSP_DEFAULT | PSP_HIDEHEADER; // Page 1: Find a network user page psp.pszTemplate = MAKEINTRESOURCE(IDD_USR_FINDNETUSER_WIZARD_PAGE); CNetworkUserWizardPage page1(pNewUser); page1.SetPropSheetPageMembers(&psp); rghPages[cPages++] = CreatePropertySheetPage(&psp); // Page 2: Local group addition psp.pszTemplate = MAKEINTRESOURCE(IDD_USR_CHOOSEGROUP_WIZARD_PAGE); CGroupWizardPage page2(pNewUser, m_pData->GetGroupList()); page2.SetPropSheetPageMembers(&psp); rghPages[cPages++] = CreatePropertySheetPage(&psp); TraceAssert(cPages <= nPages); PROPSHEETHEADER psh = {0}; psh.dwSize = sizeof (psh); psh.dwFlags = PSH_NOCONTEXTHELP | PSH_WIZARD | PSH_WIZARD_LITE; psh.hwndParent = hwndParent; psh.hInstance = g_hInstance; psh.nPages = nPages; psh.phpage = rghPages; int iRetCode = (int)PropertySheet(&psh); if (iRetCode == IDOK) { AddUserToListView(GetDlgItem(hwndParent, IDC_USER_LIST), pNewUser, TRUE); m_pData->UserInfoChanged(pNewUser->m_szUsername, pNewUser->m_szDomain); } else { // No errors, but the user clicked Cancel... delete pNewUser; pNewUser = NULL; } } else { hr = E_OUTOFMEMORY; TraceMsg("CreateNewUserInfo() failed!"); DisplayFormatMessage(hwndParent, IDS_USR_NEWUSERWIZARD_CAPTION, IDS_USR_CREATE_MISC_ERROR, MB_OK | MB_ICONERROR); } if (FAILED(hr)) { if (pNewUser) { delete pNewUser; } } TraceLeaveResult(hr); } HRESULT CUserlistPropertyPage::LaunchUserProperties(HWND hwndParent) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::LaunchUserProperties"); HRESULT hr = S_OK; ADDPROPSHEETDATA apsd; apsd.nPages = 0; // Create a new user record HWND hwndList = GetDlgItem(hwndParent, IDC_USER_LIST); CUserInfo* pUserInfo = GetSelectedUserInfo(hwndList); if (pUserInfo != NULL) { pUserInfo->GetExtraUserInfo(); PROPSHEETPAGE psp = {0}; // Common propsheetpage settings psp.dwSize = sizeof (psp); psp.hInstance = g_hInstance; psp.dwFlags = PSP_DEFAULT; // If we have a local user, show both the username and group page, ow // just the group page // Page 1: Username entry page psp.pszTemplate = MAKEINTRESOURCE(IDD_USR_USERNAME_PROP_PAGE); CUsernamePropertyPage page1(pUserInfo); page1.SetPropSheetPageMembers(&psp); // Only actually create the prop page if we have a local user if (pUserInfo->m_userType == CUserInfo::LOCALUSER) { apsd.rgPages[apsd.nPages++] = CreatePropertySheetPage(&psp); } // Always add the second page // Page 2: Local group addition psp.pszTemplate = MAKEINTRESOURCE(IDD_USR_CHOOSEGROUP_PROP_PAGE); CGroupPropertyPage page2(pUserInfo, m_pData->GetGroupList()); page2.SetPropSheetPageMembers(&psp); apsd.rgPages[apsd.nPages++] = CreatePropertySheetPage(&psp); HPSXA hpsxa = AddExtraUserPropPages(&apsd, pUserInfo->m_psid); PROPSHEETHEADER psh = {0}; psh.dwSize = sizeof (psh); psh.dwFlags = PSH_DEFAULT | PSH_PROPTITLE; TCHAR szDomainUser[MAX_USER + MAX_DOMAIN + 2]; MakeDomainUserString(pUserInfo->m_szDomain, pUserInfo->m_szUsername, szDomainUser, ARRAYSIZE(szDomainUser)); psh.pszCaption = szDomainUser; psh.hwndParent = hwndParent; psh.hInstance = g_hInstance; psh.nPages = apsd.nPages; psh.phpage = apsd.rgPages; int iRetCode = (int)PropertySheet(&psh); if (hpsxa != NULL) SHDestroyPropSheetExtArray(hpsxa); if (iRetCode == IDOK) { // PropSheet_Changed(GetParent(hwndParent), hwndParent); // So that we don't delete this pUserInfo when we remove // this user from the list: m_pData->UserInfoChanged(pUserInfo->m_szUsername, (pUserInfo->m_szDomain[0] == 0) ? NULL : pUserInfo->m_szDomain); RemoveSelectedUserFromList(hwndList, FALSE); AddUserToListView(hwndList, pUserInfo, TRUE); } } else { TraceMsg("Couldn't Get selected CUserInfo"); } TraceLeaveResult(hr); } CUserInfo* CUserlistPropertyPage::GetSelectedUserInfo(HWND hwndList) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::GetSelectedUserInfo"); CUserInfo* pUserInfo = NULL; int iItem = ListView_GetNextItem(hwndList, -1, LVNI_SELECTED); if (iItem >= 0) { LVITEM lvi = {0}; lvi.mask = LVIF_PARAM; lvi.iItem = iItem; if (ListView_GetItem(hwndList, &lvi)) { pUserInfo = (CUserInfo*) lvi.lParam; } } TraceLeaveValue(pUserInfo); } void CUserlistPropertyPage::RemoveSelectedUserFromList(HWND hwndList, BOOL fFreeUserInfo) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::RemoveSelectedUserFromList"); int iItem = ListView_GetNextItem(hwndList, -1, LVNI_SELECTED); // If we don't want to delete this user info, better set it to NULL if (!fFreeUserInfo) { LVITEM lvi = {0}; lvi.iItem = iItem; lvi.mask = LVIF_PARAM; lvi.lParam = (LPARAM) (CUserInfo*) NULL; ListView_SetItem(hwndList, &lvi); } ListView_DeleteItem(hwndList, iItem); int iSelect = iItem > 0 ? iItem - 1 : 0; ListView_SetItemState(hwndList, iSelect, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); SetFocus(hwndList); TraceLeaveVoid(); } void CUserlistPropertyPage::OnRemove(HWND hwnd) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::OnRemove"); HWND hwndList = GetDlgItem(hwnd, IDC_USER_LIST); CUserInfo* pUserInfo = GetSelectedUserInfo(hwndList); if (pUserInfo != NULL) { if (ConfirmRemove(hwnd, pUserInfo) == IDYES) { if (SUCCEEDED(pUserInfo->Remove())) { RemoveSelectedUserFromList(hwndList, TRUE); } else { // Error removing user TCHAR szDisplayName[MAX_USER + MAX_DOMAIN + 2]; ::MakeDomainUserString(pUserInfo->m_szDomain, pUserInfo->m_szUsername, szDisplayName, ARRAYSIZE(szDisplayName)); DisplayFormatMessage(hwnd, IDS_USR_APPLET_CAPTION, IDS_USR_REMOVE_MISC_ERROR, MB_ICONERROR | MB_OK, szDisplayName); } } } else { // Unexpected! There should always be a selection TraceMsg("GetSelectedUserInfo failed"); } TraceLeaveVoid(); } int CUserlistPropertyPage::ConfirmRemove(HWND hwnd, CUserInfo* pUserInfo) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::ConfirmRemove"); TCHAR szDomainUser[MAX_USER + MAX_DOMAIN + 2]; MakeDomainUserString(pUserInfo->m_szDomain, pUserInfo->m_szUsername, szDomainUser, ARRAYSIZE(szDomainUser)); int iReturn = DisplayFormatMessage(hwnd, IDS_USR_APPLET_CAPTION, IDS_USR_REMOVEUSER_WARNING, MB_ICONEXCLAMATION | MB_YESNO, szDomainUser); TraceLeaveValue(iReturn); } void CUserlistPropertyPage::SetPageState(HWND hwnd) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::SetPageState"); BOOL fAutologon = (BST_UNCHECKED == SendMessage(GetDlgItem(hwnd, IDC_AUTOLOGON_CHECK), BM_GETCHECK, 0, 0)); EnableControls(hwnd, rgidDisableOnAutologon, ARRAYSIZE(rgidDisableOnAutologon), !fAutologon); HWND hwndList = GetDlgItem(hwnd, IDC_USER_LIST); CUserInfo* pUserInfo = GetSelectedUserInfo(hwndList); if (pUserInfo != NULL) { // EnableControls(hwnd, rgidDisableOnNoSelection, ARRAYSIZE(rgidDisableOnNoSelection), // TRUE); TCHAR szPWGroup[128]; FormatMessageString(IDS_USR_PWGROUP_FORMAT, szPWGroup, ARRAYSIZE(szPWGroup), pUserInfo->m_szUsername); SetWindowText(GetDlgItem(hwnd, IDC_PWGROUP_STATIC), szPWGroup); TCHAR szPWMessage[128]; // If the logged on user is the selected user CUserInfo* pLoggedOnUser = m_pData->GetLoggedOnUserInfo(); if ((StrCmpI(pUserInfo->m_szUsername, pLoggedOnUser->m_szUsername) == 0) && (StrCmpI(pUserInfo->m_szDomain, pLoggedOnUser->m_szDomain) == 0)) { LoadString(g_hInstance, IDS_USR_YOURPWMESSAGE_FORMAT, szPWMessage, ARRAYSIZE(szPWMessage)); EnableWindow(GetDlgItem(hwnd, IDC_PASSWORD_BUTTON), FALSE); } // If the user is a local user else if (pUserInfo->m_userType == CUserInfo::LOCALUSER) { // We can set this user's password FormatMessageString(IDS_USR_PWMESSAGE_FORMAT, szPWMessage, ARRAYSIZE(szPWMessage), pUserInfo->m_szUsername); } else { // Nothing can be done with this user's password // the selected user may be a domain user or a group or something // We can set this user's password FormatMessageString(IDS_USR_CANTCHANGEPW_FORMAT, szPWMessage, ARRAYSIZE(szPWMessage), pUserInfo->m_szUsername); EnableWindow(GetDlgItem(hwnd, IDC_PASSWORD_BUTTON), FALSE); } SetWindowText(GetDlgItem(hwnd, IDC_PASSWORD_STATIC), szPWMessage); // Set the icon for the user HICON hIcon = ImageList_GetIcon(m_himlLarge, pUserInfo->m_userType, ILD_NORMAL); Static_SetIcon(GetDlgItem(hwnd, IDC_CURRENTUSER_ICON), hIcon); } else { EnableControls(hwnd, rgidDisableOnNoSelection, ARRAYSIZE(rgidDisableOnNoSelection), FALSE); } // Ensure the password button wasn't enabled in ANY CASE when autologon is // enabled /*if (fAutologon) { EnableWindow(GetDlgItem(hwnd, IDC_PASSWORD_BUTTON), FALSE); } */ TraceLeaveVoid(); } HRESULT CUserlistPropertyPage::SetAutologonState(HWND hwnd, BOOL fAutologon) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::SetAutologonState"); HRESULT hr = S_OK; PropSheet_Changed(GetParent(hwnd), hwnd); TraceLeaveResult(hr); } BOOL CUserlistPropertyPage::OnListViewItemChanged(HWND hwnd) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::OnListViewItemChanged"); SetPageState(hwnd); TraceLeaveValue(TRUE); } long CUserlistPropertyPage::OnApply(HWND hwnd) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::OnApply"); long applyEffect = PSNRET_NOERROR; // Use a big buffer to catch any error that might occur so we can report them // to the user static TCHAR szErrors[2048]; szErrors[0] = TEXT('\0'); BOOL fAutologonSet = (BST_UNCHECKED == SendMessage(GetDlgItem(hwnd, IDC_AUTOLOGON_CHECK), BM_GETCHECK, 0, 0)); if (!fAutologonSet) { // Ensure autologon is cleared ClearAutoLogon(); } else { // Autologon should be set - ask for credentials if this is a change... if (m_fAutologonCheckChanged) { CUserInfo* pSelectedUser = GetSelectedUserInfo(GetDlgItem(hwnd, IDC_USER_LIST)); TCHAR szNullName[] = TEXT(""); CAutologonUserDlg dlg((pSelectedUser != NULL) ? pSelectedUser->m_szUsername : szNullName); if (dlg.DoModal(g_hInstance, MAKEINTRESOURCE(IDD_USR_AUTOLOGON_DLG), hwnd) == IDCANCEL) { applyEffect = PSNRET_INVALID_NOCHANGEPAGE; } } } m_fAutologonCheckChanged = FALSE; if (applyEffect == PSNRET_INVALID_NOCHANGEPAGE) { // Reload the data and list m_pData->Initialize(hwnd); SetupList(hwnd); } TraceLeaveValue(applyEffect); } void CUserlistPropertyPage::SetupList(HWND hwnd) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::SetupList"); HWND hwndList = GetDlgItem(hwnd, IDC_USER_LIST); // Disable autologon check box in the domain case where autologon isn't // enabled HWND hwndCheck = GetDlgItem(hwnd, IDC_AUTOLOGON_CHECK); if (m_pData->IsComputerInDomain() && !m_pData->IsAutologonEnabled()) { ShowWindow(hwndCheck, SW_HIDE); EnableWindow(hwndCheck, FALSE); // Move most controls up a bit if the autologon is not visible RECT rcBottom; GetWindowRect(GetDlgItem(hwnd, IDC_LISTTITLE_STATIC), &rcBottom); RECT rcTop; GetWindowRect(hwndCheck, &rcTop); int dy = rcTop.top - rcBottom.top; OffsetControls(hwnd, rgidMoveOnNoAutologonCheck, ARRAYSIZE(rgidMoveOnNoAutologonCheck), 0, dy); // Grow the list by this amount also RECT rcList; GetWindowRect(hwndList, &rcList); SetWindowPos(hwndList, NULL, 0, 0, rcList.right - rcList.left, rcList.bottom - rcList.top - dy, SWP_NOZORDER|SWP_NOMOVE); } SendMessage(hwndCheck, BM_SETCHECK, m_pData->IsAutologonEnabled() ? BST_UNCHECKED : BST_CHECKED, 0); // Set the text in the set password group. SetPageState(hwnd); TraceLeaveVoid(); } HRESULT CUserlistPropertyPage::LaunchSetPasswordDialog(HWND hwndParent) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::LaunchSetPasswordDialog"); HRESULT hr = S_OK; CUserInfo* pUserInfo = GetSelectedUserInfo(GetDlgItem(hwndParent, IDC_USER_LIST)); if ((pUserInfo != NULL) && (pUserInfo->m_userType == CUserInfo::LOCALUSER)) { CChangePasswordDlg dlg(pUserInfo); dlg.DoModal(g_hInstance, MAKEINTRESOURCE(IDD_USR_SETPASSWORD_DLG), hwndParent); } else { // Unexpected: The Set Password button should be disabled if we don't have // a valid selected user TraceMsg("LaunchSetPasswordDialog called with no user or wrong user type selected!"); hr = E_FAIL; } TraceLeaveResult(hr); } #define MAX_EXTRA_USERPROP_PAGES 10 HPSXA CUserlistPropertyPage::AddExtraUserPropPages(ADDPROPSHEETDATA* ppsd, PSID psid) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::AddExtraUserPropPages"); HPSXA hpsxa = NULL; CUserSidDataObject* pDataObj = new CUserSidDataObject(); if (pDataObj != NULL) { HRESULT hr = pDataObj->SetSid(psid); if (SUCCEEDED(hr)) { hpsxa = SHCreatePropSheetExtArrayEx(HKEY_LOCAL_MACHINE, REGSTR_USERPROPERTIES_SHEET, MAX_EXTRA_USERPROP_PAGES, pDataObj); if (hpsxa != NULL) { UINT nPagesAdded = SHAddFromPropSheetExtArray(hpsxa, AddPropSheetPageCallback, (LPARAM) ppsd); } } pDataObj->Release(); } TraceLeaveValue(hpsxa); } // ListCompare // Compares list items in for sorting the listview by column // lParamSort gets the 1-based column index. If lParamSort is negative // it indicates that the given column should be sorted in reverse. int CUserlistPropertyPage::ListCompare(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { TraceEnter(TRACE_USR_CORE, "CUserlistPropertyPage::ListCompare"); CUserInfo* pUserInfo1 = (CUserInfo*) lParam1; CUserInfo* pUserInfo2 = (CUserInfo*) lParam2; LPTSTR psz1; LPTSTR psz2; int iColumn = (int) lParamSort; BOOL fReverse; if (iColumn < 0) { fReverse = TRUE; iColumn = -iColumn; } else { fReverse = FALSE; } switch (iColumn) { case 1: // user name column psz1 = pUserInfo1->m_szUsername; psz2 = pUserInfo2->m_szUsername; break; case 2: // domain column psz1 = pUserInfo1->m_szDomain; psz2 = pUserInfo2->m_szDomain; break; case 3: psz1 = pUserInfo1->m_szGroups; psz2 = pUserInfo2->m_szGroups; break; } int iResult = lstrcmp(psz1, psz2); if (fReverse) iResult = -iResult; TraceLeaveValue(iResult); }
30.674709
157
0.613545
King0987654
1588e031341e4144b6340032e689b3f0fcaffa72
2,157
cpp
C++
src/Serialization/Serialize.cpp
mishazharov/caffeine
a1a8ad5bd2d69b5378d71d15ddec4658ea34f057
[ "MIT" ]
17
2021-03-04T01:10:22.000Z
2022-03-30T18:33:14.000Z
src/Serialization/Serialize.cpp
mishazharov/caffeine
a1a8ad5bd2d69b5378d71d15ddec4658ea34f057
[ "MIT" ]
320
2020-11-16T02:42:50.000Z
2022-03-31T16:43:26.000Z
src/Serialization/Serialize.cpp
mishazharov/caffeine
a1a8ad5bd2d69b5378d71d15ddec4658ea34f057
[ "MIT" ]
6
2020-11-10T02:37:10.000Z
2021-12-25T06:58:44.000Z
#include "caffeine/Serialization/Serialize.h" #include <algorithm> #include <capnp/message.h> #include <capnp/serialize-packed.h> #include "caffeine/Protos/testcase.capnp.h" namespace caffeine { namespace serialize { using caffeine::serialize::protos::Symbol; using caffeine::serialize::protos::TestCase; using caffeine::serialize::protos::Value; using capnp::word; using kj::byte; std::string serialize_test_case( const std::unordered_map<std::string, std::string>& symbols) { ::capnp::MallocMessageBuilder message; TestCase::Builder testcase = message.initRoot<TestCase>(); ::capnp::List<Symbol>::Builder testcases = testcase.initSymbols(symbols.size()); unsigned int index = 0; for (const auto& [name, value] : symbols) { Symbol::Builder v = testcases[index]; v.setName(name.c_str()); auto symbol = v.initSymbol(); const byte* b = reinterpret_cast<const unsigned char*>(value.c_str()); symbol.setArray(capnp::Data::Reader(b, value.size())); ++index; } kj::VectorOutputStream stream; ::capnp::writePackedMessage(stream, message); kj::ArrayPtr<byte> bytes = stream.getArray(); std::string result(bytes.begin(), bytes.end()); return result; } std::unordered_map<std::string, std::string> deserialize_test_case(std::string_view& data) { const byte* ptr = reinterpret_cast<const byte*>(data.data()); kj::ArrayPtr<const byte> bufferPtr = kj::arrayPtr(ptr, sizeof(data.size())); kj::ArrayInputStream stream(bufferPtr); kj::BufferedInputStreamWrapper input(stream); ::capnp::PackedMessageReader message(input); TestCase::Reader testcase = message.getRoot<TestCase>(); std::unordered_map<std::string, std::string> result; for (Symbol::Reader symbol : testcase.getSymbols()) { std::string name = std::string(symbol.getName().cStr()); std::string value; Value::Reader val = symbol.getSymbol(); auto array = val.getArray(); value = std::string(array.begin(), array.end()); result[name] = value; } return result; } } // namespace serialize } // namespace caffeine
31.720588
80
0.67733
mishazharov
1589d94aafbd7694e8f8467ebe02f044119aa2bc
14,630
cxx
C++
fregl/exe/assign_signals.cxx
tostathaina/farsight
7e9d6d15688735f34f7ca272e4e715acd11473ff
[ "Apache-2.0" ]
8
2016-07-22T11:24:19.000Z
2021-04-10T04:22:31.000Z
fregl/exe/assign_signals.cxx
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
null
null
null
fregl/exe/assign_signals.cxx
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
7
2016-07-21T07:39:17.000Z
2020-01-29T02:03:27.000Z
/*========================================================================= Copyright 2009 Rensselaer Polytechnic Institute 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. =========================================================================*/ //: Executable program to assign the average signal to the nuclei // // The usage: // // assign_signals .xml iba_image Nissl_image // // Where: // .xml The .xml file containing the segmentation result // Image The image (including path) containing the signals. // Start Starting distance (<=0) is the interior distance away // from the boundary. // End Ending distance (>=0) is the exterior distance away from // the boundary. (If start > end, the entire segmented // area is considered) // output Output file name #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageRegion.h" #include "itkImageRegionConstIterator.h" #include "itkImageRegionIterator.h" #include "itkGrayscaleDilateImageFilter.h" #include "itkGrayscaleErodeImageFilter.h" #include "itkBinaryBallStructuringElement.h" #include "itkSubtractImageFilter.h" #include <string> #include <fstream> #include <vnl/vnl_math.h> #include <vnl/vnl_vector_fixed.h> #include <maciej_seg/maciejSegmentation.h> #include <maciej_seg/xml_util.h> #include <maciej_seg/rich_cell.h> #include <vul/vul_file.h> typedef itk::Image< unsigned char, 3 > ImageType; typedef itk::Image< unsigned short, 3 > LabelImageType; typedef itk::ImageFileReader< ImageType > ReaderType; typedef itk::ImageRegion< 3 > RegionType; typedef itk::ImageRegionConstIterator< LabelImageType > LabelConstRegionIteratorType; typedef itk::ImageRegionConstIterator< ImageType > ConstRegionIteratorType; typedef itk::ImageRegionIterator< ImageType > RegionIteratorType; typedef itk::BinaryBallStructuringElement< unsigned char, 3 > StructuringElementType; typedef itk::GrayscaleDilateImageFilter< ImageType, ImageType, StructuringElementType > DilateFilterType; typedef itk::GrayscaleErodeImageFilter< ImageType, ImageType, StructuringElementType > ErodeFilterType; typedef itk::SubtractImageFilter< ImageType,ImageType, ImageType > SubFilterType; int main( int argc, char* argv[] ) { if (argc<6) { std::cerr << "Usage: " << argv[0] << " .xml signal_image start end output_name "<<std::endl; } /* if (argc<4) { std::cerr << "Usage: " << argv[0] << " .xml info_list output_name "<<std::endl; std::cerr <<"Info_list contains the following information in each line:"<<std::endl; std::cerr <<"\t- Image: The image (including path) containing the signals."<<std::endl; std::cerr <<"\t- Starting distance (<=0) is the interior distance away from the boundary."<<std::endl; std::cerr <<"\t- Ending distance (>=0) is the exterior distance away from the boundary"<<std::endl; return EXIT_FAILURE; } */ /* // count the number of signal channels std::string line_str; int count = 0; std::ifstream in_file_str( argv[2]); if ( !in_file_str ){ std::cerr<<"Couldn't open "<<argv[2]<<std::endl; exit( 0 ); } while ( in_file_str ) { std::getline(in_file_str, line_str); if (line_str.length() == 0) continue; count++; } in_file_str.close(); */ // read the segmentation maciejSegmentation maciejseg; std::string image_path, image_name; std::string output_name = argv[5] ; xml_util_read( "./", argv[1], image_path ,image_name ,maciejseg ); std::vector<rich_cell::Pointer> const & cells = maciejseg.all_cells(); int r_interior, r_exterior; std::stringstream( argv[3] ) >> r_interior; std::stringstream( argv[4] ) >> r_exterior; /* out_file<<cells.size()<<"\t"<< count <<std::endl; for (int i = 0; i<count; i++) out_file<<"\t0.0"; out_file<<"\n"; */ //if the output file already exist, record the contents of a vector //of strings, and write the string back with the new signal computed std::vector< std::string > old_stuff; std::string line_str; int cell_count, signal_count = 0; if ( vul_file::exists(output_name.c_str()) ) { std::ifstream in_file_str(output_name.c_str()); old_stuff.reserve(cells.size()); std::getline(in_file_str, line_str); std::istringstream line_stream(line_str); line_stream>>cell_count>>signal_count; assert( cell_count == cells.size()); std::getline(in_file_str, line_str);// to get rid of the first row which only contains 0's. while ( in_file_str ) { std::getline(in_file_str, line_str); if (line_str.length() == 0) continue; old_stuff.push_back( line_str ); } } signal_count++; vnl_vector_fixed<int,3> image_size = maciejseg.image_size(); std::ofstream out_file_str( output_name.c_str() ); out_file_str<<cells.size()<<"\t"<<signal_count<<std::endl; for (int i = 0; i<signal_count; i++) out_file_str<<"\t0"; out_file_str<<std::endl; // Read the signal images image_name = argv[2]; ImageType::Pointer image; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( image_name ); try { reader->Update(); } catch(itk::ExceptionObject& e) { vcl_cout << e << vcl_endl; } image = reader->GetOutput(); if (r_exterior < r_interior) std::cout<<"Exterior range < interior range: Signal is computed from the entire segmented region"<<std::endl; for (unsigned int i = 0; i<cells.size(); i++) { std::cout<<"Cell ID = "<<cells[i]->label_<<std::endl; float sum_interior = 0; float sum_exterior = 0; int count_interior = 0; int count_exterior = 0; if (r_exterior < r_interior) { // the entire segmented area is taken for (unsigned int b = 0; b<cells[i]->all_points_.size(); b++) { vnl_vector_fixed< float, 3 > const & pt = cells[i]->all_points_[b]; ImageType::IndexType pos; pos[0] = pt[0]; pos[1] = pt[1]; pos[2] = pt[2]; sum_interior += image->GetPixel(pos); } if (!old_stuff.empty()) out_file_str<<old_stuff[i]; out_file_str<<"\t"<<sum_interior/cells[i]->all_points_.size()<<std::endl; continue; } RegionType region = cells[i]->bounding_box_; if (r_interior < 0) { //erode the mask // Generate a mask image of the cell region. Erode the region by // r_interior RegionType::SizeType size = region.GetSize(); RegionType::IndexType start={{0,0,0}}; ImageType::Pointer cropped_mask = ImageType::New(); RegionType mask_region; mask_region.SetIndex( start ); mask_region.SetSize( size ); cropped_mask->SetRegions( mask_region ); cropped_mask->Allocate(); cropped_mask->FillBuffer(0); LabelConstRegionIteratorType it1( maciejseg.label_image(), region); RegionIteratorType it2( cropped_mask, mask_region ); for (it1.GoToBegin(), it2.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2) { if (it1.Get() == cells[i]->label_) it2.Set( 255 ); } ImageType::Pointer eroded_mask; ErodeFilterType::Pointer f_erode = ErodeFilterType::New(); SubFilterType::Pointer f_sub = SubFilterType::New(); StructuringElementType structuringElement; structuringElement.SetRadius( -r_interior ); structuringElement.CreateStructuringElement(); f_erode->SetKernel( structuringElement ); f_erode->SetInput(cropped_mask); f_sub->SetInput1( cropped_mask ); f_sub->SetInput2( f_erode->GetOutput() ); try { f_sub->Update(); } catch (itk::ExceptionObject & e) { std::cerr << "Exception in SubFilter: " << e << std::endl; exit(0); } eroded_mask = f_sub->GetOutput(); // Sum the signal in the eroded region only ConstRegionIteratorType it3( eroded_mask, mask_region ); ConstRegionIteratorType it4( image, region); for (it3.GoToBegin(), it4.GoToBegin(); !it3.IsAtEnd(); ++it1, ++it3, ++it4) { if (it3.Get() > 0) { sum_interior += it4.Get(); count_interior ++; } } } if (r_exterior > 0) { //dilate the mask // enlarge the bounding box by r on each side. RegionType::SizeType size = region.GetSize(); RegionType::IndexType start = region.GetIndex(); RegionType::IndexType end; end[0] = vnl_math_min((int)(start[0]+size[0]+r_exterior), image_size[0]); end[1] = vnl_math_min((int)(start[1]+size[1]+r_exterior), image_size[1]); end[2] = vnl_math_min((int)(start[2]+size[2]+r_exterior), image_size[2]); start[0] = vnl_math_max((int)(start[0]-r_exterior), 0); start[1] = vnl_math_max((int)(start[1]-r_exterior), 0); start[2] = vnl_math_max((int)(start[2]-r_exterior), 0); size[0] = end[0] - start[0]; size[1] = end[1] - start[1]; size[2] = end[2] - start[2]; region.SetSize( size ); region.SetIndex( start ); // Generate a mask image of the region just found. Dilate the // region defined by the segmentation by r. ImageType::Pointer cropped_mask = ImageType::New(); RegionType mask_region; start[0] = start[1] = start[2] = 0; mask_region.SetIndex( start ); mask_region.SetSize( size ); cropped_mask->SetRegions( mask_region ); cropped_mask->Allocate(); cropped_mask->FillBuffer(0); LabelConstRegionIteratorType it1( maciejseg.label_image(), region); RegionIteratorType it2( cropped_mask, mask_region ); for (it1.GoToBegin(), it2.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2) { if (it1.Get() == cells[i]->label_) it2.Set( 255 ); } ImageType::Pointer dilated_mask; DilateFilterType::Pointer f_dilate = DilateFilterType::New(); SubFilterType::Pointer f_sub = SubFilterType::New(); StructuringElementType structuringElement; structuringElement.SetRadius( r_exterior ); structuringElement.CreateStructuringElement(); f_dilate->SetKernel( structuringElement ); f_dilate->SetInput(cropped_mask); f_sub->SetInput1( f_dilate->GetOutput() ); f_sub->SetInput2( cropped_mask ); try { f_sub->Update(); } catch (itk::ExceptionObject & e) { std::cerr << "Exception in SubFilter: " << e << std::endl; exit(0); } dilated_mask = f_sub->GetOutput(); // Sum the signal in the dilated region only ConstRegionIteratorType it3( dilated_mask, mask_region ); ConstRegionIteratorType it4( image, region); for (it3.GoToBegin(), it4.GoToBegin(); !it3.IsAtEnd(); ++it1, ++it3, ++it4) { if (it3.Get() > 0) { sum_exterior += it4.Get(); count_exterior ++; } } } // average the interior and exterior signals if (!old_stuff.empty()) out_file_str<<old_stuff[i]; out_file_str<<"\t"<<(sum_interior+sum_exterior)/float(count_interior+count_exterior)<<"\n"; } out_file_str.close(); return 0; } /* ///////////// old stuff /////////////// // Compute the average Iba1 of all cells, valid or not. for (unsigned int b = 0; b<cells[i]->all_points_.size(); b++) { vnl_vector_fixed< float, 3 > const & pt = cells[i]->all_points_[b]; ImageType::IndexType pos; pos[0] = pt[0]; pos[1] = pt[1]; pos[2] = pt[2]; sum += Iba_image->GetPixel(pos); } out_file<<sum/cells[i]->all_points_.size()<<"\t"; // enlarge the bounding box by r on each side. int r = 5; RegionType region = cells[i]->bounding_box_; RegionType::SizeType size = region.GetSize(); RegionType::IndexType start = region.GetIndex(); RegionType::IndexType end; end[0] = vnl_math_min((int)(start[0]+size[0]+r), image_size[0]); end[1] = vnl_math_min((int)(start[1]+size[1]+r), image_size[1]); end[2] = vnl_math_min((int)(start[2]+size[2]+r), image_size[2]); start[0] = vnl_math_max((int)(start[0]-r), 0); start[1] = vnl_math_max((int)(start[1]-r), 0); start[2] = vnl_math_max((int)(start[2]-r), 0); size[0] = end[0] - start[0]; size[1] = end[1] - start[1]; size[2] = end[2] - start[2]; region.SetSize( size ); region.SetIndex( start ); // Generate a mask image of the region just found. Dilate the // region defined by the segmentation by r. ImageType::Pointer cropped_mask = ImageType::New(); RegionType mask_region; start[0] = start[1] = start[2] = 0; mask_region.SetIndex( start ); mask_region.SetSize( size ); cropped_mask->SetRegions( mask_region ); cropped_mask->Allocate(); cropped_mask->FillBuffer(0); LabelConstRegionIteratorType it1( maciejseg.label_image(), region); RegionIteratorType it2( cropped_mask, mask_region ); for (it1.GoToBegin(), it2.GoToBegin(); !it1.IsAtEnd(); ++it1, ++it2) { if (it1.Get() == cells[i]->label_) it2.Set( 255 ); } ImageType::Pointer dilated_mask; DilateFilterType::Pointer f_dilate = DilateFilterType::New(); SubFilterType::Pointer f_sub = SubFilterType::New(); StructuringElementType structuringElement; structuringElement.SetRadius( r ); structuringElement.CreateStructuringElement(); f_dilate->SetKernel( structuringElement ); f_dilate->SetInput(cropped_mask); f_sub->SetInput1( f_dilate->GetOutput() ); f_sub->SetInput2( cropped_mask ); try { f_sub->Update(); } catch (itk::ExceptionObject & e) { std::cerr << "Exception in SubFilter: " << e << std::endl; exit(0); } dilated_mask = f_sub->GetOutput(); // Sum the signal in the dilated region only ConstRegionIteratorType it3( dilated_mask, mask_region ); ConstRegionIteratorType it4( Nissl_image, region); sum = 0; for (it3.GoToBegin(), it4.GoToBegin(); !it3.IsAtEnd(); ++it1, ++it3, ++it4) { if (it3.Get() > 0) { sum += it4.Get(); count ++; } } out_file<<sum/count<<"\n"; } return 0; } */
36.758794
114
0.633766
tostathaina
158acf182a8f6192a76ac708da7f2064ff8e228b
922
cpp
C++
emulator/ibusdevice.cpp
vcato/qt-quick-6502-emulator
6202e546efddc612f229da078238f829dd756e12
[ "Unlicense" ]
null
null
null
emulator/ibusdevice.cpp
vcato/qt-quick-6502-emulator
6202e546efddc612f229da078238f829dd756e12
[ "Unlicense" ]
3
2019-09-14T02:46:26.000Z
2020-12-22T01:07:08.000Z
emulator/ibusdevice.cpp
vcato/qt-quick-6502-emulator
6202e546efddc612f229da078238f829dd756e12
[ "Unlicense" ]
null
null
null
#include "ibusdevice.hpp" IBusDevice::IBusDevice(uint16_t lower_address, uint16_t upper_address, bool writable, bool readable, QObject *parent) : QObject(parent), _lower_address_range(lower_address), _upper_address_range(upper_address), _writable(writable), _readable(readable) { } IBusDevice::~IBusDevice() { } bool IBusDevice::handlesAddress(uint16_t address) const { return (address >= _lower_address_range) && (address <= _upper_address_range); } void IBusDevice::write(uint16_t address, uint8_t data) { if (handlesAddress(address) && writable()) writeImplementation(address, data); } uint8_t IBusDevice::read(uint16_t address, bool read_only) { if (handlesAddress(address) && readable()) return readImplementation(address, read_only); return 0x00; }
23.641026
82
0.646421
vcato
158dd3ebbd21d128f0576e0bba60e5c1aaeb911f
857
cpp
C++
src/libs/tools/sc_basicmutex.cpp
suggitpe/RPMS
7a12da0128f79b8b0339fd7146105ba955079b8c
[ "Apache-2.0" ]
null
null
null
src/libs/tools/sc_basicmutex.cpp
suggitpe/RPMS
7a12da0128f79b8b0339fd7146105ba955079b8c
[ "Apache-2.0" ]
null
null
null
src/libs/tools/sc_basicmutex.cpp
suggitpe/RPMS
7a12da0128f79b8b0339fd7146105ba955079b8c
[ "Apache-2.0" ]
null
null
null
//############################# #include "sc_basicmutex.hpp" #include "sx_mutex.hpp" using rpms::SC_BasicMutex; /////////////////////////////////////////// SC_BasicMutex::SC_BasicMutex( const std::string &aName ) : mName(aName) { ::pthread_mutex_init( &mLock, 0 ); } /////////////////////////////////////////// SC_BasicMutex::~SC_BasicMutex() { ::pthread_mutex_destroy( &mLock ); } /////////////////////////////////////////// void SC_BasicMutex::lock() { if( 0 != ::pthread_mutex_lock( &mLock )) { throw SX_Mutex("Failed to lock basic mutex [" + mName + "]"); } } /////////////////////////////////////////// void SC_BasicMutex::unlock() { if( 0 != ::pthread_mutex_unlock( &mLock ) ) { throw SX_Mutex("Failed to unlock basic mutex [" + mName + "]"); } } ///////////////////////////////////////////
20.902439
71
0.436406
suggitpe
15928d6460b238c4011c7c993b51c198d715db61
6,102
cpp
C++
test/src/direct_search_handler_test.cpp
Tobi2001/asr_direct_search_manager
d24847477a37e29a1224f7261a27f91d2a2faebf
[ "BSD-3-Clause" ]
null
null
null
test/src/direct_search_handler_test.cpp
Tobi2001/asr_direct_search_manager
d24847477a37e29a1224f7261a27f91d2a2faebf
[ "BSD-3-Clause" ]
null
null
null
test/src/direct_search_handler_test.cpp
Tobi2001/asr_direct_search_manager
d24847477a37e29a1224f7261a27f91d2a2faebf
[ "BSD-3-Clause" ]
2
2017-04-06T13:36:46.000Z
2019-12-19T18:54:01.000Z
/** Copyright (c) 2016, Borella Jocelyn, Karrenbauer Oliver, Meißner Pascal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <algorithm> #include "gtest/gtest.h" #include "ros/ros.h" #include "direct_search_handler.hpp" #include "asr_msgs/AsrTypeAndId.h" using namespace directSearchWS; TEST(DirectSearchHandlerTest, FilterSearchedObjectTypes) { SearchedObjectTypes SOTToFilter; SearchedObjectTypes filterSOT; filterSOT.push_back("PlateDeep"); filterSOT.push_back("Marker0"); filterSOT.push_back("Marker1"); filterSOT.push_back("Marker1"); filterSearchedObjectTypes(SOTToFilter, filterSOT); ASSERT_EQ(0, SOTToFilter.size()); SOTToFilter.push_back("PlateDeep"); SOTToFilter.push_back("Marker1"); SOTToFilter.push_back("PlateDeep"); filterSearchedObjectTypes(SOTToFilter, filterSOT); ASSERT_EQ(0, SOTToFilter.size()); SOTToFilter.push_back("Marker1"); SOTToFilter.push_back("PlateDeep"); SOTToFilter.push_back("Marker10"); SOTToFilter.push_back("Marker1"); SOTToFilter.push_back("Marker1"); SOTToFilter.push_back("PlateDeep"); filterSearchedObjectTypes(SOTToFilter, filterSOT); ASSERT_EQ(1, SOTToFilter.size()); ASSERT_EQ("Marker10", SOTToFilter[0]); } TEST(DirectSearchHandlerTest, filterSearchedObjectTypesAndIds) { SearchedObjectTypesAndIds SOTToFilter; SearchedObjectTypes filterSOT; filterSOT.push_back("PlateDeep"); filterSOT.push_back("Marker0"); filterSOT.push_back("Marker1"); filterSOT.push_back("Marker1"); filterSearchedObjectTypesAndIds(SOTToFilter, filterSOT); ASSERT_EQ(0, SOTToFilter.size()); asr_msgs::AsrTypeAndId typeAndId1; typeAndId1.type = "PlateDeep"; typeAndId1.identifier = "2"; SOTToFilter.push_back(typeAndId1); asr_msgs::AsrTypeAndId typeAndId2; typeAndId2.type = "Marker1"; typeAndId2.identifier = "3"; SOTToFilter.push_back(typeAndId2); asr_msgs::AsrTypeAndId typeAndId3; typeAndId3.type = "PlateDeep"; typeAndId3.identifier = "2"; SOTToFilter.push_back(typeAndId3); filterSearchedObjectTypesAndIds(SOTToFilter, filterSOT); ASSERT_EQ(0, SOTToFilter.size()); asr_msgs::AsrTypeAndId typeAndId4; typeAndId4.type = "Marker1"; typeAndId4.identifier = "3"; SOTToFilter.push_back(typeAndId4); asr_msgs::AsrTypeAndId typeAndId5; typeAndId5.type = "PlateDeep"; typeAndId5.identifier = "4"; SOTToFilter.push_back(typeAndId5); asr_msgs::AsrTypeAndId typeAndId6; typeAndId6.type = "Marker10"; typeAndId6.identifier = "4"; SOTToFilter.push_back(typeAndId6); asr_msgs::AsrTypeAndId typeAndId7; typeAndId7.type = "Marker1"; typeAndId7.identifier = "2"; SOTToFilter.push_back(typeAndId7); asr_msgs::AsrTypeAndId typeAndId8; typeAndId8.type = "Marker1"; typeAndId8.identifier = "3"; SOTToFilter.push_back(typeAndId8); asr_msgs::AsrTypeAndId typeAndId9; typeAndId9.type = "PlateDeep"; typeAndId9.identifier = "3"; SOTToFilter.push_back(typeAndId9); filterSearchedObjectTypesAndIds(SOTToFilter, filterSOT); ASSERT_EQ(1, SOTToFilter.size()); ASSERT_EQ("Marker10", SOTToFilter[0].type); ASSERT_EQ("4", SOTToFilter[0].identifier); } TEST(DirectSearchHandlerTest, GetIntersectionOfSearchObjectTypes) { SearchedObjectTypes SOT1; SearchedObjectTypes SOT2; SearchedObjectTypes intersectionSOT; intersectionSOT = getIntersectionOfSearchObjectTypes(SOT1, SOT2); ASSERT_EQ(0, intersectionSOT.size()); SOT1.push_back("PlateDeep"); SOT1.push_back("Marker0"); SOT1.push_back("Marker10"); SOT2.push_back("Marker2"); SOT2.push_back("Marker3"); SOT2.push_back("Marker4"); intersectionSOT = getIntersectionOfSearchObjectTypes(SOT1, SOT2); ASSERT_EQ(0, intersectionSOT.size()); SOT2.push_back("Marker0"); SOT2.push_back("Marker3"); SOT2.push_back("Marker0"); intersectionSOT = getIntersectionOfSearchObjectTypes(SOT1, SOT2); ASSERT_EQ(1, intersectionSOT.size()); ASSERT_EQ("Marker0", intersectionSOT[0]); SOT1.push_back("Marker0"); intersectionSOT = getIntersectionOfSearchObjectTypes(SOT1, SOT2); ASSERT_EQ(2, intersectionSOT.size()); ASSERT_EQ("Marker0", intersectionSOT[0]); ASSERT_EQ("Marker0", intersectionSOT[1]); SOT1.push_back("Marker3"); intersectionSOT = getIntersectionOfSearchObjectTypes(SOT1, SOT2); ASSERT_EQ(3, intersectionSOT.size()); ASSERT_NE(intersectionSOT.end(), std::find(intersectionSOT.begin(), intersectionSOT.end(), "Marker0")); ASSERT_NE(intersectionSOT.end(), std::find(intersectionSOT.begin(), intersectionSOT.end(), "Marker3")); }
37.900621
755
0.749754
Tobi2001
159ac049b5289bda5c24ce31fca4993168eedc71
760
cpp
C++
src/luogu/P3374/27261005_ua_70_36ms_784k_O2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
src/luogu/P3374/27261005_ua_70_36ms_784k_O2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
src/luogu/P3374/27261005_ua_70_36ms_784k_O2.cpp
lnkkerst/oj-codes
d778489182d644370b2a690aa92c3df6542cc306
[ "MIT" ]
null
null
null
#include <cstdio> using namespace std; const int MAXN = 1e5 + 5; int q,a[MAXN], n; #define foreach(i, a, b) for(int i = (a);i <= (b);++i) int lowbit(int x) { return x & (-x); } void add(int x, int val) { for (; x <= n; x += lowbit(x)) { a[x] += val; } } int query(int x) { int ret = 0; for (; x; x -= lowbit(x)) { ret += a[x]; } return ret; } int query(int l, int r) { return query(r) - query(l - 1); } int main() { scanf("%d%d", &n,&q); foreach(i, 1, n) { int x; scanf("%d", &x); add(i, x); } int opt; int a, b; while (q--) { scanf("%d", &opt); if (opt == 1) { scanf("%d%d", &a, &b); add(a, b); } else { scanf("%d%d", &a, &b); printf("%d\n", query(a, b)); } } return 0; }
19
59
0.45
lnkkerst
159be018d59e57473754590ad73ca61354607c8f
188
cpp
C++
281A_22.cpp
tihorygit/codeforces
0b60531dd3faa3e4fccf95847457ef823f803d1b
[ "Unlicense" ]
null
null
null
281A_22.cpp
tihorygit/codeforces
0b60531dd3faa3e4fccf95847457ef823f803d1b
[ "Unlicense" ]
null
null
null
281A_22.cpp
tihorygit/codeforces
0b60531dd3faa3e4fccf95847457ef823f803d1b
[ "Unlicense" ]
null
null
null
#include <iostream> using namespace std; int main() { string s; cin >> s; if(s[0]>='a' && s[0]<='z') s[0]=(char)(s[0]-'a'+'A'); cout << s << endl; return 0; }
14.461538
34
0.446809
tihorygit
159cc110d8281cdbb00f79d34d0b09b95ba3c8e0
7,080
hpp
C++
general_decimal_arithmetic/libgdatest/test_file.hpp
GaryHughes/stddecimal
ebec00e6cdad29a978ee5b0d4998e8b484d8dce1
[ "MIT" ]
5
2020-08-08T07:01:00.000Z
2022-03-05T02:45:05.000Z
general_decimal_arithmetic/libgdatest/test_file.hpp
GaryHughes/stddecimal
ebec00e6cdad29a978ee5b0d4998e8b484d8dce1
[ "MIT" ]
6
2020-06-28T02:22:07.000Z
2021-04-01T20:14:29.000Z
general_decimal_arithmetic/libgdatest/test_file.hpp
GaryHughes/stddecimal
ebec00e6cdad29a978ee5b0d4998e8b484d8dce1
[ "MIT" ]
1
2021-02-05T08:59:49.000Z
2021-02-05T08:59:49.000Z
#ifndef stddecimal_general_decimal_arithmetic_test_runner_test_file_hpp #define stddecimal_general_decimal_arithmetic_test_runner_test_file_hpp #include <string> #include <vector> #include <fstream> #include "test_context.hpp" #include "test_line.hpp" #include "test_results.hpp" #include "tests.hpp" #include <iostream> #include <boost/algorithm/string/trim_all.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string.hpp> #include <boost/regex.hpp> #include <decimal_numeric_limits.hpp> namespace gda { template<int Bits> class test_file { public: test_file(const std::string& filename, test_results& results) : m_is(filename), m_results(results) { if (!m_is) { throw std::runtime_error("Unable to open test file '" + filename + "'"); } } void process() { test_context context; while (m_is) { std::string text; if (!std::getline(m_is, text)) { break; } try { test_line line(text); if (line.is_blank()) { continue; } if (line.is_comment()) { continue; } if (line.is_directive()) { context.apply_directive(line.keyword(), line.value()); continue; } if (line.is_test()) { if (context.clamp()) { m_results.record(result::skip); continue; } test test; test.id = line.id(); test.operation = line.operation(); test.operands = line.operands(); test.expected_result = line.expected_result(); test.expected_conditions = line.expected_conditions(); using traits = operation_traits<Bits>; using limits = std::decimal::numeric_limits<typename traits::decimal_type>; // if (context.precision() > limits::digits) { // std::cerr << "skipping due to precision " << *context.precision() << " v " << limits::digits << "\n"; // m_results.record(result::skip); // continue; // } try { context.apply_rounding(); // std::decimal::clear_exceptions(std::decimal::FE_DEC_ALL_EXCEPT); std::decimal::set_exceptions(std::decimal::FE_DEC_DIVBYZERO | std::decimal::FE_DEC_INEXACT | std::decimal::FE_DEC_INVALID | std::decimal::FE_DEC_OVERFLOW | std::decimal::FE_DEC_UNDERFLOW); m_results.record(process_test(test)); } catch (std::decimal::exception& ex) { if (ex.flags() != test.expected_conditions) { report_failure(test, ex.flags()); m_results.record(result::fail); } else { m_results.record(result::pass); } } catch (std::exception& ex) { std::cerr << "GENERIC EXCEPTION " << test.id << " " << ex.what() << std::endl; m_results.record(result::skip); } continue; } std::cerr << "failed to process line: " << text << '\n'; } catch (std::exception& ex) { std::cerr << "failed to parse line: " + text << '\n'; } } } private: result process_test(const test& test) { using traits = operation_traits<Bits>; if (test.operation == "add") { return add_test<typename traits::decimal_type>::run(test); } if (test.operation == "subtract") { return subtract_test<typename traits::decimal_type>::run(test); } if (test.operation == "divide") { return divide_test<typename traits::decimal_type>::run(test); } if (test.operation == "multiply") { return multiply_test<typename traits::decimal_type>::run(test); } if (test.operation == "squareroot") { return square_root_test<typename traits::decimal_type>::run(test); } if (test.operation == "abs") { return abs_test<typename traits::decimal_type>::run(test); } if (test.operation == "plus") { return plus_test<typename traits::decimal_type>::run(test); } if (test.operation == "minus") { return minus_test<typename traits::decimal_type>::run(test); } if (test.operation == "power") { return power_test<typename traits::decimal_type>::run(test); } if (test.operation == "quantize") { return quantize_test<typename traits::decimal_type>::run(test); } if (test.operation == "log10") { return log10_test<typename traits::decimal_type>::run(test); } if (test.operation == "fma") { return fma_test<typename traits::decimal_type>::run(test); } if (test.operation == "min") { return min_test<typename traits::decimal_type>::run(test); } if (test.operation == "max") { return max_test<typename traits::decimal_type>::run(test); } if (test.operation == "remainder") { return remainder_test<typename traits::decimal_type>::run(test); } if (test.operation == "exp") { return exp_test<typename traits::decimal_type>::run(test); } if (test.operation == "ln") { return log_test<typename traits::decimal_type>::run(test); } if (test.operation == "samequantum") { return samequantum_test<typename traits::decimal_type>::run(test); } if (test.operation == "compare") { return compare_test<typename traits::decimal_type>::run(test); } // comparetotal0.decTest // randoms0.decTest // rescale0.decTest // inexact0.decTest // reduce0.decTest // testall0.decTest // base0.decTest // divideint0.decTest // tointegral0.decTest // remaindernear0.decTest // trim0.decTest std::cerr << "skipping: " << test.id << '\n'; return result::skip; } std::ifstream m_is; test_results& m_results; }; } // namespace gda #endif
30.649351
129
0.491667
GaryHughes
159e64a6a9f23aa921f7ae181010b6a6f2b64219
2,025
hpp
C++
src/ngraph/frontend/onnx_import/core/model.hpp
srinivasputta/ngraph
7506133fff4a8e5c25914a8370a567c4da5b53be
[ "Apache-2.0" ]
null
null
null
src/ngraph/frontend/onnx_import/core/model.hpp
srinivasputta/ngraph
7506133fff4a8e5c25914a8370a567c4da5b53be
[ "Apache-2.0" ]
null
null
null
src/ngraph/frontend/onnx_import/core/model.hpp
srinivasputta/ngraph
7506133fff4a8e5c25914a8370a567c4da5b53be
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2018 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 <onnx.pb.h> #include <ostream> namespace ngraph { namespace onnx_import { class Model { public: Model() = delete; explicit Model(const onnx::ModelProto& model_proto) : m_model_proto{&model_proto} { } Model(Model&&) noexcept = default; Model(const Model&) = default; Model& operator=(Model&&) noexcept = delete; Model& operator=(const Model&) = delete; const std::string& get_producer_name() const { return m_model_proto->producer_name(); } const onnx::GraphProto& get_graph() const { return m_model_proto->graph(); } std::int64_t get_model_version() const { return m_model_proto->model_version(); } const std::string& get_producer_version() const { return m_model_proto->producer_version(); } private: const onnx::ModelProto* m_model_proto; }; inline std::ostream& operator<<(std::ostream& outs, const Model& model) { return (outs << "<Model: " << model.get_producer_name() << ">"); } } // namespace onnx_import } // namespace ngraph
33.196721
99
0.568395
srinivasputta
159ed5d5ed3ac8c68bab6c58b1d03f2c9976479e
2,711
cpp
C++
src/main/cpp/disenum/ProtocolFamily.cpp
Updownquark/DISEnumerations
6b90dd4fb4323d3daf5e1d282078d9c0ffe0545c
[ "BSD-2-Clause" ]
1
2022-03-04T16:17:47.000Z
2022-03-04T16:17:47.000Z
src/main/cpp/disenum/ProtocolFamily.cpp
Updownquark/DISEnumerations
6b90dd4fb4323d3daf5e1d282078d9c0ffe0545c
[ "BSD-2-Clause" ]
1
2020-03-11T04:12:32.000Z
2020-03-11T23:55:58.000Z
src/main/cpp/disenum/ProtocolFamily.cpp
Updownquark/DISEnumerations
6b90dd4fb4323d3daf5e1d282078d9c0ffe0545c
[ "BSD-2-Clause" ]
2
2020-03-09T15:25:08.000Z
2020-04-12T13:41:47.000Z
#include <sstream> #include <cstddef> #include <disenum/ProtocolFamily.h> namespace DIS { hashMap<int,ProtocolFamily*> ProtocolFamily::enumerations; ProtocolFamily ProtocolFamily::OTHER(0, "Other"); ProtocolFamily ProtocolFamily::ENTITY_INFORMATION_INTERACTION(1, "Entity Information/Interaction"); ProtocolFamily ProtocolFamily::WARFARE(2, "Warfare"); ProtocolFamily ProtocolFamily::LOGISTICS(3, "Logistics"); ProtocolFamily ProtocolFamily::RADIO_COMMUNICATION(4, "Radio Communication"); ProtocolFamily ProtocolFamily::SIMULATION_MANAGEMENT(5, "Simulation Management"); ProtocolFamily ProtocolFamily::DISTRIBUTED_EMISSION_REGENERATION(6, "Distributed Emission Regeneration"); ProtocolFamily ProtocolFamily::ENTITY_MANAGEMENT(7, "Entity Management"); ProtocolFamily ProtocolFamily::MINEFIELD(8, "Minefield"); ProtocolFamily ProtocolFamily::SYNTHETIC_ENVIRONMENT(9, "Synthetic Environment"); ProtocolFamily ProtocolFamily::SIMULATION_MANAGEMENT_WITH_RELIABILITY(10, "Simulation Management with Reliability"); ProtocolFamily ProtocolFamily::LIVE_ENTITY(11, "Live Entity"); ProtocolFamily ProtocolFamily::NON_REAL_TIME(12, "Non-Real Time"); ProtocolFamily ProtocolFamily::EXPERIMENTAL_COMPUTER_GENERATED_FORCES(129, "Experimental - Computer Generated Forces"); ProtocolFamily::ProtocolFamily(int value, std::string description) : Enumeration(value, description) { enumerations[value] = this; }; ProtocolFamily* ProtocolFamily::findEnumeration(int aVal) { ProtocolFamily* pEnum; enumContainer::iterator enumIter = enumerations.find(aVal); if (enumIter == enumerations.end()) pEnum = NULL; else pEnum = (*enumIter).second; return pEnum; }; std::string ProtocolFamily::getDescriptionForValue(int aVal) { ProtocolFamily* pEnum = findEnumeration(aVal); if (pEnum) return pEnum->description; else { std::stringstream ss; ss << "Invalid enumeration: " << aVal; return (ss.str()); } }; ProtocolFamily ProtocolFamily::getEnumerationForValue(int aVal) throw(EnumException) { ProtocolFamily* pEnum = findEnumeration(aVal); if (pEnum) return (*pEnum); else { std::stringstream ss; ss << "No enumeration found for value " << aVal << " of enumeration ProtocolFamily"; throw EnumException("ProtocolFamily", aVal, ss.str()); } }; bool ProtocolFamily::enumerationForValueExists(int aVal) { ProtocolFamily* pEnum = findEnumeration(aVal); if (pEnum) return (true); else return (false); }; ProtocolFamily::enumContainer ProtocolFamily::getEnumerations() { return (enumerations); }; ProtocolFamily& ProtocolFamily::operator=(const int& aVal) throw(EnumException) { (*this) = getEnumerationForValue(aVal); return (*this); }; } /* namespace DIS */
33.8875
119
0.76872
Updownquark
159ee5cbf8ba53e95889d129e7d791cb43500182
1,514
cpp
C++
examples/miscellaneous/zelikovsky_11_per_6_example.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
examples/miscellaneous/zelikovsky_11_per_6_example.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
null
null
null
examples/miscellaneous/zelikovsky_11_per_6_example.cpp
Kommeren/AA
e537b58d50e93d4a72709821b9ea413008970c6b
[ "BSL-1.0" ]
1
2021-02-24T06:23:56.000Z
2021-02-24T06:23:56.000Z
//======================================================================= // Copyright (c) // // 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) //======================================================================= /** * @file zelikovsky_11_per_6_example.cpp * @brief This is example for zelikovsky 11/6 approximation for steiner tree * problem. * @author Piotr Wygocki * @version 1.0 * @date 2013-02-04 */ //! [Steiner Tree Example] #include "paal/steiner_tree/zelikovsky_11_per_6.hpp" #include "test/test_utils/sample_graph.hpp" #include <iostream> int main() { // sample metric typedef sample_graphs_metrics SGM; auto gm = SGM::get_graph_metric_steiner(); typedef decltype(gm) Metric; // sample voronoi typedef paal::data_structures::voronoi<Metric> voronoiT; typedef paal::data_structures::voronoi_traits<voronoiT> VT; typedef VT::GeneratorsSet GSet; typedef VT::VerticesSet VSet; voronoiT voronoi(GSet{ SGM::A, SGM::B, SGM::C, SGM::D }, VSet{ SGM::E }, gm); // run algorithm std::vector<int> steiner_points; paal::steiner_tree_zelikovsky11per6approximation( gm, voronoi, std::back_inserter(steiner_points)); // print result std::cout << "Steiner points:" << std::endl; boost::copy(steiner_points, std::ostream_iterator<int>(std::cout, "\n")); return 0; } //! [Steiner Tree Example]
31.541667
77
0.616248
Kommeren
15a5da197e95f764348ae56df3a252f0e1221618
3,446
cpp
C++
TSDF/TSDFVolumeCPU.cpp
justanhduc/ray-casting
25ea97f3ff10d2b0cb3c9e935f1adb9201e42908
[ "MIT" ]
1
2021-09-08T22:38:06.000Z
2021-09-08T22:38:06.000Z
TSDF/TSDFVolumeCPU.cpp
justanhduc/ray-casting
25ea97f3ff10d2b0cb3c9e935f1adb9201e42908
[ "MIT" ]
1
2021-04-12T02:19:00.000Z
2021-04-26T02:46:41.000Z
TSDF/TSDFVolumeCPU.cpp
justanhduc/ray-casting
25ea97f3ff10d2b0cb3c9e935f1adb9201e42908
[ "MIT" ]
null
null
null
// // Created by justanhduc on 10/24/20. // #include "TSDFVolumeCPU.hpp" //#include "TSDF_utilities.hpp" /** * Constructor with specified number of voxels in each dimension * @param size * @param physical_size */ TSDFVolumeCPU::TSDFVolumeCPU( const UInt3& size, const Float3& physical_size ) : m_offset { 0.0, 0.0, 0.0 }, m_distances {NULL}, m_weights {NULL}, m_deformation_nodes{NULL}, m_colours{NULL} { if ( ( size.x > 0 ) && ( size.y > 0 ) && ( size.z > 0 ) && ( physical_size.x > 0 ) && ( physical_size.y > 0 ) && ( physical_size.z > 0 ) ) { set_size( size.x, size.y, size.z , physical_size.x, physical_size.y, physical_size.z ); } else { throw std::invalid_argument( "Attempt to construct TSDFVolume with zero or negative size" ); } } /** * Make a TSDFVolume with the given dimensins and physical dimensions * @param volume_x X dimension in voxels * @param volume_y Y dimension in voxels * @param volume_z Z dimension in voxels * @param psize_x Physical size in X dimension in mm * @param psize_y Physical size in Y dimension in mm * @param psize_z Physical size in Z dimension in mm */ TSDFVolumeCPU::TSDFVolumeCPU( uint16_t volume_x, uint16_t volume_y, uint16_t volume_z, float psize_x, float psize_y, float psize_z ) : m_offset { 0.0, 0.0, 0.0 }, m_distances {NULL}, m_weights {NULL}, m_deformation_nodes{NULL}, m_colours{NULL} { if ( ( volume_x > 0 ) && ( volume_y > 0 ) && ( volume_z > 0 ) && ( psize_x > 0 ) && ( psize_y > 0 ) && ( psize_z > 0 ) ) { set_size( volume_x, volume_y, volume_z , psize_x, psize_y, psize_z ); } else { throw std::invalid_argument( "Attempt to construct CPUTSDFVolume with zero or negative size" ); } } /** * Set the distance data for the TSDF in one call * @param distance_data Pointer to enough floats to populate the TSFD */ void TSDFVolumeCPU::set_distance_data(float * distance_data) { m_distances = distance_data; } void TSDFVolumeCPU::set_size( uint16_t volume_x, uint16_t volume_y, uint16_t volume_z, float psize_x, float psize_y, float psize_z) { if ( ( volume_x != 0 && volume_y != 0 && volume_z != 0 ) && ( psize_x != 0 && psize_y != 0 && psize_z != 0 ) ) { m_size = dim3cpu { volume_x, volume_y, volume_z }; m_physical_size = float3cpu { psize_x, psize_y, psize_z }; // Compute truncation distance - must be at least 2x max voxel size m_voxel_size = f3_div_elem( m_physical_size, m_size ); // Set t > diagonal of voxel m_truncation_distance = 1.1f * f3_norm( m_voxel_size ); // Allocate device storage size_t data_size = volume_x * volume_y * volume_z; m_distances = new float [data_size]; m_weights = new float [data_size]; m_colours = new uchar3cpu [data_size]; // m_deformation_nodes = new DeformationNode[data_size]; m_global_rotation = float3cpu{0.0f, 0.0f, 0.0f}; m_global_translation = float3cpu{0.0f, 0.0f, 0.0f}; // Max weight for integrating depth images m_max_weight = 15.0f; } else { throw std::invalid_argument( "Attempt to set TSDF size or physical size to zero" ); } } void TSDFVolumeCPU::set_truncation_distance(float d) { m_truncation_distance = d; } TSDFVolumeCPU::~TSDFVolumeCPU() { std::cout << "Destroying TSDFVolume" << std::endl; delete [] m_distances; delete [] m_colours; delete [] m_weights; }
38.288889
246
0.660476
justanhduc
15a74f451822d2b1bdc3817204c5eae613421d84
18,956
cc
C++
CMC040/cmcfun/outp_line.cc
khandy21yo/aplus
3b4024a2a8315f5dcc78479a24100efa3c4a6504
[ "MIT" ]
1
2018-10-17T08:53:17.000Z
2018-10-17T08:53:17.000Z
CMC040/cmcfun/outp_line.cc
khandy21yo/aplus
3b4024a2a8315f5dcc78479a24100efa3c4a6504
[ "MIT" ]
null
null
null
CMC040/cmcfun/outp_line.cc
khandy21yo/aplus
3b4024a2a8315f5dcc78479a24100efa3c4a6504
[ "MIT" ]
null
null
null
//! \file //! \brief Handle Paging on Reports // %SBTTL "OUTP_LINE" // %IDENT "V3.6a Calico" // // Source: ../../CMC030/cmcfun/source/outp_line.bas // Translated from Basic to C++ using btran // on Wednesday, December 20, 2017 at 17:16:51 // #include <iostream> #include <cstdlib> #include <cstring> #include <unistd.h> #include "basicfun.h" #include "smg/smg.h" #include "preferences.h" #include "cmcfun.h" #include "database.h" #include "scopedef.h" #include "cmcfun/report.h" #include "utl/utl_reportx.h" #include "utl/utl_profile.h" #include "scroll.h" extern scope_struct scope; //! //! \brief Handle Paging on Reports //! //! This subroutine handles paging for the report //! programs existing in all systems. //! //! Example: //! //! CALL OUTP_INITFROMFILE(UTL_REPORTX, 80%) //! //! TITLE$(1%) = "This is the report" //! TITLE$(2%) = "For the current period" //! TITLE$(3%) = "" //! TITLE$(4%) = "Key Description Date Time Flag" //! TITLE$(5%) = "" //! //! LAYOUT$ = "$KEY:005,$DESCR:026,DDATE:035,TTIME:041,VFLAG:043" //! //! LINE$ = KEY$ + " " + //! DESCRIPTION$ + " " + //! PRNT_DATE(DATE$, 0%) + " " + //! PRNT_TIME(TIME$, 2048%) + " " + //! FORMAT$(FLAG%, "#") //! //! CALL OUTP_LINE(LAYOUT$, UTL_REPORTX, TITLES$(), LINE$, 0%) //! //! \author 03/23/87 - Kevin Handy //! void outp_line( const std::string &columns, //!< Passed specification for not only where the //! columns are, but also labels for //! these columns. This string is used for shipping //! the report to Graphics, a Spreadsheet, or a //! Database. Each column of data should have a //! section in this string, in this form: //! //! ... [DataType][Label]:[EndingPos], ... //! //! [DataType] is a single character describing //! the type of data passed in that column: //! ($ = String, D = Date, P = Phone number, //! T = Time, and V = Number value). //! [Label] is a label for the data passed in that //! column. //! [EndingPos] is the horizontal position along //! the line where this column ends. utl_reportx_cdd &utl_reportx, //!< This passed structure contains the definitions of //! various items for the report being printed. These //! items are modified according to actions taken; line //! number, page number incremented, etc. const std::vector<std::string> &hdr, //!< Headers to be printed on the top of every page. const std::string &txt, //!< Passed text to print. long lineoff) //!< Variable used to control paging. A positive value //! causes paging to occur that many lines earlier, //! and a negitive value causes it to occur that many //! lines later. A special case of LINEOFF >= 1000 //! exists that forces a new page, but the line is not //! counted/printed. { long colonpos; std::string column; long commapos; std::string data; long endpos; long i; std::string junk; long junk_V2; long junk1; std::string junk3; std::string old_help_item; std::string old_help_severity; std::string old_program; long print_flag1; long print_flag2; long q_flag; long smg_status; long startpos; std::string temp; long temp_V4; std::string text; std::string this_col; std::string tolocal; std::string toscreen; long v; BStack(20); const long max_smg_text = 200; utl_profile_cdd utl_profile; smg_scroll_cdd smg_scroll; std::vector<std::string> smg_text; smg_text.resize(max_smg_text + 1); long rrr_flag; std::string title1; extern long outp_xunsol; // // ++ // // Helper function for the offset business // auto fnoffset = [&](std::string source, long offset) { std::string Result; // ** Converted from a select statement ** if (offset > 0) { Result = std::string(offset, ' ') + source; } else if (offset < 0) { Result = basic::right(source, -offset + 1); } else { Result = source; } return Result; }; // // Save the key for help // old_help_severity = scope.prg_ident; old_program = scope.prg_program; old_help_item = scope.prg_item; scope.prg_program = "OUTP_LINE"; scope.prg_item = "HELP"; scope.prg_ident = "H"; junk3 = ""; // // Exit due to report request // if (utl_reportx.stat != 0) { goto exitsub; } if (boost::trim_right_copy(hdr[1]) != "") { title1 = boost::trim_right_copy(hdr[1]); } // // Special LINEOFF (-12345) for OUTP_FINISH when in display mode. // This is used so that when you hit the end of the report, you // can still arrow back up and down to your hearts content. // Q_FLAG% is used to change the flag used by DSPL_SCROLLCIR. // if ((lineoff == -12345) && (utl_reportx.printto == OUTP_TODISPLAY)) { q_flag = 2; BGosub(L_2000); goto exitsub; } q_flag = 6; // // Output goes to printer if to printer port // if ((utl_reportx.printto == OUTP_TOLOCAL) && (utl_reportx.pageno >= utl_reportx.startp)) { writ_string(utl_reportx.tolocal, tolocal); utl_reportx.chan << tolocal; } // // Force the title if this is the first time through, // or it is time to do a page. // if (((utl_reportx.pageno == 0) && (utl_reportx.printto < 10)) || ((utl_reportx.lineno + lineoff) >= (utl_reportx.pagelen - 7) && (utl_reportx.printto != OUTP_TODISPLAY) && (utl_reportx.printto < 10)) || ((utl_reportx.lineno) >= (utl_reportx.pagelen) && (utl_reportx.printto == OUTP_TODISPLAY))) { BGosub(L_2000); } // // Count the line // if (lineoff < 1000 && utl_reportx.autoscroll == 0) { utl_reportx.lineno = utl_reportx.lineno + 1; } // // Will we be printing? (Check for start and end page, as // well as report request to exit) // if (!((utl_reportx.pageno >= utl_reportx.startp) && ((utl_reportx.pageno <= utl_reportx.endp) || (utl_reportx.endp == 0)))) { goto L_1500; } if (utl_reportx.stat != 0) { goto L_1500; } // // If the lineoff<1000 then line will print otherwise line // will not print // if (lineoff < 1000) { // // Handle the various types of output // // ** Converted from a select statement ** // // Display // if (utl_reportx.printto == OUTP_TODISPLAY) { smg_scroll.end_element = smg_scroll.end_element + 1; if (smg_scroll.end_element > smg_scroll.bot_array) { smg_scroll.end_element = smg_scroll.top_array; } if (smg_scroll.beg_element == smg_scroll.end_element) { smg_scroll.beg_element = smg_scroll.end_element + 1; } if (smg_scroll.beg_element > smg_scroll.bot_array) { smg_scroll.beg_element = smg_scroll.top_array; } smg_text[smg_scroll.end_element] = fnoffset(txt, utl_reportx.offset); smg_scroll.find_line = smg_scroll.end_element; junk_V2 = dspl_scrollcir(smg_scroll, smg_text, SMG$K_TRM_FIND, ""); // // SuperComp 20/20, PlanPerfect // } else if ((utl_reportx.printto == OUTP_TO2020) || (utl_reportx.printto == OUTP_TOPL)) { if (columns == "") { column = "$Line:255,"; } else { column = columns + ","; } startpos = 0; print_flag2 = 0; temp = ""; while (column != "") { commapos = (column.find(",", 0) + 1); this_col = column.substr(0, commapos - 1); column = basic::right(column, commapos + 1); colonpos = (this_col.find(":", 0) + 1); endpos = std::stol(basic::right(this_col, colonpos + 1)); data = boost::trim_right_copy(basic::Qseg(txt, startpos, endpos)); if (basic::edit(this_col.substr(0, 1), -1) == "V") { // // Clean up data a little // data = boost::trim_copy(data); if (basic::right(data, data.size()) == ")" && data.substr(0, 1) == "(") { data = std::string("-") + basic::Qseg(data, 2, data.size() - 1); } if (basic::right(data, data.size()) == "-") { data = std::string("-") + data.substr(0, data.size() - 1); } i = (data.find(",", 0) + 1); while (i) { data = data.substr(0, i - 1) + basic::right(data, i + 1); i = (data.find(",", 0) + 1); } i = (data.find("$", 0) + 1); if (i) { data = data.substr(0, i - 1) + basic::right(data, i + 1); } } if (utl_reportx.printto == OUTP_TOPL) { temp = temp + "\t" + data; if (data != "") { print_flag2 = -1; } } else { // ** Converted from a select statement ** if (basic::edit(this_col.substr(0, 1), -1) == "V") { temp = temp + data + " #"; if (data.find_first_of("123456789") + 1) { print_flag2 = -1; } } else { temp = temp + "\"" + data + "\" #"; if (data != "") { print_flag2 = -1; } } } startpos = endpos + 1; } // ** Converted from a select statement ** if (utl_reportx.printto == OUTP_TO2020) { temp = temp + "#"; } else if (utl_reportx.printto == OUTP_TOPL) { temp = basic::right(temp, 2); } if (print_flag2) { utl_reportx.chan << temp << std::endl; } if (utl_reportx.lineno == 1) { entr_3message(scope, title1, 1 + 16); } // // Normal output // } else { utl_reportx.chan << fnoffset(txt, utl_reportx.offset) << std::endl; } } // L_1500:; // Output goes to the screen if in printer port mode // if (utl_reportx.printto == OUTP_TOLOCAL) { writ_string(utl_reportx.toscreen, toscreen); utl_reportx.chan << toscreen; } if (junk3 != "") { // // Test to force a buffer flush // entr_3message(scope, junk3 + " of " + title1, 1 + 16); smg_status = smg$flush_buffer(scope.smg_pbid); } // // Flag to end program if we reach the end page number // if ((utl_reportx.pageno > utl_reportx.endp) && (utl_reportx.endp != 0)) { utl_reportx.stat = -50; } // // Handle any special junk in RRR_FLAG% // // ** Converted from a select statement ** // // Nothing // if (rrr_flag == 0) { // Nothing // // Autoscroll Toggle Key Typed // } else if (rrr_flag == 1) { if (utl_reportx.autoscroll == 0) { utl_reportx.autoscroll = -1; } else { utl_reportx.autoscroll = 0; } // // Exit keys // } else if ((rrr_flag == 3) || ((rrr_flag == SMG$K_TRM_F10) || ((rrr_flag == SMG$K_TRM_CTRLZ) || (rrr_flag == SMG$K_TRM_F8)))) { utl_reportx.stat = rrr_flag; // // Else // } else { smg_status = entr_4specialkeys(scope, scope.smg_option, 256, rrr_flag); } rrr_flag = 0; exitsub:; // // Restore the key for help // scope.prg_ident = old_help_severity; scope.prg_program = old_program; scope.prg_item = old_help_item; return; //******************************************************************* L_2000:; // This subroutine does the actual paging //******************************************************************* // // Count one page // utl_reportx.pageno = utl_reportx.pageno + 1; // // Are we skipping this page? Check first for page range, but // force first title when printing to a clipboard, wp document, // or file cabinet. // print_flag1 = ((utl_reportx.pageno >= utl_reportx.startp) && ((utl_reportx.pageno <= utl_reportx.endp) || (utl_reportx.endp == 0))); // // On first page, enable unsolicited input trapping // if (utl_reportx.pageno == 1) { rrr_flag = 0; } // // While in display, title goes on line two and three // // ** Converted from a select statement ** if (utl_reportx.printto == OUTP_TODISPLAY) { // // Pause // scope.scope_exit = 0; if ((utl_reportx.pageno != 1) && (utl_reportx.autoscroll == 0)) { pauseloop:; entr_3message(scope, title1, 0); // ** Converted from a select statement ** // // Autoscroll Toggle Key Typed // if (scope.scope_exit == 1) { utl_reportx.autoscroll = -1; // // An exit key was typed // } else if ((scope.scope_exit == 3) || ((scope.scope_exit == SMG$K_TRM_CTRLZ) || ((scope.scope_exit == SMG$K_TRM_F10) || (scope.scope_exit == SMG$K_TRM_F8)))) { utl_reportx.stat = scope.scope_exit; goto ret2000; // // Cursor positioning (up) key was typed // } else if ((scope.scope_exit == SMG$K_TRM_UP) || ((scope.scope_exit == SMG$K_TRM_F18) || (scope.scope_exit == SMG$K_TRM_PREV_SCREEN))) { smg_scroll.smg_flag = 2; temp_V4 = dspl_scrollcir(smg_scroll, smg_text, scope.scope_exit, ""); goto pauseloop; // // Cursor positioning key (down) was typed // } else if ((scope.scope_exit == SMG$K_TRM_DOWN) || ((scope.scope_exit == SMG$K_TRM_F19) || (scope.scope_exit == SMG$K_TRM_NEXT_SCREEN))) { smg_scroll.smg_flag = q_flag; temp_V4 = dspl_scrollcir(smg_scroll, smg_text, scope.scope_exit, ""); if (temp_V4 <= 0) { goto pauseloop; } utl_reportx.lineno = utl_reportx.lineno - temp_V4; // // Return, etc. act as next screen // } else if ((scope.scope_exit == 10) || ((scope.scope_exit == 12) || ((scope.scope_exit == 13) || ((scope.scope_exit == SMG$K_TRM_F7) || (scope.scope_exit == SMG$K_TRM_DO))))) { smg_scroll.smg_flag = q_flag; temp_V4 = dspl_scrollcir(smg_scroll, smg_text, SMG$K_TRM_NEXT_SCREEN, ""); if (temp_V4 <= 0) { goto pauseloop; } utl_reportx.lineno = utl_reportx.lineno - temp_V4; // // Case else // } else { entr_3badkey(scope, scope.scope_exit); goto pauseloop; } } // // Search for header // for (junk_V2 = 1; !(hdr[junk_V2] == ""); junk_V2++) { v = 0; } for (junk1 = junk_V2 + 1; !(hdr[junk1] == ""); junk1++) { v = 0; } // // Clear the screen and print the title if necessary // if ((utl_reportx.pageno == 1) || (lineoff > 1000)) { // // Display the header // for (i = junk_V2 + 1; i <= junk1 - 1; i++) { junk = hdr[i]; if (junk == ".") { junk = ""; } junk = fnoffset(junk, utl_reportx.offset); smg_status = smg$put_chars(utl_reportx.window, junk + std::string(utl_reportx.repwidth - junk.size(), ' '), (i - junk_V2), 1, 1, SMG$M_REVERSE); } // // Set up scrolling region // // smg_status = smg$set_display_scroll_region(utl_reportx.window, junk1 - junk_V2, 20); // // Create SMG_SCROLL array // smg_scroll.window = &utl_reportx.window; smg_scroll.scroll_top = junk1 - junk_V2; smg_scroll.scroll_bot = 20; smg_scroll.top_array = 1; smg_scroll.bot_array = max_smg_text; smg_scroll.cur_line = smg_scroll.cur_w_col = 1; smg_scroll.find_line = smg_scroll.top_line = smg_scroll.cur_w_row = smg_scroll.beg_element = 1; smg_scroll.end_element = 1; smg_text[1] = ""; smg_scroll.smg_flag = 6; smg_scroll.prompt = ""; smg_scroll.num_colm = 1; // // Calculate number of lines available on the screen // utl_reportx.lineno = junk1 - junk_V2; } } else { // // Skip to the top of the next page // if (utl_reportx.pageno == 1) { utl_reportx.sdate = basic::Qdate(0); utl_reportx.stime = basic::Qtime(0); } // // Print the page title // junk3 = std::string("Page ") + std::to_string(utl_reportx.pageno); // // Switch to screen mode // // SMG_STATUS% = SMG$FLUSH_BUFFER(SCOPE::SMG_PBID) // IF UTL_REPORTX::PRINTTO = OUTP_TOLOCAL // THEN // CALL WRIT_STRING(UTL_REPORTX::TOSCREEN, TOSCREEN$) // PRINT #UTL_REPORTX::CHAN, TOSCREEN$; // END IF // // CALL ENTR_3MESSAGE(SCOPE, JUNK3$ + " of " + TITLE1, 1% + 16%) utl_reportx.stat = scope.macroflag; // // SMG_STATUS% = SMG$FLUSH_BUFFER(SCOPE::SMG_PBID) // IF UTL_REPORTX::PRINTTO = OUTP_TOLOCAL // THEN // CALL WRIT_STRING(UTL_REPORTX::TOLOCAL, TOLOCAL$) // PRINT #UTL_REPORTX::CHAN, TOLOCAL$; // END IF // // Handle title while skipping pages (Use special loop // because it looks better than 1000 if statements in // the printing section that follows). // // Also, handle types 7, and 8 (Word Processing, // File cabinet), after the first header, so that the user // can actuall use start/end page. // if ((print_flag1 == 0) || ((utl_reportx.pageno != 1) && (utl_reportx.printto == OUTP_TOWP))) { // // Print page anyway if need a title for wp. // if ((utl_reportx.pageno == 1) && (utl_reportx.printto == OUTP_TOWP)) { goto L_2050; } // // Special GOSUB 3000's in title // utl_reportx.lineno = 5; if (utl_reportx.repyn != "N") { utl_reportx.lineno = utl_reportx.lineno + 1; } // // Title // for (junk1 = 1; !(hdr[junk1] == ""); junk1++) { utl_reportx.lineno = utl_reportx.lineno + 1; } // // Header // for (junk1 = junk1 + 1; !(hdr[junk1] == ""); junk1++) { utl_reportx.lineno = utl_reportx.lineno + 1; } goto L_2100; } // L_2050:; // Output the title // if (utl_reportx.pageno != 1) { outp_formff(utl_reportx); // (Hack) utl_reportx.pageno = utl_reportx.pageno - 1; } // Minimum number of lines in header utl_reportx.lineno = 4; // Modified to adjust for excesses in // paging section, and room for blank // lines at bottom of page. utl_reportx.chan << std::endl; utl_reportx.chan << std::endl; junk_V2 = 0; junk = boost::trim_right_copy(utl_profile.rep_name); BGosub(L_3000); for (junk1 = 1; !(hdr[junk1] == ""); junk1++) { junk = boost::trim_right_copy(hdr[junk1]); BGosub(L_3000); } if (utl_reportx.repyn != "N") { junk = boost::trim_right_copy(utl_reportx.repdate); BGosub(L_3000); } utl_reportx.chan << std::endl; utl_reportx.chan << fnoffset(basic::Qstring(utl_reportx.repwidth, '='), utl_reportx.offset) << std::endl; for (junk1 = junk1 + 1; !(hdr[junk1] == ""); junk1++) { junk = boost::trim_right_copy(hdr[junk1]); if (junk == ".") { junk = ""; } utl_reportx.chan << fnoffset(junk, utl_reportx.offset) << std::endl; utl_reportx.lineno = utl_reportx.lineno + 1; } } L_2100:; BReturn; // L_3000:; // Print the heading stuff // junk_V2 = junk_V2 + 1; if (junk == ".") { junk = ""; } utl_reportx.lineno = utl_reportx.lineno + 1; switch (junk_V2) { case 1: text = std::string("Date: ") + basic::Qdate(0); text = text + std::string(utl_reportx.repwidth / 2 - text.size() - junk.size() / 2, ' ') + junk; text = text + std::string(utl_reportx.repwidth - text.size() - junk3.size(), ' ') + junk3; utl_reportx.chan << fnoffset(text, utl_reportx.offset) << std::endl; break; case 2: text = std::string("Time: ") + basic::Qtime(0); text = text + std::string(utl_reportx.repwidth / 2 - text.size() - junk.size() / 2, ' ') + junk; text = text + std::string(utl_reportx.repwidth - text.size() - strlen("V3.6"), ' ') + "V3.6"; utl_reportx.chan << fnoffset(text, utl_reportx.offset) << std::endl; break; default: text = ""; text = text + std::string(utl_reportx.repwidth / 2 - text.size() - junk.size() / 2, ' ') + junk; utl_reportx.chan << fnoffset(text, utl_reportx.offset) << std::endl; break; } ret2000:; BReturn; } // +-+-+ // ++ // Success:DISPLAY // ^*Display Report\* // .b // .lm +5 // Scrolling the report to the next screen, previous screen, // line by line or exit. // .lm -5 // // Index: // // --
24.811518
175
0.605982
khandy21yo
15aa337ded8a2ac4f339de7496763b561defc935
3,126
cpp
C++
src/VDF/Sources/instancie_src_VDF_Sources.cpp
pledac/trust-code
46ab5c5da3f674185f53423090f526a38ecdbad1
[ "BSD-3-Clause" ]
1
2021-10-04T09:20:19.000Z
2021-10-04T09:20:19.000Z
src/VDF/Sources/instancie_src_VDF_Sources.cpp
pledac/trust-code
46ab5c5da3f674185f53423090f526a38ecdbad1
[ "BSD-3-Clause" ]
null
null
null
src/VDF/Sources/instancie_src_VDF_Sources.cpp
pledac/trust-code
46ab5c5da3f674185f53423090f526a38ecdbad1
[ "BSD-3-Clause" ]
null
null
null
// // Warning : DO NOT EDIT ! // To update this file, run: make depend // #include <verifie_pere.h> #include <ModPerm_Carman_Kozeny.h> #include <ModPerm_Cte.h> #include <ModPerm_ErgunPourDarcy.h> #include <ModPerm_ErgunPourForch.h> #include <Perte_Charge_Reguliere_VDF_Face.h> #include <Perte_Charge_Singuliere_VDF_Face.h> #include <Source_Darcy_VDF_Face.h> #include <Source_Dirac_VDF_Elem.h> #include <Source_Echange_Th_VDF.h> #include <Source_Forchheimer_VDF_Face.h> #include <Source_Generique_VDF_Elem.h> #include <Source_Generique_VDF_Face.h> #include <Source_Neutronique_VDF.h> #include <Terme_Boussinesq_VDF_Face.h> #include <Terme_Gravite_VDF_Face.h> #include <Terme_Puissance_Thermique_Echange_Impose_P0_VDF.h> #include <Terme_Puissance_Thermique_VDF_Elem.h> #include <Terme_Source_Acceleration_VDF_Face.h> #include <Terme_Source_Canal_RANS_LES_VDF_Elem.h> #include <Terme_Source_Canal_RANS_LES_VDF_Face.h> #include <Terme_Source_Canal_perio_VDF_Face.h> #include <Terme_Source_Canal_perio_VDF_P0.h> #include <Terme_Source_Constituant_VDF_Elem.h> #include <Terme_Source_Coriolis_VDF_Face.h> #include <Terme_Source_Qdm_VDF_Face.h> #include <Terme_Source_Solide_SWIFT_VDF.h> #include <Terme_Source_inc_VDF_Face.h> #include <Terme_Source_inc_th_VDF_Face.h> void instancie_src_VDF_Sources() { Cerr << "src_VDF_Sources" << finl; ModPerm_Carman_Kozeny inst1;verifie_pere(inst1); ModPerm_Cte inst2;verifie_pere(inst2); ModPerm_ErgunPourDarcy inst3;verifie_pere(inst3); ModPerm_ErgunPourForch inst4;verifie_pere(inst4); Perte_Charge_Reguliere_VDF_Face inst5;verifie_pere(inst5); Perte_Charge_Singuliere_VDF_Face inst6;verifie_pere(inst6); Source_Darcy_VDF_Face inst7;verifie_pere(inst7); Source_Dirac_VDF_Elem inst8;verifie_pere(inst8); Source_Echange_Th_VDF inst9;verifie_pere(inst9); Source_Forchheimer_VDF_Face inst10;verifie_pere(inst10); Source_Generique_VDF_Elem inst11;verifie_pere(inst11); Source_Generique_VDF_Face inst12;verifie_pere(inst12); Source_Neutronique_VDF inst13;verifie_pere(inst13); Terme_Boussinesq_VDF_Face inst14;verifie_pere(inst14); Terme_Gravite_VDF_Face inst15;verifie_pere(inst15); Terme_Puissance_Thermique_Echange_Impose_P0_VDF inst16;verifie_pere(inst16); Terme_Puissance_Thermique_VDF_Elem inst17;verifie_pere(inst17); Terme_Source_Acceleration_VDF_Face inst18;verifie_pere(inst18); Terme_Source_Canal_RANS_LES_VDF_Elem inst19;verifie_pere(inst19); Terme_Source_Canal_RANS_LES_VDF_Face inst20;verifie_pere(inst20); Terme_Source_Canal_perio_VDF_Face inst21;verifie_pere(inst21); Terme_Source_Canal_perio_QC_VDF_Face inst22;verifie_pere(inst22); Terme_Source_Canal_perio_VDF_Front_Tracking inst23;verifie_pere(inst23); Terme_Source_Canal_perio_VDF_P0 inst24;verifie_pere(inst24); Terme_Source_Constituant_VDF_Elem inst25;verifie_pere(inst25); Terme_Source_Coriolis_VDF_Face inst26;verifie_pere(inst26); Terme_Source_Coriolis_QC_VDF_Face inst27;verifie_pere(inst27); Terme_Source_Qdm_VDF_Face inst28;verifie_pere(inst28); Terme_Source_Solide_SWIFT_VDF inst29;verifie_pere(inst29); Terme_Source_inc_VDF_Face inst30;verifie_pere(inst30); Terme_Source_inc_th_VDF_Face inst31;verifie_pere(inst31); }
45.970588
76
0.869162
pledac
15b5cb76cde69f2b70572fff8e2a457ef1b09306
827
cpp
C++
Leetcode/0562. Longest Line of Consecutive One in Matrix/0562.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0562. Longest Line of Consecutive One in Matrix/0562.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
Leetcode/0562. Longest Line of Consecutive One in Matrix/0562.cpp
Next-Gen-UI/Code-Dynamics
a9b9d5e3f27e870b3e030c75a1060d88292de01c
[ "MIT" ]
null
null
null
class Solution { public: int longestLine(vector<vector<int>>& mat) { const int m = mat.size(); const int n = mat[0].size(); int ans = 0; // dp[i][j][0] := horizontal // dp[i][j][1] := vertical // dp[i][j][2] := diagonal // dp[i][j][3] := anti-diagonal vector<vector<vector<int>>> dp(m, vector<vector<int>>(n, vector<int>(4))); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (mat[i][j] == 1) { dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1; dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1; dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1; dp[i][j][3] = (i > 0 && j < n - 1) ? dp[i - 1][j + 1][3] + 1 : 1; ans = max(ans, *max_element(begin(dp[i][j]), end(dp[i][j]))); } return ans; } };
31.807692
78
0.412334
Next-Gen-UI
15be4ec551d4674edb68896fef3222e9bb0188a6
13,479
cc
C++
components/services/leveldb/leveldb_database_impl.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
components/services/leveldb/leveldb_database_impl.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
components/services/leveldb/leveldb_database_impl.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/services/leveldb/leveldb_database_impl.h" #include <inttypes.h> #include <algorithm> #include <map> #include <string> #include <utility> #include "base/optional.h" #include "base/rand_util.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/trace_event/memory_dump_manager.h" #include "components/services/leveldb/env_mojo.h" #include "components/services/leveldb/public/cpp/util.h" #include "third_party/leveldatabase/env_chromium.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/leveldatabase/src/include/leveldb/write_batch.h" namespace leveldb { namespace { template <typename FunctionType> leveldb::Status ForEachWithPrefix(leveldb::DB* db, const leveldb::Slice& key_prefix, FunctionType function) { leveldb::ReadOptions read_options; // Disable filling the cache for bulk scans. Either this is for deletion // (where caching those blocks doesn't make sense) or a mass-read, which the // user "should" be caching / only needing once. read_options.fill_cache = false; std::unique_ptr<leveldb::Iterator> it(db->NewIterator(read_options)); it->Seek(key_prefix); for (; it->Valid(); it->Next()) { if (!it->key().starts_with(key_prefix)) break; function(it->key(), it->value()); } return it->status(); } } // namespace LevelDBDatabaseImpl::LevelDBDatabaseImpl( std::unique_ptr<Env> environment, std::unique_ptr<DB> db, std::unique_ptr<Cache> cache, base::Optional<base::trace_event::MemoryAllocatorDumpGuid> memory_dump_id) : environment_(std::move(environment)), cache_(std::move(cache)), db_(std::move(db)), memory_dump_id_(memory_dump_id) { base::trace_event::MemoryDumpManager::GetInstance() ->RegisterDumpProviderWithSequencedTaskRunner( this, "MojoLevelDB", base::SequencedTaskRunnerHandle::Get(), MemoryDumpProvider::Options()); } LevelDBDatabaseImpl::~LevelDBDatabaseImpl() { base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider( this); for (auto& p : iterator_map_) delete p.second; for (auto& p : snapshot_map_) db_->ReleaseSnapshot(p.second); } void LevelDBDatabaseImpl::Put(const std::vector<uint8_t>& key, const std::vector<uint8_t>& value, PutCallback callback) { Status status = db_->Put(leveldb::WriteOptions(), GetSliceFor(key), GetSliceFor(value)); std::move(callback).Run(LeveldbStatusToError(status)); } void LevelDBDatabaseImpl::Delete(const std::vector<uint8_t>& key, DeleteCallback callback) { Status status = db_->Delete(leveldb::WriteOptions(), GetSliceFor(key)); std::move(callback).Run(LeveldbStatusToError(status)); } void LevelDBDatabaseImpl::DeletePrefixed(const std::vector<uint8_t>& key_prefix, DeletePrefixedCallback callback) { WriteBatch batch; Status status = DeletePrefixedHelper(GetSliceFor(key_prefix), &batch); if (status.ok()) status = db_->Write(leveldb::WriteOptions(), &batch); std::move(callback).Run(LeveldbStatusToError(status)); } void LevelDBDatabaseImpl::Write( std::vector<mojom::BatchedOperationPtr> operations, WriteCallback callback) { WriteBatch batch; for (size_t i = 0; i < operations.size(); ++i) { switch (operations[i]->type) { case mojom::BatchOperationType::PUT_KEY: { if (operations[i]->value) { batch.Put(GetSliceFor(operations[i]->key), GetSliceFor(*(operations[i]->value))); } else { batch.Put(GetSliceFor(operations[i]->key), Slice()); } break; } case mojom::BatchOperationType::DELETE_KEY: { batch.Delete(GetSliceFor(operations[i]->key)); break; } case mojom::BatchOperationType::DELETE_PREFIXED_KEY: { DeletePrefixedHelper(GetSliceFor(operations[i]->key), &batch); break; } case mojom::BatchOperationType::COPY_PREFIXED_KEY: { if (!operations[i]->value) { mojo::ReportBadMessage( "COPY_PREFIXED_KEY operation must provide a value."); std::move(callback).Run(mojom::DatabaseError::INVALID_ARGUMENT); return; } CopyPrefixedHelper(operations[i]->key, *(operations[i]->value), &batch); break; } } } Status status = db_->Write(leveldb::WriteOptions(), &batch); std::move(callback).Run(LeveldbStatusToError(status)); } void LevelDBDatabaseImpl::Get(const std::vector<uint8_t>& key, GetCallback callback) { std::string value; Status status = db_->Get(leveldb::ReadOptions(), GetSliceFor(key), &value); std::move(callback).Run(LeveldbStatusToError(status), StdStringToUint8Vector(value)); } void LevelDBDatabaseImpl::GetPrefixed(const std::vector<uint8_t>& key_prefix, GetPrefixedCallback callback) { std::vector<mojom::KeyValuePtr> data; Status status = ForEachWithPrefix(db_.get(), GetSliceFor(key_prefix), [&data](const Slice& key, const Slice& value) { mojom::KeyValuePtr kv = mojom::KeyValue::New(); kv->key = GetVectorFor(key); kv->value = GetVectorFor(value); data.push_back(std::move(kv)); }); std::move(callback).Run(LeveldbStatusToError(status), std::move(data)); } void LevelDBDatabaseImpl::CopyPrefixed( const std::vector<uint8_t>& source_key_prefix, const std::vector<uint8_t>& destination_key_prefix, CopyPrefixedCallback callback) { WriteBatch batch; Status status = CopyPrefixedHelper(source_key_prefix, destination_key_prefix, &batch); if (status.ok()) status = db_->Write(leveldb::WriteOptions(), &batch); std::move(callback).Run(LeveldbStatusToError(status)); } void LevelDBDatabaseImpl::GetSnapshot(GetSnapshotCallback callback) { const Snapshot* s = db_->GetSnapshot(); base::UnguessableToken token = base::UnguessableToken::Create(); snapshot_map_.insert(std::make_pair(token, s)); std::move(callback).Run(token); } void LevelDBDatabaseImpl::ReleaseSnapshot( const base::UnguessableToken& snapshot) { auto it = snapshot_map_.find(snapshot); if (it != snapshot_map_.end()) { db_->ReleaseSnapshot(it->second); snapshot_map_.erase(it); } } void LevelDBDatabaseImpl::GetFromSnapshot( const base::UnguessableToken& snapshot, const std::vector<uint8_t>& key, GetCallback callback) { // If the snapshot id is invalid, send back invalid argument auto it = snapshot_map_.find(snapshot); if (it == snapshot_map_.end()) { std::move(callback).Run(mojom::DatabaseError::INVALID_ARGUMENT, std::vector<uint8_t>()); return; } std::string value; leveldb::ReadOptions options; options.snapshot = it->second; Status status = db_->Get(options, GetSliceFor(key), &value); std::move(callback).Run(LeveldbStatusToError(status), StdStringToUint8Vector(value)); } void LevelDBDatabaseImpl::NewIterator(NewIteratorCallback callback) { Iterator* iterator = db_->NewIterator(leveldb::ReadOptions()); base::UnguessableToken token = base::UnguessableToken::Create(); iterator_map_.insert(std::make_pair(token, iterator)); std::move(callback).Run(token); } void LevelDBDatabaseImpl::NewIteratorFromSnapshot( const base::UnguessableToken& snapshot, NewIteratorFromSnapshotCallback callback) { // If the snapshot id is invalid, send back invalid argument auto it = snapshot_map_.find(snapshot); if (it == snapshot_map_.end()) { std::move(callback).Run(base::Optional<base::UnguessableToken>()); return; } leveldb::ReadOptions options; options.snapshot = it->second; Iterator* iterator = db_->NewIterator(options); base::UnguessableToken new_token = base::UnguessableToken::Create(); iterator_map_.insert(std::make_pair(new_token, iterator)); std::move(callback).Run(new_token); } void LevelDBDatabaseImpl::ReleaseIterator( const base::UnguessableToken& iterator) { auto it = iterator_map_.find(iterator); if (it != iterator_map_.end()) { delete it->second; iterator_map_.erase(it); } } void LevelDBDatabaseImpl::IteratorSeekToFirst( const base::UnguessableToken& iterator, IteratorSeekToFirstCallback callback) { auto it = iterator_map_.find(iterator); if (it == iterator_map_.end()) { std::move(callback).Run(false, mojom::DatabaseError::INVALID_ARGUMENT, base::nullopt, base::nullopt); return; } it->second->SeekToFirst(); ReplyToIteratorMessage(it->second, std::move(callback)); } void LevelDBDatabaseImpl::IteratorSeekToLast( const base::UnguessableToken& iterator, IteratorSeekToLastCallback callback) { auto it = iterator_map_.find(iterator); if (it == iterator_map_.end()) { std::move(callback).Run(false, mojom::DatabaseError::INVALID_ARGUMENT, base::nullopt, base::nullopt); return; } it->second->SeekToLast(); ReplyToIteratorMessage(it->second, std::move(callback)); } void LevelDBDatabaseImpl::IteratorSeek(const base::UnguessableToken& iterator, const std::vector<uint8_t>& target, IteratorSeekToLastCallback callback) { auto it = iterator_map_.find(iterator); if (it == iterator_map_.end()) { std::move(callback).Run(false, mojom::DatabaseError::INVALID_ARGUMENT, base::nullopt, base::nullopt); return; } it->second->Seek(GetSliceFor(target)); ReplyToIteratorMessage(it->second, std::move(callback)); } void LevelDBDatabaseImpl::IteratorNext(const base::UnguessableToken& iterator, IteratorNextCallback callback) { auto it = iterator_map_.find(iterator); if (it == iterator_map_.end()) { std::move(callback).Run(false, mojom::DatabaseError::INVALID_ARGUMENT, base::nullopt, base::nullopt); return; } it->second->Next(); ReplyToIteratorMessage(it->second, std::move(callback)); } void LevelDBDatabaseImpl::IteratorPrev(const base::UnguessableToken& iterator, IteratorPrevCallback callback) { auto it = iterator_map_.find(iterator); if (it == iterator_map_.end()) { std::move(callback).Run(false, mojom::DatabaseError::INVALID_ARGUMENT, base::nullopt, base::nullopt); return; } it->second->Prev(); ReplyToIteratorMessage(it->second, std::move(callback)); } bool LevelDBDatabaseImpl::OnMemoryDump( const base::trace_event::MemoryDumpArgs& args, base::trace_event::ProcessMemoryDump* pmd) { auto* dump = leveldb_env::DBTracker::GetOrCreateAllocatorDump(pmd, db_.get()); if (!dump) return true; auto* global_dump = pmd->CreateSharedGlobalAllocatorDump(*memory_dump_id_); pmd->AddOwnershipEdge(global_dump->guid(), dump->guid()); // Add size to global dump to propagate the size of the database to the // client's dump. global_dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize, base::trace_event::MemoryAllocatorDump::kUnitsBytes, dump->GetSizeInternal()); return true; } void LevelDBDatabaseImpl::ReplyToIteratorMessage( leveldb::Iterator* it, IteratorSeekToFirstCallback callback) { if (!it->Valid()) { std::move(callback).Run(false, LeveldbStatusToError(it->status()), base::nullopt, base::nullopt); return; } std::move(callback).Run(true, LeveldbStatusToError(it->status()), GetVectorFor(it->key()), GetVectorFor(it->value())); } Status LevelDBDatabaseImpl::DeletePrefixedHelper(const Slice& key_prefix, WriteBatch* batch) { Status status = ForEachWithPrefix( db_.get(), key_prefix, [batch](const Slice& key, const Slice& value) { batch->Delete(key); }); return status; } Status LevelDBDatabaseImpl::CopyPrefixedHelper( const std::vector<uint8_t>& source_key_prefix, const std::vector<uint8_t>& destination_key_prefix, leveldb::WriteBatch* batch) { std::vector<uint8_t> new_prefix = destination_key_prefix; size_t source_key_prefix_size = source_key_prefix.size(); size_t destination_key_prefix_size = destination_key_prefix.size(); Status status = ForEachWithPrefix( db_.get(), GetSliceFor(source_key_prefix), [&batch, &new_prefix, source_key_prefix_size, destination_key_prefix_size](const Slice& key, const Slice& value) { size_t excess_key = key.size() - source_key_prefix_size; new_prefix.resize(destination_key_prefix_size + excess_key); std::copy(key.data() + source_key_prefix_size, key.data() + key.size(), new_prefix.begin() + destination_key_prefix_size); batch->Put(GetSliceFor(new_prefix), value); }); return status; } } // namespace leveldb
36.233871
80
0.668818
zipated
15bebeca817926b244b37b283193cebb83b5f002
103
hpp
C++
include/modprop/optim/optim.hpp
Humhu/modprop
0cff8240d5e1522f620de8004c22a74491a0c9fb
[ "AFL-3.0" ]
1
2017-11-10T00:54:53.000Z
2017-11-10T00:54:53.000Z
include/modprop/optim/optim.hpp
Humhu/modprop
0cff8240d5e1522f620de8004c22a74491a0c9fb
[ "AFL-3.0" ]
null
null
null
include/modprop/optim/optim.hpp
Humhu/modprop
0cff8240d5e1522f620de8004c22a74491a0c9fb
[ "AFL-3.0" ]
null
null
null
#pragma once #include "modprop/optim/GaussianLikelihoodModule.h" #include "modprop/optim/MeanModule.h"
25.75
51
0.815534
Humhu
15c08ce7c071ba50f4fa54b97c35a5e00807fa14
2,423
cpp
C++
src/umpire/util/Backtrace.cpp
bmhan12/Umpire
de82bcd066f153958aff2f68091cac2125d9c5bc
[ "MIT-0", "MIT" ]
null
null
null
src/umpire/util/Backtrace.cpp
bmhan12/Umpire
de82bcd066f153958aff2f68091cac2125d9c5bc
[ "MIT-0", "MIT" ]
null
null
null
src/umpire/util/Backtrace.cpp
bmhan12/Umpire
de82bcd066f153958aff2f68091cac2125d9c5bc
[ "MIT-0", "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2016-20, Lawrence Livermore National Security, LLC and Umpire // project contributors. See the COPYRIGHT file for details. // // SPDX-License-Identifier: (MIT) ////////////////////////////////////////////////////////////////////////////// #include <cstdio> #include <cstdlib> #if !defined(_MSC_VER) && !defined(_LIBCPP_VERSION) #include <cxxabi.h> // for __cxa_demangle #endif // !defined(_MSC_VER) && !defined(_LIBCPP_VERSION) #if !defined(_MSC_VER) #include <dlfcn.h> // for dladdr #include <execinfo.h> // for backtrace #endif // !defined(_MSC_VER) #include <iostream> #include <iomanip> #include "umpire/util/Backtrace.hpp" #include "umpire/util/Macros.hpp" namespace umpire { namespace util { Backtrace::Backtrace() noexcept { } void Backtrace::getBacktrace() { #if !defined(_MSC_VER) void *callstack[128]; const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]); for (int i = 0; i < backtrace(callstack, nMaxFrames); ++i) m_backtrace.push_back(callstack[i]); #endif // !defined(_MSC_VER) } std::ostream& operator<<(std::ostream& os, const Backtrace& bt) { #if !defined(_MSC_VER) char **symbols = backtrace_symbols(&bt.m_backtrace[0], bt.m_backtrace.size()); os << " Backtrace: " << bt.m_backtrace.size() << " frames" << std::endl; int index = 0; for ( const auto& it : bt.m_backtrace ) { os << " " << index << " " << it << " "; Dl_info info; if (dladdr(it, &info) && info.dli_sname) { char *demangled = NULL; int status = -1; #if !defined(_LIBCPP_VERSION) if (info.dli_sname[0] == '_') demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status); #endif // !defined(_MSC_VER) && !defined(_LIBCPP_VERSION) os << ( status == 0 ? demangled : ( info.dli_sname == 0 ? symbols[index] : info.dli_sname ) ) << "+0x" << std::hex << static_cast<int>(static_cast<char*>(it) - static_cast<char*>(info.dli_saddr)); #if !defined(_LIBCPP_VERSION) free(demangled); #endif // !defined(_MSC_VER) && !defined(_LIBCPP_VERSION) } else { os << "No dladdr: " << symbols[index]; } os << std::endl; ++index; } free(symbols); #else UMPIRE_USE_VAR(bt); os << " Backtrace not supported on Windows platform" << std::endl; #endif return os; } } // end of namespace util } // end of namespace umpire
28.505882
110
0.606686
bmhan12
15c15f8a739fa8adbfe09234204cf52d613b4286
2,734
cpp
C++
UVa 1432 - Fire-Control System/sample/1432 - Fire-Control System.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 1432 - Fire-Control System/sample/1432 - Fire-Control System.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 1432 - Fire-Control System/sample/1432 - Fire-Control System.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <stdio.h> #include <math.h> #include <algorithm> using namespace std; struct Pt { int x, y; int dist; double theta; bool operator<(const Pt &a) const { if(theta != a.theta) return theta < a.theta; return dist > a.dist; } }; Pt D[5005]; int mmR[5005]; const double pi = acos(-1); int main() { /*freopen("in.txt", "r+t", stdin); freopen("out1.txt", "w+t", stdout);*/ int N, K; int cases = 0; int i, j, k; while(scanf("%d %d", &N, &K) == 2) { if(N == 0 && K == 0) break; for(i = 0; i < N; i++) { scanf("%d %d", &D[i].x, &D[i].y); mmR[i] = D[i].x*D[i].x + D[i].y*D[i].y; D[i].dist = mmR[i]; D[i].theta = atan2(D[i].y, D[i].x); } if(K == 0 || N == 0) { printf("Case #%d: 0.00\n", ++cases); continue; } sort(mmR, mmR+N); // sort maybe radius sort(D, D+N); // sort by theta double ret = 1e+50; double area, theta, theta1, theta2; /*for(i = 0; i < N; i++) { printf("%lf\n", D[i].theta); }*/ int radius = -1; for(i = K-1; i < N; i++) { if(radius == mmR[i]) continue; radius = mmR[i]; // sweep line algorithm int tmpK = 0, pre = 0; int idx1 = 0, idx2 = 0, j1, j2; int N2 = N*2; for(j1 = 0, j2 = 0; j1 < N2; j1++) { if(j1 >= N && j2 >= N) break; if(D[idx1].dist <= radius) tmpK++; while(tmpK >= K && j2 < j1) { if(tmpK > K && D[idx2].dist <= radius) tmpK--, idx2++, j2++; else if(D[idx2].dist > radius) idx2++, j2++; else break; if(idx2 >= N) idx2 = 0; } if(tmpK >= K && j1-j2 < N) { theta1 = D[idx1].theta; theta2 = D[idx2].theta; if(j1 >= N) theta1 += 2*pi; if(j2 >= N) theta2 += 2*pi; else if(theta2 <= theta1) theta = theta1 - theta2; else theta = 2*pi - (theta1 - theta2); //printf("%lf %lf %lf %d %d %d %d %d\n", theta, theta1, theta2, tmpK, j1, j2, idx1, idx2); area = 0.5*radius*theta; ret = min(ret, area); } idx1++; if(idx1 >= N) idx1 = 0; } } printf("Case #%d: %.2lf\n", ++cases, ret); } return 0; }
31.790698
110
0.365399
tadvi
15c2497b52050a249901afd165f46573da689cb4
738
cpp
C++
SPOJ Solutions/BOGGLE.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
13
2021-09-02T07:30:02.000Z
2022-03-22T19:32:03.000Z
SPOJ Solutions/BOGGLE.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
null
null
null
SPOJ Solutions/BOGGLE.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
3
2021-08-24T16:06:22.000Z
2021-09-17T15:39:53.000Z
#include <stdio.h> #include <iostream> #include <string> #include <cstring> #include <map> #include <sstream> using namespace std; int main() { int n; int a[10]={0,1,1,1,1,2,3,5,11,11}; scanf("%d ",&n); string s[n+9]; int i; for(i=0;i<n;i++) getline(cin,s[i]); map<string , int >mp; map<string ,int >::iterator t; i=0; string word; for(i=0;i<n;i++){ istringstream iss(s[i]); while(iss>>word) mp[word]+=1; } int count=0,max=-1; for(i=0;i<n;i++) { count=0; istringstream iss(s[i]); while(iss>>word) { t=mp.find(word); if((*t).second==1) { if((*t).first.size()>7) count+=11; else count+=a[(*t).first.size()]; } } if(max<count) max=count; } cout<<max<<endl; return 0; }
15.375
35
0.556911
UtkarshPathrabe
15c264868451a5d330f1bb6c9f8feb459bcce78f
2,823
cpp
C++
QtPredict/PredictKeyHandleUI.cpp
Kay01010101/PredictVersion
adde9de5dd39b2f22e103f3294d1beab4f327d62
[ "MIT" ]
null
null
null
QtPredict/PredictKeyHandleUI.cpp
Kay01010101/PredictVersion
adde9de5dd39b2f22e103f3294d1beab4f327d62
[ "MIT" ]
null
null
null
QtPredict/PredictKeyHandleUI.cpp
Kay01010101/PredictVersion
adde9de5dd39b2f22e103f3294d1beab4f327d62
[ "MIT" ]
null
null
null
/* Time : 2016/06/13 Author: Kay Yang (1025115216@qq.com) */ #ifndef CONSOLE #include "PredictKeyHandleUI.h" #include "PredictGeneratorKey.h" #include "PredictMainWindow.h" #include "QDebug" #include "PredictCheck.h" TextEditorThread::TextEditorThread() : mStopped(false) { } TextEditorThread::~TextEditorThread() { mMessages.Clear(); } void TextEditorThread::Push(const QString& text) { mMutex.Lock(); mMessages.Push(text); mMutex.Unlock(); } void TextEditorThread::SetStop(bool isStop) { mStopped = isStop; } void TextEditorThread::run() { while (!mStopped) { while (mMessages.Size() > 0) { mMutex.Lock(); emit MsgSignal(mMessages.Pop()); mMutex.Unlock(); } QThread::msleep(1); } } PredictKeyHandleUI::PredictKeyHandleUI(QWidget* parent) : QWidget(parent), ui(new Ui::GeneratorUI()) { ui->setupUi(this); mTextEditor = new TextEditorThread(); mTextEditor->start(); } PredictKeyHandleUI::~PredictKeyHandleUI() { if (ui) { delete ui; } ui = 0; mTextEditor->SetStop(true); while (mTextEditor->isRunning()) { Sleep(2); } if (mTextEditor) delete mTextEditor; mTextEditor = 0; } void PredictKeyHandleUI::LoadOldKeySequence() { //PredictGeneratorKey::Instance()->Clear(); //PredictGeneratorKey::Instance()->LoadFromFile(PredictConfig::Inistance()->mConfigData.GetFullGeneratorPath().C_String()); } void PredictKeyHandleUI::onStart() { //LoadOldKeySequence(); //PredictCheck::Instance()->Start(); //PredictMainWindow* mainWind = (PredictMainWindow*)mOwner; //mainWind->StartServer(); //ui->mGeneratorKey->setEnabled(false); //ui->mStart->setEnabled(false); //ui->mDump->setEnabled(true); //ui->mStop->setEnabled(true); } void PredictKeyHandleUI::onDump() { //PredictGeneratorKey::Instance()->WriteToFile(PredictConfig::Inistance()->mConfigData.GetFullGeneratorPath().C_String()); } void PredictKeyHandleUI::onStop() { //PredictGeneratorKey::Instance()->WriteToFile(PredictConfig::Inistance()->mConfigData.GetFullGeneratorPath().C_String()); //mTextEditor->Push("Write keys file successfully!"); //PredictMainWindow* mainWind = (PredictMainWindow*)mOwner; //mainWind->StopServer(); //ui->mGeneratorKey->setEnabled(true); //ui->mStart->setEnabled(true); //ui->mDump->setEnabled(false); //ui->mStop->setEnabled(false); } void PredictKeyHandleUI::onToggle(bool state) { //PredictGeneratorKey::Instance()->ToggleGeneratorKey(state); } void PredictKeyHandleUI::PrintMessage(const QString& text) { mTextEditor->Push(text); } void PredictKeyHandleUI::SetMainWidget(PredictMainWindow* owner) { mOwner = owner; if (mOwner) { connect(mTextEditor, SIGNAL(MsgSignal(const QString&)), mOwner, SLOT(printText(const QString&))); } } void PredictKeyHandleUI::closeEvent(QCloseEvent *event) { //if (ui->mStop->isEnabled()) //{ // onStop(); //} } #endif
20.911111
124
0.72051
Kay01010101
15c3b6f4f9e959fdc0a528612a4a8c50c32b543a
383
cpp
C++
basic exp/5. matrix-II & III/unit_test.cpp
ltg001/word_game
3b4e537f1b61b9523a8120a96627442d5558debe
[ "MIT" ]
null
null
null
basic exp/5. matrix-II & III/unit_test.cpp
ltg001/word_game
3b4e537f1b61b9523a8120a96627442d5558debe
[ "MIT" ]
null
null
null
basic exp/5. matrix-II & III/unit_test.cpp
ltg001/word_game
3b4e537f1b61b9523a8120a96627442d5558debe
[ "MIT" ]
null
null
null
#include "matrix.h" #include "matrix.hpp" #include <iostream> using namespace std; int main(int argc, char *argv[]) { Matrix<int> mat1(3, 4); Matrix<int> mat2(3, 4); cin >> mat1; cin >> mat2; cout << "load" << endl; cout << mat1 << mat2 << endl; cout << mat1 + mat2 << endl; cout << mat1 - mat2 << endl; cout << mat1 * 2 << endl; return 0; }
20.157895
33
0.543081
ltg001
15c4b580075344e39dd02f308078a7d804cc75b3
918
cpp
C++
codeforces/1165d.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
1
2020-04-04T14:56:12.000Z
2020-04-04T14:56:12.000Z
codeforces/1165d.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
codeforces/1165d.cpp
sogapalag/problems
0ea7d65448e1177f8b3f81124a82d187980d659c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void solve() { int T; cin >> T; while (T--) { int n; cin >> n; vector<long long> d(n); for (auto& x: d) { cin >> x; } sort(d.begin(), d.end()); long long res = d[0] * d[n-1]; bool flag = true; for (int i = 0; i < n; i++) { if (d[i]*d[n-i-1] != res){ flag = false; break; } } if (!flag){ cout << "-1\n"; }else{ int cnt = 0; long long i = 2; for (; i*i <= res; i++){ if (res % i == 0) cnt++; } if (cnt != (n+1)/2){ cout << "-1\n"; }else{ cout << res << "\n"; } } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); cout << endl; }
20.863636
40
0.334423
sogapalag
15c68556997bff4a7ca8dc695b0e1edd9baa9e46
38,366
cpp
C++
src/ftl/x86/func.cpp
janweinstock/ftl
64b25fa821ab001384290a4a71fb1a7377d3b239
[ "Apache-2.0" ]
4
2019-05-22T18:27:14.000Z
2021-11-17T11:42:51.000Z
src/ftl/x86/func.cpp
janweinstock/ftl
64b25fa821ab001384290a4a71fb1a7377d3b239
[ "Apache-2.0" ]
null
null
null
src/ftl/x86/func.cpp
janweinstock/ftl
64b25fa821ab001384290a4a71fb1a7377d3b239
[ "Apache-2.0" ]
2
2019-11-14T08:51:52.000Z
2020-12-12T15:13:47.000Z
/****************************************************************************** * * * Copyright 2019 Jan Henrik Weinstock * * * * 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 "ftl/x86/func.h" namespace ftl { namespace x86 { void func::gen_prologue_epilogue() { for (reg r : CALLEE_SAVED_REGS) m_emitter.push(r); i32 frame_size = 64 * sizeof(u64); m_emitter.subi(64, STACK_POINTER, frame_size); m_emitter.movr(64, BASE_POINTER, argreg(1)); m_emitter.jmpr(argreg(0)); m_buffer.align(4); m_buffer.mark_exit(); m_exit.place(false); m_emitter.addi(64, STACK_POINTER, frame_size); for (size_t i = FTL_ARRAY_SIZE(CALLEE_SAVED_REGS); i != 0; i--) m_emitter.pop(CALLEE_SAVED_REGS[i-1]); m_emitter.ret(); m_buffer.align(4); m_code = m_buffer.get_code_ptr(); } func::func(const string& nm, size_t bufsz): m_name(nm), m_bufptr(new cbuf(bufsz)), m_buffer(*m_bufptr), m_emitter(m_buffer), m_broker(m_emitter), m_head(m_buffer.get_code_entry()), m_code(m_buffer.get_code_ptr()), m_last(nullptr), m_entry(nm + ".entry", m_buffer, m_broker, true, nullptr), m_exit(nm + ".exit", m_buffer, m_broker, true, nullptr) { if (m_buffer.is_empty()) gen_prologue_epilogue(); m_entry.place(m_buffer.get_code_entry(), false); m_exit.place(m_buffer.get_code_exit(), false); } func::func(const string& nm, cbuf& buffer, void* dataptr): m_name(nm), m_bufptr(nullptr), m_buffer(buffer), m_emitter(m_buffer), m_broker(m_emitter), m_head(m_buffer.get_code_entry()), m_code(m_buffer.get_code_ptr()), m_last(nullptr), m_entry(nm + ".entry", m_buffer, m_broker, true, nullptr), m_exit(nm + ".exit", m_buffer, m_broker, true, nullptr) { if (m_buffer.is_empty()) gen_prologue_epilogue(); if (dataptr != nullptr) set_data_ptr(dataptr); m_entry.place(m_buffer.get_code_entry(), false); m_exit.place(m_buffer.get_code_exit(), false); } func::func(func&& other): m_name(other.m_name), m_bufptr(other.m_bufptr), m_buffer(other.m_buffer), m_emitter(std::move(other.m_emitter)), m_broker(std::move(other.m_broker)), m_head(other.m_head), m_code(other.m_code), m_last(other.m_last), m_entry(std::move(other.m_entry)), m_exit(std::move(other.m_exit)) { other.m_bufptr = nullptr; } func::~func() { if (m_bufptr) delete m_bufptr; } i64 func::exec() { return exec((void*)m_broker.get_base_addr()); } i64 func::exec(void* data) { FTL_ERROR_ON(!is_finished(), "function '%s' not finished", name()); return invoke(m_buffer, m_code, data); } void func::set_data_ptr(void* ptr) { m_broker.set_base_addr((u64)ptr); } void func::set_data_ptr_stack() { int dummy; set_data_ptr(&dummy); } void func::set_data_ptr_heap() { int* dummy = new int; set_data_ptr(dummy); delete dummy; } void func::set_data_ptr_code() { set_data_ptr(m_buffer.get_code_ptr()); } void func::gen_ret() { m_broker.flush_all_regs(); gen_jmp(m_exit); } void func::gen_ret(i64 val) { m_broker.flush_all_regs(); m_emitter.movi(64, RETURN_VALUE, val); gen_ret(); } void func::gen_ret(value& val) { m_emitter.movsx(64, val.bits, RETURN_VALUE, val); m_broker.flush_all_regs(); gen_ret(); } void func::gen_cmp(value& src1, value& src2, int bits) { if (!abi<reg>::fits(bits)) bits = min(src1.bits, src2.bits); if (src1.is_mem() && src2.is_mem()) src1.fetch(); m_emitter.cmpr(bits, src1, src2); } void func::gen_cmp(value& src, i32 imm, int bits) { if (!abi<reg>::fits(bits)) bits = src.bits; if (imm == 0) { src.fetch(); gen_tst(src, src, bits); } else { m_emitter.cmpi(bits, src, imm); } } void func::gen_tst(value& src1, value& src2, int bits) { if (!abi<reg>::fits(bits)) bits = min(src1.bits, src2.bits); if (src1.is_mem() && src2.is_mem()) src1.fetch(); m_emitter.tstr(bits, src1, src2); } void func::gen_tst(value& src, i32 imm, int bits) { if (!abi<reg>::fits(bits)) bits = src.bits; m_emitter.tsti(bits, src, imm); } void func::gen_branch(cc cond, label& l) { const i32 FAR_OFFSET = 0xff; fixup fix; switch (cond) { case FTL_CC_NEVER: return; case FTL_CC_ALWAYS: m_broker.flush_all_regs(); m_emitter.jmpi(l.is_far() ? FAR_OFFSET : 0, &fix); break; default: m_broker.flush_all_regs(); m_emitter.branch(cond, l.is_far() ? FAR_OFFSET : 0, &fix); break; } l.add(fix); } void func::gen_branch(cc cond, value& a, value& b, label& l, int bits) { if (!abi<reg>::fits(bits)) bits = min(a.bits, b.bits); switch (cond) { case FTL_CC_NEVER: return; case FTL_CC_ALWAYS: gen_jmp(l); return; case FTL_CC_Z: case FTL_CC_NZ: gen_tst(a, b, bits); break; case FTL_CC_EQ: case FTL_CC_NE: gen_cmp(a, b, bits); break; case FTL_CC_GT: case FTL_CC_LE: case FTL_CC_LT: case FTL_CC_GE: case FTL_CC_GTU: case FTL_CC_LEU: case FTL_CC_LTU: case FTL_CC_GEU: if (b.is_reg() && !a.is_reg()) { m_emitter.cmpr(bits, b.r(), a); cond = invert(cond); FTL_ERROR("hit invert condition"); } else { m_emitter.cmpr(bits, a.fetch(), b); } break; default: FTL_ERROR("invalid condition code %d", (int)cond); } gen_branch(cond, l); } void func::gen_branch(cc cond, value& op, i32 imm, label& l, int bits) { if (!abi<reg>::fits(bits)) bits = op.bits; switch (cond) { case FTL_CC_NEVER: return; case FTL_CC_ALWAYS: gen_jmp(l); return; case FTL_CC_Z: if (imm == 0) { gen_jmp(l); return; } else { m_emitter.tsti(bits, op, imm); break; } case FTL_CC_NZ: m_emitter.tsti(bits, op, imm); break; case FTL_CC_EQ: case FTL_CC_NE: case FTL_CC_GT: case FTL_CC_LE: case FTL_CC_LT: case FTL_CC_GE: case FTL_CC_GTU: case FTL_CC_LEU: case FTL_CC_LTU: case FTL_CC_GEU: m_emitter.cmpi(bits, op, imm); break; default: FTL_ERROR("invalid condition code %d", (int)cond); } gen_branch(cond, l); } void func::gen_setcc(cc cond, value& dest, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; reg r = dest.r(); if (!reg_valid(r)) r = dest.assign(); m_emitter.setcc(cond, r); m_emitter.movzx(bits, 8, r, r); dest.mark_dirty(); } void func::gen_cmov(cc cond, value& dest, value& src, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; if (dest == src) return; // we fetch dest here so that mark_dirty() works m_emitter.movcc(bits, cond, dest.fetch(), src); dest.mark_dirty(); } void func::gen_setp(value& dest, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; if (dest.is_mem()) dest.assign(); m_emitter.setp(dest); m_emitter.movzx(bits, 8, dest, dest); dest.mark_dirty(); } void func::gen_setnp(value& dest, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; if (dest.is_mem()) dest.assign(); m_emitter.setnp(dest); m_emitter.movzx(bits, 8, dest, dest); dest.mark_dirty(); } void func::gen_mov(value& dest, value& src, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; if (dest == src) return; if (dest.is_mem() && src.is_mem()) dest.assign(); if (bits > src.bits && src.bits < 32) m_emitter.movzx(bits, src.bits, dest, src); else m_emitter.movr(min(bits, src.bits), dest, src); dest.mark_dirty(); } void func::gen_add(value& dest, value& src) { if (dest.is_mem() && src.is_mem()) dest.fetch(); m_emitter.addr(dest.bits, dest, src); dest.mark_dirty(); } void func::gen_or(value& dest, value& src) { if (dest.is_mem() && src.is_mem()) dest.fetch(); m_emitter.orr(dest.bits, dest, src); dest.mark_dirty(); } void func::gen_adc(value& dest, value& src) { if (dest.is_mem() && src.is_mem()) dest.fetch(); m_emitter.adcr(dest.bits, dest, src); dest.mark_dirty(); } void func::gen_sbb(value& dest, value& src) { if (dest.is_mem() && src.is_mem()) dest.fetch(); m_emitter.sbbr(dest.bits, dest, src); dest.mark_dirty(); } void func::gen_and(value& dest, value& src) { if (dest.is_mem() && src.is_mem()) dest.fetch(); m_emitter.andr(dest.bits, dest, src); dest.mark_dirty(); } void func::gen_sub(value& dest, value& src) { if (dest.is_mem() && src.is_mem()) dest.fetch(); m_emitter.subr(dest.bits, dest, src); dest.mark_dirty(); } void func::gen_xor(value& dest, value& src) { if (dest.is_mem() && src.is_mem()) dest.fetch(); m_emitter.xorr(dest.bits, dest, src); dest.mark_dirty(); } void func::gen_xch(value& dest, value& src) { if (dest.is_mem()) dest.fetch(); m_emitter.xchg(dest.bits, dest, src); dest.mark_dirty(); src.mark_dirty(); } void func::gen_add(value& dest, value& src1, value& src2) { if (dest == src1) { gen_add(dest, src2); } else if (dest == src2) { gen_add(dest, src1); } else { gen_mov(dest, src1); gen_add(dest, src2); } } void func::gen_or(value& dest, value& src1, value& src2) { if (dest == src1) { gen_or(dest, src2); } else if (dest == src2) { gen_or(dest, src1); } else { gen_mov(dest, src1); gen_or(dest, src2); } } void func::gen_adc(value& dest, value& src1, value& src2) { if (dest == src1) { gen_adc(dest, src2); } else if (dest == src2) { gen_adc(dest, src1); } else { gen_mov(dest, src1); gen_adc(dest, src2); } } void func::gen_sbb(value& dest, value& src1, value& src2) { if (dest != src2) { gen_mov(dest, src1); gen_sbb(dest, src2); } else { ftl::value res = gen_scratch_i64("sub.res"); gen_mov(res, src1); gen_sub(res, src2); gen_sbb(dest, res); } } void func::gen_and(value& dest, value& src1, value& src2) { if (dest == src1) { gen_and(dest, src2); } else if (dest == src2) { gen_and(dest, src1); } else { gen_mov(dest, src1); gen_and(dest, src2); } } void func::gen_sub(value& dest, value& src1, value& src2) { if (src1 == src2) { gen_mov(dest, 0); } else if (dest != src2) { gen_mov(dest, src1); gen_sub(dest, src2); } else { ftl::value res = gen_scratch_i64("sub.res"); gen_mov(res, src1); gen_sub(res, src2); gen_mov(dest, res); } } void func::gen_xor(value& dest, value& src1, value& src2) { if (dest == src1) { gen_xor(dest, src2); } else if (dest == src2) { gen_xor(dest, src1); } else { gen_mov(dest, src1); gen_xor(dest, src2); } } void func::gen_mov(value& dest, i64 val) { int immlen = max(encode_size(val), dest.bits); if (dest.is_mem() && immlen > 32) dest.assign(); if (val == 0 && dest.is_reg()) m_emitter.xorr(dest.bits, dest, dest); else m_emitter.movi(dest.bits, dest, val); dest.mark_dirty(); } void func::gen_add(value& dest, i32 val) { switch (val) { case 0: return; case 1: m_emitter.incr(dest.bits, dest); break; case -1: m_emitter.decr(dest.bits, dest); break; default: m_emitter.addi(dest.bits, dest, val); break; } dest.mark_dirty(); } void func::gen_or(value& dest, i32 val) { if (val == 0) return; m_emitter.ori(dest.bits, dest, val); dest.mark_dirty(); } void func::gen_adc(value& dest, i32 val) { m_emitter.adci(dest.bits, dest, val); dest.mark_dirty(); } void func::gen_sbb(value& dest, i32 val) { m_emitter.sbbi(dest.bits, dest, val); dest.mark_dirty(); } void func::gen_and(value& dest, i32 val) { if (val == -1) return; if (val == 0 && dest.is_reg()) m_emitter.xorr(dest.bits, dest, dest); else m_emitter.andi(dest.bits, dest, val); dest.mark_dirty(); } void func::gen_sub(value& dest, i32 val) { switch (val) { case 0: return; case 1: m_emitter.decr(dest.bits, dest); break; case -1: m_emitter.incr(dest.bits, dest); break; default: m_emitter.subi(dest.bits, dest, val); break; } dest.mark_dirty(); } void func::gen_xor(value& dest, i32 val) { if (val == 0) return; m_emitter.xori(dest.bits, dest, val); dest.mark_dirty(); } void func::gen_lea(value& dest, value& src, i32 val) { src.fetch(); if (dest != src) dest.assign(); m_emitter.lear(dest.bits, dest, src.r(), val); dest.mark_dirty(); } void func::gen_add(value& dest, value& src, i32 val) { if (dest == src) { gen_add(dest, val); return; } if (dest.is_mem()) dest.assign(); if (src.is_reg()) { dest.mark_dirty(); m_emitter.lear(dest.bits, dest, src.r(), val); } else { gen_mov(dest, src); gen_add(dest, val); } } void func::gen_or(value& dest, value& src, i32 val) { gen_mov(dest, src); gen_or(dest, val); } void func::gen_adc(value& dest, value& src, i32 val) { gen_mov(dest, src); gen_adc(dest, val); } void func::gen_sbb(value& dest, value& src, i32 val) { gen_mov(dest, src); gen_sbb(dest, val); } void func::gen_and(value& dest, value& src, i32 val) { gen_mov(dest, src); gen_and(dest, val); } void func::gen_sub(value& dest, value& src, i32 val) { gen_mov(dest, src); gen_sub(dest, val); } void func::gen_xor(value& dest, value& src, i32 val) { gen_mov(dest, src); gen_xor(dest, val); } void func::gen_imul(value& hi, value& lo, value& src1, value& src2) { gen_imul(lo, src1, src2); hi.assign(RDX); hi.mark_dirty(); } void func::gen_imul(value& dest, value& src1, value& src2) { auto guard = create_guard(RAX, RDX); if (dest != src1) { reg src1_r = src1.r(); if (src1_r == RAX || src1_r == RDX) src1.fetch(m_broker.select()); } if (dest != src2) { reg src2_r = src2.r(); if (src2_r == RAX || src2_r == RDX) src2.fetch(m_broker.select()); } if (dest == src1) { dest.fetch(RAX); m_broker.flush(RDX); m_emitter.imul(dest.bits, src2); } else if (dest == src2) { dest.fetch(RAX); m_broker.flush(RDX); m_emitter.imul(dest.bits, src1); } else { dest.assign(RAX); gen_mov(dest, src1); m_broker.flush(RDX); m_emitter.imul(dest.bits, src2); } dest.mark_dirty(); } void func::gen_idiv(value& dest, value& src1, value& src2) { auto guard = create_guard(RAX, RDX); reg src2_r = src2.r(); if (src2_r == RAX || src2_r == RDX) src2.fetch(m_broker.select()); if (dest == src2) { m_broker.flush(RAX); m_broker.flush(RDX); m_emitter.movr(src1.bits, RAX, src1); m_emitter.cwd(dest.bits); m_emitter.idiv(dest.bits, src2); dest.assign(RAX); } else { if (dest == src1) dest.fetch(RAX); else { dest.assign(RAX); gen_mov(dest, src1); } m_broker.flush(RDX); m_emitter.cwd(dest.bits); m_emitter.idiv(dest.bits, src2); } dest.mark_dirty(); } void func::gen_imod(value& dest, value& src1, value& src2) { gen_idiv(dest, src1, src2); dest.assign(RDX); dest.mark_dirty(); } void func::gen_umul(value& hi, value& lo, value& src1, value& src2) { gen_umul(lo, src1, src2); hi.assign(RDX); hi.mark_dirty(); } void func::gen_umul(value& dest, value& src1, value& src2) { auto guard = create_guard(RAX, RDX); if (dest != src1) { reg src1_r = src1.r(); if (src1_r == RAX || src1_r == RDX) src1.fetch(m_broker.select()); } if (dest != src2) { reg src2_r = src2.r(); if (src2_r == RAX || src2_r == RDX) src2.fetch(m_broker.select()); } if (dest == src1) { dest.fetch(RAX); m_broker.flush(RDX); m_emitter.mulr(dest.bits, src2); } else if (dest == src2) { dest.fetch(RAX); m_broker.flush(RDX); m_emitter.mulr(dest.bits, src1); } else { dest.assign(RAX); gen_mov(dest, src1); m_broker.flush(RDX); m_emitter.mulr(dest.bits, src2); } dest.mark_dirty(); } void func::gen_udiv(value& dest, value& src1, value& src2) { auto guard = create_guard(RAX, RDX); reg src2_r = src2.r(); if (src2_r == RAX || src2_r == RDX) src2.fetch(m_broker.select()); if (dest == src2) { m_broker.flush(RAX); m_broker.flush(RDX); m_emitter.movr(src1.bits, RAX, src1); m_emitter.xorr(32, RDX, RDX); m_emitter.divr(dest.bits, src2); dest.assign(RAX); } else { if (dest == src1) dest.fetch(RAX); else { dest.assign(RAX); gen_mov(dest, src1); } m_broker.flush(RDX); m_emitter.xorr(32, RDX, RDX); m_emitter.divr(dest.bits, src2); } dest.mark_dirty(); } void func::gen_umod(value& dest, value& src1, value& src2) { gen_udiv(dest, src1, src2); dest.assign(RDX); dest.mark_dirty(); } void func::gen_imul(value& dest, value& src, i64 val) { FTL_ERROR_ON(encode_size(val) > dest.bits, "immediate too large"); if (val == 0) { gen_xor(dest, dest); return; } if (val == 1) { gen_mov(dest, src); return; } if (val == -1) { gen_mov(dest, src); gen_neg(dest); return; } if (is_pow2(val)) { gen_mov(dest, src); gen_shli(dest, log2i(val)); return; } auto guard = create_guard(RAX, RDX); value imm = gen_scratch_val("temp_imul_imm", dest.bits, val); gen_imul(dest, src, imm); } void func::gen_idiv(value& dest, value& src, i64 val) { FTL_ERROR_ON(encode_size(val) > dest.bits, "immediate too large"); FTL_ERROR_ON(val == 0, "division by zero"); if (val == 1) { gen_mov(dest, src); return; } if (val == -1) { gen_mov(dest, src); gen_neg(dest); return; } if (is_pow2(val)) { gen_mov(dest, src); gen_shai(dest, log2i(val)); return; } auto guard = create_guard(RAX, RDX); value imm = gen_scratch_val("temp_idiv_imm", dest.bits, val); gen_idiv(dest, src, imm); } void func::gen_imod(value& dest, value& src, i64 val) { FTL_ERROR_ON(encode_size(val) > dest.bits, "immediate too large"); FTL_ERROR_ON(val == 0, "division by zero"); if (val == 1 || val == -1) { gen_xor(dest, dest); return; } auto guard = create_guard(RAX, RDX); value imm = gen_scratch_val("temp_imod_imm", dest.bits, val); gen_imod(dest, src, imm); } void func::gen_umul(value& dest, value& src, u64 val) { FTL_ERROR_ON(encode_size(val) > dest.bits, "immediate too large"); if (val == 0) { gen_xor(dest, dest); return; } if (val == 1) { gen_mov(dest, src); return; } if (is_pow2(val)) { gen_mov(dest, src); gen_shli(dest, log2i(val)); return; } auto guard = create_guard(RAX, RDX); value imm = gen_scratch_val("temp_umul_imm", dest.bits, val); gen_umul(dest, src, imm); } void func::gen_udiv(value& dest, value& src, u64 val) { FTL_ERROR_ON(encode_size(val) > dest.bits, "immediate too large"); FTL_ERROR_ON(val == 0, "division by zero"); if (val == 1) { gen_mov(dest, src); return; } if (is_pow2(val)) { gen_mov(dest, src); gen_shri(dest, log2i(val)); return; } auto guard = create_guard(RAX, RDX); value imm = gen_scratch_val("temp_udiv_imm", dest.bits, val); gen_udiv(dest, src, imm); } void func::gen_umod(value& dest, value& src, u64 val) { FTL_ERROR_ON(encode_size(val) > dest.bits, "immediate too large"); FTL_ERROR_ON(val == 0, "division by zero"); if (val == 1) { gen_xor(dest, dest); return; } if (is_pow2(val) && fits_i32(val)) { gen_mov(dest, src); gen_and(dest, val - 1); return; } auto guard = create_guard(RAX, RDX); value imm = gen_scratch_val("temp_umod_imm", dest.bits, val); gen_umod(dest, src, imm); } void func::gen_inc(value& dest) { m_emitter.incr(dest.bits, dest); dest.mark_dirty(); } void func::gen_dec(value& dest) { m_emitter.decr(dest.bits, dest); dest.mark_dirty(); } void func::gen_not(value& dest) { m_emitter.notr(dest.bits, dest); dest.mark_dirty(); } void func::gen_neg(value& dest) { m_emitter.negr(dest.bits, dest); dest.mark_dirty(); } void func::gen_shl(value& dest, value& shift, int bits) { gen_shl(dest, dest, shift, bits); } void func::gen_shr(value& dest, value& shift, int bits) { gen_shr(dest, dest, shift, bits); } void func::gen_sha(value& dest, value& shift, int bits) { gen_sha(dest, dest, shift, bits); } void func::gen_rol(value& dest, value& shift, int bits) { gen_rol(dest, dest, shift, bits); } void func::gen_ror(value& dest, value& shift, int bits) { gen_ror(dest, dest, shift, bits); } void func::gen_shl(value& dest, value& src, value& shift, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; auto guard = create_guard(RCX); m_broker.flush(RCX); m_emitter.movr(8, RCX, shift); gen_mov(dest, src, bits); m_emitter.shlr(bits, dest); dest.mark_dirty(); } void func::gen_shr(value& dest, value& src, value& shift, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; auto guard = create_guard(RCX); m_broker.flush(RCX); m_emitter.movr(8, RCX, shift); gen_mov(dest, src, bits); m_emitter.shrr(bits, dest); dest.mark_dirty(); } void func::gen_sha(value& dest, value& src, value& shift, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; auto guard = create_guard(RCX); m_broker.flush(RCX); m_emitter.movr(8, RCX, shift); gen_mov(dest, src, bits); m_emitter.sarr(bits, dest); dest.mark_dirty(); } void func::gen_rol(value& dest, value& src, value& shift, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; auto guard = create_guard(RCX); m_broker.flush(RCX); m_emitter.movr(8, RCX, shift); gen_mov(dest, src, bits); m_emitter.rolr(bits, dest); dest.mark_dirty(); } void func::gen_ror(value& dest, value& src, value& shift, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; auto guard = create_guard(RCX); m_broker.flush(RCX); m_emitter.movr(8, RCX, shift); gen_mov(dest, src, bits); m_emitter.rorr(bits, dest); dest.mark_dirty(); } void func::gen_shli(value& dest, u8 shift, int bits) { gen_shli(dest, dest, shift, bits); } void func::gen_shri(value& dest, u8 shift, int bits) { gen_shri(dest, dest, shift, bits); } void func::gen_shai(value& dest, u8 shift, int bits) { gen_shai(dest, dest, shift, bits); } void func::gen_roli(value& dest, u8 shift, int bits) { gen_roli(dest, dest, shift, bits); } void func::gen_rori(value& dest, u8 shift, int bits) { gen_rori(dest, dest, shift, bits); } void func::gen_shli(value& dest, value& src, u8 shift, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; if (dest != src) gen_mov(dest, src, bits); if (shift == 0) return; m_emitter.shli(bits, dest, shift & (bits - 1)); dest.mark_dirty(); } void func::gen_shri(value& dest, value& src, u8 shift, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; if (dest != src) gen_mov(dest, src, bits); if (shift == 0) return; m_emitter.shri(bits, dest, shift & (bits - 1)); dest.mark_dirty(); } void func::gen_shai(value& dest, value& src, u8 shift, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; if (dest != src) gen_mov(dest, src, bits); if (shift == 0) return; m_emitter.sari(bits, dest, shift & (bits - 1)); dest.mark_dirty(); } void func::gen_roli(value& dest, value& src, u8 shift, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; if (dest != src) gen_mov(dest, src, bits); if (shift == 0) return; m_emitter.roli(bits, dest, shift & (bits - 1)); dest.mark_dirty(); } void func::gen_rori(value& dest, value& src, u8 shift, int bits) { if (!abi<reg>::fits(bits)) bits = dest.bits; if (dest != src) gen_mov(dest, src, bits); if (shift == 0) return; m_emitter.rori(bits, dest, shift & (bits - 1)); dest.mark_dirty(); } void func::gen_bt(value& dest, value& src) { src.fetch(); // dest is not modified! m_emitter.btr(dest.bits, dest, src); } void func::gen_bts(value& dest, value& src) { src.fetch(); dest.mark_dirty(); m_emitter.btsr(dest.bits, dest, src); } void func::gen_btr(value& dest, value& src) { src.fetch(); dest.mark_dirty(); m_emitter.btrr(dest.bits, dest, src); } void func::gen_btc(value& dest, value& src) { src.fetch(); dest.mark_dirty(); m_emitter.btcr(dest.bits, dest, src); } void func::gen_bt(value& dest, u8 idx) { m_emitter.bti(dest.bits, dest, idx & (dest.bits - 1)); } void func::gen_bts(value& dest, u8 idx) { dest.mark_dirty(); m_emitter.btsi(dest.bits, dest, idx & (dest.bits - 1)); } void func::gen_btr(value& dest, u8 idx) { dest.mark_dirty(); m_emitter.btri(dest.bits, dest, idx & (dest.bits - 1)); } void func::gen_btc(value& dest, u8 idx) { dest.mark_dirty(); m_emitter.btci(dest.bits, dest, idx & (dest.bits - 1)); } void func::gen_zxt(value& dest, value& src) { gen_zxt(dest, src, dest.bits, src.bits); } void func::gen_zxt(value& dest, value& src, int dbits, int sbits) { FTL_ERROR_ON(dbits < sbits, "target width too narrow"); if (dest != src) { dest.assign(); m_emitter.movzx(dbits, sbits, dest, src); } else { reg r = m_broker.select(); m_broker.flush(r); m_emitter.movzx(dbits, sbits, r, src); dest.assign(r); } dest.mark_dirty(); } void func::gen_sxt(value& dest, value& src) { gen_sxt(dest, src, dest.bits, src.bits); } void func::gen_sxt(value& dest, value& src, int dbits, int sbits) { FTL_ERROR_ON(dbits < sbits, "target width too narrow"); if (dest != src) { dest.assign(); m_emitter.movsx(dbits, sbits, dest, src); } else { reg r = m_broker.select(); m_broker.flush(r); m_emitter.movsx(dbits, sbits, r, src); dest.assign(r); } dest.mark_dirty(); } void func::gen_zxt(value& dest, int bits) { if (dest.bits != bits) gen_zxt(dest, dest, bits, dest.bits); dest.bits = bits; } void func::gen_sxt(value& dest, int bits) { if (dest.bits != bits) gen_sxt(dest, dest, bits, dest.bits); dest.bits = bits; } void func::gen_cmpxchg(value& dest, value& src, value& cmpv) { dest.flush(); src.fetch(); cmpv.fetch(RAX); m_emitter.cmpxchg(dest.bits, dest, src); } void func::gen_fence(bool sync_loads, bool sync_stores) { if (sync_loads && sync_stores) m_emitter.mfence(); else if (sync_loads) m_emitter.lfence(); else if (sync_stores) m_emitter.sfence(); } void func::gen_mov(scalar& dest, value& src) { FTL_ERROR_ON(src.bits < 32, "integer value too narrow"); if (dest.is_mem()) dest.assign(); dest.mark_dirty(); int bits = min(dest.bits, src.bits); m_emitter.movx(bits, dest, src); } void func::gen_mov(value& dest, scalar& src) { FTL_ERROR_ON(dest.bits < 32, "integer value too narrow"); src.fetch(); // fp value must be in a register dest.mark_dirty(); int bits = min(dest.bits, src.bits); if (dest.bits > src.bits) { dest.assign(); gen_mov(dest, 0); } m_emitter.movx(bits, dest, src); } void func::gen_mov(scalar& dest, scalar& src) { if (dest == src) return; if (dest.is_mem()) dest.assign(); dest.mark_dirty(); if (dest.bits == src.bits) m_emitter.movs(dest.bits, dest, src); else m_emitter.cvts2s(dest.bits, src.bits, dest, src); } void func::gen_add(scalar& dest, scalar& src) { if (dest.is_mem()) dest.fetch(); dest.mark_dirty(); if (dest.bits == src.bits) { m_emitter.adds(dest.bits, dest, src); return; } scalar temp = gen_scratch_fp("add.temp", dest.bits); m_emitter.cvts2s(temp.bits, src.bits, temp, src); m_emitter.adds(dest.bits, dest, temp); } void func::gen_sub(scalar& dest, scalar& src) { if (dest.is_mem()) dest.fetch(); dest.mark_dirty(); if (dest.bits == src.bits) { m_emitter.subs(dest.bits, dest, src); return; } scalar temp = gen_scratch_fp("sub.temp", dest.bits); m_emitter.cvts2s(temp.bits, src.bits, temp, src); m_emitter.subs(dest.bits, dest, temp); } void func::gen_mul(scalar& dest, scalar& src) { if (dest.is_mem()) dest.fetch(); dest.mark_dirty(); if (dest.bits == src.bits) { m_emitter.muls(dest.bits, dest, src); return; } scalar temp = gen_scratch_fp("mul.temp", dest.bits); m_emitter.cvts2s(temp.bits, src.bits, temp, src); m_emitter.muls(dest.bits, dest, temp); } void func::gen_div(scalar& dest, scalar& src) { if (dest.is_mem()) dest.fetch(); dest.mark_dirty(); if (dest.bits == src.bits) { m_emitter.divs(dest.bits, dest, src); return; } scalar temp = gen_scratch_fp("div.temp", dest.bits); m_emitter.cvts2s(temp.bits, src.bits, temp, src); m_emitter.divs(dest.bits, dest, temp); } void func::gen_min(scalar& dest, scalar& src) { if (dest.is_mem()) dest.fetch(); dest.mark_dirty(); if (dest.bits == src.bits) { m_emitter.mins(dest.bits, dest, src); return; } scalar temp = gen_scratch_fp("min.temp", dest.bits); m_emitter.cvts2s(temp.bits, src.bits, temp, src); m_emitter.mins(dest.bits, dest, temp); } void func::gen_max(scalar& dest, scalar& src) { if (dest.is_mem()) dest.fetch(); dest.mark_dirty(); if (dest.bits == src.bits) { m_emitter.maxs(dest.bits, dest, src); return; } scalar temp = gen_scratch_fp("max.temp", dest.bits); m_emitter.cvts2s(temp.bits, src.bits, temp, src); m_emitter.maxs(dest.bits, dest, temp); } void func::gen_sqrt(scalar& dest, scalar& src) { if (dest.is_mem()) { if (dest == src) dest.fetch(); else dest.assign(); } dest.mark_dirty(); if (dest.bits == src.bits) { m_emitter.sqrt(dest.bits, dest, src); return; } scalar temp = gen_scratch_fp("sqrt.temp", dest.bits); m_emitter.cvts2s(temp.bits, src.bits, temp, src); m_emitter.sqrt(dest.bits, dest, temp); } void func::gen_pxor(scalar& dest, scalar& src) { if (dest.is_mem()) { if (dest == src) dest.assign(); else dest.fetch(); } dest.mark_dirty(); m_emitter.pxor(dest.bits, dest, src); } void func::gen_cmp(scalar& op1, scalar& op2, bool signal_qnan) { if (op1.is_mem()) op1.fetch(); auto handler = signal_qnan ? &emitter::comis : &emitter::ucomis; if (op1.bits == op2.bits) { (m_emitter.*handler)(op1.bits, op1, op2); return; } scalar temp = gen_scratch_fp("convert.temp", op1.bits); m_emitter.cvts2s(temp.bits, op2.bits, temp, op2); (m_emitter.*handler)(op1.bits, op1, temp); } void func::gen_cvt(scalar& dest, value& src) { if (dest.is_mem()) dest.assign(); m_emitter.cvti2s(dest.bits, src.bits, dest, src); dest.mark_dirty(); } void func::gen_cvt(value& dest, scalar& src) { if (dest.is_mem()) dest.assign(); m_emitter.cvts2i(dest.bits, src.bits, dest, src); dest.mark_dirty(); } }}
27.075512
80
0.504196
janweinstock
15c8014894e74be47912df906b2ec46574c05460
969
cpp
C++
lib/libCFG/src/EventManager.cpp
cyber-itl/citl-static-analysis
32ef8e519dac1c6a49ff41d902a62df8f5a8e948
[ "MIT" ]
14
2021-05-03T16:03:22.000Z
2022-02-14T23:42:39.000Z
lib/libCFG/src/EventManager.cpp
cyber-itl/citl-static-analysis
32ef8e519dac1c6a49ff41d902a62df8f5a8e948
[ "MIT" ]
1
2021-09-27T12:01:33.000Z
2021-09-27T12:01:33.000Z
lib/libCFG/src/EventManager.cpp
cyber-itl/citl-static-analysis
32ef8e519dac1c6a49ff41d902a62df8f5a8e948
[ "MIT" ]
null
null
null
#include <vector> #include <memory> #include "capstone/capstone.h" #include "glog/logging.h" #include "EventManager.hpp" class CpuState; struct Block; struct Symbol; void EventManager::register_event(std::unique_ptr<AnalyzerEvent> event) { m_events.push_back(std::move(event)); } void EventManager::run_events(event_type type, CpuState *cpu, Block *block, cs_insn *insn) { this->run_events(type, cpu, block, insn, nullptr); } void EventManager::run_events(event_type type, CpuState *cpu, Block *block, cs_insn *insn, const Symbol *sym) { for (const auto &event : m_events) { if (event->get_type() == type) { if (event->run(cpu, block, insn, sym)) { LOG(FATAL) << "Failed to run event analyzer: " << event->get_name(); } } } } void EventManager::clear() { m_events.clear(); } const std::vector<std::unique_ptr<AnalyzerEvent>> *EventManager::get_events() const { return &m_events; }
25.5
111
0.661507
cyber-itl
15c86cc428860a4cb7b800b221c2f84e7ff73eb2
329
cpp
C++
Ejercicios/Ejercicio2-mensaje/mensajes.cpp
Maldanar201/LenguajeProgramacion1
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
[ "MIT" ]
null
null
null
Ejercicios/Ejercicio2-mensaje/mensajes.cpp
Maldanar201/LenguajeProgramacion1
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
[ "MIT" ]
null
null
null
Ejercicios/Ejercicio2-mensaje/mensajes.cpp
Maldanar201/LenguajeProgramacion1
5a53c51077c0e41deff8daf40dbe6f0778b41f9c
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { string nombre; cout << " ingrese su nombre: "; cin >> nombre; cout <<"\n Hola mi nombre es " << nombre <<endl; cout << " Hola "<<nombre<<" Bienvenido a la Clase de Lenguaje de Programacion I "<< endl; return 0; }
19.352941
93
0.595745
Maldanar201
15c911684394101812f4ea2488ae2663af5ac441
3,012
hpp
C++
thirdparty/jni.hpp/include/jni/tagging.hpp
rh101/engine-x
17ad9829dd410c689857760b6ece89d99e877a95
[ "MIT" ]
76
2021-05-20T12:27:10.000Z
2022-03-23T15:27:42.000Z
thirdparty/jni.hpp/include/jni/tagging.hpp
rh101/engine-x
17ad9829dd410c689857760b6ece89d99e877a95
[ "MIT" ]
171
2021-05-18T11:07:25.000Z
2022-03-29T20:53:27.000Z
thirdparty/jni.hpp/include/jni/tagging.hpp
rh101/engine-x
17ad9829dd410c689857760b6ece89d99e877a95
[ "MIT" ]
42
2021-05-18T10:05:06.000Z
2022-03-22T05:40:56.000Z
#pragma once #include <jni/traits.hpp> #include <jni/unique.hpp> #include <type_traits> namespace jni { class ObjectBase; template < class Tag > class Object; template < class E, class = void > class Array; template < class > struct TypeSignature; struct ObjectTag { static constexpr auto Name() { return "java/lang/Object"; } }; struct StringTag { static constexpr auto Name() { return "java/lang/String"; } }; struct ClassTag { static constexpr auto Name() { return "java/lang/Class"; } }; template < class T > struct ArrayTag { static constexpr auto Name() { return TypeSignature<Array<T>>()(); } }; template < class Tag, class = int > struct SuperTag { using Type = ObjectTag; }; template < class Tag > struct SuperTag< Tag, decltype(std::declval<typename Tag::SuperTag>(), 0) > { using Type = typename Tag::SuperTag; }; template < class Tag, class Enable = void > struct TagTraits { using SuperType = Object<typename SuperTag<Tag>::Type>; using UntaggedType = jobject; }; template <> struct TagTraits< ObjectTag > { using SuperType = ObjectBase; using UntaggedType = jobject; }; template <> struct TagTraits< StringTag > { using SuperType = Object<ObjectTag>; using UntaggedType = jstring; }; template <> struct TagTraits< ClassTag > { using SuperType = Object<ObjectTag>; using UntaggedType = jclass; }; template < class E > struct TagTraits< ArrayTag<E>, std::enable_if_t<IsPrimitive<E>::value> > { using SuperType = Object<ObjectTag>; using UntaggedType = jarray<E>; }; template < class Tag > struct TagTraits< ArrayTag<Object<Tag>> > { using SuperType = Object<ObjectTag>; using UntaggedType = jarray<jobject>; }; template < class T > auto Tag(JNIEnv&, T primitive) -> std::enable_if_t< IsPrimitive<T>::value, T > { return primitive; } template < class T, class U > auto Tag(JNIEnv& env, U* u) -> std::enable_if_t< !IsPrimitive<T>::value, Input<T> > { return Input<T>(env, u); } template < class T, class U > auto Tag(JNIEnv& env, U& u) -> std::enable_if_t< !IsPrimitive<T>::value, Input<T> > { return Input<T>(env, &u); } template < class T > auto Untag(T primitive) -> std::enable_if_t< IsPrimitive<T>::value, T > { return primitive; } template < class T > auto Untag(const T& t) -> std::enable_if_t< !IsPrimitive<T>::value, decltype(t.get()) > { return t.get(); } template < class T > using UntaggedType = decltype(Untag(std::declval<T>())); }
22.818182
79
0.551793
rh101
15ca1dd9280671a1ebf989edc6c2ae70928e8279
2,409
cc
C++
research/carls/base/thread_bundle.cc
srihari-humbarwadi/neural-structured-learning
345b8d644dd7745179263bf6dc9aeb8a921528f4
[ "Apache-2.0" ]
939
2019-08-28T06:50:30.000Z
2022-03-30T02:37:07.000Z
research/carls/base/thread_bundle.cc
srihari-humbarwadi/neural-structured-learning
345b8d644dd7745179263bf6dc9aeb8a921528f4
[ "Apache-2.0" ]
80
2019-09-01T19:47:30.000Z
2022-02-02T20:38:38.000Z
research/carls/base/thread_bundle.cc
srihari-humbarwadi/neural-structured-learning
345b8d644dd7745179263bf6dc9aeb8a921528f4
[ "Apache-2.0" ]
196
2019-09-01T19:38:53.000Z
2022-02-08T01:25:57.000Z
/*Copyright 2021 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://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 "research/carls/base/thread_bundle.h" #include "absl/base/call_once.h" #include "absl/flags/flag.h" #include "tensorflow/core/platform/env.h" ABSL_FLAG(int, num_threads_for_global_thread_bundle, 1000, "Number of threads for the default global thread pool."); namespace carls { namespace { using ::tensorflow::thread::ThreadPool; constexpr char kDefaultThreadPooleName[] = "GlobalThreadBundle"; ThreadPool* g_thread_pool = nullptr; } // namespace ThreadBundle::ThreadBundle() { Init(); } ThreadBundle::ThreadBundle(const std::string& name, int num_threads) : thread_pool_(absl::make_unique<ThreadPool>(tensorflow::Env::Default(), name, num_threads)) {} ThreadBundle::~ThreadBundle() { JoinAll(); } void ThreadBundle::Init() { static absl::once_flag once; absl::call_once(once, []() { CHECK(g_thread_pool == nullptr); g_thread_pool = new ThreadPool( tensorflow::Env::Default(), kDefaultThreadPooleName, absl::GetFlag(FLAGS_num_threads_for_global_thread_bundle)); }); } void ThreadBundle::Add(std::function<void()> f) { Inc(); auto job = [f, this]() { f(); Dec(); }; if (thread_pool_ != nullptr) { thread_pool_->Schedule(job); } else { g_thread_pool->Schedule(job); } } void ThreadBundle::JoinAll() { JoinAllWithDeadline(absl::InfiniteFuture()); } bool ThreadBundle::JoinAllWithDeadline(absl::Time deadline) { absl::MutexLock l(&mu_); while (count_ > 0) { if (cv_.WaitWithDeadline(&mu_, deadline)) return false; } return true; } void ThreadBundle::Inc() { absl::MutexLock l(&mu_); ++count_; } void ThreadBundle::Dec() { absl::MutexLock l(&mu_); if (--count_ == 0) cv_.SignalAll(); } } // namespace carls
26.766667
80
0.674554
srihari-humbarwadi
15ccd0fc98b06c5e61c55537bbc9f61e1f002480
68,063
cpp
C++
modules/tracktion_engine/3rd_party/airwindows/Monitoring/MonitoringProc.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
734
2018-11-16T09:39:40.000Z
2022-03-30T16:56:14.000Z
modules/tracktion_engine/3rd_party/airwindows/Monitoring/MonitoringProc.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
100
2018-11-16T18:04:08.000Z
2022-03-31T17:47:53.000Z
modules/tracktion_engine/3rd_party/airwindows/Monitoring/MonitoringProc.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
123
2018-11-16T15:51:50.000Z
2022-03-29T12:21:27.000Z
/* ======================================== * Monitoring - Monitoring.h * Copyright (c) 2016 airwindows, All rights reserved * ======================================== */ #ifndef __Monitoring_H #include "Monitoring.h" #endif void Monitoring::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames) { float* in1 = inputs[0]; float* in2 = inputs[1]; float* out1 = outputs[0]; float* out2 = outputs[1]; double overallscale = 1.0; overallscale /= 44100.0; overallscale *= getSampleRate(); int processing = (VstInt32)( A * 16.999 ); int am = (int)149.0 * overallscale; int bm = (int)179.0 * overallscale; int cm = (int)191.0 * overallscale; int dm = (int)223.0 * overallscale; //these are 'good' primes, spacing out the allpasses int allpasstemp; //for PeaksOnly biquadL[0] = 0.0375/overallscale; biquadL[1] = 0.1575; //define as AURAT, MONORAT, MONOLAT unless overridden if (processing == 7) {biquadL[0] = 0.0385/overallscale; biquadL[1] = 0.0825;} if (processing == 11) {biquadL[0] = 0.1245/overallscale; biquadL[1] = 0.46;} double K = tan(M_PI * biquadL[0]); double norm = 1.0 / (1.0 + K / biquadL[1] + K * K); biquadL[2] = K / biquadL[1] * norm; biquadL[4] = -biquadL[2]; //for bandpass, ignore [3] = 0.0 biquadL[5] = 2.0 * (K * K - 1.0) * norm; biquadL[6] = (1.0 - K / biquadL[1] + K * K) * norm; //for Bandpasses biquadR[0] = 0.0375/overallscale; biquadR[1] = 0.1575; //define as AURAT, MONORAT, MONOLAT unless overridden if (processing == 7) {biquadR[0] = 0.0385/overallscale; biquadR[1] = 0.0825;} if (processing == 11) {biquadR[0] = 0.1245/overallscale; biquadR[1] = 0.46;} K = tan(M_PI * biquadR[0]); norm = 1.0 / (1.0 + K / biquadR[1] + K * K); biquadR[2] = K / biquadR[1] * norm; biquadR[4] = -biquadR[2]; //for bandpass, ignore [3] = 0.0 biquadR[5] = 2.0 * (K * K - 1.0) * norm; biquadR[6] = (1.0 - K / biquadR[1] + K * K) * norm; //for Bandpasses while (--sampleFrames >= 0) { long double inputSampleL = *in1; long double inputSampleR = *in2; if (fabs(inputSampleL)<1.18e-37) inputSampleL = fpd * 1.18e-37; if (fabs(inputSampleR)<1.18e-37) inputSampleR = fpd * 1.18e-37; switch (processing) { case 0: case 1: break; case 2: if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //amplitude aspect allpasstemp = ax - 1; if (allpasstemp < 0 || allpasstemp > am) allpasstemp = am; inputSampleL -= aL[allpasstemp]*0.5; aL[ax] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= aR[allpasstemp]*0.5; aR[ax] = inputSampleR; inputSampleR *= 0.5; ax--; if (ax < 0 || ax > am) {ax = am;} inputSampleL += (aL[ax]); inputSampleR += (aR[ax]); //a single Midiverb-style allpass if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //amplitude aspect allpasstemp = bx - 1; if (allpasstemp < 0 || allpasstemp > bm) allpasstemp = bm; inputSampleL -= bL[allpasstemp]*0.5; bL[bx] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= bR[allpasstemp]*0.5; bR[bx] = inputSampleR; inputSampleR *= 0.5; bx--; if (bx < 0 || bx > bm) {bx = bm;} inputSampleL += (bL[bx]); inputSampleR += (bR[bx]); //a single Midiverb-style allpass if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //amplitude aspect allpasstemp = cx - 1; if (allpasstemp < 0 || allpasstemp > cm) allpasstemp = cm; inputSampleL -= cL[allpasstemp]*0.5; cL[cx] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= cR[allpasstemp]*0.5; cR[cx] = inputSampleR; inputSampleR *= 0.5; cx--; if (cx < 0 || cx > cm) {cx = cm;} inputSampleL += (cL[cx]); inputSampleR += (cR[cx]); //a single Midiverb-style allpass if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //amplitude aspect allpasstemp = dx - 1; if (allpasstemp < 0 || allpasstemp > dm) allpasstemp = dm; inputSampleL -= dL[allpasstemp]*0.5; dL[dx] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= dR[allpasstemp]*0.5; dR[dx] = inputSampleR; inputSampleR *= 0.5; dx--; if (dx < 0 || dx > dm) {dx = dm;} inputSampleL += (dL[dx]); inputSampleR += (dR[dx]); //a single Midiverb-style allpass if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //amplitude aspect inputSampleL *= 0.63679; inputSampleR *= 0.63679; //scale it to 0dB output at full blast //PeaksOnly break; case 3: double trim; trim = 2.302585092994045684017991; //natural logarithm of 10 long double slewSample; slewSample = (inputSampleL - lastSampleL)*trim; lastSampleL = inputSampleL; if (slewSample > 1.0) slewSample = 1.0; if (slewSample < -1.0) slewSample = -1.0; inputSampleL = slewSample; slewSample = (inputSampleR - lastSampleR)*trim; lastSampleR = inputSampleR; if (slewSample > 1.0) slewSample = 1.0; if (slewSample < -1.0) slewSample = -1.0; inputSampleR = slewSample; //SlewOnly break; case 4: double iirAmount; iirAmount = (2250/44100.0) / overallscale; double gain; gain = 1.42; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; iirSampleAL = (iirSampleAL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleAL; iirSampleAR = (iirSampleAR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleAR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleBL = (iirSampleBL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleBL; iirSampleBR = (iirSampleBR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleBR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleCL = (iirSampleCL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleCL; iirSampleCR = (iirSampleCR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleCR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleDL = (iirSampleDL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleDL; iirSampleDR = (iirSampleDR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleDR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleEL = (iirSampleEL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleEL; iirSampleER = (iirSampleER * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleER; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleFL = (iirSampleFL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleFL; iirSampleFR = (iirSampleFR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleFR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleGL = (iirSampleGL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleGL; iirSampleGR = (iirSampleGR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleGR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleHL = (iirSampleHL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleHL; iirSampleHR = (iirSampleHR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleHR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleIL = (iirSampleIL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleIL; iirSampleIR = (iirSampleIR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleIR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleJL = (iirSampleJL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleJL; iirSampleJR = (iirSampleJR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleJR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleKL = (iirSampleKL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleKL; iirSampleKR = (iirSampleKR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleKR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleLL = (iirSampleLL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleLL; iirSampleLR = (iirSampleLR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleLR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleML = (iirSampleML * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleML; iirSampleMR = (iirSampleMR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleMR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleNL = (iirSampleNL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleNL; iirSampleNR = (iirSampleNR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleNR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleOL = (iirSampleOL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleOL; iirSampleOR = (iirSampleOR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleOR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSamplePL = (iirSamplePL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSamplePL; iirSamplePR = (iirSamplePR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSamplePR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleQL = (iirSampleQL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleQL; iirSampleQR = (iirSampleQR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleQR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleRL = (iirSampleRL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleRL; iirSampleRR = (iirSampleRR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleRR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleSL = (iirSampleSL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleSL; iirSampleSR = (iirSampleSR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleSR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleTL = (iirSampleTL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleTL; iirSampleTR = (iirSampleTR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleTR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleUL = (iirSampleUL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleUL; iirSampleUR = (iirSampleUR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleUR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleVL = (iirSampleVL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleVL; iirSampleVR = (iirSampleVR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleVR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleWL = (iirSampleWL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleWL; iirSampleWR = (iirSampleWR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleWR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleXL = (iirSampleXL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleXL; iirSampleXR = (iirSampleXR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleXR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleYL = (iirSampleYL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleYL; iirSampleYR = (iirSampleYR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleYR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleZL = (iirSampleZL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleZL; iirSampleZR = (iirSampleZR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleZR; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; //SubsOnly break; case 5: case 6: long double mid; mid = inputSampleL + inputSampleR; long double side; side = inputSampleL - inputSampleR; if (processing < 6) side = 0.0; else mid = 0.0; //mono monitoring, or side-only monitoring inputSampleL = (mid+side)/2.0; inputSampleR = (mid-side)/2.0; break; case 7: case 8: case 9: case 10: case 11: //Bandpass: changes in EQ are up in the variable defining, not here //7 Vinyl, 8 9 10 Aurat, 11 Phone if (processing == 9) {inputSampleR = (inputSampleL + inputSampleR)*0.5;inputSampleL = 0.0;} if (processing == 10) {inputSampleL = (inputSampleL + inputSampleR)*0.5;inputSampleR = 0.0;} if (processing == 11) {long double M; M = (inputSampleL + inputSampleR)*0.5; inputSampleL = M;inputSampleR = M;} inputSampleL = sin(inputSampleL); inputSampleR = sin(inputSampleR); //encode Console5: good cleanness long double tempSampleL; tempSampleL = (inputSampleL * biquadL[2]) + biquadL[7]; biquadL[7] = (-tempSampleL * biquadL[5]) + biquadL[8]; biquadL[8] = (inputSampleL * biquadL[4]) - (tempSampleL * biquadL[6]); inputSampleL = tempSampleL; //like mono AU, 7 and 8 store L channel long double tempSampleR; tempSampleR = (inputSampleR * biquadR[2]) + biquadR[7]; biquadR[7] = (-tempSampleR * biquadR[5]) + biquadR[8]; biquadR[8] = (inputSampleR * biquadR[4]) - (tempSampleR * biquadR[6]); inputSampleR = tempSampleR; // we are using the mono configuration if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; //without this, you can get a NaN condition where it spits out DC offset at full blast! inputSampleL = asin(inputSampleL); inputSampleR = asin(inputSampleR); //amplitude aspect break; case 12: case 13: case 14: case 15: if (processing == 12) {inputSampleL *= 0.855; inputSampleR *= 0.855;} if (processing == 13) {inputSampleL *= 0.748; inputSampleR *= 0.748;} if (processing == 14) {inputSampleL *= 0.713; inputSampleR *= 0.713;} if (processing == 15) {inputSampleL *= 0.680; inputSampleR *= 0.680;} //we do a volume compensation immediately to gain stage stuff cleanly inputSampleL = sin(inputSampleL); inputSampleR = sin(inputSampleR); long double drySampleL; drySampleL = inputSampleL; long double drySampleR; drySampleR = inputSampleR; //everything runs 'inside' Console long double bass; bass = (processing * processing * 0.00001) / overallscale; //we are using the iir filters from out of SubsOnly mid = inputSampleL + inputSampleR; side = inputSampleL - inputSampleR; iirSampleAL = (iirSampleAL * (1.0 - (bass*0.618))) + (side * bass * 0.618); side = side - iirSampleAL; inputSampleL = (mid+side)/2.0; inputSampleR = (mid-side)/2.0; //bass narrowing filter allpasstemp = ax - 1; if (allpasstemp < 0 || allpasstemp > am) allpasstemp = am; inputSampleL -= aL[allpasstemp]*0.5; aL[ax] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= aR[allpasstemp]*0.5; aR[ax] = inputSampleR; inputSampleR *= 0.5; ax--; if (ax < 0 || ax > am) {ax = am;} inputSampleL += (aL[ax])*0.5; inputSampleR += (aR[ax])*0.5; if (ax == am) {inputSampleL += (aL[0])*0.5; inputSampleR += (aR[0])*0.5;} else {inputSampleL += (aL[ax+1])*0.5; inputSampleR += (aR[ax+1])*0.5;} //a darkened Midiverb-style allpass if (processing == 12) {inputSampleL *= 0.125; inputSampleR *= 0.125;} if (processing == 13) {inputSampleL *= 0.25; inputSampleR *= 0.25;} if (processing == 14) {inputSampleL *= 0.30; inputSampleR *= 0.30;} if (processing == 15) {inputSampleL *= 0.35; inputSampleR *= 0.35;} //Cans A suppresses the crossfeed more, Cans B makes it louder drySampleL += inputSampleR; drySampleR += inputSampleL; //the crossfeed allpasstemp = dx - 1; if (allpasstemp < 0 || allpasstemp > dm) allpasstemp = dm; inputSampleL -= dL[allpasstemp]*0.5; dL[dx] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= dR[allpasstemp]*0.5; dR[dx] = inputSampleR; inputSampleR *= 0.5; dx--; if (dx < 0 || dx > dm) {dx = dm;} inputSampleL += (dL[dx])*0.5; inputSampleR += (dR[dx])*0.5; if (dx == dm) {inputSampleL += (dL[0])*0.5; inputSampleR += (dR[0])*0.5;} else {inputSampleL += (dL[dx+1])*0.5; inputSampleR += (dR[dx+1])*0.5;} //a darkened Midiverb-style allpass, which is stretching the previous one even more inputSampleL *= 0.25; inputSampleR *= 0.25; //for all versions of Cans the second level of bloom is this far down //and, remains on the opposite speaker rather than crossing again to the original side drySampleL += inputSampleR; drySampleR += inputSampleL; //add the crossfeed and very faint extra verbyness inputSampleL = drySampleL; inputSampleR = drySampleR; //and output our can-opened headphone feed mid = inputSampleL + inputSampleR; side = inputSampleL - inputSampleR; iirSampleAR = (iirSampleAR * (1.0 - bass)) + (side * bass); side = side - iirSampleAR; inputSampleL = (mid+side)/2.0; inputSampleR = (mid-side)/2.0; //bass narrowing filter if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //ConsoleBuss processing break; case 16: long double inputSample = (inputSampleL + inputSampleR) * 0.5; inputSampleL = -inputSample; inputSampleR = inputSample; break; } //begin Not Just Another Dither if (processing == 1) { inputSampleL = inputSampleL * 32768.0; //or 16 bit option inputSampleR = inputSampleR * 32768.0; //or 16 bit option } else { inputSampleL = inputSampleL * 8388608.0; //for literally everything else inputSampleR = inputSampleR * 8388608.0; //we will apply the 24 bit NJAD } //on the not unreasonable assumption that we are very likely playing back on 24 bit DAC //if we're not, then all we did was apply a Benford Realness function at 24 bits down. bool cutbinsL; cutbinsL = false; bool cutbinsR; cutbinsR = false; long double drySampleL; drySampleL = inputSampleL; long double drySampleR; drySampleR = inputSampleR; inputSampleL -= noiseShapingL; inputSampleR -= noiseShapingR; //NJAD L long double benfordize; benfordize = floor(inputSampleL); while (benfordize >= 1.0) benfordize /= 10; while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10; int hotbinA; hotbinA = floor(benfordize); //hotbin becomes the Benford bin value for this number floored long double totalA; totalA = 0; if ((hotbinA > 0) && (hotbinA < 10)) { bynL[hotbinA] += 1; if (bynL[hotbinA] > 982) cutbinsL = true; totalA += (301-bynL[1]); totalA += (176-bynL[2]); totalA += (125-bynL[3]); totalA += (97-bynL[4]); totalA += (79-bynL[5]); totalA += (67-bynL[6]); totalA += (58-bynL[7]); totalA += (51-bynL[8]); totalA += (46-bynL[9]); bynL[hotbinA] -= 1; } else hotbinA = 10; //produce total number- smaller is closer to Benford real benfordize = ceil(inputSampleL); while (benfordize >= 1.0) benfordize /= 10; while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10; int hotbinB; hotbinB = floor(benfordize); //hotbin becomes the Benford bin value for this number ceiled long double totalB; totalB = 0; if ((hotbinB > 0) && (hotbinB < 10)) { bynL[hotbinB] += 1; if (bynL[hotbinB] > 982) cutbinsL = true; totalB += (301-bynL[1]); totalB += (176-bynL[2]); totalB += (125-bynL[3]); totalB += (97-bynL[4]); totalB += (79-bynL[5]); totalB += (67-bynL[6]); totalB += (58-bynL[7]); totalB += (51-bynL[8]); totalB += (46-bynL[9]); bynL[hotbinB] -= 1; } else hotbinB = 10; //produce total number- smaller is closer to Benford real long double outputSample; if (totalA < totalB) {bynL[hotbinA] += 1; outputSample = floor(inputSampleL);} else {bynL[hotbinB] += 1; outputSample = floor(inputSampleL+1);} //assign the relevant one to the delay line //and floor/ceil signal accordingly if (cutbinsL) { bynL[1] *= 0.99; bynL[2] *= 0.99; bynL[3] *= 0.99; bynL[4] *= 0.99; bynL[5] *= 0.99; bynL[6] *= 0.99; bynL[7] *= 0.99; bynL[8] *= 0.99; bynL[9] *= 0.99; bynL[10] *= 0.99; } noiseShapingL += outputSample - drySampleL; if (noiseShapingL > fabs(inputSampleL)) noiseShapingL = fabs(inputSampleL); if (noiseShapingL < -fabs(inputSampleL)) noiseShapingL = -fabs(inputSampleL); if (processing == 1) inputSampleL = outputSample / 32768.0; else inputSampleL = outputSample / 8388608.0; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; //finished NJAD L //NJAD R benfordize = floor(inputSampleR); while (benfordize >= 1.0) benfordize /= 10; while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10; hotbinA = floor(benfordize); //hotbin becomes the Benford bin value for this number floored totalA = 0; if ((hotbinA > 0) && (hotbinA < 10)) { bynR[hotbinA] += 1; if (bynR[hotbinA] > 982) cutbinsR = true; totalA += (301-bynR[1]); totalA += (176-bynR[2]); totalA += (125-bynR[3]); totalA += (97-bynR[4]); totalA += (79-bynR[5]); totalA += (67-bynR[6]); totalA += (58-bynR[7]); totalA += (51-bynR[8]); totalA += (46-bynR[9]); bynR[hotbinA] -= 1; } else hotbinA = 10; //produce total number- smaller is closer to Benford real benfordize = ceil(inputSampleR); while (benfordize >= 1.0) benfordize /= 10; while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10; hotbinB = floor(benfordize); //hotbin becomes the Benford bin value for this number ceiled totalB = 0; if ((hotbinB > 0) && (hotbinB < 10)) { bynR[hotbinB] += 1; if (bynR[hotbinB] > 982) cutbinsR = true; totalB += (301-bynR[1]); totalB += (176-bynR[2]); totalB += (125-bynR[3]); totalB += (97-bynR[4]); totalB += (79-bynR[5]); totalB += (67-bynR[6]); totalB += (58-bynR[7]); totalB += (51-bynR[8]); totalB += (46-bynR[9]); bynR[hotbinB] -= 1; } else hotbinB = 10; //produce total number- smaller is closer to Benford real if (totalA < totalB) {bynR[hotbinA] += 1; outputSample = floor(inputSampleR);} else {bynR[hotbinB] += 1; outputSample = floor(inputSampleR+1);} //assign the relevant one to the delay line //and floor/ceil signal accordingly if (cutbinsR) { bynR[1] *= 0.99; bynR[2] *= 0.99; bynR[3] *= 0.99; bynR[4] *= 0.99; bynR[5] *= 0.99; bynR[6] *= 0.99; bynR[7] *= 0.99; bynR[8] *= 0.99; bynR[9] *= 0.99; bynR[10] *= 0.99; } noiseShapingR += outputSample - drySampleR; if (noiseShapingR > fabs(inputSampleR)) noiseShapingR = fabs(inputSampleR); if (noiseShapingR < -fabs(inputSampleR)) noiseShapingR = -fabs(inputSampleR); if (processing == 1) inputSampleR = outputSample / 32768.0; else inputSampleR = outputSample / 8388608.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; //finished NJAD R //does not use 32 bit stereo floating point dither *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } } void Monitoring::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames) { double* in1 = inputs[0]; double* in2 = inputs[1]; double* out1 = outputs[0]; double* out2 = outputs[1]; double overallscale = 1.0; overallscale /= 44100.0; overallscale *= getSampleRate(); int processing = (VstInt32)( A * 16.999 ); int am = (int)149.0 * overallscale; int bm = (int)179.0 * overallscale; int cm = (int)191.0 * overallscale; int dm = (int)223.0 * overallscale; //these are 'good' primes, spacing out the allpasses int allpasstemp; //for PeaksOnly biquadL[0] = 0.0375/overallscale; biquadL[1] = 0.1575; //define as AURAT, MONORAT, MONOLAT unless overridden if (processing == 7) {biquadL[0] = 0.0385/overallscale; biquadL[1] = 0.0825;} if (processing == 11) {biquadL[0] = 0.1245/overallscale; biquadL[1] = 0.46;} double K = tan(M_PI * biquadL[0]); double norm = 1.0 / (1.0 + K / biquadL[1] + K * K); biquadL[2] = K / biquadL[1] * norm; biquadL[4] = -biquadL[2]; //for bandpass, ignore [3] = 0.0 biquadL[5] = 2.0 * (K * K - 1.0) * norm; biquadL[6] = (1.0 - K / biquadL[1] + K * K) * norm; //for Bandpasses biquadR[0] = 0.0375/overallscale; biquadR[1] = 0.1575; //define as AURAT, MONORAT, MONOLAT unless overridden if (processing == 7) {biquadR[0] = 0.0385/overallscale; biquadR[1] = 0.0825;} if (processing == 11) {biquadR[0] = 0.1245/overallscale; biquadR[1] = 0.46;} K = tan(M_PI * biquadR[0]); norm = 1.0 / (1.0 + K / biquadR[1] + K * K); biquadR[2] = K / biquadR[1] * norm; biquadR[4] = -biquadR[2]; //for bandpass, ignore [3] = 0.0 biquadR[5] = 2.0 * (K * K - 1.0) * norm; biquadR[6] = (1.0 - K / biquadR[1] + K * K) * norm; //for Bandpasses while (--sampleFrames >= 0) { long double inputSampleL = *in1; long double inputSampleR = *in2; if (fabs(inputSampleL)<1.18e-43) inputSampleL = fpd * 1.18e-43; if (fabs(inputSampleR)<1.18e-43) inputSampleR = fpd * 1.18e-43; switch (processing) { case 0: case 1: break; case 2: if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //amplitude aspect allpasstemp = ax - 1; if (allpasstemp < 0 || allpasstemp > am) allpasstemp = am; inputSampleL -= aL[allpasstemp]*0.5; aL[ax] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= aR[allpasstemp]*0.5; aR[ax] = inputSampleR; inputSampleR *= 0.5; ax--; if (ax < 0 || ax > am) {ax = am;} inputSampleL += (aL[ax]); inputSampleR += (aR[ax]); //a single Midiverb-style allpass if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //amplitude aspect allpasstemp = bx - 1; if (allpasstemp < 0 || allpasstemp > bm) allpasstemp = bm; inputSampleL -= bL[allpasstemp]*0.5; bL[bx] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= bR[allpasstemp]*0.5; bR[bx] = inputSampleR; inputSampleR *= 0.5; bx--; if (bx < 0 || bx > bm) {bx = bm;} inputSampleL += (bL[bx]); inputSampleR += (bR[bx]); //a single Midiverb-style allpass if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //amplitude aspect allpasstemp = cx - 1; if (allpasstemp < 0 || allpasstemp > cm) allpasstemp = cm; inputSampleL -= cL[allpasstemp]*0.5; cL[cx] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= cR[allpasstemp]*0.5; cR[cx] = inputSampleR; inputSampleR *= 0.5; cx--; if (cx < 0 || cx > cm) {cx = cm;} inputSampleL += (cL[cx]); inputSampleR += (cR[cx]); //a single Midiverb-style allpass if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //amplitude aspect allpasstemp = dx - 1; if (allpasstemp < 0 || allpasstemp > dm) allpasstemp = dm; inputSampleL -= dL[allpasstemp]*0.5; dL[dx] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= dR[allpasstemp]*0.5; dR[dx] = inputSampleR; inputSampleR *= 0.5; dx--; if (dx < 0 || dx > dm) {dx = dm;} inputSampleL += (dL[dx]); inputSampleR += (dR[dx]); //a single Midiverb-style allpass if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //amplitude aspect inputSampleL *= 0.63679; inputSampleR *= 0.63679; //scale it to 0dB output at full blast //PeaksOnly break; case 3: double trim; trim = 2.302585092994045684017991; //natural logarithm of 10 long double slewSample; slewSample = (inputSampleL - lastSampleL)*trim; lastSampleL = inputSampleL; if (slewSample > 1.0) slewSample = 1.0; if (slewSample < -1.0) slewSample = -1.0; inputSampleL = slewSample; slewSample = (inputSampleR - lastSampleR)*trim; lastSampleR = inputSampleR; if (slewSample > 1.0) slewSample = 1.0; if (slewSample < -1.0) slewSample = -1.0; inputSampleR = slewSample; //SlewOnly break; case 4: double iirAmount; iirAmount = (2250/44100.0) / overallscale; double gain; gain = 1.42; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; iirSampleAL = (iirSampleAL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleAL; iirSampleAR = (iirSampleAR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleAR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleBL = (iirSampleBL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleBL; iirSampleBR = (iirSampleBR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleBR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleCL = (iirSampleCL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleCL; iirSampleCR = (iirSampleCR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleCR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleDL = (iirSampleDL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleDL; iirSampleDR = (iirSampleDR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleDR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleEL = (iirSampleEL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleEL; iirSampleER = (iirSampleER * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleER; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleFL = (iirSampleFL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleFL; iirSampleFR = (iirSampleFR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleFR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleGL = (iirSampleGL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleGL; iirSampleGR = (iirSampleGR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleGR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleHL = (iirSampleHL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleHL; iirSampleHR = (iirSampleHR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleHR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleIL = (iirSampleIL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleIL; iirSampleIR = (iirSampleIR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleIR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleJL = (iirSampleJL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleJL; iirSampleJR = (iirSampleJR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleJR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleKL = (iirSampleKL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleKL; iirSampleKR = (iirSampleKR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleKR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleLL = (iirSampleLL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleLL; iirSampleLR = (iirSampleLR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleLR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleML = (iirSampleML * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleML; iirSampleMR = (iirSampleMR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleMR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleNL = (iirSampleNL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleNL; iirSampleNR = (iirSampleNR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleNR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleOL = (iirSampleOL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleOL; iirSampleOR = (iirSampleOR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleOR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSamplePL = (iirSamplePL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSamplePL; iirSamplePR = (iirSamplePR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSamplePR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleQL = (iirSampleQL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleQL; iirSampleQR = (iirSampleQR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleQR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleRL = (iirSampleRL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleRL; iirSampleRR = (iirSampleRR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleRR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleSL = (iirSampleSL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleSL; iirSampleSR = (iirSampleSR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleSR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleTL = (iirSampleTL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleTL; iirSampleTR = (iirSampleTR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleTR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleUL = (iirSampleUL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleUL; iirSampleUR = (iirSampleUR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleUR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleVL = (iirSampleVL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleVL; iirSampleVR = (iirSampleVR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleVR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleWL = (iirSampleWL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleWL; iirSampleWR = (iirSampleWR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleWR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleXL = (iirSampleXL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleXL; iirSampleXR = (iirSampleXR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleXR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleYL = (iirSampleYL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleYL; iirSampleYR = (iirSampleYR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleYR; inputSampleL *= gain; inputSampleR *= gain; gain = ((gain-1)*0.75)+1; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; iirSampleZL = (iirSampleZL * (1.0-iirAmount)) + (inputSampleL * iirAmount); inputSampleL = iirSampleZL; iirSampleZR = (iirSampleZR * (1.0-iirAmount)) + (inputSampleR * iirAmount); inputSampleR = iirSampleZR; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; //SubsOnly break; case 5: case 6: long double mid; mid = inputSampleL + inputSampleR; long double side; side = inputSampleL - inputSampleR; if (processing < 6) side = 0.0; else mid = 0.0; //mono monitoring, or side-only monitoring inputSampleL = (mid+side)/2.0; inputSampleR = (mid-side)/2.0; break; case 7: case 8: case 9: case 10: case 11: //Bandpass: changes in EQ are up in the variable defining, not here //7 Vinyl, 8 9 10 Aurat, 11 Phone if (processing == 9) {inputSampleR = (inputSampleL + inputSampleR)*0.5;inputSampleL = 0.0;} if (processing == 10) {inputSampleL = (inputSampleL + inputSampleR)*0.5;inputSampleR = 0.0;} if (processing == 11) {long double M; M = (inputSampleL + inputSampleR)*0.5; inputSampleL = M;inputSampleR = M;} inputSampleL = sin(inputSampleL); inputSampleR = sin(inputSampleR); //encode Console5: good cleanness long double tempSampleL; tempSampleL = (inputSampleL * biquadL[2]) + biquadL[7]; biquadL[7] = (-tempSampleL * biquadL[5]) + biquadL[8]; biquadL[8] = (inputSampleL * biquadL[4]) - (tempSampleL * biquadL[6]); inputSampleL = tempSampleL; //like mono AU, 7 and 8 store L channel long double tempSampleR; tempSampleR = (inputSampleR * biquadR[2]) + biquadR[7]; biquadR[7] = (-tempSampleR * biquadR[5]) + biquadR[8]; biquadR[8] = (inputSampleR * biquadR[4]) - (tempSampleR * biquadR[6]); inputSampleR = tempSampleR; // we are using the mono configuration if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; //without this, you can get a NaN condition where it spits out DC offset at full blast! inputSampleL = asin(inputSampleL); inputSampleR = asin(inputSampleR); //amplitude aspect break; case 12: case 13: case 14: case 15: if (processing == 12) {inputSampleL *= 0.855; inputSampleR *= 0.855;} if (processing == 13) {inputSampleL *= 0.748; inputSampleR *= 0.748;} if (processing == 14) {inputSampleL *= 0.713; inputSampleR *= 0.713;} if (processing == 15) {inputSampleL *= 0.680; inputSampleR *= 0.680;} //we do a volume compensation immediately to gain stage stuff cleanly inputSampleL = sin(inputSampleL); inputSampleR = sin(inputSampleR); long double drySampleL; drySampleL = inputSampleL; long double drySampleR; drySampleR = inputSampleR; //everything runs 'inside' Console long double bass; bass = (processing * processing * 0.00001) / overallscale; //we are using the iir filters from out of SubsOnly mid = inputSampleL + inputSampleR; side = inputSampleL - inputSampleR; iirSampleAL = (iirSampleAL * (1.0 - (bass*0.618))) + (side * bass * 0.618); side = side - iirSampleAL; inputSampleL = (mid+side)/2.0; inputSampleR = (mid-side)/2.0; //bass narrowing filter allpasstemp = ax - 1; if (allpasstemp < 0 || allpasstemp > am) allpasstemp = am; inputSampleL -= aL[allpasstemp]*0.5; aL[ax] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= aR[allpasstemp]*0.5; aR[ax] = inputSampleR; inputSampleR *= 0.5; ax--; if (ax < 0 || ax > am) {ax = am;} inputSampleL += (aL[ax])*0.5; inputSampleR += (aR[ax])*0.5; if (ax == am) {inputSampleL += (aL[0])*0.5; inputSampleR += (aR[0])*0.5;} else {inputSampleL += (aL[ax+1])*0.5; inputSampleR += (aR[ax+1])*0.5;} //a darkened Midiverb-style allpass if (processing == 12) {inputSampleL *= 0.125; inputSampleR *= 0.125;} if (processing == 13) {inputSampleL *= 0.25; inputSampleR *= 0.25;} if (processing == 14) {inputSampleL *= 0.30; inputSampleR *= 0.30;} if (processing == 15) {inputSampleL *= 0.35; inputSampleR *= 0.35;} //Cans A suppresses the crossfeed more, Cans B makes it louder drySampleL += inputSampleR; drySampleR += inputSampleL; //the crossfeed allpasstemp = dx - 1; if (allpasstemp < 0 || allpasstemp > dm) allpasstemp = dm; inputSampleL -= dL[allpasstemp]*0.5; dL[dx] = inputSampleL; inputSampleL *= 0.5; inputSampleR -= dR[allpasstemp]*0.5; dR[dx] = inputSampleR; inputSampleR *= 0.5; dx--; if (dx < 0 || dx > dm) {dx = dm;} inputSampleL += (dL[dx])*0.5; inputSampleR += (dR[dx])*0.5; if (dx == dm) {inputSampleL += (dL[0])*0.5; inputSampleR += (dR[0])*0.5;} else {inputSampleL += (dL[dx+1])*0.5; inputSampleR += (dR[dx+1])*0.5;} //a darkened Midiverb-style allpass, which is stretching the previous one even more inputSampleL *= 0.25; inputSampleR *= 0.25; //for all versions of Cans the second level of bloom is this far down //and, remains on the opposite speaker rather than crossing again to the original side drySampleL += inputSampleR; drySampleR += inputSampleL; //add the crossfeed and very faint extra verbyness inputSampleL = drySampleL; inputSampleR = drySampleR; //and output our can-opened headphone feed mid = inputSampleL + inputSampleR; side = inputSampleL - inputSampleR; iirSampleAR = (iirSampleAR * (1.0 - bass)) + (side * bass); side = side - iirSampleAR; inputSampleL = (mid+side)/2.0; inputSampleR = (mid-side)/2.0; //bass narrowing filter if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; inputSampleL = asin(inputSampleL); if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; inputSampleR = asin(inputSampleR); //ConsoleBuss processing break; case 16: long double inputSample = (inputSampleL + inputSampleR) * 0.5; inputSampleL = -inputSample; inputSampleR = inputSample; break; } //begin Not Just Another Dither if (processing == 1) { inputSampleL = inputSampleL * 32768.0; //or 16 bit option inputSampleR = inputSampleR * 32768.0; //or 16 bit option } else { inputSampleL = inputSampleL * 8388608.0; //for literally everything else inputSampleR = inputSampleR * 8388608.0; //we will apply the 24 bit NJAD } //on the not unreasonable assumption that we are very likely playing back on 24 bit DAC //if we're not, then all we did was apply a Benford Realness function at 24 bits down. bool cutbinsL; cutbinsL = false; bool cutbinsR; cutbinsR = false; long double drySampleL; drySampleL = inputSampleL; long double drySampleR; drySampleR = inputSampleR; inputSampleL -= noiseShapingL; inputSampleR -= noiseShapingR; //NJAD L long double benfordize; benfordize = floor(inputSampleL); while (benfordize >= 1.0) benfordize /= 10; while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10; int hotbinA; hotbinA = floor(benfordize); //hotbin becomes the Benford bin value for this number floored long double totalA; totalA = 0; if ((hotbinA > 0) && (hotbinA < 10)) { bynL[hotbinA] += 1; if (bynL[hotbinA] > 982) cutbinsL = true; totalA += (301-bynL[1]); totalA += (176-bynL[2]); totalA += (125-bynL[3]); totalA += (97-bynL[4]); totalA += (79-bynL[5]); totalA += (67-bynL[6]); totalA += (58-bynL[7]); totalA += (51-bynL[8]); totalA += (46-bynL[9]); bynL[hotbinA] -= 1; } else hotbinA = 10; //produce total number- smaller is closer to Benford real benfordize = ceil(inputSampleL); while (benfordize >= 1.0) benfordize /= 10; while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10; int hotbinB; hotbinB = floor(benfordize); //hotbin becomes the Benford bin value for this number ceiled long double totalB; totalB = 0; if ((hotbinB > 0) && (hotbinB < 10)) { bynL[hotbinB] += 1; if (bynL[hotbinB] > 982) cutbinsL = true; totalB += (301-bynL[1]); totalB += (176-bynL[2]); totalB += (125-bynL[3]); totalB += (97-bynL[4]); totalB += (79-bynL[5]); totalB += (67-bynL[6]); totalB += (58-bynL[7]); totalB += (51-bynL[8]); totalB += (46-bynL[9]); bynL[hotbinB] -= 1; } else hotbinB = 10; //produce total number- smaller is closer to Benford real long double outputSample; if (totalA < totalB) {bynL[hotbinA] += 1; outputSample = floor(inputSampleL);} else {bynL[hotbinB] += 1; outputSample = floor(inputSampleL+1);} //assign the relevant one to the delay line //and floor/ceil signal accordingly if (cutbinsL) { bynL[1] *= 0.99; bynL[2] *= 0.99; bynL[3] *= 0.99; bynL[4] *= 0.99; bynL[5] *= 0.99; bynL[6] *= 0.99; bynL[7] *= 0.99; bynL[8] *= 0.99; bynL[9] *= 0.99; bynL[10] *= 0.99; } noiseShapingL += outputSample - drySampleL; if (noiseShapingL > fabs(inputSampleL)) noiseShapingL = fabs(inputSampleL); if (noiseShapingL < -fabs(inputSampleL)) noiseShapingL = -fabs(inputSampleL); if (processing == 1) inputSampleL = outputSample / 32768.0; else inputSampleL = outputSample / 8388608.0; if (inputSampleL > 1.0) inputSampleL = 1.0; if (inputSampleL < -1.0) inputSampleL = -1.0; //finished NJAD L //NJAD R benfordize = floor(inputSampleR); while (benfordize >= 1.0) benfordize /= 10; while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10; hotbinA = floor(benfordize); //hotbin becomes the Benford bin value for this number floored totalA = 0; if ((hotbinA > 0) && (hotbinA < 10)) { bynR[hotbinA] += 1; if (bynR[hotbinA] > 982) cutbinsR = true; totalA += (301-bynR[1]); totalA += (176-bynR[2]); totalA += (125-bynR[3]); totalA += (97-bynR[4]); totalA += (79-bynR[5]); totalA += (67-bynR[6]); totalA += (58-bynR[7]); totalA += (51-bynR[8]); totalA += (46-bynR[9]); bynR[hotbinA] -= 1; } else hotbinA = 10; //produce total number- smaller is closer to Benford real benfordize = ceil(inputSampleR); while (benfordize >= 1.0) benfordize /= 10; while (benfordize < 1.0 && benfordize > 0.0000001) benfordize *= 10; hotbinB = floor(benfordize); //hotbin becomes the Benford bin value for this number ceiled totalB = 0; if ((hotbinB > 0) && (hotbinB < 10)) { bynR[hotbinB] += 1; if (bynR[hotbinB] > 982) cutbinsR = true; totalB += (301-bynR[1]); totalB += (176-bynR[2]); totalB += (125-bynR[3]); totalB += (97-bynR[4]); totalB += (79-bynR[5]); totalB += (67-bynR[6]); totalB += (58-bynR[7]); totalB += (51-bynR[8]); totalB += (46-bynR[9]); bynR[hotbinB] -= 1; } else hotbinB = 10; //produce total number- smaller is closer to Benford real if (totalA < totalB) {bynR[hotbinA] += 1; outputSample = floor(inputSampleR);} else {bynR[hotbinB] += 1; outputSample = floor(inputSampleR+1);} //assign the relevant one to the delay line //and floor/ceil signal accordingly if (cutbinsR) { bynR[1] *= 0.99; bynR[2] *= 0.99; bynR[3] *= 0.99; bynR[4] *= 0.99; bynR[5] *= 0.99; bynR[6] *= 0.99; bynR[7] *= 0.99; bynR[8] *= 0.99; bynR[9] *= 0.99; bynR[10] *= 0.99; } noiseShapingR += outputSample - drySampleR; if (noiseShapingR > fabs(inputSampleR)) noiseShapingR = fabs(inputSampleR); if (noiseShapingR < -fabs(inputSampleR)) noiseShapingR = -fabs(inputSampleR); if (processing == 1) inputSampleR = outputSample / 32768.0; else inputSampleR = outputSample / 8388608.0; if (inputSampleR > 1.0) inputSampleR = 1.0; if (inputSampleR < -1.0) inputSampleR = -1.0; //finished NJAD R //does not use 64 bit stereo floating point dither *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } }
65.256951
140
0.569516
jbloit
15cfb5d87983ddf99b425ae960cbfe3584a0de92
13,750
cc
C++
RecoLocalMuon/RPCRecHit/test/RPCRecHitReader.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
RecoLocalMuon/RPCRecHit/test/RPCRecHitReader.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
RecoLocalMuon/RPCRecHit/test/RPCRecHitReader.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/* * Program to calculate the global and local efficiency of * RPC chambers using a software autotrigger and * a linear reconstruction of tracks. * * Author: R. Trentadue - Bari University */ #include "RPCRecHitReader.h" #include <memory> #include <fstream> #include <iostream> #include <string> #include <cmath> #include <cmath> #include <vector> #include <iomanip> #include <set> #include <stdio.h> #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/RPCRecHit/interface/RPCRecHit.h" #include "DataFormats/RPCRecHit/interface/RPCRecHitCollection.h" #include "DataFormats/RPCDigi/interface/RPCDigiCollection.h" #include "SimDataFormats/TrackingHit/interface/PSimHitContainer.h" #include "Geometry/RPCGeometry/interface/RPCGeometry.h" #include "Geometry/RPCGeometry/interface/RPCRoll.h" #include "Geometry/Records/interface/MuonGeometryRecord.h" #include "DataFormats/GeometryVector/interface/GlobalPoint.h" #include "DataFormats/GeometryVector/interface/GlobalVector.h" #include "DataFormats/GeometryVector/interface/LocalPoint.h" #include "DataFormats/GeometryVector/interface/LocalVector.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESHandle.h" #include "TFile.h" #include "TVector3.h" #include "TH1F.h" #include "TH2F.h" #include "TF1.h" #include "TF2.h" #include "TVectorT.h" #include "TGraph.h" #include <map> Double_t linearF(Double_t* x, Double_t* par) { Double_t y = 0.; y = par[0] * (*x) + par[1]; return y; } // Constructor RPCRecHitReader::RPCRecHitReader(const edm::ParameterSet& pset) : _phi(0) { // Get the various input parameters fOutputFileName = pset.getUntrackedParameter<std::string>("HistOutFile"); recHitLabel1 = pset.getUntrackedParameter<std::string>("recHitLabel1"); recHitLabel2 = pset.getUntrackedParameter<std::string>("recHitLabel2"); region = pset.getUntrackedParameter<int>("region", 0); wheel = pset.getUntrackedParameter<int>("wheel", 1); sector = pset.getUntrackedParameter<int>("sector", 10); station = pset.getUntrackedParameter<int>("station"); layer = pset.getUntrackedParameter<int>("layer"); subsector = pset.getUntrackedParameter<int>("subsector"); _trigConfig.clear(); _trigRPC1 = pset.getUntrackedParameter<bool>("trigRPC1"); _trigRPC2 = pset.getUntrackedParameter<bool>("trigRPC2"); _trigRPC3 = pset.getUntrackedParameter<bool>("trigRPC3"); _trigRPC4 = pset.getUntrackedParameter<bool>("trigRPC4"); _trigRPC5 = pset.getUntrackedParameter<bool>("trigRPC5"); _trigRPC6 = pset.getUntrackedParameter<bool>("trigRPC6"); _trigConfig.push_back(_trigRPC1); _trigConfig.push_back(_trigRPC2); _trigConfig.push_back(_trigRPC3); _trigConfig.push_back(_trigRPC4); _trigConfig.push_back(_trigRPC5); _trigConfig.push_back(_trigRPC6); } void RPCRecHitReader::beginRun(const edm::Run&, const edm::EventSetup& iSetup) { edm::ESHandle<RPCGeometry> rpcGeo; iSetup.get<MuonGeometryRecord>().get(rpcGeo); RPCDetId id(region, wheel, station, sector, layer, subsector, 3); const RPCRoll* roll = dynamic_cast<const RPCRoll*>(rpcGeo->roll(id)); _rollEff = roll; fOutputFile = new TFile(fOutputFileName.c_str(), "RECREATE"); fout = new std::fstream("RecHitOut.dat", std::ios::out); _mapLayer[0] = -413.675; _mapLayer[1] = -448.675; _mapLayer[2] = -494.975; _mapLayer[3] = -529.975; _mapLayer[4] = -602.150; _mapLayer[5] = -704.550; unsigned int layer = 0; for (unsigned int i = 0; i < _trigConfig.size(); ++i) { if (_trigConfig[i] == false) layer = i; } yLayer = _mapLayer[layer]; if (sector != 10) { GlobalPoint cntr10, cntr11; for (RPCGeometry::DetContainer::const_iterator it = rpcGeo->dets().begin(); it < rpcGeo->dets().end(); it++) { RPCRoll const* ir = dynamic_cast<const RPCRoll*>(*it); RPCDetId id = ir->id(); const Surface& bSurface = ir->surface(); if (id.region() == region && id.ring() == wheel && id.sector() == 10 && id.station() == 1 && id.layer() == 1) { LocalPoint orgn(0, 0, 0); cntr10 = bSurface.toGlobal(orgn); } if (id.region() == region && id.ring() == wheel && id.sector() == sector && id.station() == 1 && id.layer() == 1) { LocalPoint orng(0, 0, 0); cntr11 = bSurface.toGlobal(orng); } } float radius = 413.675; float crd = sqrt(std::pow((cntr10.x() - cntr11.x()), 2) + std::pow((cntr10.y() - cntr11.y()), 2)); _phi = 2 * asin(crd / (2 * radius)); } *fout << "Angolo di rotazione = " << _phi << std::endl; _trigger = 0; _triggerGOOD = 0; _spurious = 0; _spuriousPeak = 0; _efficiencyBAD = 0; _efficiencyGOOD = 0; _efficiencyBEST = 0; histoXY = new TH2F("HistoXY", "Histoxy", 300, -300, 300, 300, -900, -300); histoSlope = new TH1F("Slope", "Slope", 100, -100, 100); histoChi2 = new TH1F("Chi2", "Chi2", 100, 0, 10000); histoRes = new TH1F("Residui", "Residui", 500, -100, 100); histoRes1 = new TH1F("Single Cluster Residuals", "Single Cluster Residuals", 500, -100, 100); histoRes2 = new TH1F("Double Cluster Residuals", "Double Cluster Residuals", 500, -100, 100); histoRes3 = new TH1F("Triple Cluster Residuals", "Triple Cluster Residuals", 500, -100, 100); histoPool1 = new TH1F("Single Cluster Size Pools", "Single Cluster Size Pools", 500, -100, 100); histoPool2 = new TH1F("Double Cluster Size Pools", "Double Cluster Size Pools", 500, -100, 100); histoPool3 = new TH1F("Triple Cluster Size Pools", "Triple Cluster Size Pools", 500, -100, 100); histoExpectedOcc = new TH1F("ExpectedOcc", "ExpectedOcc", 100, -0.5, 99.5); histoRealOcc = new TH1F("RealOcc", "RealOcc", 100, -0.5, 99.5); histoLocalEff = new TH1F("LocalEff", "LocalEff", 100, -0.5, 99.5); return; } // The Analysis (the main) void RPCRecHitReader::analyze(const edm::Event& event, const edm::EventSetup& eventSetup) { if (event.id().event() % 100 == 0) std::cout << " Event analysed #Run: " << event.id().run() << " #Event: " << event.id().event() << std::endl; // Get the RPC Geometry : edm::ESHandle<RPCGeometry> rpcGeom; eventSetup.get<MuonGeometryRecord>().get(rpcGeom); // Get the RecHits collection : edm::Handle<RPCRecHitCollection> recHits; event.getByLabel(recHitLabel1, recHitLabel2, recHits); //---------------------------------------------------------------------- //--------------- Loop over rechits ----------------------------------- // Build iterator for rechits and loop : RPCRecHitCollection::const_iterator recIt; std::vector<float> globalX, globalY, globalZ; std::vector<float> effX, effY, effZ; std::vector<float> errX, clus, rescut; std::map<int, bool> _mapTrig; TF1* func = new TF1("linearF", linearF, -300, 300, 2); func->SetParameters(0., 0.); func->SetParNames("angCoef", "interc"); for (recIt = recHits->begin(); recIt != recHits->end(); recIt++) { // Find chamber with rechits in RPC RPCDetId id = (RPCDetId)(*recIt).rpcId(); const RPCRoll* roll = dynamic_cast<const RPCRoll*>(rpcGeom->roll(id)); const Surface& bSurface = roll->surface(); if ((roll->isForward())) return; LocalPoint rhitlocal = (*recIt).localPosition(); LocalError locerr = (*recIt).localPositionError(); GlobalPoint rhitglob = bSurface.toGlobal(rhitlocal); float x = 0, y = 0, z = 0; if (id.sector() > 10 || (1 <= id.sector() && id.sector() <= 4)) { x = rhitglob.x() * cos(-_phi) - rhitglob.y() * sin(-_phi); y = rhitglob.y() * cos(-_phi) + rhitglob.x() * sin(-_phi); z = rhitglob.z(); } else if (5 <= id.sector() && id.sector() <= 9) { x = rhitglob.x() * cos(_phi) - rhitglob.y() * sin(_phi); y = rhitglob.y() * cos(_phi) + rhitglob.x() * sin(_phi); z = rhitglob.z(); } else if (id.sector() == 10) { x = rhitglob.x(); y = rhitglob.y(); z = rhitglob.z(); } if (_trigConfig[layerRecHit(*recIt)] == true && id.sector() == sector) { _mapTrig[layerRecHit(*recIt)] = true; globalX.push_back(x); globalY.push_back(y); globalZ.push_back(z); } else if (_trigConfig[layerRecHit(*recIt)] == false && id.sector() == sector) { effX.push_back(rhitglob.x()); effY.push_back(rhitglob.y()); effZ.push_back(rhitglob.z()); errX.push_back(locerr.xx()); clus.push_back((*recIt).clusterSize()); } else { continue; } } if (_mapTrig.size() == 0) return; char folder[128]; sprintf(folder, "HistoXYFit_%llu", event.id().event()); TH1F* histoXYFit = new TH1F(folder, folder, 300, -300, 300); for (unsigned int i = 0; i < globalX.size(); ++i) { histoXY->Fill(globalX[i], globalY[i]); histoXYFit->Fill(globalX[i], globalY[i]); } //-------- PRIMA STIMA EFFICIENZA ---------------------- if (_mapTrig.size() > 4) { _trigger++; if (effX.size() > 0) _efficiencyBAD++; //----------------------------------------------------- //--------------- FIT SULLE TRACCE--------------------- histoXYFit->Fit("linearF", "r"); histoSlope->Fill(func->GetParameter(0)); histoChi2->Fill(func->GetChisquare()); if (func->GetChisquare() < 0.5) { _triggerGOOD++; float prepoint = ((yLayer)-func->GetParameter(1)) / func->GetParameter(0); LocalPoint expPoint(prepoint, 0, 0); float expStrip = _rollEff->strip(expPoint); histoExpectedOcc->Fill(expStrip); if (effX.size() > 0) { _efficiencyGOOD++; unsigned int k = 0; for (unsigned int i = 0; i < effX.size(); ++i) { float res = (effX[i] - prepoint); float errcl = errX[i] * clus[i]; float pools = res / errX[i]; histoRes->Fill(res); if (clus[i] == 1) { histoRes1->Fill(res); histoPool1->Fill(pools); } else if (clus[i] == 2) { histoRes2->Fill(res); histoPool2->Fill(pools); } else if (clus[i] == 3) { histoRes3->Fill(res); histoPool3->Fill(pools); } if (fabs(res) > errcl) { _spurious++; *fout << "Il residuo è maggiore di " << errcl << " "; *fout << " #Event: " << event.id().event() << std::endl; } else if (fabs(res) <= errcl) { k++; rescut.push_back(res); if (k == 1) histoRealOcc->Fill(expStrip); } } if (rescut.size() > 1) { _spuriousPeak += rescut.size() - 1; *fout << "Ci sono più RecHit = " << rescut.size() << " "; *fout << " #Event: " << event.id().event() << std::endl; } } else { *fout << "Camera non efficiente!" << " " << " #Event: " << event.id().event() << std::endl; } } } else { *fout << "Non esiste RecHit appartenente a piani di interesse!" << " "; *fout << " #Event: " << event.id().event() << std::endl; } } unsigned int RPCRecHitReader::layerRecHit(RPCRecHit rechit) { unsigned int layer = 0; RPCDetId id = (RPCDetId)(rechit).rpcId(); if (id.station() == 1 && id.layer() == 1) layer = 0; if (id.station() == 1 && id.layer() == 2) layer = 1; if (id.station() == 2 && id.layer() == 1) layer = 2; if (id.station() == 2 && id.layer() == 2) layer = 3; if (id.station() == 3 && id.layer() == 1) layer = 4; if (id.station() == 4 && id.layer() == 1) layer = 5; return layer; } void RPCRecHitReader::endJob() { TF1* bell = new TF1("Gaussiana", "gaus", -50, 50); histoRes->Fit("Gaussiana", "r"); float sgmp = bell->GetParameter(1) + 3 * (bell->GetParameter(2)); float sgmm = bell->GetParameter(1) - 3 * (bell->GetParameter(2)); int binmax = histoRes->GetXaxis()->FindBin(sgmp); int binmin = histoRes->GetXaxis()->FindBin(sgmm); _efficiencyBEST = histoRes->Integral(binmin, binmax); _efficiencyBEST -= _spuriousPeak; *fout << "Media = " << bell->GetParameter(1) << " Deviazione standard = " << bell->GetParameter(2) << std::endl; *fout << "Taglio a 3 sigma" << std::endl; for (unsigned int i = 1; i <= 100; ++i) { if (histoExpectedOcc->GetBinContent(i) != 0) { float eff = histoRealOcc->GetBinContent(i) / histoExpectedOcc->GetBinContent(i); float erreff = sqrt(eff * (1 - eff) / histoExpectedOcc->GetBinContent(i)); histoLocalEff->SetBinContent(i, eff); histoLocalEff->SetBinError(i, erreff); } } histoRes1->Fit("Gaussiana", "r"); histoRes2->Fit("Gaussiana", "r"); histoRes3->Fit("Gaussiana", "r"); histoPool1->Fit("Gaussiana", "r"); histoPool2->Fit("Gaussiana", "r"); histoPool3->Fit("Gaussiana", "r"); fOutputFile->Write(); fOutputFile->Close(); return; } // Destructor RPCRecHitReader::~RPCRecHitReader() { *fout << "Trigger Complessivi = " << _trigger << std::endl; *fout << "Trigger GOOD = " << _triggerGOOD << std::endl; *fout << "Efficiency BAD Counter = " << _efficiencyBAD << std::endl; *fout << "Efficiency GOOD Counter = " << _efficiencyGOOD << std::endl; *fout << "Efficiency BEST Counter = " << _efficiencyBEST << std::endl; *fout << "Spurious counter = " << _spurious << std::endl; *fout << "Efficienza BAD = " << _efficiencyBAD / _trigger << std::endl; *fout << "Efficienza GOOD = " << _efficiencyGOOD / _triggerGOOD << std::endl; *fout << "Efficienza BEST = " << _efficiencyBEST / _triggerGOOD << std::endl; } DEFINE_FWK_MODULE(RPCRecHitReader);
33.783784
117
0.614109
ckamtsikis
15d676c6180ce90376b5d3c6186a56672ded86c5
2,928
hpp
C++
filterbuf.hpp
hmito/hmLib
0f2515ba9c99c06d02e2fa633eeae73bcd793983
[ "MIT" ]
null
null
null
filterbuf.hpp
hmito/hmLib
0f2515ba9c99c06d02e2fa633eeae73bcd793983
[ "MIT" ]
null
null
null
filterbuf.hpp
hmito/hmLib
0f2515ba9c99c06d02e2fa633eeae73bcd793983
[ "MIT" ]
1
2015-09-22T03:32:11.000Z
2015-09-22T03:32:11.000Z
#ifndef HMLIB_FILTERBUF_INC #define HMLIB_FILTERBUF_INC 102 # /*===filterbuf=== filterbuf_v1_02/130101 hmIto iostreamに対応 */ #include<streambuf> #include<iostream> namespace hmLib{ template<class _Elem,class _Traits=std::char_traits<_Elem>> class basic_filterbuf{ protected: typedef std::basic_istream<_Elem,_Traits> istream; typedef std::basic_ostream<_Elem,_Traits> ostream; typedef std::basic_iostream<_Elem,_Traits> iostream; typedef basic_filterbuf<_Elem,_Traits> my_type; typedef std::ios::pos_type pos_type; typedef std::ios::off_type off_type; private: iostream* ptr_io; istream* ptr_i; ostream* ptr_o; public: basic_filterbuf() :ptr_io(nullptr) ,ptr_o(nullptr) ,ptr_i(nullptr){ } basic_filterbuf(iostream& io_) :ptr_io(&io_) ,ptr_o(&io_) ,ptr_i(&io_){ } basic_filterbuf(istream& in_) :ptr_io(nullptr) ,ptr_o(nullptr) ,ptr_i(&in_){ } basic_filterbuf(ostream& out_) :ptr_io(nullptr) ,ptr_o(&out_) ,ptr_i(nullptr){ } public: iostream& ref_io(){return *ptr_io;} istream& ref_i(){return *ptr_i;} ostream& ref_o(){return *ptr_o;} const iostream& ref_io(){return *ptr_io;} const istream& cref_i()const{return *ptr_i;} const ostream& cref_o()const{return *ptr_o;} bool has_i()const{return ptr_i!=nullptr;} bool has_o()const{return ptr_o!=nullptr;} bool has_io()const{return has_io!=nullptr;} bool is_open()const{return has_i() || has_o();} bool open(iostream& io_){ if(is_open())return true; ptr_io=&io_; ptr_o=&io_; ptr_i=&io_; return false; } bool open(ostream& out_){ if(is_open())return true; ptr_io=nullptr; ptr_o=&out_; ptr_i=nullptr; return false; } bool open(istream& in_){ if(is_open())return true; ptr_io=nullptr; ptr_o=nullptr; ptr_i=&in_; return false; } bool close(){ if(!is_open())return true; ptr_io=nullptr; ptr_o=nullptr; ptr_i=nullptr; return false; } pos_type tell_i()const{ hmLib_assert(has_i(),"There is no istream"); return ptr_i->tellg(); } pos_type tell_o()const{ hmLib_assert(has_o(),"There is no ostream"); return ptr_o->tellp(); } void seek_i(pos_type pos){ hmLib_assert(has_i(),"There is no istream"); return ptr_i->seelg(pos); } void seek_o(pos_type pos){ hmLib_assert(has_o(),"There is no ostream"); return ptr_o->seelp(pos); } void seek_i(off_type off,std::ios_base::seekdir way){ hmLib_assert(has_i(),"There is no istream"); return ptr_i->seelg(off,way); } void seek_o(off_type off,std::ios_base::seekdir way){ hmLib_assert(has_o(),"There is no ostream"); return ptr_o->seelg(off,way); } bool eof_i()const{ hmLib_assert(has_i(),"There is no istream"); return ptr_i->eof(); } bool eof_o()const{ hmLib_assert(has_o(),"There is no ostream"); return ptr_o->eof(); } }; typedef basic_filterbuf<char,std::char_traits<char>> filterbuf; } # #endif
24.198347
64
0.682377
hmito
15db7a855b9baf11ffae5ba8058a1179edf08491
143
cpp
C++
hello-world/hello_world.cpp
akilram/exercism-cpp-answers
88d1247beb6ad003640efd5af87a05ad1a0d3a88
[ "MIT" ]
null
null
null
hello-world/hello_world.cpp
akilram/exercism-cpp-answers
88d1247beb6ad003640efd5af87a05ad1a0d3a88
[ "MIT" ]
null
null
null
hello-world/hello_world.cpp
akilram/exercism-cpp-answers
88d1247beb6ad003640efd5af87a05ad1a0d3a88
[ "MIT" ]
null
null
null
#include "hello_world.h" using namespace std; namespace hello_world { string hello() { return string("Hello, World!"); } }
11
34
0.622378
akilram
15ddc88593f6c838a589214d16593e10eff17a49
4,557
cpp
C++
ardupilot/libraries/AP_RangeFinder/AP_RangeFinder_PX4.cpp
quadrotor-IITKgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
1
2021-07-17T11:37:16.000Z
2021-07-17T11:37:16.000Z
ardupilot/libraries/AP_RangeFinder/AP_RangeFinder_PX4.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
ardupilot/libraries/AP_RangeFinder/AP_RangeFinder_PX4.cpp
arl-kgp/emulate_GPS
3c888d5b27b81fb17e74d995370f64bdb110fb65
[ "MIT" ]
null
null
null
// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <AP_HAL/AP_HAL.h> #if CONFIG_HAL_BOARD == HAL_BOARD_PX4 || CONFIG_HAL_BOARD == HAL_BOARD_VRBRAIN #include "AP_RangeFinder_PX4.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <drivers/drv_range_finder.h> #include <drivers/drv_hrt.h> #include <uORB/topics/distance_sensor.h> #include <stdio.h> #include <errno.h> extern const AP_HAL::HAL& hal; uint8_t AP_RangeFinder_PX4::num_px4_instances = 0; /* The constructor also initialises the rangefinder. Note that this constructor is not called until detect() returns true, so we already know that we should setup the rangefinder */ AP_RangeFinder_PX4::AP_RangeFinder_PX4(RangeFinder &_ranger, uint8_t instance, RangeFinder::RangeFinder_State &_state) : AP_RangeFinder_Backend(_ranger, instance, _state), _last_max_distance_cm(-1), _last_min_distance_cm(-1) { _fd = open_driver(); // consider this path used up num_px4_instances++; if (_fd == -1) { hal.console->printf("Unable to open PX4 rangefinder %u\n", num_px4_instances); set_status(RangeFinder::RangeFinder_NotConnected); return; } // average over up to 20 samples if (ioctl(_fd, SENSORIOCSQUEUEDEPTH, 20) != 0) { hal.console->printf("Failed to setup range finder queue\n"); set_status(RangeFinder::RangeFinder_NotConnected); return; } // initialise to connected but no data set_status(RangeFinder::RangeFinder_NoData); } /* close the file descriptor */ AP_RangeFinder_PX4::~AP_RangeFinder_PX4() { if (_fd != -1) { close(_fd); } } /* open the PX4 driver, returning the file descriptor */ int AP_RangeFinder_PX4::open_driver(void) { // work out the device path based on how many PX4 drivers we have loaded char path[] = RANGE_FINDER_BASE_DEVICE_PATH "n"; path[strlen(path)-1] = '0' + num_px4_instances; return open(path, O_RDONLY); } /* see if the PX4 driver is available */ bool AP_RangeFinder_PX4::detect(RangeFinder &_ranger, uint8_t instance) { int fd = open_driver(); if (fd == -1) { return false; } close(fd); return true; } void AP_RangeFinder_PX4::update(void) { if (_fd == -1) { set_status(RangeFinder::RangeFinder_NotConnected); return; } struct distance_sensor_s range_report; float sum = 0; uint16_t count = 0; if (_last_max_distance_cm != ranger._max_distance_cm[state.instance] || _last_min_distance_cm != ranger._min_distance_cm[state.instance]) { float max_distance = ranger._max_distance_cm[state.instance]*0.01f; float min_distance = ranger._min_distance_cm[state.instance]*0.01f; if (ioctl(_fd, RANGEFINDERIOCSETMAXIUMDISTANCE, (unsigned long)&max_distance) == 0 && ioctl(_fd, RANGEFINDERIOCSETMINIUMDISTANCE, (unsigned long)&min_distance) == 0) { _last_max_distance_cm = ranger._max_distance_cm[state.instance]; _last_min_distance_cm = ranger._min_distance_cm[state.instance]; } } while (::read(_fd, &range_report, sizeof(range_report)) == sizeof(range_report) && range_report.timestamp != _last_timestamp) { // take reading sum += range_report.current_distance; count++; _last_timestamp = range_report.timestamp; } // if we have not taken a reading in the last 0.2s set status to No Data if (hal.scheduler->micros64() - _last_timestamp >= 200000) { set_status(RangeFinder::RangeFinder_NoData); } if (count != 0) { state.distance_cm = sum / count * 100.0f; state.distance_cm += ranger._offset[state.instance]; // update range_valid state based on distance measured update_status(); } } #endif // CONFIG_HAL_BOARD
30.583893
120
0.686636
quadrotor-IITKgp
15e5947867da7a5c962299a141d2915102bcedf7
2,030
cpp
C++
bipedenv/cpp/Render/Shader.cpp
snumrl/DistributedDeepMimic
364d07dbdd5378b6d46d944e472e1632712ef5f6
[ "MIT" ]
null
null
null
bipedenv/cpp/Render/Shader.cpp
snumrl/DistributedDeepMimic
364d07dbdd5378b6d46d944e472e1632712ef5f6
[ "MIT" ]
null
null
null
bipedenv/cpp/Render/Shader.cpp
snumrl/DistributedDeepMimic
364d07dbdd5378b6d46d944e472e1632712ef5f6
[ "MIT" ]
null
null
null
#include "Render/Shader.h" static const std::string vertexShader = "./bipedenv/Shader/vertexshader.txt"; static const std::string fragShader = "./bipedenv/Shader/fragshader.txt"; namespace Shader{ GLuint program; void printShaderInfoLog(GLuint shader) { int len = 0; int charsWritten = 0; char* infoLog; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len); if (len > 0) { infoLog = (char*)malloc(len); glGetShaderInfoLog(shader, len, &charsWritten, infoLog); printf("%s\n", infoLog); free(infoLog); } } void printProgramInfoLog(GLuint obj) { int len = 0, charsWritten = 0; char* infoLog; glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &len); if (len > 0) { infoLog = (char*)malloc(len); glGetProgramInfoLog(obj, len, &charsWritten, infoLog); printf("%s\n", infoLog); free(infoLog); } } GLuint createProgram(std::string vertexShaderFile, std::string fragShaderFile){ FILE *f = fopen(vertexShaderFile.c_str(), "rb"); fseek(f, 0, SEEK_END); long fsize = ftell(f); fseek(f, 0, SEEK_SET); char *vert = (char *)malloc(fsize + 1); fread(vert, fsize, 1, f); fclose(f); vert[fsize] = 0; f = fopen(fragShaderFile.c_str(), "rb"); fseek(f, 0, SEEK_END); fsize = ftell(f); fseek(f, 0, SEEK_SET); char *frag = (char *)malloc(fsize + 1); fread(frag, fsize, 1, f); fclose(f); frag[fsize] = 0; auto createShader = [](const char* src, GLenum type) { GLuint shader = glCreateShader(type); glShaderSource(shader, 1, &src, NULL); glCompileShader(shader); printShaderInfoLog(shader); return shader; }; GLuint vertShader = createShader(vert, GL_VERTEX_SHADER); GLuint fragShader = createShader(frag, GL_FRAGMENT_SHADER); GLuint program = glCreateProgram(); glAttachShader(program, vertShader); glAttachShader(program, fragShader); glLinkProgram(program); printProgramInfoLog(program); return program; } void useShader(int on){ if(!program) program = createProgram(vertexShader, fragShader); glUseProgram(on ? program : 0); } }
26.025641
80
0.683251
snumrl
15e88fd4d0070e0407162c0b14b44d71cf3ce069
6,917
cpp
C++
build/moc/moc_CameraSpec.cpp
UNIST-ESCL/UNIST_GCS
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
[ "Apache-2.0" ]
1
2018-11-07T06:10:53.000Z
2018-11-07T06:10:53.000Z
build/moc/moc_CameraSpec.cpp
UNIST-ESCL/UNIST_GCS
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
[ "Apache-2.0" ]
null
null
null
build/moc/moc_CameraSpec.cpp
UNIST-ESCL/UNIST_GCS
f61f0c12bbb028869e4494f507ea8ab52c8c79c2
[ "Apache-2.0" ]
1
2018-11-07T06:10:47.000Z
2018-11-07T06:10:47.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'CameraSpec.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../src/MissionManager/CameraSpec.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'CameraSpec.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.9.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_CameraSpec_t { QByteArrayData data[13]; char stringdata0[143]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_CameraSpec_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_CameraSpec_t qt_meta_stringdata_CameraSpec = { { QT_MOC_LITERAL(0, 0, 10), // "CameraSpec" QT_MOC_LITERAL(1, 11, 12), // "dirtyChanged" QT_MOC_LITERAL(2, 24, 0), // "" QT_MOC_LITERAL(3, 25, 5), // "dirty" QT_MOC_LITERAL(4, 31, 11), // "sensorWidth" QT_MOC_LITERAL(5, 43, 5), // "Fact*" QT_MOC_LITERAL(6, 49, 12), // "sensorHeight" QT_MOC_LITERAL(7, 62, 10), // "imageWidth" QT_MOC_LITERAL(8, 73, 11), // "imageHeight" QT_MOC_LITERAL(9, 85, 11), // "focalLength" QT_MOC_LITERAL(10, 97, 9), // "landscape" QT_MOC_LITERAL(11, 107, 16), // "fixedOrientation" QT_MOC_LITERAL(12, 124, 18) // "minTriggerInterval" }, "CameraSpec\0dirtyChanged\0\0dirty\0" "sensorWidth\0Fact*\0sensorHeight\0" "imageWidth\0imageHeight\0focalLength\0" "landscape\0fixedOrientation\0" "minTriggerInterval" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_CameraSpec[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 8, 22, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 19, 2, 0x06 /* Public */, // signals: parameters QMetaType::Void, QMetaType::Bool, 3, // properties: name, type, flags 4, 0x80000000 | 5, 0x00095409, 6, 0x80000000 | 5, 0x00095409, 7, 0x80000000 | 5, 0x00095409, 8, 0x80000000 | 5, 0x00095409, 9, 0x80000000 | 5, 0x00095409, 10, 0x80000000 | 5, 0x00095409, 11, 0x80000000 | 5, 0x00095409, 12, 0x80000000 | 5, 0x00095409, 0 // eod }; void CameraSpec::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { CameraSpec *_t = static_cast<CameraSpec *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->dirtyChanged((*reinterpret_cast< bool(*)>(_a[1]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { typedef void (CameraSpec::*_t)(bool ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&CameraSpec::dirtyChanged)) { *result = 0; return; } } } else if (_c == QMetaObject::RegisterPropertyMetaType) { switch (_id) { default: *reinterpret_cast<int*>(_a[0]) = -1; break; case 7: case 6: case 5: case 4: case 3: case 2: case 1: case 0: *reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< Fact* >(); break; } } #ifndef QT_NO_PROPERTIES else if (_c == QMetaObject::ReadProperty) { CameraSpec *_t = static_cast<CameraSpec *>(_o); Q_UNUSED(_t) void *_v = _a[0]; switch (_id) { case 0: *reinterpret_cast< Fact**>(_v) = _t->sensorWidth(); break; case 1: *reinterpret_cast< Fact**>(_v) = _t->sensorHeight(); break; case 2: *reinterpret_cast< Fact**>(_v) = _t->imageWidth(); break; case 3: *reinterpret_cast< Fact**>(_v) = _t->imageHeight(); break; case 4: *reinterpret_cast< Fact**>(_v) = _t->focalLength(); break; case 5: *reinterpret_cast< Fact**>(_v) = _t->landscape(); break; case 6: *reinterpret_cast< Fact**>(_v) = _t->fixedOrientation(); break; case 7: *reinterpret_cast< Fact**>(_v) = _t->minTriggerInterval(); break; default: break; } } else if (_c == QMetaObject::WriteProperty) { } else if (_c == QMetaObject::ResetProperty) { } #endif // QT_NO_PROPERTIES } const QMetaObject CameraSpec::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_CameraSpec.data, qt_meta_data_CameraSpec, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *CameraSpec::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *CameraSpec::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_CameraSpec.stringdata0)) return static_cast<void*>(this); return QObject::qt_metacast(_clname); } int CameraSpec::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 1; } #ifndef QT_NO_PROPERTIES else if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty || _c == QMetaObject::ResetProperty || _c == QMetaObject::RegisterPropertyMetaType) { qt_static_metacall(this, _c, _id, _a); _id -= 8; } else if (_c == QMetaObject::QueryPropertyDesignable) { _id -= 8; } else if (_c == QMetaObject::QueryPropertyScriptable) { _id -= 8; } else if (_c == QMetaObject::QueryPropertyStored) { _id -= 8; } else if (_c == QMetaObject::QueryPropertyEditable) { _id -= 8; } else if (_c == QMetaObject::QueryPropertyUser) { _id -= 8; } #endif // QT_NO_PROPERTIES return _id; } // SIGNAL 0 void CameraSpec::dirtyChanged(bool _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } QT_WARNING_POP QT_END_MOC_NAMESPACE
33.741463
97
0.609802
UNIST-ESCL
15ebccd1e10788efac79dca03c3613f9be828fd4
6,866
cpp
C++
FPSLighting/Dependencies/DIRECTX/Samples/C++/Misc/DxDiagOutput/DxDiagOutput.cpp
billionare/FPSLighting
c7d646f51cf4dee360dcc7c8e2fd2821b421b418
[ "MIT" ]
null
null
null
FPSLighting/Dependencies/DIRECTX/Samples/C++/Misc/DxDiagOutput/DxDiagOutput.cpp
billionare/FPSLighting
c7d646f51cf4dee360dcc7c8e2fd2821b421b418
[ "MIT" ]
null
null
null
FPSLighting/Dependencies/DIRECTX/Samples/C++/Misc/DxDiagOutput/DxDiagOutput.cpp
billionare/FPSLighting
c7d646f51cf4dee360dcc7c8e2fd2821b421b418
[ "MIT" ]
null
null
null
//---------------------------------------------------------------------------- // File: DxDiagOutput.cpp // // Desc: Sample app to read info from dxdiagn.dll by enumeration // // Copyright (c) Microsoft Corp. All rights reserved. //----------------------------------------------------------------------------- #define INITGUID #include <windows.h> #pragma warning( disable : 4996 ) // disable deprecated warning #include <strsafe.h> #pragma warning( default : 4996 ) #include <stdio.h> #include <assert.h> #include <initguid.h> #include <dxdiag.h> //----------------------------------------------------------------------------- // Defines, and constants //----------------------------------------------------------------------------- #define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } } #define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } } #define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } } //----------------------------------------------------------------------------- // Function-prototypes //----------------------------------------------------------------------------- HRESULT PrintContainerAndChildren( WCHAR* wszParentName, IDxDiagContainer* pDxDiagContainer ); //----------------------------------------------------------------------------- // Name: main() // Desc: Entry point for the application. We use just the console window //----------------------------------------------------------------------------- int main( int argc, char* argv[] ) { HRESULT hr; CoInitialize( NULL ); IDxDiagProvider* pDxDiagProvider = NULL; IDxDiagContainer* pDxDiagRoot = NULL; // CoCreate a IDxDiagProvider* hr = CoCreateInstance( CLSID_DxDiagProvider, NULL, CLSCTX_INPROC_SERVER, IID_IDxDiagProvider, ( LPVOID* )&pDxDiagProvider ); if( SUCCEEDED( hr ) ) // if FAILED(hr) then DirectX 9 is not installed { // Fill out a DXDIAG_INIT_PARAMS struct and pass it to IDxDiagContainer::Initialize // Passing in TRUE for bAllowWHQLChecks, allows dxdiag to check if drivers are // digital signed as logo'd by WHQL which may connect via internet to update // WHQL certificates. DXDIAG_INIT_PARAMS dxDiagInitParam; ZeroMemory( &dxDiagInitParam, sizeof( DXDIAG_INIT_PARAMS ) ); dxDiagInitParam.dwSize = sizeof( DXDIAG_INIT_PARAMS ); dxDiagInitParam.dwDxDiagHeaderVersion = DXDIAG_DX9_SDK_VERSION; dxDiagInitParam.bAllowWHQLChecks = TRUE; dxDiagInitParam.pReserved = NULL; hr = pDxDiagProvider->Initialize( &dxDiagInitParam ); if( FAILED( hr ) ) goto LCleanup; hr = pDxDiagProvider->GetRootContainer( &pDxDiagRoot ); if( FAILED( hr ) ) goto LCleanup; // This function will recursivly print the properties // the root node and all its child. hr = PrintContainerAndChildren( NULL, pDxDiagRoot ); if( FAILED( hr ) ) goto LCleanup; } LCleanup: SAFE_RELEASE( pDxDiagRoot ); SAFE_RELEASE( pDxDiagProvider ); CoUninitialize(); return 0; } //----------------------------------------------------------------------------- // Name: PrintContainerAndChildren() // Desc: Recursivly print the properties the root node and all its child // to the console window //----------------------------------------------------------------------------- HRESULT PrintContainerAndChildren( WCHAR* wszParentName, IDxDiagContainer* pDxDiagContainer ) { HRESULT hr; DWORD dwPropCount; DWORD dwPropIndex; WCHAR wszPropName[256]; VARIANT var; WCHAR wszPropValue[256]; DWORD dwChildCount; DWORD dwChildIndex; WCHAR wszChildName[256]; IDxDiagContainer* pChildContainer = NULL; VariantInit( &var ); hr = pDxDiagContainer->GetNumberOfProps( &dwPropCount ); if( SUCCEEDED( hr ) ) { // Print each property in this container for( dwPropIndex = 0; dwPropIndex < dwPropCount; dwPropIndex++ ) { hr = pDxDiagContainer->EnumPropNames( dwPropIndex, wszPropName, 256 ); if( SUCCEEDED( hr ) ) { hr = pDxDiagContainer->GetProp( wszPropName, &var ); if( SUCCEEDED( hr ) ) { // Switch off the type. There's 4 different types: switch( var.vt ) { case VT_UI4: StringCchPrintfW( wszPropValue, 256, L"%d", var.ulVal ); break; case VT_I4: StringCchPrintfW( wszPropValue, 256, L"%d", var.lVal ); break; case VT_BOOL: StringCchCopyW( wszPropValue, 256, ( var.boolVal ) ? L"true" : L"false" ); break; case VT_BSTR: StringCchCopyW( wszPropValue, 256, var.bstrVal ); break; } // Add the parent name to the front if there's one, so that // its easier to read on the screen if( wszParentName ) wprintf( L"%s.%s = %s\n", wszParentName, wszPropName, wszPropValue ); else wprintf( L"%s = %s\n", wszPropName, wszPropValue ); // Clear the variant (this is needed to free BSTR memory) VariantClear( &var ); } } } } // Recursivly call this function for each of its child containers hr = pDxDiagContainer->GetNumberOfChildContainers( &dwChildCount ); if( SUCCEEDED( hr ) ) { for( dwChildIndex = 0; dwChildIndex < dwChildCount; dwChildIndex++ ) { hr = pDxDiagContainer->EnumChildContainerNames( dwChildIndex, wszChildName, 256 ); if( SUCCEEDED( hr ) ) { hr = pDxDiagContainer->GetChildContainer( wszChildName, &pChildContainer ); if( SUCCEEDED( hr ) ) { // wszFullChildName isn't needed but is used for text output WCHAR wszFullChildName[256]; if( wszParentName ) StringCchPrintfW( wszFullChildName, 256, L"%s.%s", wszParentName, wszChildName ); else StringCchCopyW( wszFullChildName, 256, wszChildName ); PrintContainerAndChildren( wszFullChildName, pChildContainer ); SAFE_RELEASE( pChildContainer ); } } } } return S_OK; }
35.760417
105
0.498689
billionare
15edd3fefada798892adcfe58e2b6f9f20e082b8
1,294
cpp
C++
cpp/0_libuv/uv_dynamic_so/load_library.cpp
ForrestSu/StudyNotes
7e823de2edbbdb1dc192dfa57c83b1776ef29836
[ "MIT" ]
null
null
null
cpp/0_libuv/uv_dynamic_so/load_library.cpp
ForrestSu/StudyNotes
7e823de2edbbdb1dc192dfa57c83b1776ef29836
[ "MIT" ]
1
2020-10-24T11:30:30.000Z
2020-10-24T11:30:32.000Z
cpp/0_libuv/uv_dynamic_so/load_library.cpp
ForrestSu/StudyNotes
7e823de2edbbdb1dc192dfa57c83b1776ef29836
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <uv.h> class Factory { public: virtual ~Factory() = default; virtual const char* GetMainService(const char *serviceName) = 0; }; typedef Factory* (*EntryGetServiceFactory)(); int main(int argc, char **argv) { /** str_so_name is utf-8 encode */ const char* str_so_name = "libtestzuv.so"; uv_lib_t* m_hdl = (uv_lib_t*) malloc(sizeof(uv_lib_t)); //1 open shared library int rc = uv_dlopen(str_so_name, m_hdl); if (rc == -1) { //uv_dlerror(): Returns the last uv_dlopen() or uv_dlsym() error message. fprintf(stderr, "uv_dlopen(%s) error: %s\n", str_so_name, uv_dlerror(m_hdl)); return 1; } // 2 get entry address EntryGetServiceFactory entry = NULL; rc = uv_dlsym(m_hdl, "GetServiceFactory", (void **) &entry); if (rc == -1) { fprintf(stderr, "uv_dlsym(%s) can't find factory entry! error: <%s>.\n", str_so_name, uv_dlerror(m_hdl)); return 1; } // 3 call c function: entry() Factory* factoryPtr = entry(); if (factoryPtr == NULL) { fprintf(stderr, "error: factoryInstancePtr is null!\n"); return 1; } // 4 close shared library uv_dlclose(m_hdl); printf("exit!\n"); return rc; }
28.755556
113
0.619011
ForrestSu
15eee06bdc7d3770f655b119ef81c9552c117089
5,815
cpp
C++
librtsp/test/rtsp-client-input-test.cpp
neonkingfr/MediaServer
8dc2fbf275628ab306a0976ac54533dd0e181f65
[ "MIT" ]
1
2022-03-25T03:09:10.000Z
2022-03-25T03:09:10.000Z
librtsp/test/rtsp-client-input-test.cpp
neonkingfr/MediaServer
8dc2fbf275628ab306a0976ac54533dd0e181f65
[ "MIT" ]
null
null
null
librtsp/test/rtsp-client-input-test.cpp
neonkingfr/MediaServer
8dc2fbf275628ab306a0976ac54533dd0e181f65
[ "MIT" ]
null
null
null
#if defined(_DEBUG) || defined(DEBUG) #include "sockutil.h" #include "rtsp-client.h" #include <assert.h> #include <stdlib.h> #include "sockpair.h" #include "cstringext.h" #include "sys/system.h" #include "cpm/unuse.h" #include "sdp.h" //#define UDP_MULTICAST_ADDR "239.0.0.2" extern "C" void rtp_receiver_tcp_input(uint8_t channel, const void* data, uint16_t bytes); extern "C" void rtp_receiver_test(socket_t rtp[2], const char* peer, int peerport[2], int payload, const char* encoding); extern "C" void* rtp_receiver_tcp_test(uint8_t interleave1, uint8_t interleave2, int payload, const char* encoding); extern "C" int rtsp_addr_is_multicast(const char* ip); struct rtsp_client_input_test_t { rtsp_client_t* rtsp; int transport; socket_t rtp[5][2]; unsigned short port[5][2]; }; static int rtsp_client_send(void* param, const char* uri, const void* req, size_t bytes) { //TODO: check uri and make socket //1. uri != rtsp describe uri(user input) //2. multi-uri if media_count > 1 struct rtsp_client_input_test_t* ctx = (struct rtsp_client_input_test_t*)param; return bytes; } static int rtpport(void* param, int media, const char* source, unsigned short rtp[2], char* ip, int len) { struct rtsp_client_input_test_t* ctx = (struct rtsp_client_input_test_t*)param; int m = rtsp_client_get_media_type(ctx->rtsp, media); //if (SDP_M_MEDIA_AUDIO != m && SDP_M_MEDIA_VIDEO != m) if (SDP_M_MEDIA_VIDEO != m) return 0; // ignore switch (ctx->transport) { case RTSP_TRANSPORT_RTP_UDP: // TODO: ipv6 assert(0 == sockpair_create("127.0.0.1", ctx->rtp[media], ctx->port[media])); rtp[0] = ctx->port[media][0]; rtp[1] = ctx->port[media][1]; if (rtsp_addr_is_multicast(ip)) { if (0 != socket_udp_multicast(ctx->rtp[media][0], ip, source, 16) || 0 != socket_udp_multicast(ctx->rtp[media][1], ip, source, 16)) return -1; } #if defined(UDP_MULTICAST_ADDR) else { if (0 != socket_udp_multicast(ctx->rtp[media][0], UDP_MULTICAST_ADDR, source, 16) || 0 != socket_udp_multicast(ctx->rtp[media][1], UDP_MULTICAST_ADDR, source, 16)) return -1; snprintf(ip, len, "%s", UDP_MULTICAST_ADDR); } #endif break; case RTSP_TRANSPORT_RTP_TCP: rtp[0] = 2 * media; rtp[1] = 2 * media + 1; break; default: assert(0); return -1; } return ctx->transport; } int rtsp_client_options(rtsp_client_t* rtsp, const char* commands); static void onrtp(void* param, uint8_t channel, const void* data, uint16_t bytes) { static int keepalive = 0; struct rtsp_client_input_test_t* ctx = (struct rtsp_client_input_test_t*)param; rtp_receiver_tcp_input(channel, data, bytes); if (++keepalive % 1000 == 0) { rtsp_client_play(ctx->rtsp, NULL, NULL); } } static int ondescribe(void* param, const char* sdp, int len) { struct rtsp_client_input_test_t* ctx = (struct rtsp_client_input_test_t*)param; return rtsp_client_setup(ctx->rtsp, sdp, len); } static int onsetup(void* param, int timeout, int64_t duration) { int i; uint64_t npt = 0; char ip[65]; u_short rtspport; struct rtsp_client_input_test_t* ctx = (struct rtsp_client_input_test_t*)param; assert(0 == rtsp_client_play(ctx->rtsp, &npt, NULL)); for (i = 0; i < rtsp_client_media_count(ctx->rtsp); i++) { int payload, port[2]; const char* encoding; const struct rtsp_header_transport_t* transport; transport = rtsp_client_get_media_transport(ctx->rtsp, i); encoding = rtsp_client_get_media_encoding(ctx->rtsp, i); payload = rtsp_client_get_media_payload(ctx->rtsp, i); if (RTSP_TRANSPORT_RTP_UDP == transport->transport) { //assert(RTSP_TRANSPORT_RTP_UDP == transport->transport); // udp only assert(0 == transport->multicast); // unicast only assert(transport->rtp.u.client_port1 == ctx->port[i][0]); assert(transport->rtp.u.client_port2 == ctx->port[i][1]); port[0] = transport->rtp.u.server_port1; port[1] = transport->rtp.u.server_port2; if (*transport->source) { rtp_receiver_test(ctx->rtp[i], transport->source, port, payload, encoding); } else { assert(0); //socket_getpeername(ctx->socket, ip, &rtspport); rtp_receiver_test(ctx->rtp[i], ip, port, payload, encoding); } } else if (RTSP_TRANSPORT_RTP_TCP == transport->transport) { //assert(transport->rtp.u.client_port1 == transport->interleaved1); //assert(transport->rtp.u.client_port2 == transport->interleaved2); rtp_receiver_tcp_test(transport->interleaved1, transport->interleaved2, payload, encoding); } else { assert(0); // TODO } } return 0; } static int onteardown(void* param) { return 0; } static int onplay(void* param, int media, const uint64_t* nptbegin, const uint64_t* nptend, const double* scale, const struct rtsp_rtp_info_t* rtpinfo, int count) { return 0; } static int onpause(void* param) { return 0; } void rtsp_client_input_test(const char* file) { int r; struct rtsp_client_input_test_t ctx; struct rtsp_client_handler_t handler; static char packet[2 * 1024 * 1024]; memset(&ctx, 0, sizeof(ctx)); handler.send = rtsp_client_send; handler.rtpport = rtpport; handler.ondescribe = ondescribe; handler.onsetup = onsetup; handler.onplay = onplay; handler.onpause = onpause; handler.onteardown = onteardown; handler.onrtp = onrtp; ctx.transport = RTSP_TRANSPORT_RTP_TCP; snprintf(packet, sizeof(packet), "rtsp://%s/%s", "127.0.0.1", file); // url //ctx.rtsp = rtsp_client_create(NULL, NULL, &handler, &ctx); ctx.rtsp = rtsp_client_create(packet, "username1", "password1", &handler, &ctx); assert(ctx.rtsp); assert(0 == rtsp_client_describe(ctx.rtsp)); FILE* fp = fopen(file, "rb"); while ( (r = fread(packet, 1, sizeof(packet), fp)) > 0) { assert(0 == rtsp_client_input(ctx.rtsp, packet, r)); } assert(0 == rtsp_client_teardown(ctx.rtsp)); rtsp_client_destroy(ctx.rtsp); fclose(fp); } #endif
28.504902
166
0.709028
neonkingfr
15f216ea7dba8896a70c427afb4ac7620c65a7f2
2,491
hpp
C++
include/codegen/include/Valve/VR/IVRExtendedDisplay__GetEyeOutputViewport.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Valve/VR/IVRExtendedDisplay__GetEyeOutputViewport.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Valve/VR/IVRExtendedDisplay__GetEyeOutputViewport.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:12 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" // Including type: Valve.VR.IVRExtendedDisplay #include "Valve/VR/IVRExtendedDisplay.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Forward declaring namespace: Valve::VR namespace Valve::VR { // Forward declaring type: EVREye struct EVREye; } // Completed forward declares // Type namespace: Valve.VR namespace Valve::VR { // Autogenerated type: Valve.VR.IVRExtendedDisplay/_GetEyeOutputViewport class IVRExtendedDisplay::_GetEyeOutputViewport : public System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x15EFF5C static IVRExtendedDisplay::_GetEyeOutputViewport* New_ctor(::Il2CppObject* object, System::IntPtr method); // public System.Void Invoke(Valve.VR.EVREye eEye, System.UInt32 pnX, System.UInt32 pnY, System.UInt32 pnWidth, System.UInt32 pnHeight) // Offset: 0x15EFF70 void Invoke(Valve::VR::EVREye eEye, uint& pnX, uint& pnY, uint& pnWidth, uint& pnHeight); // public System.IAsyncResult BeginInvoke(Valve.VR.EVREye eEye, System.UInt32 pnX, System.UInt32 pnY, System.UInt32 pnWidth, System.UInt32 pnHeight, System.AsyncCallback callback, System.Object object) // Offset: 0x15F024C System::IAsyncResult* BeginInvoke(Valve::VR::EVREye eEye, uint& pnX, uint& pnY, uint& pnWidth, uint& pnHeight, System::AsyncCallback* callback, ::Il2CppObject* object); // public System.Void EndInvoke(System.UInt32 pnX, System.UInt32 pnY, System.UInt32 pnWidth, System.UInt32 pnHeight, System.IAsyncResult result) // Offset: 0x15F0350 void EndInvoke(uint& pnX, uint& pnY, uint& pnWidth, uint& pnHeight, System::IAsyncResult* result); }; // Valve.VR.IVRExtendedDisplay/_GetEyeOutputViewport } DEFINE_IL2CPP_ARG_TYPE(Valve::VR::IVRExtendedDisplay::_GetEyeOutputViewport*, "Valve.VR", "IVRExtendedDisplay/_GetEyeOutputViewport"); #pragma pack(pop)
49.82
205
0.741871
Futuremappermydud
15f32244b1e1f5a8b5bbdf5323595a8ea8b29d5a
564
cpp
C++
c++/45 operator overload 04/src/coordinate.cpp
dev-go/hello-world
a99e6dfb2868cfc5f04ccab87888619c5c420d0a
[ "BSD-3-Clause" ]
null
null
null
c++/45 operator overload 04/src/coordinate.cpp
dev-go/hello-world
a99e6dfb2868cfc5f04ccab87888619c5c420d0a
[ "BSD-3-Clause" ]
null
null
null
c++/45 operator overload 04/src/coordinate.cpp
dev-go/hello-world
a99e6dfb2868cfc5f04ccab87888619c5c420d0a
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2020, devgo.club // All rights reserved. #include <stdint.h> #include "coordinate.h" // Coordinate Coordinate::operator+(const Coordinate &coor) // { // Coordinate tmp; // tmp.x_ = x_ + coor.x_; // tmp.y_ = y_ + coor.y_; // return tmp; // } int32_t Coordinate::operator[](uint8_t index) { if (index == 0) { return x_; } if (index == 1) { return y_; } return 0; } Coordinate::Coordinate(int32_t x, int32_t y) : x_(x), y_(y) {} Coordinate::Coordinate(const Coordinate &coor) : x_(coor.x_), y_(coor.y_) {}
17.625
76
0.602837
dev-go
15f3abc7d46fcce7e0010971d91995eb69cabba2
33,289
cc
C++
third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/accessibility/inspector_accessibility_agent.h" #include <memory> #include "third_party/blink/renderer/core/accessibility/ax_object_cache.h" #include "third_party/blink/renderer/core/dom/dom_node_ids.h" #include "third_party/blink/renderer/core/dom/element.h" #include "third_party/blink/renderer/core/dom/flat_tree_traversal.h" #include "third_party/blink/renderer/core/dom/node.h" #include "third_party/blink/renderer/core/dom/node_list.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/html_names.h" #include "third_party/blink/renderer/core/inspector/identifiers_factory.h" #include "third_party/blink/renderer/core/inspector/inspected_frames.h" #include "third_party/blink/renderer/core/inspector/inspector_dom_agent.h" #include "third_party/blink/renderer/core/inspector/inspector_style_sheet.h" #include "third_party/blink/renderer/modules/accessibility/ax_object.h" #include "third_party/blink/renderer/modules/accessibility/ax_object_cache_impl.h" #include "third_party/blink/renderer/modules/accessibility/inspector_type_builder_helper.h" #include "third_party/blink/renderer/platform/wtf/deque.h" namespace blink { using protocol::Accessibility::AXPropertyName; using protocol::Accessibility::AXNode; using protocol::Accessibility::AXNodeId; using protocol::Accessibility::AXProperty; using protocol::Accessibility::AXValueSource; using protocol::Accessibility::AXValueType; using protocol::Accessibility::AXRelatedNode; using protocol::Accessibility::AXValue; using protocol::Maybe; using protocol::Response; namespace AXPropertyNameEnum = protocol::Accessibility::AXPropertyNameEnum; namespace { static const AXID kIDForInspectedNodeWithNoAXNode = 0; void AddHasPopupProperty(ax::mojom::HasPopup has_popup, protocol::Array<AXProperty>& properties) { switch (has_popup) { case ax::mojom::HasPopup::kFalse: break; case ax::mojom::HasPopup::kTrue: properties.emplace_back( CreateProperty(AXPropertyNameEnum::HasPopup, CreateValue("true", AXValueTypeEnum::Token))); break; case ax::mojom::HasPopup::kMenu: properties.emplace_back( CreateProperty(AXPropertyNameEnum::HasPopup, CreateValue("menu", AXValueTypeEnum::Token))); break; case ax::mojom::HasPopup::kListbox: properties.emplace_back( CreateProperty(AXPropertyNameEnum::HasPopup, CreateValue("listbox", AXValueTypeEnum::Token))); break; case ax::mojom::HasPopup::kTree: properties.emplace_back( CreateProperty(AXPropertyNameEnum::HasPopup, CreateValue("tree", AXValueTypeEnum::Token))); break; case ax::mojom::HasPopup::kGrid: properties.emplace_back( CreateProperty(AXPropertyNameEnum::HasPopup, CreateValue("grid", AXValueTypeEnum::Token))); break; case ax::mojom::HasPopup::kDialog: properties.emplace_back( CreateProperty(AXPropertyNameEnum::HasPopup, CreateValue("dialog", AXValueTypeEnum::Token))); break; } } void FillLiveRegionProperties(AXObject& ax_object, protocol::Array<AXProperty>& properties) { if (!ax_object.LiveRegionRoot()) return; properties.emplace_back( CreateProperty(AXPropertyNameEnum::Live, CreateValue(ax_object.ContainerLiveRegionStatus(), AXValueTypeEnum::Token))); properties.emplace_back(CreateProperty( AXPropertyNameEnum::Atomic, CreateBooleanValue(ax_object.ContainerLiveRegionAtomic()))); properties.emplace_back( CreateProperty(AXPropertyNameEnum::Relevant, CreateValue(ax_object.ContainerLiveRegionRelevant(), AXValueTypeEnum::TokenList))); if (!ax_object.IsLiveRegionRoot()) { properties.emplace_back(CreateProperty( AXPropertyNameEnum::Root, CreateRelatedNodeListValue(*(ax_object.LiveRegionRoot())))); } } void FillGlobalStates(AXObject& ax_object, protocol::Array<AXProperty>& properties) { if (ax_object.Restriction() == kRestrictionDisabled) { properties.emplace_back( CreateProperty(AXPropertyNameEnum::Disabled, CreateBooleanValue(true))); } if (const AXObject* hidden_root = ax_object.AriaHiddenRoot()) { properties.emplace_back( CreateProperty(AXPropertyNameEnum::Hidden, CreateBooleanValue(true))); properties.emplace_back( CreateProperty(AXPropertyNameEnum::HiddenRoot, CreateRelatedNodeListValue(*hidden_root))); } ax::mojom::InvalidState invalid_state = ax_object.GetInvalidState(); switch (invalid_state) { case ax::mojom::InvalidState::kNone: break; case ax::mojom::InvalidState::kFalse: properties.emplace_back( CreateProperty(AXPropertyNameEnum::Invalid, CreateValue("false", AXValueTypeEnum::Token))); break; case ax::mojom::InvalidState::kTrue: properties.emplace_back( CreateProperty(AXPropertyNameEnum::Invalid, CreateValue("true", AXValueTypeEnum::Token))); break; default: // TODO(aboxhall): expose invalid: <nothing> and source: aria-invalid as // invalid value properties.emplace_back(CreateProperty( AXPropertyNameEnum::Invalid, CreateValue(ax_object.AriaInvalidValue(), AXValueTypeEnum::String))); break; } if (ax_object.CanSetFocusAttribute()) { properties.emplace_back(CreateProperty( AXPropertyNameEnum::Focusable, CreateBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined))); } if (ax_object.IsFocused()) { properties.emplace_back(CreateProperty( AXPropertyNameEnum::Focused, CreateBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined))); } if (ax_object.IsEditable()) { properties.emplace_back(CreateProperty( AXPropertyNameEnum::Editable, CreateValue(ax_object.IsRichlyEditable() ? "richtext" : "plaintext", AXValueTypeEnum::Token))); } if (ax_object.CanSetValueAttribute()) { properties.emplace_back(CreateProperty( AXPropertyNameEnum::Settable, CreateBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined))); } } bool RoleAllowsModal(ax::mojom::Role role) { return role == ax::mojom::Role::kDialog || role == ax::mojom::Role::kAlertDialog; } bool RoleAllowsMultiselectable(ax::mojom::Role role) { return role == ax::mojom::Role::kGrid || role == ax::mojom::Role::kListBox || role == ax::mojom::Role::kTabList || role == ax::mojom::Role::kTreeGrid || role == ax::mojom::Role::kTree; } bool RoleAllowsOrientation(ax::mojom::Role role) { return role == ax::mojom::Role::kScrollBar || role == ax::mojom::Role::kSplitter || role == ax::mojom::Role::kSlider; } bool RoleAllowsReadonly(ax::mojom::Role role) { return role == ax::mojom::Role::kGrid || role == ax::mojom::Role::kCell || role == ax::mojom::Role::kTextField || role == ax::mojom::Role::kColumnHeader || role == ax::mojom::Role::kRowHeader || role == ax::mojom::Role::kTreeGrid; } bool RoleAllowsRequired(ax::mojom::Role role) { return role == ax::mojom::Role::kComboBoxGrouping || role == ax::mojom::Role::kComboBoxMenuButton || role == ax::mojom::Role::kCell || role == ax::mojom::Role::kListBox || role == ax::mojom::Role::kRadioGroup || role == ax::mojom::Role::kSpinButton || role == ax::mojom::Role::kTextField || role == ax::mojom::Role::kTextFieldWithComboBox || role == ax::mojom::Role::kTree || role == ax::mojom::Role::kColumnHeader || role == ax::mojom::Role::kRowHeader || role == ax::mojom::Role::kTreeGrid; } bool RoleAllowsSort(ax::mojom::Role role) { return role == ax::mojom::Role::kColumnHeader || role == ax::mojom::Role::kRowHeader; } void FillWidgetProperties(AXObject& ax_object, protocol::Array<AXProperty>& properties) { ax::mojom::Role role = ax_object.RoleValue(); String autocomplete = ax_object.AutoComplete(); if (!autocomplete.IsEmpty()) properties.emplace_back( CreateProperty(AXPropertyNameEnum::Autocomplete, CreateValue(autocomplete, AXValueTypeEnum::Token))); AddHasPopupProperty(ax_object.HasPopup(), properties); int heading_level = ax_object.HeadingLevel(); if (heading_level > 0) { properties.emplace_back( CreateProperty(AXPropertyNameEnum::Level, CreateValue(heading_level))); } int hierarchical_level = ax_object.HierarchicalLevel(); if (hierarchical_level > 0 || ax_object.HasAttribute(html_names::kAriaLevelAttr)) { properties.emplace_back(CreateProperty(AXPropertyNameEnum::Level, CreateValue(hierarchical_level))); } if (RoleAllowsMultiselectable(role)) { bool multiselectable = ax_object.IsMultiSelectable(); properties.emplace_back( CreateProperty(AXPropertyNameEnum::Multiselectable, CreateBooleanValue(multiselectable))); } if (RoleAllowsOrientation(role)) { AccessibilityOrientation orientation = ax_object.Orientation(); switch (orientation) { case kAccessibilityOrientationVertical: properties.emplace_back( CreateProperty(AXPropertyNameEnum::Orientation, CreateValue("vertical", AXValueTypeEnum::Token))); break; case kAccessibilityOrientationHorizontal: properties.emplace_back( CreateProperty(AXPropertyNameEnum::Orientation, CreateValue("horizontal", AXValueTypeEnum::Token))); break; case kAccessibilityOrientationUndefined: break; } } if (role == ax::mojom::Role::kTextField) { properties.emplace_back( CreateProperty(AXPropertyNameEnum::Multiline, CreateBooleanValue(ax_object.IsMultiline()))); } if (RoleAllowsReadonly(role)) { properties.emplace_back(CreateProperty( AXPropertyNameEnum::Readonly, CreateBooleanValue(ax_object.Restriction() == kRestrictionReadOnly))); } if (RoleAllowsRequired(role)) { properties.emplace_back( CreateProperty(AXPropertyNameEnum::Required, CreateBooleanValue(ax_object.IsRequired()))); } if (RoleAllowsSort(role)) { // TODO(aboxhall): sort } if (ax_object.IsRangeValueSupported()) { float min_value; if (ax_object.MinValueForRange(&min_value)) { properties.emplace_back( CreateProperty(AXPropertyNameEnum::Valuemin, CreateValue(min_value))); } float max_value; if (ax_object.MaxValueForRange(&max_value)) { properties.emplace_back( CreateProperty(AXPropertyNameEnum::Valuemax, CreateValue(max_value))); } properties.emplace_back( CreateProperty(AXPropertyNameEnum::Valuetext, CreateValue(ax_object.ValueDescription()))); } } void FillWidgetStates(AXObject& ax_object, protocol::Array<AXProperty>& properties) { ax::mojom::Role role = ax_object.RoleValue(); const char* checked_prop_val = nullptr; switch (ax_object.CheckedState()) { case ax::mojom::CheckedState::kTrue: checked_prop_val = "true"; break; case ax::mojom::CheckedState::kMixed: checked_prop_val = "mixed"; break; case ax::mojom::CheckedState::kFalse: checked_prop_val = "false"; break; case ax::mojom::CheckedState::kNone: break; } if (checked_prop_val) { auto* const checked_prop_name = role == ax::mojom::Role::kToggleButton ? AXPropertyNameEnum::Pressed : AXPropertyNameEnum::Checked; properties.emplace_back(CreateProperty( checked_prop_name, CreateValue(checked_prop_val, AXValueTypeEnum::Tristate))); } AccessibilityExpanded expanded = ax_object.IsExpanded(); switch (expanded) { case kExpandedUndefined: break; case kExpandedCollapsed: properties.emplace_back(CreateProperty( AXPropertyNameEnum::Expanded, CreateBooleanValue(false, AXValueTypeEnum::BooleanOrUndefined))); break; case kExpandedExpanded: properties.emplace_back(CreateProperty( AXPropertyNameEnum::Expanded, CreateBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined))); break; } AccessibilitySelectedState selected = ax_object.IsSelected(); switch (selected) { case kSelectedStateUndefined: break; case kSelectedStateFalse: properties.emplace_back(CreateProperty( AXPropertyNameEnum::Selected, CreateBooleanValue(false, AXValueTypeEnum::BooleanOrUndefined))); break; case kSelectedStateTrue: properties.emplace_back(CreateProperty( AXPropertyNameEnum::Selected, CreateBooleanValue(true, AXValueTypeEnum::BooleanOrUndefined))); break; } if (RoleAllowsModal(role)) { properties.emplace_back(CreateProperty( AXPropertyNameEnum::Modal, CreateBooleanValue(ax_object.IsModal()))); } } std::unique_ptr<AXProperty> CreateRelatedNodeListProperty( const String& key, AXRelatedObjectVector& nodes) { std::unique_ptr<AXValue> node_list_value = CreateRelatedNodeListValue(nodes, AXValueTypeEnum::NodeList); return CreateProperty(key, std::move(node_list_value)); } std::unique_ptr<AXProperty> CreateRelatedNodeListProperty( const String& key, AXObject::AXObjectVector& nodes, const QualifiedName& attr, AXObject& ax_object) { std::unique_ptr<AXValue> node_list_value = CreateRelatedNodeListValue(nodes); const AtomicString& attr_value = ax_object.GetAttribute(attr); node_list_value->setValue(protocol::StringValue::create(attr_value)); return CreateProperty(key, std::move(node_list_value)); } class SparseAttributeAXPropertyAdapter : public GarbageCollected<SparseAttributeAXPropertyAdapter>, public AXSparseAttributeClient { public: SparseAttributeAXPropertyAdapter(AXObject& ax_object, protocol::Array<AXProperty>& properties) : ax_object_(&ax_object), properties_(properties) {} void Trace(Visitor* visitor) const { visitor->Trace(ax_object_); } private: Member<AXObject> ax_object_; protocol::Array<AXProperty>& properties_; void AddBoolAttribute(AXBoolAttribute attribute, bool value) override { switch (attribute) { case AXBoolAttribute::kAriaBusy: properties_.emplace_back( CreateProperty(AXPropertyNameEnum::Busy, CreateValue(value, AXValueTypeEnum::Boolean))); break; } } void AddIntAttribute(AXIntAttribute attribute, int32_t value) override {} void AddUIntAttribute(AXUIntAttribute attribute, uint32_t value) override {} void AddStringAttribute(AXStringAttribute attribute, const String& value) override { switch (attribute) { case AXStringAttribute::kAriaKeyShortcuts: properties_.emplace_back( CreateProperty(AXPropertyNameEnum::Keyshortcuts, CreateValue(value, AXValueTypeEnum::String))); break; case AXStringAttribute::kAriaRoleDescription: properties_.emplace_back( CreateProperty(AXPropertyNameEnum::Roledescription, CreateValue(value, AXValueTypeEnum::String))); break; } } void AddObjectAttribute(AXObjectAttribute attribute, AXObject& object) override { switch (attribute) { case AXObjectAttribute::kAriaActiveDescendant: properties_.emplace_back( CreateProperty(AXPropertyNameEnum::Activedescendant, CreateRelatedNodeListValue(object))); break; case AXObjectAttribute::kAriaErrorMessage: properties_.emplace_back( CreateProperty(AXPropertyNameEnum::Errormessage, CreateRelatedNodeListValue(object))); break; } } void AddObjectVectorAttribute( AXObjectVectorAttribute attribute, HeapVector<Member<AXObject>>* objects) override { switch (attribute) { case AXObjectVectorAttribute::kAriaControls: properties_.emplace_back(CreateRelatedNodeListProperty( AXPropertyNameEnum::Controls, *objects, html_names::kAriaControlsAttr, *ax_object_)); break; case AXObjectVectorAttribute::kAriaDetails: properties_.emplace_back(CreateRelatedNodeListProperty( AXPropertyNameEnum::Details, *objects, html_names::kAriaDetailsAttr, *ax_object_)); break; case AXObjectVectorAttribute::kAriaFlowTo: properties_.emplace_back(CreateRelatedNodeListProperty( AXPropertyNameEnum::Flowto, *objects, html_names::kAriaFlowtoAttr, *ax_object_)); break; } } }; void FillRelationships(AXObject& ax_object, protocol::Array<AXProperty>& properties) { AXObject::AXObjectVector results; ax_object.AriaDescribedbyElements(results); if (!results.IsEmpty()) { properties.emplace_back(CreateRelatedNodeListProperty( AXPropertyNameEnum::Describedby, results, html_names::kAriaDescribedbyAttr, ax_object)); } results.clear(); ax_object.AriaOwnsElements(results); if (!results.IsEmpty()) { properties.emplace_back( CreateRelatedNodeListProperty(AXPropertyNameEnum::Owns, results, html_names::kAriaOwnsAttr, ax_object)); } results.clear(); } std::unique_ptr<AXValue> CreateRoleNameValue(ax::mojom::Role role) { AtomicString role_name = AXObject::RoleName(role); std::unique_ptr<AXValue> role_name_value; if (!role_name.IsNull()) { role_name_value = CreateValue(role_name, AXValueTypeEnum::Role); } else { role_name_value = CreateValue(AXObject::InternalRoleName(role), AXValueTypeEnum::InternalRole); } return role_name_value; } } // namespace using EnabledAgentsMultimap = HeapHashMap<WeakMember<LocalFrame>, Member<HeapHashSet<Member<InspectorAccessibilityAgent>>>>; EnabledAgentsMultimap& EnabledAgents() { DEFINE_STATIC_LOCAL(Persistent<EnabledAgentsMultimap>, enabled_agents, (MakeGarbageCollected<EnabledAgentsMultimap>())); return *enabled_agents; } InspectorAccessibilityAgent::InspectorAccessibilityAgent( InspectedFrames* inspected_frames, InspectorDOMAgent* dom_agent) : inspected_frames_(inspected_frames), dom_agent_(dom_agent), enabled_(&agent_state_, /*default_value=*/false) {} Response InspectorAccessibilityAgent::getPartialAXTree( Maybe<int> dom_node_id, Maybe<int> backend_node_id, Maybe<String> object_id, Maybe<bool> fetch_relatives, std::unique_ptr<protocol::Array<AXNode>>* nodes) { Node* dom_node = nullptr; Response response = dom_agent_->AssertNode(dom_node_id, backend_node_id, object_id, dom_node); if (!response.IsSuccess()) return response; Document& document = dom_node->GetDocument(); document.UpdateStyleAndLayout(DocumentUpdateReason::kInspector); DocumentLifecycle::DisallowTransitionScope disallow_transition( document.Lifecycle()); LocalFrame* local_frame = document.GetFrame(); if (!local_frame) return Response::ServerError("Frame is detached."); AXContext ax_context(document); auto& cache = To<AXObjectCacheImpl>(ax_context.GetAXObjectCache()); AXObject* inspected_ax_object = cache.GetOrCreate(dom_node); *nodes = std::make_unique<protocol::Array<protocol::Accessibility::AXNode>>(); if (!inspected_ax_object || inspected_ax_object->AccessibilityIsIgnored()) { (*nodes)->emplace_back(BuildObjectForIgnoredNode( dom_node, inspected_ax_object, fetch_relatives.fromMaybe(true), *nodes, cache)); return Response::Success(); } else { (*nodes)->emplace_back( BuildProtocolAXObject(*inspected_ax_object, inspected_ax_object, fetch_relatives.fromMaybe(true), *nodes, cache)); } if (!inspected_ax_object) return Response::Success(); AXObject* parent = inspected_ax_object->ParentObjectUnignored(); if (!parent) return Response::Success(); if (fetch_relatives.fromMaybe(true)) AddAncestors(*parent, inspected_ax_object, *nodes, cache); return Response::Success(); } void InspectorAccessibilityAgent::AddAncestors( AXObject& first_ancestor, AXObject* inspected_ax_object, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { AXObject* ancestor = &first_ancestor; AXObject* child = inspected_ax_object; while (ancestor) { std::unique_ptr<AXNode> parent_node_object = BuildProtocolAXObject( *ancestor, inspected_ax_object, true, nodes, cache); auto child_ids = std::make_unique<protocol::Array<AXNodeId>>(); if (child) child_ids->emplace_back(String::Number(child->AXObjectID())); else child_ids->emplace_back(String::Number(kIDForInspectedNodeWithNoAXNode)); parent_node_object->setChildIds(std::move(child_ids)); nodes->emplace_back(std::move(parent_node_object)); child = ancestor; ancestor = ancestor->ParentObjectUnignored(); } } std::unique_ptr<AXNode> InspectorAccessibilityAgent::BuildObjectForIgnoredNode( Node* dom_node, AXObject* ax_object, bool fetch_relatives, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { AXObject::IgnoredReasons ignored_reasons; AXID ax_id = kIDForInspectedNodeWithNoAXNode; if (ax_object && ax_object->IsAXLayoutObject()) ax_id = ax_object->AXObjectID(); std::unique_ptr<AXNode> ignored_node_object = AXNode::create() .setNodeId(String::Number(ax_id)) .setIgnored(true) .build(); ax::mojom::Role role = ax::mojom::Role::kIgnored; ignored_node_object->setRole(CreateRoleNameValue(role)); if (ax_object && ax_object->IsAXLayoutObject()) { ax_object->ComputeAccessibilityIsIgnored(&ignored_reasons); AXObject* parent_object = ax_object->ParentObjectUnignored(); if (parent_object && fetch_relatives) AddAncestors(*parent_object, ax_object, nodes, cache); } else if (dom_node && !dom_node->GetLayoutObject()) { if (fetch_relatives) { PopulateDOMNodeAncestors(*dom_node, *(ignored_node_object.get()), nodes, cache); } ignored_reasons.emplace_back(IgnoredReason(kAXNotRendered)); } if (dom_node) { ignored_node_object->setBackendDOMNodeId( IdentifiersFactory::IntIdForNode(dom_node)); } auto ignored_reason_properties = std::make_unique<protocol::Array<AXProperty>>(); for (IgnoredReason& reason : ignored_reasons) ignored_reason_properties->emplace_back(CreateProperty(reason)); ignored_node_object->setIgnoredReasons(std::move(ignored_reason_properties)); return ignored_node_object; } void InspectorAccessibilityAgent::PopulateDOMNodeAncestors( Node& inspected_dom_node, AXNode& node_object, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { // Walk up parents until an AXObject can be found. auto* shadow_root = DynamicTo<ShadowRoot>(inspected_dom_node); Node* parent_node = shadow_root ? &shadow_root->host() : FlatTreeTraversal::Parent(inspected_dom_node); AXObject* parent_ax_object = cache.GetOrCreate(parent_node); while (parent_node && !parent_ax_object) { shadow_root = DynamicTo<ShadowRoot>(parent_node); parent_node = shadow_root ? &shadow_root->host() : FlatTreeTraversal::Parent(*parent_node); parent_ax_object = cache.GetOrCreate(parent_node); } if (!parent_ax_object) return; if (parent_ax_object->AccessibilityIsIgnored()) parent_ax_object = parent_ax_object->ParentObjectUnignored(); if (!parent_ax_object) return; // Populate parent and ancestors. AddAncestors(*parent_ax_object, nullptr, nodes, cache); } std::unique_ptr<AXNode> InspectorAccessibilityAgent::BuildProtocolAXObject( AXObject& ax_object, AXObject* inspected_ax_object, bool fetch_relatives, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { ax::mojom::Role role = ax_object.RoleValue(); std::unique_ptr<AXNode> node_object = AXNode::create() .setNodeId(String::Number(ax_object.AXObjectID())) .setIgnored(false) .build(); node_object->setRole(CreateRoleNameValue(role)); auto properties = std::make_unique<protocol::Array<AXProperty>>(); FillLiveRegionProperties(ax_object, *(properties.get())); FillGlobalStates(ax_object, *(properties.get())); FillWidgetProperties(ax_object, *(properties.get())); FillWidgetStates(ax_object, *(properties.get())); FillRelationships(ax_object, *(properties.get())); SparseAttributeAXPropertyAdapter adapter(ax_object, *properties); ax_object.GetSparseAXAttributes(adapter); AXObject::NameSources name_sources; String computed_name = ax_object.GetName(&name_sources); if (!name_sources.IsEmpty()) { std::unique_ptr<AXValue> name = CreateValue(computed_name, AXValueTypeEnum::ComputedString); if (!name_sources.IsEmpty()) { auto name_source_properties = std::make_unique<protocol::Array<AXValueSource>>(); for (NameSource& name_source : name_sources) { name_source_properties->emplace_back(CreateValueSource(name_source)); if (name_source.text.IsNull() || name_source.superseded) continue; if (!name_source.related_objects.IsEmpty()) { properties->emplace_back(CreateRelatedNodeListProperty( AXPropertyNameEnum::Labelledby, name_source.related_objects)); } } name->setSources(std::move(name_source_properties)); } node_object->setProperties(std::move(properties)); node_object->setName(std::move(name)); } else { node_object->setProperties(std::move(properties)); } FillCoreProperties(ax_object, inspected_ax_object, fetch_relatives, *(node_object.get()), nodes, cache); return node_object; } Response InspectorAccessibilityAgent::getFullAXTree( std::unique_ptr<protocol::Array<AXNode>>* nodes) { Document* document = inspected_frames_->Root()->GetDocument(); if (!document) return Response::ServerError("No document."); if (document->View()->NeedsLayout() || document->NeedsLayoutTreeUpdate()) document->UpdateStyleAndLayout(DocumentUpdateReason::kInspector); *nodes = std::make_unique<protocol::Array<protocol::Accessibility::AXNode>>(); AXContext ax_context(*document); auto& cache = To<AXObjectCacheImpl>(ax_context.GetAXObjectCache()); Deque<AXID> ids; ids.emplace_back(cache.Root()->AXObjectID()); while (!ids.empty()) { AXID ax_id = ids.front(); ids.pop_front(); AXObject* ax_object = cache.ObjectFromAXID(ax_id); std::unique_ptr<AXNode> node = BuildProtocolAXObject(*ax_object, nullptr, false, *nodes, cache); auto child_ids = std::make_unique<protocol::Array<AXNodeId>>(); const AXObject::AXObjectVector& children = ax_object->ChildrenIncludingIgnored(); for (unsigned i = 0; i < children.size(); i++) { AXObject& child_ax_object = *children[i].Get(); child_ids->emplace_back(String::Number(child_ax_object.AXObjectID())); ids.emplace_back(child_ax_object.AXObjectID()); } node->setChildIds(std::move(child_ids)); (*nodes)->emplace_back(std::move(node)); } return Response::Success(); } void InspectorAccessibilityAgent::FillCoreProperties( AXObject& ax_object, AXObject* inspected_ax_object, bool fetch_relatives, AXNode& node_object, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { ax::mojom::NameFrom name_from; AXObject::AXObjectVector name_objects; ax_object.GetName(name_from, &name_objects); ax::mojom::DescriptionFrom description_from; AXObject::AXObjectVector description_objects; String description = ax_object.Description(name_from, description_from, &description_objects); if (!description.IsEmpty()) { node_object.setDescription( CreateValue(description, AXValueTypeEnum::ComputedString)); } // Value. if (ax_object.IsRangeValueSupported()) { float value; if (ax_object.ValueForRange(&value)) node_object.setValue(CreateValue(value)); } else { String string_value = ax_object.StringValue(); if (!string_value.IsEmpty()) node_object.setValue(CreateValue(string_value)); } if (fetch_relatives) PopulateRelatives(ax_object, inspected_ax_object, node_object, nodes, cache); Node* node = ax_object.GetNode(); if (node) node_object.setBackendDOMNodeId(IdentifiersFactory::IntIdForNode(node)); } void InspectorAccessibilityAgent::PopulateRelatives( AXObject& ax_object, AXObject* inspected_ax_object, AXNode& node_object, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { AXObject* parent_object = ax_object.ParentObject(); if (parent_object && parent_object != inspected_ax_object) { // Use unignored parent unless parent is inspected ignored object. parent_object = ax_object.ParentObjectUnignored(); } auto child_ids = std::make_unique<protocol::Array<AXNodeId>>(); if (!ax_object.AccessibilityIsIgnored()) AddChildren(ax_object, inspected_ax_object, child_ids, nodes, cache); node_object.setChildIds(std::move(child_ids)); } void InspectorAccessibilityAgent::AddChildren( AXObject& ax_object, AXObject* inspected_ax_object, std::unique_ptr<protocol::Array<AXNodeId>>& child_ids, std::unique_ptr<protocol::Array<AXNode>>& nodes, AXObjectCacheImpl& cache) const { if (inspected_ax_object && inspected_ax_object->AccessibilityIsIgnored() && &ax_object == inspected_ax_object->ParentObjectUnignored()) { child_ids->emplace_back(String::Number(inspected_ax_object->AXObjectID())); return; } const AXObject::AXObjectVector& children = ax_object.ChildrenIncludingIgnored(); for (unsigned i = 0; i < children.size(); i++) { AXObject& child_ax_object = *children[i].Get(); child_ids->emplace_back(String::Number(child_ax_object.AXObjectID())); if (&child_ax_object == inspected_ax_object) continue; if (&ax_object != inspected_ax_object) { if (!inspected_ax_object) continue; if (&ax_object != inspected_ax_object->ParentObjectUnignored() && ax_object.GetNode()) continue; } // Only add children of inspected node (or un-inspectable children of // inspected node) to returned nodes. std::unique_ptr<AXNode> child_node = BuildProtocolAXObject( child_ax_object, inspected_ax_object, true, nodes, cache); nodes->emplace_back(std::move(child_node)); } } void InspectorAccessibilityAgent::EnableAndReset() { enabled_.Set(true); LocalFrame* frame = inspected_frames_->Root(); if (!EnabledAgents().Contains(frame)) { EnabledAgents().Set( frame, MakeGarbageCollected< HeapHashSet<Member<InspectorAccessibilityAgent>>>()); } EnabledAgents().find(frame)->value->insert(this); CreateAXContext(); } protocol::Response InspectorAccessibilityAgent::enable() { if (!enabled_.Get()) EnableAndReset(); return Response::Success(); } protocol::Response InspectorAccessibilityAgent::disable() { if (!enabled_.Get()) return Response::Success(); enabled_.Set(false); context_ = nullptr; LocalFrame* frame = inspected_frames_->Root(); DCHECK(EnabledAgents().Contains(frame)); auto it = EnabledAgents().find(frame); it->value->erase(this); if (it->value->IsEmpty()) EnabledAgents().erase(frame); return Response::Success(); } void InspectorAccessibilityAgent::Restore() { if (enabled_.Get()) EnableAndReset(); } void InspectorAccessibilityAgent::ProvideTo(LocalFrame* frame) { if (!EnabledAgents().Contains(frame)) return; for (InspectorAccessibilityAgent* agent : *EnabledAgents().find(frame)->value) agent->CreateAXContext(); } void InspectorAccessibilityAgent::CreateAXContext() { Document* document = inspected_frames_->Root()->GetDocument(); if (document) context_ = std::make_unique<AXContext>(*document); } void InspectorAccessibilityAgent::Trace(Visitor* visitor) const { visitor->Trace(inspected_frames_); visitor->Trace(dom_agent_); InspectorBaseAgent::Trace(visitor); } } // namespace blink
37.028921
91
0.697047
mghgroup
15f496114b018e5ff02915197ea3791a70a9b1fb
6,289
cc
C++
mindspore/lite/test/ut/src/runtime/kernel/opencl/caffe_prelu_tests.cc
Joejiong/mindspore
083fd6565cab1aa1d3114feeacccf1cba0d55e80
[ "Apache-2.0" ]
null
null
null
mindspore/lite/test/ut/src/runtime/kernel/opencl/caffe_prelu_tests.cc
Joejiong/mindspore
083fd6565cab1aa1d3114feeacccf1cba0d55e80
[ "Apache-2.0" ]
null
null
null
mindspore/lite/test/ut/src/runtime/kernel/opencl/caffe_prelu_tests.cc
Joejiong/mindspore
083fd6565cab1aa1d3114feeacccf1cba0d55e80
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020 Huawei Technologies Co., Ltd * * 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 <iostream> #include "utils/log_adapter.h" #include "common/common_test.h" #include "mindspore/lite/src/common/file_utils.h" #include "src/runtime/kernel/arm/nnacl/pack.h" #include "mindspore/lite/src/runtime/opencl/opencl_runtime.h" #include "mindspore/lite/src/runtime/kernel/opencl/subgraph_opencl_kernel.h" #include "mindspore/lite/src/runtime/kernel/opencl/kernel/caffe_prelu.h" #include "mindspore/lite/src/runtime/kernel/arm/nnacl/caffeprelu.h" using mindspore::kernel::CaffePReluOpenCLKernel; using mindspore::kernel::LiteKernel; using mindspore::kernel::SubGraphOpenCLKernel; using mindspore::lite::RET_ERROR; using mindspore::lite::RET_OK; namespace mindspore { class TestCaffePReluOpenCL : public mindspore::CommonTest {}; void LoadDataCaffePRelu(void *dst, size_t dst_size, const std::string &file_path) { if (file_path.empty()) { memset(dst, 0x00, dst_size); } else { auto src_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(file_path.c_str(), &dst_size)); memcpy(dst, src_data, dst_size); } } void CompareOutCaffePRelu(lite::tensor::Tensor *output_tensor, const std::string &standard_answer_file) { auto *output_data = reinterpret_cast<float *>(output_tensor->Data()); size_t output_size = output_tensor->ElementsC4Num(); auto expect_data = reinterpret_cast<float *>(mindspore::lite::ReadFile(standard_answer_file.c_str(), &output_size)); constexpr float atol = 0.0002; for (int i = 0; i < output_tensor->ElementsC4Num(); ++i) { if (std::fabs(output_data[i] - expect_data[i]) > atol) { printf("error at idx[%d] expect=%.3f output=%.3f\n", i, expect_data[i], output_data[i]); printf("error at idx[%d] expect=%.3f output=%.3f\n", i, expect_data[i], output_data[i]); printf("error at idx[%d] expect=%.3f output=%.3f\n\n\n", i, expect_data[i], output_data[i]); return; } } printf("compare success!\n"); printf("compare success!\n"); printf("compare success!\n\n\n"); } void printf_tensor_caffeprelu(mindspore::lite::tensor::Tensor *in_data, int size) { auto input_data = reinterpret_cast<float *>(in_data->Data()); for (int i = 0; i < size; ++i) { printf("%f ", input_data[i]); } printf("\n"); MS_LOG(INFO) << "Print tensor done"; } void printf_float(float *data, int num = 0) { float *temp = data; for (int i = 0; i < num; ++i) { std::cout << *temp << " "; temp++; } std::cout << std::endl; } TEST_F(TestCaffePReluOpenCL, CaffePReluFp32_dim4) { std::string in_file = "/data/local/tmp/in_data.bin"; std::string weight_file = "/data/local/tmp/weight_data.bin"; std::string standard_answer_file = "/data/local/tmp/caffeprelu.bin"; MS_LOG(INFO) << "CaffePRelu Begin test:"; auto ocl_runtime = lite::opencl::OpenCLRuntime::GetInstance(); ocl_runtime->Init(); auto allocator = ocl_runtime->GetAllocator(); MS_LOG(INFO) << "CaffePRelu init tensors."; std::vector<int> input_shape = {1, 4, 3, 9}; std::vector<int> output_shape = {1, 4, 3, 9}; auto data_type = kNumberTypeFloat32; auto tensor_type = schema::NodeType_ValueNode; auto *input_tensor = new lite::tensor::Tensor(data_type, input_shape, schema::Format_NHWC, tensor_type); auto *output_tensor = new lite::tensor::Tensor(data_type, output_shape, schema::Format_NHWC4, tensor_type); auto *weight_tensor = new lite::tensor::Tensor(data_type, std::vector<int>{input_shape[3]}, schema::Format_NHWC, tensor_type); std::vector<lite::tensor::Tensor *> inputs{input_tensor, weight_tensor}; std::vector<lite::tensor::Tensor *> outputs{output_tensor}; std::cout << input_tensor->ElementsNum() << std::endl; std::cout << input_tensor->ElementsC4Num() << std::endl; // freamework to do!!! allocate memory by hand inputs[0]->MallocData(allocator); inputs[1]->MallocData(allocator); std::cout << input_tensor->Size() << std::endl; LoadDataCaffePRelu(input_tensor->Data(), input_tensor->Size(), in_file); MS_LOG(INFO) << "CaffePRelu==================input data================"; printf_tensor_caffeprelu(inputs[0], input_tensor->ElementsNum()); LoadDataCaffePRelu(weight_tensor->Data(), weight_tensor->Size(), weight_file); MS_LOG(INFO) << "CaffePRelu==================weight data================"; printf_tensor_caffeprelu(inputs[1], weight_tensor->ElementsNum()); auto param = new CaffePReluParameter(); param->channel_num_ = input_shape[3]; auto *caffeprelu_kernel = new (std::nothrow) kernel::CaffePReluOpenCLKernel(reinterpret_cast<OpParameter *>(param), inputs, outputs); if (caffeprelu_kernel == nullptr) { MS_LOG(ERROR) << "Create caffe prelu kernel error."; return; } auto ret = caffeprelu_kernel->Init(); if (ret != RET_OK) { MS_LOG(ERROR) << "caffeprelu_kernel init error."; return; } MS_LOG(INFO) << "initialize sub_graph"; std::vector<kernel::LiteKernel *> kernels{caffeprelu_kernel}; auto *sub_graph = new (std::nothrow) kernel::SubGraphOpenCLKernel({input_tensor}, outputs, kernels, kernels, kernels); if (sub_graph == nullptr) { MS_LOG(ERROR) << "Create sub_graph kernel error."; return; } ret = sub_graph->Init(); if (ret != RET_OK) { MS_LOG(ERROR) << "sub_graph init error."; return; } MS_LOG(INFO) << "Sub graph begin running!"; ret = sub_graph->Run(); if (ret != RET_OK) { MS_LOG(ERROR) << "sub_graph run error."; return; } MS_LOG(INFO) << "CaffePRelu==================output data================"; printf_tensor_caffeprelu(outputs[0], output_tensor->ElementsC4Num()); std::cout << "output date size:" << output_tensor->Size() << std::endl; CompareOutCaffePRelu(output_tensor, standard_answer_file); } } // namespace mindspore
40.314103
120
0.694705
Joejiong
15f4d31f88ce67a62deb26ce1f292cf05281ec77
541
cpp
C++
src/complementary.cpp
nerstak/Finite-Automata---Math-CS
2ffefc63e664d7a625096b710d6897182d9bc226
[ "MIT" ]
null
null
null
src/complementary.cpp
nerstak/Finite-Automata---Math-CS
2ffefc63e664d7a625096b710d6897182d9bc226
[ "MIT" ]
null
null
null
src/complementary.cpp
nerstak/Finite-Automata---Math-CS
2ffefc63e664d7a625096b710d6897182d9bc226
[ "MIT" ]
null
null
null
#include "FA.h" FA* FA::complementarize() { if (_completed) { cout << "Complementary automate obtained from"; if (_minimized) { cout << " minimized version." << endl; } else { cout << " just completed version." << endl; } FA* complementary = new FA(*this); for (State* st: complementary->_states) { st->final = !(st->final); } complementary->_name = _name + " Complementary"; return complementary; } return nullptr; }
24.590909
56
0.521257
nerstak
15f99663419b68e51365c7952c1b5cbce2603ae7
2,846
cpp
C++
jetson/carControl/src/0.3/peripheral_driver/uart/test_uart1.cpp
thanhwins/DriveCarLessChallenge
716304f3e25b383781ade5f1560ef0d538fc634e
[ "MIT" ]
1
2017-12-19T15:53:55.000Z
2017-12-19T15:53:55.000Z
jetson/carControl/src/0.3/peripheral_driver/uart/test_uart1.cpp
thanhwins/DriveCarLessChallenge
716304f3e25b383781ade5f1560ef0d538fc634e
[ "MIT" ]
null
null
null
jetson/carControl/src/0.3/peripheral_driver/uart/test_uart1.cpp
thanhwins/DriveCarLessChallenge
716304f3e25b383781ade5f1560ef0d538fc634e
[ "MIT" ]
1
2019-11-27T03:01:55.000Z
2019-11-27T03:01:55.000Z
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> int main(int argc,char** argv) { struct termios tio; struct termios stdio; struct termios old_stdio; int tty_fd; unsigned char c='D'; tcgetattr(STDOUT_FILENO,&old_stdio); printf("Please start with %s /dev/ttyACM0 (for example)\n",argv[0]); memset(&stdio,0,sizeof(stdio)); stdio.c_iflag=0; stdio.c_oflag=0; stdio.c_cflag=0; stdio.c_lflag=0; stdio.c_cc[VMIN]=1; stdio.c_cc[VTIME]=0; tcsetattr(STDOUT_FILENO,TCSANOW,&stdio); tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio); fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking memset(&tio,0,sizeof(tio)); tio.c_iflag=0; tio.c_oflag=0; tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information tio.c_lflag=0; tio.c_cc[VMIN]=1; tio.c_cc[VTIME]=5; tty_fd=open("/dev/ttyACM0", O_RDWR | O_NONBLOCK); cfsetospeed(&tio,B9600); // 115200 baud cfsetispeed(&tio,B9600); // 115200 baud tcsetattr(tty_fd,TCSANOW,&tio); char serial_buffer_recv[16]; for( int i = 0; i < 16; i++ ) serial_buffer_recv[i] = '0'; int nbyes = 15; while (true) { for( int i = 0; i < 100; i++) { int serial_read_ret = read(tty_fd, serial_buffer_recv, nbyes); if(serial_read_ret < 1 ) printf("\nError\n"); else { break; } usleep(100); } printf("%s\n\r", serial_buffer_recv); for( int i = 0; i < 15; i++ ) serial_buffer_recv[i] = '0'; usleep(450000); } // while (true) // { // for( int k = 0; k < 15; k++ ) // { // for( int i = 0; i < 100; i++) // { // int serial_read_ret = read(tty_fd, &serial_buffer_recv[k], 1); // if(serial_read_ret < 1 ) // printf("\nError\n"); // else // { // break; // } // usleep(100); // } // usleep(1000); // } // printf("Read from serial port: %s\n\r", serial_buffer_recv); // for( int i = 0; i < 15; i++ ) // serial_buffer_recv[i] = '0'; // usleep(500000); // } close(tty_fd); tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio); return EXIT_SUCCESS; }
26.110092
90
0.457484
thanhwins
15fa858fc057c4c095ab3813186fba42856993a2
824
cpp
C++
libs/filesystem/src/filesystem/file_size.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/filesystem/src/filesystem/file_size.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/filesystem/src/filesystem/file_size.cpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 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 <fcppt/const.hpp> #include <fcppt/filesystem/file_size.hpp> #include <fcppt/filesystem/optional_size.hpp> #include <fcppt/optional/make_if.hpp> #include <fcppt/config/external_begin.hpp> #include <cstdint> #include <filesystem> #include <fcppt/config/external_end.hpp> fcppt::filesystem::optional_size fcppt::filesystem::file_size( std::filesystem::path const &_path ) { std::uintmax_t const size{ std::filesystem::file_size( _path ) }; return fcppt::optional::make_if( size != static_cast< std::uintmax_t >( -1 ), fcppt::const_( size ) ); }
19.619048
61
0.686893
pmiddend
15fb708e0854b290dfdb1b737199793bfb7bcafe
5,074
cpp
C++
particleKernels/tst/twoBodyTest.cpp
lucaparisi91/qmc4
f1ad1b105568500c9a8259e509dd3e01a933a050
[ "MIT" ]
null
null
null
particleKernels/tst/twoBodyTest.cpp
lucaparisi91/qmc4
f1ad1b105568500c9a8259e509dd3e01a933a050
[ "MIT" ]
null
null
null
particleKernels/tst/twoBodyTest.cpp
lucaparisi91/qmc4
f1ad1b105568500c9a8259e509dd3e01a933a050
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "twoBodyPotential.h" #include <random> #include <cmath> #include "timers.h" #include "testUtils.h" using Real = double; using namespace particleKernels; TEST(twoBodyPotential, evaluate) { const int N=100; const int T=10; constexpr int D = 1; Real l =1; std::array<Real,D> lBox; for(int d=0;d<D;d++) { lBox[d]=l; } double * particles = new double[N*D*T]; double * forces = new double[N*D*T]; double * forcesCheck = new double[N*D*T]; int nTrials = 20; setConstant(forces,0,N-1,0,T-1,N,D,T, 0 ); setConstant(forcesCheck,0,N-1,0,T-1,N,D,T, 0 ); std::array<int,2> rangeA { 0,N/2}; std::array<int,2> rangeB { N/2 + 1, N-1}; std::array<int,2> rangeC { 0 , N-1}; int seed=10; std::default_random_engine generator(seed); generateRandomParticlesInBox(particles,0,N-1,0,T-1,N ,D, T, generator, lBox.data() ); twoBodyPotential<D> potAB(rangeA,rangeB,lBox,{N,D,T}); twoBodyPotential<D> potAA(rangeA,rangeA,lBox,{N,D,T}); twoBodyPotential<D> potBB(rangeB,rangeB,lBox,{N,D,T}); twoBodyPotential<D> potCC(rangeC,rangeC,lBox,{N,D,T}); potAA.setRange(rangeA,rangeA); gaussianPotential V(1); Real sum=0; Real sumCheck=0; for(int nT=0;nT<nTrials;nT++) { sum = potAB(V,particles,rangeA[0],rangeA[1],0,T-1); sumCheck=potAB(V,particles,rangeA[0],rangeB[1],0,T-1); ASSERT_NEAR(sumCheck,sum,1e-6); sumCheck=0; for(int t=0;t<=T-1;t++) for(int i=rangeA[0];i<=rangeA[1];i++) for(int j=rangeB[0];j<=rangeB[1];j++) { Real r2=0; for (int d=0;d<D;d++) { Real diffd=particles[ i + N*d + t*D*N] - particles[ j + N*d + t*D*N]; diffd=utils::differencePBC(diffd,lBox[d],1./lBox[d]); r2+=diffd*diffd; } sumCheck+=V(std::sqrt(r2)); } ASSERT_NEAR(sum,sumCheck,1e-6); } sum = potAA(V,particles,rangeA[0],rangeA[1],0,T-1); sumCheck=0; for(int t=0;t<=T-1;t++) for(int i=rangeA[0];i<=rangeA[1];i++) for(int j=rangeA[0];j<i;j++) { Real r2=0; for (int d=0;d<D;d++) { Real diffd=particles[ i + N*d + t*D*N] - particles[ j + N*d + t*D*N]; diffd=utils::differencePBC(diffd,lBox[d],1./lBox[d]); r2+=diffd*diffd; } sumCheck+=V(std::sqrt(r2)); } ASSERT_NEAR(sum,sumCheck,1e-6); // test on multiple partial updates std::uniform_int_distribution<int> disIndexA(rangeA[0],rangeA[1]); std::uniform_int_distribution<int> disIndexB(rangeB[0],rangeB[1]); std::uniform_int_distribution<int> disIndexAB(rangeA[0],rangeB[1]); auto sumABOld = potAB(V,particles,rangeA[0],rangeA[1],0,T-1); auto sumAAOld = potAA(V,particles,rangeA[0],rangeA[1],0,T-1); int t0=0; int t1=T-1; for (int nT=0;nT<nTrials;nT++) { //std::cout << nT << std::flush << std::endl; int iStart= disIndexAB(generator); int iEnd= disIndexAB(generator); auto deltaSumAB=-potAB(V,particles,iStart,iEnd,0,T-1); auto deltaSumAA=-potAA(V,particles,iStart,iEnd,0,T-1); generateRandomParticlesInBox(particles,iStart,iEnd,t0,t1,N ,D, T, generator, lBox.data() ); deltaSumAB+=potAB(V,particles,iStart,iEnd,0,T-1); deltaSumAA+=potAA(V,particles,iStart,iEnd,0,T-1); auto sumABNew = sumABOld +deltaSumAB; auto sumAANew = sumAAOld +deltaSumAA; auto sumABNewCheck = potAB(V,particles,rangeA[0],rangeB[1],0,T-1); auto sumAANewCheck = potAA(V,particles,rangeA[0],rangeA[1],0,T-1); ASSERT_NEAR(sumABNewCheck,sumABNew,1e-5); ASSERT_NEAR(sumAANewCheck,sumAANew,1e-5); sumAAOld=sumAANewCheck; sumABOld=sumABNewCheck; } { // triangular two body forces and potential of a set C should be the same when split into two different sets A + B auto sumAA = potAA(V,particles,rangeA[0],rangeB[1],0,T-1); auto sumAB = potAB(V,particles,rangeA[0],rangeB[1],0,T-1); auto sumBB = potBB(V,particles,rangeA[0],rangeB[1],0,T-1); auto sumCC = potCC(V,particles,rangeA[0],rangeB[1],0,T-1); sum=sumAA + sumAB + sumBB; ASSERT_NEAR(sumCC,sum,1e-6); potAA.addForce(V,particles,forces,rangeA[0],rangeA[1],0,T-1); potBB.addForce(V,particles,forces,rangeB[0],rangeB[1],0,T-1); potAB.addForce(V,particles,forces,rangeA[0],rangeB[1],0,T-1); potCC.addForce(V,particles,forcesCheck,rangeA[0],rangeB[1],0,T-1); for(int i=0;i<N*D*T;i++) { ASSERT_NEAR(forcesCheck[i],forces[i],1e-6); } } }
26.020513
118
0.55203
lucaparisi91
15fead12ef5fd9b20de544e14e9babeb934ae2ad
866
hpp
C++
Web-Server/include/Server.hpp
marmal95/Web-Server
6f1fc5fe75d7ca516697a93149880a9c67933a2c
[ "MIT" ]
null
null
null
Web-Server/include/Server.hpp
marmal95/Web-Server
6f1fc5fe75d7ca516697a93149880a9c67933a2c
[ "MIT" ]
null
null
null
Web-Server/include/Server.hpp
marmal95/Web-Server
6f1fc5fe75d7ca516697a93149880a9c67933a2c
[ "MIT" ]
null
null
null
#pragma once #include "IServer.hpp" #include "RequestHandler.hpp" #include "ConnectionManager.hpp" #include "ResponseBuilder.hpp" #include "RequestParser.hpp" #include <string> #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> namespace web { using namespace boost::asio; using namespace boost::asio::ip; class Server : public IServer { public: Server(std::string_view address, uint32_t port, std::string_view root_dir); Server(const Server&) = delete; Server& operator=(const Server&) = delete; void start() override; void stop() override; void reset() override; private: io_service service_io; tcp::acceptor tcp_acceptor; tcp::socket tcp_socket; ResponseBuilder response_builder; RequestHandler request_handler; RequestParser request_parser; ConnectionManager connection_manager; void accept(); }; }
20.619048
77
0.748268
marmal95
c6008a802c6d22a4acb6acef6e2bf8db635ca5dc
400
cpp
C++
sum_values.cpp
lionkor/cpp-examples
6458ab8b1ae383215e4a2148e427bccbf7e27e41
[ "MIT" ]
null
null
null
sum_values.cpp
lionkor/cpp-examples
6458ab8b1ae383215e4a2148e427bccbf7e27e41
[ "MIT" ]
null
null
null
sum_values.cpp
lionkor/cpp-examples
6458ab8b1ae383215e4a2148e427bccbf7e27e41
[ "MIT" ]
null
null
null
#include <iostream> int main() { int numbers[10]; for (int i = 0; i < 10; ++i) { // i + 1 so that it's 1-10 instead of 0-9 std::cout << "Enter number (" << i + 1 << "/10): "; std::cin >> numbers[i]; } // now sum them up int sum = 0; for (int i = 0; i < 10; ++i) { sum += numbers[i]; } std::cout << "The sum is " << sum << std::endl; }
23.529412
59
0.435
lionkor
c603d09c1ccdd018fb99196aa32f1eaa159c4b14
3,605
cpp
C++
vm/compiler/codegen/x86/NcgHelper.cpp
leewp14/android_dalvik
c1202ff8b476a3445f3b844c795ffe47ab526313
[ "Apache-2.0" ]
1,306
2015-09-01T05:06:16.000Z
2022-03-10T07:13:10.000Z
dalvik/vm/compiler/codegen/x86/NcgHelper.cpp
cnrat/DexHunter
b8f46563c7f3aeb79cf40db09e1d231649f1a29a
[ "Apache-2.0" ]
11
2015-09-02T09:06:42.000Z
2020-12-26T04:59:34.000Z
dalvik/vm/compiler/codegen/x86/NcgHelper.cpp
cnrat/DexHunter
b8f46563c7f3aeb79cf40db09e1d231649f1a29a
[ "Apache-2.0" ]
598
2015-09-01T05:06:18.000Z
2022-03-27T07:59:49.000Z
/* * Copyright (C) 2012 The Android Open Source Project * * 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 "Dalvik.h" #include "NcgHelper.h" #include "interp/InterpDefs.h" /* * Find the matching case. Returns the offset to the handler instructions. * * Returns 3 if we don't find a match (it's the size of the packed-switch * instruction). */ s4 dvmNcgHandlePackedSwitch(const s4* entries, s4 firstKey, u2 size, s4 testVal) { //skip add_reg_reg (ADD_REG_REG_SIZE) and jump_reg (JUMP_REG_SIZE) const int kInstrLen = 4; //default to next bytecode if (testVal < firstKey || testVal >= firstKey + size) { LOGVV("Value %d not found in switch (%d-%d)", testVal, firstKey, firstKey+size-1); return kInstrLen; } assert(testVal - firstKey >= 0 && testVal - firstKey < size); LOGVV("Value %d found in slot %d (goto 0x%02x)", testVal, testVal - firstKey, s4FromSwitchData(&entries[testVal - firstKey])); return s4FromSwitchData(&entries[testVal - firstKey]); } /* return the number of bytes to increase the bytecode pointer by */ s4 dvmJitHandlePackedSwitch(const s4* entries, s4 firstKey, u2 size, s4 testVal) { if (testVal < firstKey || testVal >= firstKey + size) { LOGVV("Value %d not found in switch (%d-%d)", testVal, firstKey, firstKey+size-1); return 2*3;//bytecode packed_switch is 6(2*3) bytes long } LOGVV("Value %d found in slot %d (goto 0x%02x)", testVal, testVal - firstKey, s4FromSwitchData(&entries[testVal - firstKey])); return 2*s4FromSwitchData(&entries[testVal - firstKey]); //convert from u2 to byte } /* * Find the matching case. Returns the offset to the handler instructions. * * Returns 3 if we don't find a match (it's the size of the sparse-switch * instruction). */ s4 dvmNcgHandleSparseSwitch(const s4* keys, u2 size, s4 testVal) { const int kInstrLen = 4; //CHECK const s4* entries = keys + size; int i; for (i = 0; i < size; i++) { s4 k = s4FromSwitchData(&keys[i]); if (k == testVal) { LOGVV("Value %d found in entry %d (goto 0x%02x)", testVal, i, s4FromSwitchData(&entries[i])); return s4FromSwitchData(&entries[i]); } else if (k > testVal) { break; } } LOGVV("Value %d not found in switch", testVal); return kInstrLen; } /* return the number of bytes to increase the bytecode pointer by */ s4 dvmJitHandleSparseSwitch(const s4* keys, u2 size, s4 testVal) { const s4* entries = keys + size; int i; for (i = 0; i < size; i++) { s4 k = s4FromSwitchData(&keys[i]); if (k == testVal) { LOGVV("Value %d found in entry %d (goto 0x%02x)", testVal, i, s4FromSwitchData(&entries[i])); return 2*s4FromSwitchData(&entries[i]); //convert from u2 to byte } else if (k > testVal) { break; } } LOGVV("Value %d not found in switch", testVal); return 2*3; //bytecode sparse_switch is 6(2*3) bytes long }
34.333333
86
0.639667
leewp14
c603f74b4fb65b5c383dc8289e2725dbba2dbe58
4,449
cpp
C++
demo/gpu_scatter_mpi/main.cpp
Excalibur-SLE/wave-fenics
2d3345c4cffecbe382acd1005a9dcc2bbc62ad1c
[ "MIT" ]
1
2022-02-27T23:36:14.000Z
2022-02-27T23:36:14.000Z
demo/gpu_scatter_mpi/main.cpp
Excalibur-SLE/wave-fenics
2d3345c4cffecbe382acd1005a9dcc2bbc62ad1c
[ "MIT" ]
5
2022-02-23T13:22:29.000Z
2022-03-01T12:40:10.000Z
demo/gpu_scatter_mpi/main.cpp
Excalibur-SLE/wave-fenics
2d3345c4cffecbe382acd1005a9dcc2bbc62ad1c
[ "MIT" ]
null
null
null
// Copyright (C) 2022 Chris Richardson and Athena Elafrou // SPDX-License-Identifier: MIT #include <basix/e-lagrange.h> #include <boost/program_options.hpp> #include <cmath> #include <dolfinx.h> #include <dolfinx/common/Timer.h> #include <dolfinx/common/log.h> #include <dolfinx/io/XDMFFile.h> #include <iostream> #include <memory> #include <cuda_profiler_api.h> #include <nvToolsExt.h> // Helper functions #include <cuda/allocator.hpp> #include <cuda/la.hpp> #include <cuda/utils.hpp> #include "VectorUpdater.hpp" using namespace dolfinx; namespace po = boost::program_options; int main(int argc, char* argv[]) { po::options_description desc("Allowed options"); desc.add_options()("help,h", "print usage message")( "size", po::value<std::size_t>()->default_value(32))( "degree", po::value<int>()->default_value(1)); po::variables_map vm; po::store(po::command_line_parser(argc, argv) .options(desc) .allow_unregistered() .run(), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; return 0; } const std::size_t Nx = vm["size"].as<std::size_t>(); const int degree = vm["degree"].as<int>(); // common::subsystem::init_logging(argc, argv); common::subsystem::init_mpi(argc, argv); { // MPI MPI_Comm mpi_comm{MPI_COMM_WORLD}; MPI_Comm local_comm; MPI_Comm_split_type(mpi_comm, MPI_COMM_TYPE_SHARED, 0, MPI_INFO_NULL, &local_comm); int gpu_rank = utils::set_device(local_comm); int mpi_rank = dolfinx::MPI::rank(mpi_comm); MPI_Comm_free(&local_comm); std::string thread_name = "MPI: " + std::to_string(mpi_rank); loguru::set_thread_name(thread_name.c_str()); MPI_Datatype data_type = dolfinx::MPI::mpi_type<double>(); LOG(INFO) << "GPU rank=" << gpu_rank; // Read mesh and mesh tags std::array<std::array<double, 3>, 2> p = {{{0.0, 0.0, 0.0}, {1.0, 1.0, 1.0}}}; std::array<std::size_t, 3> n = {Nx, Nx, Nx}; auto mesh = std::make_shared<mesh::Mesh>(mesh::create_box( mpi_comm, p, n, mesh::CellType::hexahedron, mesh::GhostMode::none)); // Create a Basix continuous Lagrange element of given degree basix::FiniteElement e = basix::element::create_lagrange( mesh::cell_type_to_basix_type(mesh::CellType::hexahedron), degree, basix::element::lagrange_variant::equispaced, false); // Create a scalar function space auto V = std::make_shared<fem::FunctionSpace>( fem::create_functionspace(mesh, e, 1)); auto idxmap = V->dofmap()->index_map; // Start profiling cudaProfilerStart(); // Assemble RHS vector LOG(INFO) << "Allocate vector"; CUDA::allocator<double> allocator{}; la::Vector<double, decltype(allocator)> x(idxmap, 1, allocator); // Fill with rank values x.set((double)mpi_rank); VectorUpdater vu(x); nvtxMarkA("prefetch"); // Prefetch data to gpu linalg::prefetch(gpu_rank, x); nvtxMarkA("update_fwd"); for (int i = 0; i < 50; ++i) vu.update_fwd(x); nvtxMarkA("scatter_fwd"); for (int i = 0; i < 50; ++i) x.scatter_fwd(); nvtxMarkA("update_rev"); for (int i = 0; i < 50; ++i) vu.update_rev(x); nvtxMarkA("scatter_rev"); for (int i = 0; i < 50; ++i) x.scatter_rev(dolfinx::common::IndexMap::Mode::add); nvtxMarkA("end"); // End profiling cudaProfilerStop(); common::subsystem::finalize_mpi(); return 0; // Now some timings dolfinx::common::Timer tcuda("Fwd CUDA-MPI"); LOG(INFO) << "CUDA MPI updates"; { for (int i = 0; i < 10000; ++i) vu.update_fwd(x); } tcuda.stop(); dolfinx::common::Timer tcpu("Fwd CPU-MPI"); LOG(INFO) << "CPU MPI updates"; { for (int i = 0; i < 10000; ++i) x.scatter_fwd(); } tcpu.stop(); dolfinx::common::Timer tcuda2("Rev CUDA-MPI"); LOG(INFO) << "CUDA MPI rev updates"; { for (int i = 0; i < 10000; ++i) vu.update_rev(x); } tcuda2.stop(); dolfinx::common::Timer tcpu2("Rev CPU-MPI"); LOG(INFO) << "CPU MPI rev updates"; { for (int i = 0; i < 10000; ++i) x.scatter_rev(dolfinx::common::IndexMap::Mode::add); } tcpu2.stop(); } dolfinx::list_timings(MPI_COMM_WORLD, {dolfinx::TimingType::wall}); common::subsystem::finalize_mpi(); return 0; }
26.482143
76
0.613846
Excalibur-SLE
c606b9b63403c11c92230eed5ee8a047eb00ecd3
2,728
cpp
C++
searchlib/src/vespa/searchlib/memoryindex/field_index_collection.cpp
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
searchlib/src/vespa/searchlib/memoryindex/field_index_collection.cpp
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
searchlib/src/vespa/searchlib/memoryindex/field_index_collection.cpp
alexeyche/vespa
7585981b32937d2b13da1a8f94b42c8a0833a4c2
[ "Apache-2.0" ]
null
null
null
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "field_index_collection.h" #include "field_inverter.h" #include "ordered_field_index_inserter.h" #include <vespa/searchlib/bitcompression/posocccompression.h> #include <vespa/searchlib/index/i_field_length_inspector.h> #include <vespa/searchcommon/common/schema.h> #include <vespa/vespalib/btree/btree.hpp> #include <vespa/vespalib/btree/btreeiterator.hpp> #include <vespa/vespalib/btree/btreenode.hpp> #include <vespa/vespalib/btree/btreenodeallocator.hpp> #include <vespa/vespalib/btree/btreenodestore.hpp> #include <vespa/vespalib/btree/btreeroot.hpp> #include <vespa/vespalib/btree/btreestore.hpp> #include <vespa/vespalib/util/exceptions.h> namespace search { using index::DocIdAndFeatures; using index::IFieldLengthInspector; using index::Schema; using index::WordDocElementFeatures; namespace memoryindex { FieldIndexCollection::FieldIndexCollection(const Schema& schema, const IFieldLengthInspector& inspector) : _fieldIndexes(), _numFields(schema.getNumIndexFields()) { for (uint32_t fieldId = 0; fieldId < _numFields; ++fieldId) { const auto& field = schema.getIndexField(fieldId); if (field.use_interleaved_features()) { _fieldIndexes.push_back(std::make_unique<FieldIndex<true>>(schema, fieldId, inspector.get_field_length_info(field.getName()))); } else { _fieldIndexes.push_back(std::make_unique<FieldIndex<false>>(schema, fieldId, inspector.get_field_length_info(field.getName()))); } } } FieldIndexCollection::~FieldIndexCollection() = default; void FieldIndexCollection::dump(search::index::IndexBuilder &indexBuilder) { for (uint32_t fieldId = 0; fieldId < _numFields; ++fieldId) { indexBuilder.startField(fieldId); _fieldIndexes[fieldId]->dump(indexBuilder); indexBuilder.endField(); } } vespalib::MemoryUsage FieldIndexCollection::getMemoryUsage() const { vespalib::MemoryUsage usage; for (auto &fieldIndex : _fieldIndexes) { usage.merge(fieldIndex->getMemoryUsage()); } return usage; } FieldIndexRemover & FieldIndexCollection::get_remover(uint32_t field_id) { return _fieldIndexes[field_id]->getDocumentRemover(); } IOrderedFieldIndexInserter & FieldIndexCollection::get_inserter(uint32_t field_id) { return _fieldIndexes[field_id]->getInserter(); } index::FieldLengthCalculator & FieldIndexCollection::get_calculator(uint32_t field_id) { return _fieldIndexes[field_id]->get_calculator(); } } }
32.094118
123
0.718109
alexeyche
c6078ef854ae11e3009b24840b26c3d4d4277f1c
1,542
cpp
C++
Pener SDK/FEATURES/Fakewalk.cpp
younasiqw/Thulium-Beta
968591340449e65824458142a40c1f35ce17f3ac
[ "Apache-2.0" ]
null
null
null
Pener SDK/FEATURES/Fakewalk.cpp
younasiqw/Thulium-Beta
968591340449e65824458142a40c1f35ce17f3ac
[ "Apache-2.0" ]
null
null
null
Pener SDK/FEATURES/Fakewalk.cpp
younasiqw/Thulium-Beta
968591340449e65824458142a40c1f35ce17f3ac
[ "Apache-2.0" ]
1
2019-04-02T17:36:55.000Z
2019-04-02T17:36:55.000Z
#include "../includes.h" #include "../UTILS/interfaces.h" #include "../SDK/IEngine.h" #include "../SDK/CUserCmd.h" #include "../SDK/CBaseEntity.h" #include "../SDK/CClientEntityList.h" #include "../SDK/CTrace.h" #include "../SDK/CBaseWeapon.h" #include "../SDK/CGlobalVars.h" #include "../SDK/NetChannel.h" #include "../SDK/CBaseAnimState.h" #include "../SDK/ConVar.h" #include "../FEATURES/AutoWall.h" #include "../FEATURES/Fakewalk.h" #include "../FEATURES/Aimbot.h" #include <time.h> #include <iostream> void CFakewalk::do_fakewalk(SDK::CUserCmd* cmd) { if (UTILS::INPUT::input_handler.GetKeyState(UTILS::INPUT::input_handler.keyBindings(SETTINGS::settings.fakewalk_key)) & 1) { auto local_player = INTERFACES::ClientEntityList->GetClientEntity(INTERFACES::Engine->GetLocalPlayer()); if (!local_player || local_player->GetHealth() <= 0) return; auto net_channel = INTERFACES::Engine->GetNetChannel(); if (!net_channel) return; auto animstate = local_player->GetAnimState(); if (!animstate) return; fake_walk = true; if (fabs(local_update - INTERFACES::Globals->curtime) <= 0.05) { cmd->move.x = 450; aimbot->rotate_movement(UTILS::CalcAngle(Vector(0, 0, 0), local_player->GetVelocity()).y + 180.f, cmd); } static int choked = 0; choked = choked > 7 ? 0 : choked + 1; cmd->move.x = choked < 2 || choked > 5 ? 0 : cmd->move.x; cmd->move.y = choked < 2 || choked > 5 ? 0 : cmd->move.y; GLOBAL::should_send_packet = choked < 1; } else fake_walk = false; } CFakewalk* fakewalk = new CFakewalk();
30.84
123
0.681582
younasiqw
c608bb0a31e9f235b918cf67acf16af88eba5e73
3,122
cpp
C++
llvm/lib/CodeGen/WinEHPrepare.cpp
impedimentToProgress/ratchet
4a0f4994ee7e16819849fc0a1a1dbb04921a25fd
[ "MIT" ]
4
2018-12-31T04:46:13.000Z
2021-02-04T15:11:03.000Z
llvm/lib/CodeGen/WinEHPrepare.cpp
impedimentToProgress/ratchet
4a0f4994ee7e16819849fc0a1a1dbb04921a25fd
[ "MIT" ]
null
null
null
llvm/lib/CodeGen/WinEHPrepare.cpp
impedimentToProgress/ratchet
4a0f4994ee7e16819849fc0a1a1dbb04921a25fd
[ "MIT" ]
3
2017-10-28T16:15:33.000Z
2021-11-16T05:11:43.000Z
//===-- WinEHPrepare - Prepare exception handling for code generation ---===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass lowers LLVM IR exception handling into something closer to what the // backend wants. It snifs the personality function to see which kind of // preparation is necessary. If the personality function uses the Itanium LSDA, // this pass delegates to the DWARF EH preparation pass. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "llvm/Analysis/LibCallSemantics.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Instructions.h" #include "llvm/Pass.h" #include <memory> using namespace llvm; #define DEBUG_TYPE "winehprepare" namespace { class WinEHPrepare : public FunctionPass { std::unique_ptr<FunctionPass> DwarfPrepare; public: static char ID; // Pass identification, replacement for typeid. WinEHPrepare(const TargetMachine *TM = nullptr) : FunctionPass(ID), DwarfPrepare(createDwarfEHPass(TM)) {} bool runOnFunction(Function &Fn) override; bool doFinalization(Module &M) override; void getAnalysisUsage(AnalysisUsage &AU) const override; const char *getPassName() const override { return "Windows exception handling preparation"; } }; } // end anonymous namespace char WinEHPrepare::ID = 0; INITIALIZE_TM_PASS(WinEHPrepare, "winehprepare", "Prepare Windows exceptions", false, false) FunctionPass *llvm::createWinEHPass(const TargetMachine *TM) { return new WinEHPrepare(TM); } static bool isMSVCPersonality(EHPersonality Pers) { return Pers == EHPersonality::MSVC_Win64SEH || Pers == EHPersonality::MSVC_CXX; } bool WinEHPrepare::runOnFunction(Function &Fn) { SmallVector<LandingPadInst *, 4> LPads; SmallVector<ResumeInst *, 4> Resumes; for (BasicBlock &BB : Fn) { if (auto *LP = BB.getLandingPadInst()) LPads.push_back(LP); if (auto *Resume = dyn_cast<ResumeInst>(BB.getTerminator())) Resumes.push_back(Resume); } // No need to prepare functions that lack landing pads. if (LPads.empty()) return false; // Classify the personality to see what kind of preparation we need. EHPersonality Pers = ClassifyEHPersonality(LPads.back()->getPersonalityFn()); // Delegate through to the DWARF pass if this is unrecognized. if (!isMSVCPersonality(Pers)) return DwarfPrepare->runOnFunction(Fn); // FIXME: Cleanups are unimplemented. Replace them with unreachable. if (Resumes.empty()) return false; for (ResumeInst *Resume : Resumes) { IRBuilder<>(Resume).CreateUnreachable(); Resume->eraseFromParent(); } return true; } bool WinEHPrepare::doFinalization(Module &M) { return DwarfPrepare->doFinalization(M); } void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const { DwarfPrepare->getAnalysisUsage(AU); }
30.31068
80
0.688341
impedimentToProgress
c60aa953d8aabd149415ea1f7cbea98518ee6427
241
hpp
C++
src/game_window_opt_opengl.hpp
bggd/game_window
da9474472dd4988f4926fa2b50734b0ffa3b10af
[ "MIT" ]
null
null
null
src/game_window_opt_opengl.hpp
bggd/game_window
da9474472dd4988f4926fa2b50734b0ffa3b10af
[ "MIT" ]
null
null
null
src/game_window_opt_opengl.hpp
bggd/game_window
da9474472dd4988f4926fa2b50734b0ffa3b10af
[ "MIT" ]
null
null
null
namespace gwin { struct GameWindowOptionOpenGL { bool fullscreen; bool resizable; bool set_pos; int32_t x, y; uint32_t w, h; bool gles; uint8_t major; uint8_t minor; bool debug_ctx; bool vsync; }; } // namespace gwin
12.684211
31
0.684647
bggd
c60ab8ca2a3c1188b8057b04bed3cfb3d57375a5
80,781
cpp
C++
indra/newview/llfloatertools.cpp
SaladDais/LLUDP-Encryption
8a426cd0dd154e1a10903e0e6383f4deb2a6098a
[ "ISC" ]
1
2022-01-29T07:10:03.000Z
2022-01-29T07:10:03.000Z
indra/newview/llfloatertools.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
null
null
null
indra/newview/llfloatertools.cpp
bloomsirenix/Firestorm-manikineko
67e1bb03b2d05ab16ab98097870094a8cc9de2e7
[ "Unlicense" ]
1
2021-10-01T22:22:27.000Z
2021-10-01T22:22:27.000Z
/** * @file llfloatertools.cpp * @brief The edit tools, including move, position, land, etc. * * $LicenseInfo:firstyear=2002&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llfloatertools.h" #include "llfontgl.h" #include "llcoord.h" //#include "llgl.h" #include "llagent.h" #include "llagentcamera.h" #include "llbutton.h" #include "llcheckboxctrl.h" #include "llcombobox.h" #include "lldraghandle.h" #include "llerror.h" #include "llfloaterbuildoptions.h" #include "llfloatermediasettings.h" #include "llfloateropenobject.h" #include "llfloaterobjectweights.h" #include "llfloaterreg.h" #include "llfocusmgr.h" #include "llmediaentry.h" #include "llmediactrl.h" #include "llmenugl.h" #include "llnotificationsutil.h" #include "llpanelcontents.h" #include "llpanelface.h" #include "llpanelland.h" #include "llpanelobjectinventory.h" #include "llpanelobject.h" #include "llpanelvolume.h" #include "llpanelpermissions.h" #include "llparcel.h" #include "llradiogroup.h" #include "llresmgr.h" #include "llselectmgr.h" #include "llslider.h" #include "llstatusbar.h" #include "lltabcontainer.h" #include "lltextbox.h" #include "lltoolbrush.h" #include "lltoolcomp.h" #include "lltooldraganddrop.h" #include "lltoolface.h" #include "lltoolfocus.h" #include "lltoolgrab.h" #include "lltoolgrab.h" #include "lltoolindividual.h" #include "lltoolmgr.h" #include "lltoolpie.h" #include "lltoolpipette.h" #include "lltoolplacer.h" #include "lltoolselectland.h" #include "lltrans.h" #include "llui.h" #include "llviewercontrol.h" #include "llviewerjoystick.h" #include "llviewerregion.h" #include "llviewermenu.h" #include "llviewerparcelmgr.h" #include "llviewerwindow.h" #include "llvovolume.h" #include "lluictrlfactory.h" #include "qtoolalign.h" #include "llselectmgr.h" #include "llmeshrepository.h" #include "llviewernetwork.h" // <FS:CR> Aurora Sim #include "llvograss.h" #include "llvotree.h" // Globals LLFloaterTools *gFloaterTools = NULL; bool LLFloaterTools::sShowObjectCost = true; bool LLFloaterTools::sPreviousFocusOnAvatar = false; const std::string PANEL_NAMES[LLFloaterTools::PANEL_COUNT] = { std::string("General"), // PANEL_GENERAL, std::string("Object"), // PANEL_OBJECT, std::string("Features"), // PANEL_FEATURES, std::string("Texture"), // PANEL_FACE, std::string("Content"), // PANEL_CONTENTS, }; // Local prototypes void commit_grid_mode(LLUICtrl *ctrl); void commit_select_component(void *data); //void click_show_more(void*); void click_popup_info(void*); void click_popup_done(void*); void click_popup_minimize(void*); void commit_slider_dozer_force(LLUICtrl *); void click_apply_to_selection(void*); void commit_radio_group_focus(LLUICtrl* ctrl); void commit_radio_group_move(LLUICtrl* ctrl); void commit_radio_group_edit(LLUICtrl* ctrl); void commit_radio_group_land(LLUICtrl* ctrl); void commit_grid_mode(LLUICtrl *); void commit_slider_zoom(LLUICtrl *ctrl); // <FS:KC> show/hide build highlight void commit_show_highlight(void *ctrl); /** * Class LLLandImpactsObserver * * An observer class to monitor parcel selection and update * the land impacts data from a parcel containing the selected object. */ class LLLandImpactsObserver : public LLParcelObserver { public: virtual void changed() { LLFloaterTools* tools_floater = LLFloaterReg::getTypedInstance<LLFloaterTools>("build"); if(tools_floater) { tools_floater->updateLandImpacts(); } } }; //static void* LLFloaterTools::createPanelPermissions(void* data) { LLFloaterTools* floater = (LLFloaterTools*)data; floater->mPanelPermissions = new LLPanelPermissions(); return floater->mPanelPermissions; } //static void* LLFloaterTools::createPanelObject(void* data) { LLFloaterTools* floater = (LLFloaterTools*)data; floater->mPanelObject = new LLPanelObject(); return floater->mPanelObject; } //static void* LLFloaterTools::createPanelVolume(void* data) { LLFloaterTools* floater = (LLFloaterTools*)data; floater->mPanelVolume = new LLPanelVolume(); return floater->mPanelVolume; } //static void* LLFloaterTools::createPanelFace(void* data) { LLFloaterTools* floater = (LLFloaterTools*)data; floater->mPanelFace = new LLPanelFace(); return floater->mPanelFace; } //static void* LLFloaterTools::createPanelContents(void* data) { LLFloaterTools* floater = (LLFloaterTools*)data; floater->mPanelContents = new LLPanelContents(); return floater->mPanelContents; } //static void* LLFloaterTools::createPanelLandInfo(void* data) { LLFloaterTools* floater = (LLFloaterTools*)data; floater->mPanelLandInfo = new LLPanelLandInfo(); return floater->mPanelLandInfo; } static const std::string toolNames[]={ "ToolCube", "ToolPrism", "ToolPyramid", "ToolTetrahedron", "ToolCylinder", "ToolHemiCylinder", "ToolCone", "ToolHemiCone", "ToolSphere", "ToolHemiSphere", "ToolTorus", "ToolTube", "ToolRing", "ToolTree", "ToolGrass"}; LLPCode toolData[]={ LL_PCODE_CUBE, LL_PCODE_PRISM, LL_PCODE_PYRAMID, LL_PCODE_TETRAHEDRON, LL_PCODE_CYLINDER, LL_PCODE_CYLINDER_HEMI, LL_PCODE_CONE, LL_PCODE_CONE_HEMI, LL_PCODE_SPHERE, LL_PCODE_SPHERE_HEMI, LL_PCODE_TORUS, LLViewerObject::LL_VO_SQUARE_TORUS, LLViewerObject::LL_VO_TRIANGLE_TORUS, LL_PCODE_LEGACY_TREE, LL_PCODE_LEGACY_GRASS}; BOOL LLFloaterTools::postBuild() { // Hide until tool selected setVisible(FALSE); // Since we constantly show and hide this during drags, don't // make sounds on visibility changes. setSoundFlags(LLView::SILENT); getDragHandle()->setEnabled( !gSavedSettings.getBOOL("ToolboxAutoMove") ); LLRect rect; mBtnFocus = getChild<LLButton>("button focus");//btn; mBtnMove = getChild<LLButton>("button move"); mBtnEdit = getChild<LLButton>("button edit"); mBtnCreate = getChild<LLButton>("button create"); mBtnLand = getChild<LLButton>("button land" ); mTextStatus = getChild<LLTextBox>("text status"); mRadioGroupFocus = getChild<LLRadioGroup>("focus_radio_group"); mRadioGroupMove = getChild<LLRadioGroup>("move_radio_group"); mRadioGroupEdit = getChild<LLRadioGroup>("edit_radio_group"); mBtnGridOptions = getChild<LLButton>("Options..."); mTitleMedia = getChild<LLMediaCtrl>("title_media"); mBtnLink = getChild<LLButton>("link_btn"); mBtnUnlink = getChild<LLButton>("unlink_btn"); // <FS:PP> FIRE-14493: Buttons to cycle through linkset mBtnPrevPart = getChild<LLButton>("prev_part_btn"); mBtnNextPart = getChild<LLButton>("next_part_btn"); // </FS:PP> mCheckSelectIndividual = getChild<LLCheckBoxCtrl>("checkbox edit linked parts"); getChild<LLUICtrl>("checkbox edit linked parts")->setValue((BOOL)gSavedSettings.getBOOL("EditLinkedParts")); mCheckSnapToGrid = getChild<LLCheckBoxCtrl>("checkbox snap to grid"); getChild<LLUICtrl>("checkbox snap to grid")->setValue((BOOL)gSavedSettings.getBOOL("SnapEnabled")); mCheckStretchUniform = getChild<LLCheckBoxCtrl>("checkbox uniform"); getChild<LLUICtrl>("checkbox uniform")->setValue((BOOL)gSavedSettings.getBOOL("ScaleUniform")); mCheckStretchTexture = getChild<LLCheckBoxCtrl>("checkbox stretch textures"); getChild<LLUICtrl>("checkbox stretch textures")->setValue((BOOL)gSavedSettings.getBOOL("ScaleStretchTextures")); mComboGridMode = getChild<LLComboBox>("combobox grid mode"); // <FS:KC> show highlight mCheckShowHighlight = getChild<LLCheckBoxCtrl>("checkbox show highlight"); mCheckShowHighlight->setValue(gSavedSettings.getBOOL("RenderHighlightSelections")); LLSelectMgr::instance().setFSShowHideHighlight(FS_SHOW_HIDE_HIGHLIGHT_NORMAL); mCheckActualRoot = getChild<LLCheckBoxCtrl>("checkbox actual root"); // </FS:KC> // // Create Buttons // for(size_t t=0; t<LL_ARRAY_SIZE(toolNames); ++t) { LLButton *found = getChild<LLButton>(toolNames[t]); if(found) { found->setClickedCallback(boost::bind(&LLFloaterTools::setObjectType, toolData[t])); mButtons.push_back( found ); }else{ LL_WARNS() << "Tool button not found! DOA Pending." << LL_ENDL; } } mCheckCopySelection = getChild<LLCheckBoxCtrl>("checkbox copy selection"); getChild<LLUICtrl>("checkbox copy selection")->setValue((BOOL)gSavedSettings.getBOOL("CreateToolCopySelection")); mCheckSticky = getChild<LLCheckBoxCtrl>("checkbox sticky"); getChild<LLUICtrl>("checkbox sticky")->setValue((BOOL)gSavedSettings.getBOOL("CreateToolKeepSelected")); mCheckCopyCenters = getChild<LLCheckBoxCtrl>("checkbox copy centers"); getChild<LLUICtrl>("checkbox copy centers")->setValue((BOOL)gSavedSettings.getBOOL("CreateToolCopyCenters")); mCheckCopyRotates = getChild<LLCheckBoxCtrl>("checkbox copy rotates"); getChild<LLUICtrl>("checkbox copy rotates")->setValue((BOOL)gSavedSettings.getBOOL("CreateToolCopyRotates")); mRadioGroupLand = getChild<LLRadioGroup>("land_radio_group"); mBtnApplyToSelection = getChild<LLButton>("button apply to selection"); mSliderDozerSize = getChild<LLSlider>("slider brush size"); getChild<LLUICtrl>("slider brush size")->setValue(gSavedSettings.getF32("LandBrushSize")); mSliderDozerForce = getChild<LLSlider>("slider force"); // the setting stores the actual force multiplier, but the slider is logarithmic, so we convert here getChild<LLUICtrl>("slider force")->setValue(log10(gSavedSettings.getF32("LandBrushForce"))); // <FS:Ansariel> FIRE-7802: Grass and tree selection in build tool mTreeGrassCombo = getChild<LLComboBox>("tree_grass_combo"); mCostTextBorder = getChild<LLViewBorder>("cost_text_border"); mTab = getChild<LLTabContainer>("Object Info Tabs"); if(mTab) { //mTab->setFollows(FOLLOWS_TOP | FOLLOWS_LEFT); //mTab->setBorderVisible(FALSE); mTab->selectFirstTab(); } mStatusText["rotate"] = getString("status_rotate"); mStatusText["scale"] = getString("status_scale"); mStatusText["move"] = getString("status_move"); mStatusText["modifyland"] = getString("status_modifyland"); mStatusText["camera"] = getString("status_camera"); mStatusText["grab"] = getString("status_grab"); mStatusText["place"] = getString("status_place"); mStatusText["selectland"] = getString("status_selectland"); sShowObjectCost = gSavedSettings.getBOOL("ShowObjectRenderingCost"); // <FS:KC> Added back more/less button LLButton* btnExpand = getChild<LLButton>("btnExpand"); if (btnExpand && mTab) { mExpandedHeight = getRect().getHeight(); mCollapsedHeight = mExpandedHeight - mTab->getRect().getHeight() + btnExpand->getRect().getHeight(); if(!gSavedSettings.getBOOL("FSToolboxExpanded")) { mTab->setVisible(FALSE); reshape( getRect().getWidth(), mCollapsedHeight); btnExpand->setImageOverlay("Arrow_Down", btnExpand->getImageOverlayHAlign()); } } else { gSavedSettings.setBOOL("FSToolboxExpanded", TRUE); } // </FS:KC> return TRUE; } // <FS:CR> Aurora Sim void LLFloaterTools::updateToolsSizeLimits() { mPanelObject->updateLimits(FALSE); } // </FS:CR> Aurora Sim void LLFloaterTools::changePrecision(S32 decimal_precision) { // Precision gets funky at 8 digits. if (decimal_precision < 0) decimal_precision = 0; else if (decimal_precision > 7) decimal_precision = 7; mPanelObject->changePrecision(decimal_precision); mPanelFace->changePrecision(decimal_precision); } // Create the popupview with a dummy center. It will be moved into place // during LLViewerWindow's per-frame hover processing. LLFloaterTools::LLFloaterTools(const LLSD& key) : LLFloater(key), mBtnFocus(NULL), mBtnMove(NULL), mBtnEdit(NULL), mBtnCreate(NULL), mBtnLand(NULL), mTextStatus(NULL), mRadioGroupFocus(NULL), mRadioGroupMove(NULL), mRadioGroupEdit(NULL), mCheckSelectIndividual(NULL), mCheckSnapToGrid(NULL), mBtnGridOptions(NULL), mTitleMedia(NULL), mComboGridMode(NULL), mCheckStretchUniform(NULL), mCheckStretchTexture(NULL), // <FS:KC> mCheckShowHighlight(NULL), mCheckActualRoot(NULL), // </FS:KC> mBtnRotateLeft(NULL), mBtnRotateReset(NULL), mBtnRotateRight(NULL), mBtnLink(NULL), mBtnUnlink(NULL), // <FS:PP> FIRE-14493: Buttons to cycle through linkset mBtnPrevPart(NULL), mBtnNextPart(NULL), // </FS:PP> mBtnDelete(NULL), mBtnDuplicate(NULL), mBtnDuplicateInPlace(NULL), // <FS:Ansariel> FIRE-7802: Grass and tree selection in build tool mTreeGrassCombo(NULL), mCheckSticky(NULL), mCheckCopySelection(NULL), mCheckCopyCenters(NULL), mCheckCopyRotates(NULL), mRadioGroupLand(NULL), mSliderDozerSize(NULL), mSliderDozerForce(NULL), mBtnApplyToSelection(NULL), mTab(NULL), mPanelPermissions(NULL), mPanelObject(NULL), mPanelVolume(NULL), mPanelContents(NULL), mPanelFace(NULL), mPanelLandInfo(NULL), mCostTextBorder(NULL), mTabLand(NULL), mLandImpactsObserver(NULL), mDirty(TRUE), mHasSelection(TRUE), mNeedMediaTitle(TRUE) { gFloaterTools = this; setAutoFocus(FALSE); mFactoryMap["General"] = LLCallbackMap(createPanelPermissions, this);//LLPanelPermissions mFactoryMap["Object"] = LLCallbackMap(createPanelObject, this);//LLPanelObject mFactoryMap["Features"] = LLCallbackMap(createPanelVolume, this);//LLPanelVolume mFactoryMap["Texture"] = LLCallbackMap(createPanelFace, this);//LLPanelFace mFactoryMap["Contents"] = LLCallbackMap(createPanelContents, this);//LLPanelContents mFactoryMap["land info panel"] = LLCallbackMap(createPanelLandInfo, this);//LLPanelLandInfo mCommitCallbackRegistrar.add("BuildTool.setTool", boost::bind(&LLFloaterTools::setTool,this, _2)); mCommitCallbackRegistrar.add("BuildTool.commitZoom", boost::bind(&commit_slider_zoom, _1)); mCommitCallbackRegistrar.add("BuildTool.commitRadioFocus", boost::bind(&commit_radio_group_focus, _1)); mCommitCallbackRegistrar.add("BuildTool.commitRadioMove", boost::bind(&commit_radio_group_move,_1)); mCommitCallbackRegistrar.add("BuildTool.commitRadioEdit", boost::bind(&commit_radio_group_edit,_1)); mCommitCallbackRegistrar.add("BuildTool.gridMode", boost::bind(&commit_grid_mode,_1)); mCommitCallbackRegistrar.add("BuildTool.selectComponent", boost::bind(&commit_select_component, this)); mCommitCallbackRegistrar.add("BuildTool.gridOptions", boost::bind(&LLFloaterTools::onClickGridOptions,this)); mCommitCallbackRegistrar.add("BuildTool.applyToSelection", boost::bind(&click_apply_to_selection, this)); mCommitCallbackRegistrar.add("BuildTool.commitRadioLand", boost::bind(&commit_radio_group_land,_1)); mCommitCallbackRegistrar.add("BuildTool.LandBrushForce", boost::bind(&commit_slider_dozer_force,_1)); mCommitCallbackRegistrar.add("BuildTool.AddMedia", boost::bind(&LLFloaterTools::onClickBtnAddMedia,this)); mCommitCallbackRegistrar.add("BuildTool.DeleteMedia", boost::bind(&LLFloaterTools::onClickBtnDeleteMedia,this)); mCommitCallbackRegistrar.add("BuildTool.EditMedia", boost::bind(&LLFloaterTools::onClickBtnEditMedia,this)); mCommitCallbackRegistrar.add("BuildTool.LinkObjects", boost::bind(&LLSelectMgr::linkObjects, LLSelectMgr::getInstance())); mCommitCallbackRegistrar.add("BuildTool.UnlinkObjects", boost::bind(&LLSelectMgr::unlinkObjects, LLSelectMgr::getInstance())); // <FS> mCommitCallbackRegistrar.add("BuildTool.CopyKeys", boost::bind(&LLFloaterTools::onClickBtnCopyKeys,this)); mCommitCallbackRegistrar.add("BuildTool.Expand", boost::bind(&LLFloaterTools::onClickExpand,this)); mCommitCallbackRegistrar.add("BuildTool.Flip", boost::bind(&LLPanelFace::onCommitFlip, _1, _2)); // </FS> // <FS:Ansariel> FIRE-7802: Grass and tree selection in build tool mCommitCallbackRegistrar.add("BuildTool.TreeGrass", boost::bind(&LLFloaterTools::onSelectTreeGrassCombo, this)); // <FS:KC> show/hide build highlight mCommitCallbackRegistrar.add("BuildTool.commitShowHighlight", boost::bind(&commit_show_highlight, this)); mLandImpactsObserver = new LLLandImpactsObserver(); LLViewerParcelMgr::getInstance()->addObserver(mLandImpactsObserver); } LLFloaterTools::~LLFloaterTools() { // children automatically deleted gFloaterTools = NULL; LLViewerParcelMgr::getInstance()->removeObserver(mLandImpactsObserver); delete mLandImpactsObserver; } void LLFloaterTools::setStatusText(const std::string& text) { // <FS:ND> Can be 0 during login if( !mTextStatus ) return; // </FS:ND> std::map<std::string, std::string>::iterator iter = mStatusText.find(text); if (iter != mStatusText.end()) { mTextStatus->setText(iter->second); } else { mTextStatus->setText(text); } } void LLFloaterTools::refresh() { const S32 INFO_WIDTH = getRect().getWidth(); const S32 INFO_HEIGHT = 384; LLRect object_info_rect(0, 0, INFO_WIDTH, -INFO_HEIGHT); BOOL all_volume = LLSelectMgr::getInstance()->selectionAllPCode( LL_PCODE_VOLUME ); S32 idx_features = mTab->getPanelIndexByTitle(PANEL_NAMES[PANEL_FEATURES]); S32 idx_face = mTab->getPanelIndexByTitle(PANEL_NAMES[PANEL_FACE]); S32 idx_contents = mTab->getPanelIndexByTitle(PANEL_NAMES[PANEL_CONTENTS]); S32 selected_index = mTab->getCurrentPanelIndex(); if (!all_volume && (selected_index == idx_features || selected_index == idx_face || selected_index == idx_contents)) { mTab->selectFirstTab(); } mTab->enableTabButton(idx_features, all_volume); mTab->enableTabButton(idx_face, all_volume); mTab->enableTabButton(idx_contents, all_volume); // Refresh object and prim count labels LLLocale locale(LLLocale::USER_LOCALE); // <FS:KC> std::string desc_string; std::string num_string; bool enable_link_count = true; S32 prim_count = LLSelectMgr::getInstance()->getSelection()->getObjectCount(); if (prim_count == 1 && LLToolMgr::getInstance()->getCurrentTool() == LLToolFace::getInstance()) { desc_string = getString("selected_faces"); LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getFirstRootObject(); LLSelectNode* nodep = LLSelectMgr::getInstance()->getSelection()->getFirstRootNode(); if(!objectp || !nodep) { objectp = LLSelectMgr::getInstance()->getSelection()->getFirstObject(); nodep = LLSelectMgr::getInstance()->getSelection()->getFirstNode(); } if (objectp && objectp->getNumTEs() == LLSelectMgr::getInstance()->getSelection()->getTECount()) num_string = "ALL_SIDES"; else if (objectp && nodep) { //S32 count = 0; for (S32 i = 0; i < objectp->getNumTEs(); i++) { if (nodep->isTESelected(i)) { if (!num_string.empty()) num_string.append(", "); num_string.append(llformat("%d", i)); //count++; } } } } else if (prim_count == 1 && gSavedSettings.getBOOL("EditLinkedParts")) { desc_string = getString("link_number"); LLViewerObject* objectp = LLSelectMgr::getInstance()->getSelection()->getFirstObject(); if (objectp && objectp->getRootEdit()) { LLViewerObject::child_list_t children = objectp->getRootEdit()->getChildren(); if (children.empty()) num_string = "0"; //a childless prim is always link zero, and unhappy else if (objectp->getRootEdit()->isSelected()) num_string = "1"; //root prim is always link one else { S32 index = 1; for (LLViewerObject::child_list_t::iterator iter = children.begin(); iter != children.end(); ++iter) { index++; if ((*iter)->isSelected()) { LLResMgr::getInstance()->getIntegerString(num_string, index); break; } } } } } else { enable_link_count = false; } getChild<LLUICtrl>("link_num_obj_count")->setTextArg("[DESC]", desc_string); getChild<LLUICtrl>("link_num_obj_count")->setTextArg("[NUM]", num_string); // </FS:KC> #if 0 if (!gMeshRepo.meshRezEnabled()) { std::string obj_count_string; LLResMgr::getInstance()->getIntegerString(obj_count_string, LLSelectMgr::getInstance()->getSelection()->getRootObjectCount()); getChild<LLUICtrl>("selection_count")->setTextArg("[OBJ_COUNT]", obj_count_string); std::string prim_count_string; LLResMgr::getInstance()->getIntegerString(prim_count_string, LLSelectMgr::getInstance()->getSelection()->getObjectCount()); getChild<LLUICtrl>("selection_count")->setTextArg("[PRIM_COUNT]", prim_count_string); // calculate selection rendering cost if (sShowObjectCost) { std::string prim_cost_string; S32 render_cost = LLSelectMgr::getInstance()->getSelection()->getSelectedObjectRenderCost(); LLResMgr::getInstance()->getIntegerString(prim_cost_string, render_cost); // <FS:Ansariel> Was removed from floater_tools.xml as part of SH-1917 SH-1935 //getChild<LLUICtrl>("RenderingCost")->setTextArg("[COUNT]", prim_cost_string); } // disable the object and prim counts if nothing selected bool have_selection = ! LLSelectMgr::getInstance()->getSelection()->isEmpty(); getChildView("link_num_obj_count")->setEnabled(have_selection); //getChildView("obj_count")->setEnabled(have_selection); // <FS:Ansariel> Was removed from floater_tools.xml as part of SH-1719 //getChildView("prim_count")->setEnabled(have_selection); // <FS:Ansariel> Was removed from floater_tools.xml as part of SH-1917 SH-1935 //getChildView("RenderingCost")->setEnabled(have_selection && sShowObjectCost); } else #endif { F32 link_cost = LLSelectMgr::getInstance()->getSelection()->getSelectedLinksetCost(); // <FS:CR> FIRE-9287 - LI/Prim count not reflected on OpenSim #ifdef OPENSIM S32 prim_count = LLSelectMgr::getInstance()->getSelection()->getObjectCount(); #endif // OPENSIM // </FS:CR> S32 link_count = LLSelectMgr::getInstance()->getSelection()->getRootObjectCount(); LLCrossParcelFunctor func; if (LLSelectMgr::getInstance()->getSelection()->applyToRootObjects(&func, true)) { // Selection crosses parcel bounds. // We don't display remaining land capacity in this case. const LLStringExplicit empty_str(""); childSetTextArg("remaining_capacity", "[CAPACITY_STRING]", empty_str); } else { LLViewerObject* selected_object = mObjectSelection->getFirstObject(); if (selected_object) { // Select a parcel at the currently selected object's position. // <FS:Ansariel> FIRE-20387: Editing HUD attachment shows [CAPACITY_STRING] in tools floater //LLViewerParcelMgr::getInstance()->selectParcelAt(selected_object->getPositionGlobal()); if (!selected_object->isAttachment()) { LLViewerParcelMgr::getInstance()->selectParcelAt(selected_object->getPositionGlobal()); } else { const LLStringExplicit empty_str(""); childSetTextArg("remaining_capacity", "[CAPACITY_STRING]", empty_str); } // </FS:Ansariel> } else { LL_WARNS() << "Failed to get selected object" << LL_ENDL; } } LLStringUtil::format_map_t selection_args; selection_args["OBJ_COUNT"] = llformat("%.1d", link_count); // <FS:CR> FIRE-9287 - LI/Prim count not reflected on OpenSim #ifdef OPENSIM if (LLGridManager::getInstance()->isInOpenSim()) selection_args["LAND_IMPACT"] = llformat("%.1d", (link_cost ? (S32)link_cost : (S32)prim_count)); else #endif // OPENSIM // </FS:CR> selection_args["LAND_IMPACT"] = llformat("%.1d", (S32)link_cost); std::ostringstream selection_info; selection_info << getString("status_selectcount", selection_args); getChild<LLTextBox>("selection_count")->setText(selection_info.str()); } // <FS> disable the object and prim counts if nothing selected bool have_selection = ! LLSelectMgr::getInstance()->getSelection()->isEmpty(); getChildView("link_num_obj_count")->setEnabled(have_selection && enable_link_count); // </FS> // Refresh child tabs mPanelPermissions->refresh(); mPanelObject->refresh(); mPanelVolume->refresh(); mPanelFace->refresh(); refreshMedia(); mPanelContents->refresh(); mPanelLandInfo->refresh(); // Refresh the advanced weights floater LLFloaterObjectWeights* object_weights_floater = LLFloaterReg::findTypedInstance<LLFloaterObjectWeights>("object_weights"); if(object_weights_floater && object_weights_floater->getVisible()) { object_weights_floater->refresh(); } // <FS:CR> Only enable Copy Keys when we have something selected getChild<LLButton>("btnCopyKeys")->setEnabled(have_selection); // </FS:CR> } void LLFloaterTools::draw() { BOOL has_selection = !LLSelectMgr::getInstance()->getSelection()->isEmpty(); if(!has_selection && (mHasSelection != has_selection)) { mDirty = TRUE; } mHasSelection = has_selection; if (mDirty) { refresh(); mDirty = FALSE; } // grab media name/title and update the UI widget updateMediaTitle(); // mCheckSelectIndividual->set(gSavedSettings.getBOOL("EditLinkedParts")); LLFloater::draw(); } void LLFloaterTools::dirty() { mDirty = TRUE; LLFloaterOpenObject* instance = LLFloaterReg::findTypedInstance<LLFloaterOpenObject>("openobject"); if (instance) instance->dirty(); } // Clean up any tool state that should not persist when the // floater is closed. void LLFloaterTools::resetToolState() { gCameraBtnZoom = TRUE; gCameraBtnOrbit = FALSE; gCameraBtnPan = FALSE; gGrabBtnSpin = FALSE; gGrabBtnVertical = FALSE; } void LLFloaterTools::updatePopup(LLCoordGL center, MASK mask) { LLTool *tool = LLToolMgr::getInstance()->getCurrentTool(); // HACK to allow seeing the buttons when you have the app in a window. // Keep the visibility the same as it if (tool == gToolNull) { return; } if ( isMinimized() ) { // SL looks odd if we draw the tools while the window is minimized return; } // Focus buttons BOOL focus_visible = ( tool == LLToolCamera::getInstance() ); mBtnFocus ->setToggleState( focus_visible ); mRadioGroupFocus->setVisible( focus_visible ); getChildView("slider zoom")->setVisible( focus_visible); getChildView("slider zoom")->setEnabled(gCameraBtnZoom); if (!gCameraBtnOrbit && !gCameraBtnPan && !(mask == MASK_ORBIT) && !(mask == (MASK_ORBIT | MASK_ALT)) && !(mask == MASK_PAN) && !(mask == (MASK_PAN | MASK_ALT)) ) { mRadioGroupFocus->setValue("radio zoom"); } else if ( gCameraBtnOrbit || (mask == MASK_ORBIT) || (mask == (MASK_ORBIT | MASK_ALT)) ) { mRadioGroupFocus->setValue("radio orbit"); } else if ( gCameraBtnPan || (mask == MASK_PAN) || (mask == (MASK_PAN | MASK_ALT)) ) { mRadioGroupFocus->setValue("radio pan"); } // multiply by correction factor because volume sliders go [0, 0.5] getChild<LLUICtrl>("slider zoom")->setValue(gAgentCamera.getCameraZoomFraction() * 0.5f); // Move buttons BOOL move_visible = (tool == LLToolGrab::getInstance()); if (mBtnMove) mBtnMove ->setToggleState( move_visible ); // HACK - highlight buttons for next click mRadioGroupMove->setVisible(move_visible); if (!(gGrabBtnSpin || gGrabBtnVertical || (mask == MASK_VERTICAL) || (mask == MASK_SPIN))) { mRadioGroupMove->setValue("radio move"); } else if ((mask == MASK_VERTICAL) || (gGrabBtnVertical && (mask != MASK_SPIN))) { mRadioGroupMove->setValue("radio lift"); } else if ((mask == MASK_SPIN) || (gGrabBtnSpin && (mask != MASK_VERTICAL))) { mRadioGroupMove->setValue("radio spin"); } // Edit buttons BOOL edit_visible = tool == LLToolCompTranslate::getInstance() || tool == LLToolCompRotate::getInstance() || tool == LLToolCompScale::getInstance() || tool == LLToolFace::getInstance() || tool == LLToolIndividual::getInstance() || tool == QToolAlign::getInstance() || tool == LLToolPipette::getInstance(); mBtnEdit ->setToggleState( edit_visible ); mRadioGroupEdit->setVisible( edit_visible ); //bool linked_parts = gSavedSettings.getBOOL("EditLinkedParts"); static LLCachedControl<bool> linked_parts(gSavedSettings, "EditLinkedParts"); //getChildView("RenderingCost")->setVisible( !linked_parts && (edit_visible || focus_visible || move_visible) && sShowObjectCost); mBtnLink->setVisible(edit_visible); mBtnUnlink->setVisible(edit_visible); mBtnLink->setEnabled(LLSelectMgr::instance().enableLinkObjects()); mBtnUnlink->setEnabled(LLSelectMgr::instance().enableUnlinkObjects()); // <FS:PP> FIRE-14493: Buttons to cycle through linkset mBtnPrevPart->setVisible(edit_visible); mBtnNextPart->setVisible(edit_visible); bool select_btn_enabled = (!LLSelectMgr::getInstance()->getSelection()->isEmpty() && (linked_parts || LLToolFace::getInstance() == LLToolMgr::getInstance()->getCurrentTool())); mBtnPrevPart->setEnabled(select_btn_enabled); mBtnNextPart->setEnabled(select_btn_enabled); // </FS:PP> if (mCheckSelectIndividual) { mCheckSelectIndividual->setVisible(edit_visible); //mCheckSelectIndividual->set(gSavedSettings.getBOOL("EditLinkedParts")); } if ( tool == LLToolCompTranslate::getInstance() ) { mRadioGroupEdit->setValue("radio position"); } else if ( tool == LLToolCompRotate::getInstance() ) { mRadioGroupEdit->setValue("radio rotate"); } else if ( tool == LLToolCompScale::getInstance() ) { mRadioGroupEdit->setValue("radio stretch"); } else if ( tool == LLToolFace::getInstance() ) { mRadioGroupEdit->setValue("radio select face"); } else if ( tool == QToolAlign::getInstance() ) { mRadioGroupEdit->setValue("radio align"); } if (mComboGridMode) { mComboGridMode->setVisible( edit_visible ); S32 index = mComboGridMode->getCurrentIndex(); mComboGridMode->removeall(); switch (mObjectSelection->getSelectType()) { case SELECT_TYPE_HUD: mComboGridMode->add(getString("grid_screen_text")); mComboGridMode->add(getString("grid_local_text")); break; case SELECT_TYPE_WORLD: mComboGridMode->add(getString("grid_world_text")); mComboGridMode->add(getString("grid_local_text")); mComboGridMode->add(getString("grid_reference_text")); break; case SELECT_TYPE_ATTACHMENT: mComboGridMode->add(getString("grid_attachment_text")); mComboGridMode->add(getString("grid_local_text")); mComboGridMode->add(getString("grid_reference_text")); break; } mComboGridMode->setCurrentByIndex(index); } // Snap to grid disabled for grab tool - very confusing if (mCheckSnapToGrid) mCheckSnapToGrid->setVisible( edit_visible /* || tool == LLToolGrab::getInstance() */ ); if (mBtnGridOptions) mBtnGridOptions->setVisible( edit_visible /* || tool == LLToolGrab::getInstance() */ ); //mCheckSelectLinked ->setVisible( edit_visible ); if (mCheckStretchUniform) mCheckStretchUniform->setVisible( edit_visible ); if (mCheckStretchTexture) mCheckStretchTexture->setVisible( edit_visible ); // <FS:KC> if (mCheckShowHighlight) mCheckShowHighlight->setVisible( edit_visible ); if (mCheckActualRoot) mCheckActualRoot->setVisible( edit_visible ); // </FS:KC> // Create buttons BOOL create_visible = (tool == LLToolCompCreate::getInstance()); // <FS:Ansariel> FIRE-7802: Grass and tree selection in build tool if (mTreeGrassCombo) mTreeGrassCombo->setVisible(create_visible); if (create_visible) buildTreeGrassCombo(); mBtnCreate ->setToggleState( tool == LLToolCompCreate::getInstance() ); if (mCheckCopySelection && mCheckCopySelection->get()) { // don't highlight any placer button for (std::vector<LLButton*>::size_type i = 0; i < mButtons.size(); i++) { mButtons[i]->setToggleState(FALSE); mButtons[i]->setVisible( create_visible ); } } else { // Highlight the correct placer button for( S32 t = 0; t < (S32)mButtons.size(); t++ ) { LLPCode pcode = LLToolPlacer::getObjectType(); LLPCode button_pcode = toolData[t]; BOOL state = (pcode == button_pcode); mButtons[t]->setToggleState( state ); mButtons[t]->setVisible( create_visible ); } } if (mCheckSticky) mCheckSticky ->setVisible( create_visible ); if (mCheckCopySelection) mCheckCopySelection ->setVisible( create_visible ); if (mCheckCopyCenters) mCheckCopyCenters ->setVisible( create_visible ); if (mCheckCopyRotates) mCheckCopyRotates ->setVisible( create_visible ); if (mCheckCopyCenters && mCheckCopySelection) mCheckCopyCenters->setEnabled( mCheckCopySelection->get() ); if (mCheckCopyRotates && mCheckCopySelection) mCheckCopyRotates->setEnabled( mCheckCopySelection->get() ); // Land buttons BOOL land_visible = (tool == LLToolBrushLand::getInstance() || tool == LLToolSelectLand::getInstance() ); mCostTextBorder->setVisible(!land_visible); if (mBtnLand) mBtnLand ->setToggleState( land_visible ); mRadioGroupLand->setVisible( land_visible ); if ( tool == LLToolSelectLand::getInstance() ) { mRadioGroupLand->setValue("radio select land"); } else if ( tool == LLToolBrushLand::getInstance() ) { //S32 dozer_mode = gSavedSettings.getS32("RadioLandBrushAction"); static LLCachedControl<S32> dozer_mode(gSavedSettings, "RadioLandBrushAction"); switch(dozer_mode) { case 0: mRadioGroupLand->setValue("radio flatten"); break; case 1: mRadioGroupLand->setValue("radio raise"); break; case 2: mRadioGroupLand->setValue("radio lower"); break; case 3: mRadioGroupLand->setValue("radio smooth"); break; case 4: mRadioGroupLand->setValue("radio noise"); break; case 5: mRadioGroupLand->setValue("radio revert"); break; default: break; } } if (mBtnApplyToSelection) { mBtnApplyToSelection->setVisible( land_visible ); mBtnApplyToSelection->setEnabled( land_visible && !LLViewerParcelMgr::getInstance()->selectionEmpty() && tool != LLToolSelectLand::getInstance()); } if (mSliderDozerSize) { mSliderDozerSize ->setVisible( land_visible ); getChildView("Bulldozer:")->setVisible( land_visible); getChildView("Dozer Size:")->setVisible( land_visible); } if (mSliderDozerForce) { mSliderDozerForce ->setVisible( land_visible ); getChildView("Strength:")->setVisible( land_visible); } // <FS> static LLCachedControl<bool> sFSToolboxExpanded(gSavedSettings, "FSToolboxExpanded", TRUE); mTab->setVisible(!land_visible && sFSToolboxExpanded); mPanelLandInfo->setVisible(land_visible && sFSToolboxExpanded); // </FS> bool have_selection = !LLSelectMgr::getInstance()->getSelection()->isEmpty(); getChildView("selection_count")->setVisible(!land_visible && have_selection); getChildView("remaining_capacity")->setVisible(!land_visible && have_selection); getChildView("selection_empty")->setVisible(!land_visible && !have_selection); //mTab->setVisible(!land_visible); //mPanelLandInfo->setVisible(land_visible); } // virtual BOOL LLFloaterTools::canClose() { // don't close when quitting, so camera will stay put return !LLApp::isExiting(); } // virtual void LLFloaterTools::onOpen(const LLSD& key) { mParcelSelection = LLViewerParcelMgr::getInstance()->getFloatingParcelSelection(); mObjectSelection = LLSelectMgr::getInstance()->getEditSelection(); // <FS:KC> Set the check box value from the saved setting // this function runs on selection change if (!mOpen) { mOpen = TRUE; mCheckShowHighlight->setValue(gSavedSettings.getBOOL("RenderHighlightSelections")); } // </FS:KC> std::string panel = key.asString(); if (!panel.empty()) { mTab->selectTabByName(panel); } LLTool* tool = LLToolMgr::getInstance()->getCurrentTool(); if (tool == LLToolCompInspect::getInstance() || tool == LLToolDragAndDrop::getInstance()) { // Something called floater up while it was supressed (during drag n drop, inspect), // so it won't be getting any layout or visibility updates, update once // further updates will come from updateLayout() LLCoordGL select_center_screen; MASK mask = gKeyboard->currentMask(TRUE); updatePopup(select_center_screen, mask); } //gMenuBarView->setItemVisible("BuildTools", TRUE); } // virtual void LLFloaterTools::onClose(bool app_quitting) { mTab->setVisible(FALSE); LLViewerJoystick::getInstance()->moveAvatar(false); // destroy media source used to grab media title if( mTitleMedia ) mTitleMedia->unloadMediaSource(); // Different from handle_reset_view in that it doesn't actually // move the camera if EditCameraMovement is not set. gAgentCamera.resetView(gSavedSettings.getBOOL("EditCameraMovement")); // exit component selection mode LLSelectMgr::getInstance()->promoteSelectionToRoot(); gSavedSettings.setBOOL("EditLinkedParts", FALSE); // <FS:KC> LLSelectMgr::instance().setFSShowHideHighlight(FS_SHOW_HIDE_HIGHLIGHT_NORMAL); mOpen = FALSE; //hack cause onOpen runs on every selection change but onClose doesnt. // </FS:KC> gViewerWindow->showCursor(); resetToolState(); mParcelSelection = NULL; mObjectSelection = NULL; // <FS:Ansariel> Enable context/pie menu in mouselook // Switch back to basic toolset //LLToolMgr::getInstance()->setCurrentToolset(gBasicToolset); // we were already in basic toolset, using build tools // so manually reset tool to default (pie menu tool) //LLToolMgr::getInstance()->getCurrentToolset()->selectFirstTool(); if (!gAgentCamera.cameraMouselook()) { LLToolMgr::getInstance()->setCurrentToolset(gBasicToolset); LLToolMgr::getInstance()->getCurrentToolset()->selectFirstTool(); } else { // Switch back to mouselook toolset LLToolMgr::getInstance()->setCurrentToolset(gMouselookToolset); gViewerWindow->hideCursor(); gViewerWindow->moveCursorToCenter(); } // </FS:Ansariel> //gMenuBarView->setItemVisible("BuildTools", FALSE); LLFloaterReg::hideInstance("media_settings"); // hide the advanced object weights floater LLFloaterReg::hideInstance("object_weights"); // prepare content for next call mPanelContents->clearContents(); if(sPreviousFocusOnAvatar) { sPreviousFocusOnAvatar = false; gAgentCamera.setAllowChangeToFollow(TRUE); } } void click_popup_info(void*) { } void click_popup_done(void*) { handle_reset_view(); } void commit_radio_group_move(LLUICtrl* ctrl) { LLRadioGroup* group = (LLRadioGroup*)ctrl; std::string selected = group->getValue().asString(); if (selected == "radio move") { gGrabBtnVertical = FALSE; gGrabBtnSpin = FALSE; } else if (selected == "radio lift") { gGrabBtnVertical = TRUE; gGrabBtnSpin = FALSE; } else if (selected == "radio spin") { gGrabBtnVertical = FALSE; gGrabBtnSpin = TRUE; } } void commit_radio_group_focus(LLUICtrl* ctrl) { LLRadioGroup* group = (LLRadioGroup*)ctrl; std::string selected = group->getValue().asString(); if (selected == "radio zoom") { gCameraBtnZoom = TRUE; gCameraBtnOrbit = FALSE; gCameraBtnPan = FALSE; } else if (selected == "radio orbit") { gCameraBtnZoom = FALSE; gCameraBtnOrbit = TRUE; gCameraBtnPan = FALSE; } else if (selected == "radio pan") { gCameraBtnZoom = FALSE; gCameraBtnOrbit = FALSE; gCameraBtnPan = TRUE; } } void commit_slider_zoom(LLUICtrl *ctrl) { // renormalize value, since max "volume" level is 0.5 for some reason F32 zoom_level = (F32)ctrl->getValue().asReal() * 2.f; // / 0.5f; gAgentCamera.setCameraZoomFraction(zoom_level); } void commit_slider_dozer_force(LLUICtrl *ctrl) { // the slider is logarithmic, so we exponentiate to get the actual force multiplier F32 dozer_force = pow(10.f, (F32)ctrl->getValue().asReal()); gSavedSettings.setF32("LandBrushForce", dozer_force); } void click_apply_to_selection(void*) { LLToolBrushLand::getInstance()->modifyLandInSelectionGlobal(); } void commit_radio_group_edit(LLUICtrl *ctrl) { S32 show_owners = gSavedSettings.getBOOL("ShowParcelOwners"); LLRadioGroup* group = (LLRadioGroup*)ctrl; std::string selected = group->getValue().asString(); if (selected == "radio position") { LLFloaterTools::setEditTool( LLToolCompTranslate::getInstance() ); } else if (selected == "radio rotate") { LLFloaterTools::setEditTool( LLToolCompRotate::getInstance() ); } else if (selected == "radio stretch") { LLFloaterTools::setEditTool( LLToolCompScale::getInstance() ); } else if (selected == "radio select face") { LLFloaterTools::setEditTool( LLToolFace::getInstance() ); } else if (selected == "radio align") { LLFloaterTools::setEditTool( QToolAlign::getInstance() ); } gSavedSettings.setBOOL("ShowParcelOwners", show_owners); } void commit_radio_group_land(LLUICtrl* ctrl) { LLRadioGroup* group = (LLRadioGroup*)ctrl; std::string selected = group->getValue().asString(); if (selected == "radio select land") { LLFloaterTools::setEditTool( LLToolSelectLand::getInstance() ); } else { LLFloaterTools::setEditTool( LLToolBrushLand::getInstance() ); S32 dozer_mode = gSavedSettings.getS32("RadioLandBrushAction"); if (selected == "radio flatten") dozer_mode = 0; else if (selected == "radio raise") dozer_mode = 1; else if (selected == "radio lower") dozer_mode = 2; else if (selected == "radio smooth") dozer_mode = 3; else if (selected == "radio noise") dozer_mode = 4; else if (selected == "radio revert") dozer_mode = 5; gSavedSettings.setS32("RadioLandBrushAction", dozer_mode); } } void commit_select_component(void *data) { LLFloaterTools* floaterp = (LLFloaterTools*)data; //forfeit focus if (gFocusMgr.childHasKeyboardFocus(floaterp)) { gFocusMgr.setKeyboardFocus(NULL); } BOOL select_individuals = floaterp->mCheckSelectIndividual->get(); gSavedSettings.setBOOL("EditLinkedParts", select_individuals); floaterp->dirty(); if (select_individuals) { LLSelectMgr::getInstance()->demoteSelectionToIndividuals(); } else { LLSelectMgr::getInstance()->promoteSelectionToRoot(); } } // <FS:KC> show/hide build highlight void commit_show_highlight(void *data) { LLFloaterTools* floaterp = (LLFloaterTools*)data; BOOL show_highlight = floaterp->mCheckShowHighlight->get(); if (show_highlight) { LLSelectMgr::getInstance()->setFSShowHideHighlight(FS_SHOW_HIDE_HIGHLIGHT_SHOW); } else { LLSelectMgr::getInstance()->setFSShowHideHighlight(FS_SHOW_HIDE_HIGHLIGHT_HIDE); } } // </FS:KC> // static void LLFloaterTools::setObjectType( LLPCode pcode ) { LLToolPlacer::setObjectType( pcode ); gSavedSettings.setBOOL("CreateToolCopySelection", FALSE); // <FS:Ansariel> FIRE-7802: Grass and tree selection in build tool gFloaterTools->buildTreeGrassCombo(); // </FS:Ansariel> gFocusMgr.setMouseCapture(NULL); } void commit_grid_mode(LLUICtrl *ctrl) { LLComboBox* combo = (LLComboBox*)ctrl; LLSelectMgr::getInstance()->setGridMode((EGridMode)combo->getCurrentIndex()); } // static void LLFloaterTools::setGridMode(S32 mode) { LLFloaterTools* tools_floater = LLFloaterReg::getTypedInstance<LLFloaterTools>("build"); if (!tools_floater || !tools_floater->mComboGridMode) { return; } tools_floater->mComboGridMode->setCurrentByIndex(mode); } void LLFloaterTools::onClickGridOptions() { LLFloater* floaterp = LLFloaterReg::showInstance("build_options"); // position floater next to build tools, not over floaterp->setRect(gFloaterView->findNeighboringPosition(this, floaterp)); } // static void LLFloaterTools::setEditTool(void* tool_pointer) { LLTool *tool = (LLTool *)tool_pointer; LLToolMgr::getInstance()->getCurrentToolset()->selectTool( tool ); } void LLFloaterTools::setTool(const LLSD& user_data) { std::string control_name = user_data.asString(); if(control_name == "Focus") LLToolMgr::getInstance()->getCurrentToolset()->selectTool((LLTool *) LLToolCamera::getInstance() ); else if (control_name == "Move" ) LLToolMgr::getInstance()->getCurrentToolset()->selectTool( (LLTool *)LLToolGrab::getInstance() ); else if (control_name == "Edit" ) LLToolMgr::getInstance()->getCurrentToolset()->selectTool( (LLTool *) LLToolCompTranslate::getInstance()); else if (control_name == "Create" ) LLToolMgr::getInstance()->getCurrentToolset()->selectTool( (LLTool *) LLToolCompCreate::getInstance()); else if (control_name == "Land" ) LLToolMgr::getInstance()->getCurrentToolset()->selectTool( (LLTool *) LLToolSelectLand::getInstance()); else LL_WARNS()<<" no parameter name "<<control_name<<" found!! No Tool selected!!"<< LL_ENDL; } void LLFloaterTools::onFocusReceived() { LLToolMgr::getInstance()->setCurrentToolset(gBasicToolset); LLFloater::onFocusReceived(); } // Media stuff void LLFloaterTools::refreshMedia() { getMediaState(); } bool LLFloaterTools::selectedMediaEditable() { U32 owner_mask_on; U32 owner_mask_off; U32 valid_owner_perms = LLSelectMgr::getInstance()->selectGetPerm( PERM_OWNER, &owner_mask_on, &owner_mask_off ); U32 group_mask_on; U32 group_mask_off; U32 valid_group_perms = LLSelectMgr::getInstance()->selectGetPerm( PERM_GROUP, &group_mask_on, &group_mask_off ); U32 everyone_mask_on; U32 everyone_mask_off; S32 valid_everyone_perms = LLSelectMgr::getInstance()->selectGetPerm( PERM_EVERYONE, &everyone_mask_on, &everyone_mask_off ); bool selected_Media_editable = false; // if perms we got back are valid if ( valid_owner_perms && valid_group_perms && valid_everyone_perms ) { if ( ( owner_mask_on & PERM_MODIFY ) || ( group_mask_on & PERM_MODIFY ) || // <FS> Copy & paste error //( group_mask_on & PERM_MODIFY ) ) ( everyone_mask_on & PERM_MODIFY ) ) // </FS> { selected_Media_editable = true; } else // user is NOT allowed to press the RESET button { selected_Media_editable = false; }; }; return selected_Media_editable; } void LLFloaterTools::updateLandImpacts() { LLParcel *parcel = mParcelSelection->getParcel(); if (!parcel) { return; } S32 rezzed_prims = parcel->getSimWidePrimCount(); S32 total_capacity = parcel->getSimWideMaxPrimCapacity(); LLViewerRegion* region = LLViewerParcelMgr::getInstance()->getSelectionRegion(); if (region) { S32 max_tasks_per_region = (S32)region->getMaxTasks(); total_capacity = llmin(total_capacity, max_tasks_per_region); } std::string remaining_capacity_str = ""; bool show_mesh_cost = gMeshRepo.meshRezEnabled(); if (show_mesh_cost) { LLStringUtil::format_map_t remaining_capacity_args; remaining_capacity_args["LAND_CAPACITY"] = llformat("%d", total_capacity - rezzed_prims); remaining_capacity_str = getString("status_remaining_capacity", remaining_capacity_args); } childSetTextArg("remaining_capacity", "[CAPACITY_STRING]", remaining_capacity_str); // Update land impacts info in the weights floater LLFloaterObjectWeights* object_weights_floater = LLFloaterReg::findTypedInstance<LLFloaterObjectWeights>("object_weights"); if(object_weights_floater) { object_weights_floater->updateLandImpacts(parcel); } } void LLFloaterTools::getMediaState() { LLObjectSelectionHandle selected_objects =LLSelectMgr::getInstance()->getSelection(); LLViewerObject* first_object = selected_objects->getFirstObject(); LLTextBox* media_info = getChild<LLTextBox>("media_info"); if( !(first_object && first_object->getPCode() == LL_PCODE_VOLUME &&first_object->permModify() )) { getChildView("add_media")->setEnabled(FALSE); media_info->clear(); clearMediaSettings(); return; } std::string url = first_object->getRegion()->getCapability("ObjectMedia"); bool has_media_capability = (!url.empty()); if(!has_media_capability) { getChildView("add_media")->setEnabled(FALSE); LL_WARNS("LLFloaterToolsMedia") << "Media not enabled (no capability) in this region!" << LL_ENDL; clearMediaSettings(); return; } BOOL is_nonpermanent_enforced = (LLSelectMgr::getInstance()->getSelection()->getFirstRootNode() && LLSelectMgr::getInstance()->selectGetRootsNonPermanentEnforced()) || LLSelectMgr::getInstance()->selectGetNonPermanentEnforced(); bool editable = is_nonpermanent_enforced && (first_object->permModify() || selectedMediaEditable()); // Check modify permissions and whether any selected objects are in // the process of being fetched. If they are, then we're not editable if (editable) { LLObjectSelection::iterator iter = selected_objects->begin(); LLObjectSelection::iterator end = selected_objects->end(); for ( ; iter != end; ++iter) { LLSelectNode* node = *iter; LLVOVolume* object = dynamic_cast<LLVOVolume*>(node->getObject()); if (NULL != object) { if (!object->permModify()) { LL_INFOS("LLFloaterToolsMedia") << "Selection not editable due to lack of modify permissions on object id " << object->getID() << LL_ENDL; editable = false; break; } // XXX DISABLE this for now, because when the fetch finally // does come in, the state of this floater doesn't properly // update. Re-selecting fixes the problem, but there is // contention as to whether this is a sufficient solution. // if (object->isMediaDataBeingFetched()) // { // LL_INFOS("LLFloaterToolsMedia") // << "Selection not editable due to media data being fetched for object id " // << object->getID() << LL_ENDL; // // editable = false; // break; // } } } } // Media settings bool bool_has_media = false; struct media_functor : public LLSelectedTEGetFunctor<bool> { bool get(LLViewerObject* object, S32 face) { LLTextureEntry *te = object->getTE(face); if (te) { return te->hasMedia(); } return false; } } func; // check if all faces have media(or, all dont have media) LLFloaterMediaSettings::getInstance()->mIdenticalHasMediaInfo = selected_objects->getSelectedTEValue( &func, bool_has_media ); const LLMediaEntry default_media_data; struct functor_getter_media_data : public LLSelectedTEGetFunctor< LLMediaEntry> { functor_getter_media_data(const LLMediaEntry& entry): mMediaEntry(entry) {} LLMediaEntry get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return *(object->getTE(face)->getMediaData()); return mMediaEntry; }; const LLMediaEntry& mMediaEntry; } func_media_data(default_media_data); LLMediaEntry media_data_get; LLFloaterMediaSettings::getInstance()->mMultipleMedia = !(selected_objects->getSelectedTEValue( &func_media_data, media_data_get )); std::string multi_media_info_str = LLTrans::getString("Multiple Media"); std::string media_title = ""; // update UI depending on whether "object" (prim or face) has media // and whether or not you are allowed to edit it. getChildView("add_media")->setEnabled(editable); // IF all the faces have media (or all dont have media) if ( LLFloaterMediaSettings::getInstance()->mIdenticalHasMediaInfo ) { // TODO: get media title and set it. media_info->clear(); // if identical is set, all faces are same (whether all empty or has the same media) if(!(LLFloaterMediaSettings::getInstance()->mMultipleMedia) ) { // Media data is valid if(media_data_get!=default_media_data) { // initial media title is the media URL (until we get the name) media_title = media_data_get.getHomeURL(); } // else all faces might be empty. } else // there' re Different Medias' been set on on the faces. { media_title = multi_media_info_str; } getChildView("delete_media")->setEnabled(bool_has_media && editable ); // TODO: display a list of all media on the face - use 'identical' flag } else // not all face has media but at least one does. { // seleted faces have not identical value LLFloaterMediaSettings::getInstance()->mMultipleValidMedia = selected_objects->isMultipleTEValue(&func_media_data, default_media_data ); if(LLFloaterMediaSettings::getInstance()->mMultipleValidMedia) { media_title = multi_media_info_str; } else { // Media data is valid if(media_data_get!=default_media_data) { // initial media title is the media URL (until we get the name) media_title = media_data_get.getHomeURL(); } } getChildView("delete_media")->setEnabled(TRUE); } navigateToTitleMedia(media_title); media_info->setText(media_title); // load values for media settings updateMediaSettings(); LLFloaterMediaSettings::initValues(mMediaSettings, editable ); } ////////////////////////////////////////////////////////////////////////////// // called when a user wants to add media to a prim or prim face void LLFloaterTools::onClickBtnAddMedia() { // check if multiple faces are selected if(LLSelectMgr::getInstance()->getSelection()->isMultipleTESelected()) { LLNotificationsUtil::add("MultipleFacesSelected", LLSD(), LLSD(), multipleFacesSelectedConfirm); } else { onClickBtnEditMedia(); } } // static bool LLFloaterTools::multipleFacesSelectedConfirm(const LLSD& notification, const LLSD& response) { S32 option = LLNotificationsUtil::getSelectedOption(notification, response); switch( option ) { case 0: // "Yes" gFloaterTools->onClickBtnEditMedia(); break; case 1: // "No" default: break; } return false; } ////////////////////////////////////////////////////////////////////////////// // called when a user wants to edit existing media settings on a prim or prim face // TODO: test if there is media on the item and only allow editing if present void LLFloaterTools::onClickBtnEditMedia() { refreshMedia(); LLFloaterReg::showInstance("media_settings"); } ////////////////////////////////////////////////////////////////////////////// // called when a user wants to delete media from a prim or prim face void LLFloaterTools::onClickBtnDeleteMedia() { LLNotificationsUtil::add("DeleteMedia", LLSD(), LLSD(), deleteMediaConfirm); } // static bool LLFloaterTools::deleteMediaConfirm(const LLSD& notification, const LLSD& response) { S32 option = LLNotificationsUtil::getSelectedOption(notification, response); switch( option ) { case 0: // "Yes" LLSelectMgr::getInstance()->selectionSetMedia( 0, LLSD() ); if(LLFloaterReg::instanceVisible("media_settings")) { LLFloaterReg::hideInstance("media_settings"); } break; case 1: // "No" default: break; } return false; } ////////////////////////////////////////////////////////////////////////////// // void LLFloaterTools::clearMediaSettings() { LLFloaterMediaSettings::clearValues(false); } ////////////////////////////////////////////////////////////////////////////// // void LLFloaterTools::navigateToTitleMedia( const std::string url ) { std::string multi_media_info_str = LLTrans::getString("Multiple Media"); if (url.empty() || multi_media_info_str == url) { // nothing to show mNeedMediaTitle = false; } else if (mTitleMedia) { LLPluginClassMedia* media_plugin = mTitleMedia->getMediaPlugin(); if ( media_plugin ) // Shouldn't this be after navigateTo creates plugin? { // if it's a movie, we don't want to hear it media_plugin->setVolume( 0 ); }; // check if url changed or if we need a new media source if (mTitleMedia->getCurrentNavUrl() != url || media_plugin == NULL) { mTitleMedia->navigateTo( url ); } // flag that we need to update the title (even if no request were made) mNeedMediaTitle = true; } } ////////////////////////////////////////////////////////////////////////////// // void LLFloaterTools::updateMediaTitle() { // only get the media name if we need it if ( ! mNeedMediaTitle ) return; // get plugin impl LLPluginClassMedia* media_plugin = mTitleMedia->getMediaPlugin(); if ( media_plugin ) { // get the media name (asynchronous - must call repeatedly) std::string media_title = media_plugin->getMediaName(); // only replace the title if what we get contains something if ( ! media_title.empty() ) { // update the UI widget LLTextBox* media_title_field = getChild<LLTextBox>("media_info"); if ( media_title_field ) { media_title_field->setText( media_title ); // stop looking for a title when we get one // FIXME: check this is the right approach mNeedMediaTitle = false; }; }; }; } ////////////////////////////////////////////////////////////////////////////// // void LLFloaterTools::updateMediaSettings() { bool identical( false ); std::string base_key( "" ); std::string value_str( "" ); int value_int = 0; bool value_bool = false; LLObjectSelectionHandle selected_objects =LLSelectMgr::getInstance()->getSelection(); // TODO: (CP) refactor this using something clever or boost or both !! const LLMediaEntry default_media_data; // controls U8 value_u8 = default_media_data.getControls(); struct functor_getter_controls : public LLSelectedTEGetFunctor< U8 > { functor_getter_controls(const LLMediaEntry &entry) : mMediaEntry(entry) {} U8 get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getControls(); return mMediaEntry.getControls(); }; const LLMediaEntry &mMediaEntry; } func_controls(default_media_data); identical = selected_objects->getSelectedTEValue( &func_controls, value_u8 ); base_key = std::string( LLMediaEntry::CONTROLS_KEY ); mMediaSettings[ base_key ] = value_u8; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // First click (formerly left click) value_bool = default_media_data.getFirstClickInteract(); struct functor_getter_first_click : public LLSelectedTEGetFunctor< bool > { functor_getter_first_click(const LLMediaEntry& entry): mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getFirstClickInteract(); return mMediaEntry.getFirstClickInteract(); }; const LLMediaEntry &mMediaEntry; } func_first_click(default_media_data); identical = selected_objects->getSelectedTEValue( &func_first_click, value_bool ); base_key = std::string( LLMediaEntry::FIRST_CLICK_INTERACT_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Home URL value_str = default_media_data.getHomeURL(); struct functor_getter_home_url : public LLSelectedTEGetFunctor< std::string > { functor_getter_home_url(const LLMediaEntry& entry): mMediaEntry(entry) {} std::string get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getHomeURL(); return mMediaEntry.getHomeURL(); }; const LLMediaEntry &mMediaEntry; } func_home_url(default_media_data); identical = selected_objects->getSelectedTEValue( &func_home_url, value_str ); base_key = std::string( LLMediaEntry::HOME_URL_KEY ); mMediaSettings[ base_key ] = value_str; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Current URL value_str = default_media_data.getCurrentURL(); struct functor_getter_current_url : public LLSelectedTEGetFunctor< std::string > { functor_getter_current_url(const LLMediaEntry& entry): mMediaEntry(entry) {} std::string get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getCurrentURL(); return mMediaEntry.getCurrentURL(); }; const LLMediaEntry &mMediaEntry; } func_current_url(default_media_data); identical = selected_objects->getSelectedTEValue( &func_current_url, value_str ); base_key = std::string( LLMediaEntry::CURRENT_URL_KEY ); mMediaSettings[ base_key ] = value_str; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Auto zoom value_bool = default_media_data.getAutoZoom(); struct functor_getter_auto_zoom : public LLSelectedTEGetFunctor< bool > { functor_getter_auto_zoom(const LLMediaEntry& entry) : mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getAutoZoom(); return mMediaEntry.getAutoZoom(); }; const LLMediaEntry &mMediaEntry; } func_auto_zoom(default_media_data); identical = selected_objects->getSelectedTEValue( &func_auto_zoom, value_bool ); base_key = std::string( LLMediaEntry::AUTO_ZOOM_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Auto play //value_bool = default_media_data.getAutoPlay(); // set default to auto play TRUE -- angela EXT-5172 value_bool = true; struct functor_getter_auto_play : public LLSelectedTEGetFunctor< bool > { functor_getter_auto_play(const LLMediaEntry& entry) : mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getAutoPlay(); //return mMediaEntry.getAutoPlay(); set default to auto play TRUE -- angela EXT-5172 return true; }; const LLMediaEntry &mMediaEntry; } func_auto_play(default_media_data); identical = selected_objects->getSelectedTEValue( &func_auto_play, value_bool ); base_key = std::string( LLMediaEntry::AUTO_PLAY_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Auto scale // set default to auto scale TRUE -- angela EXT-5172 //value_bool = default_media_data.getAutoScale(); value_bool = true; struct functor_getter_auto_scale : public LLSelectedTEGetFunctor< bool > { functor_getter_auto_scale(const LLMediaEntry& entry): mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getAutoScale(); // return mMediaEntry.getAutoScale(); set default to auto scale TRUE -- angela EXT-5172 return true; }; const LLMediaEntry &mMediaEntry; } func_auto_scale(default_media_data); identical = selected_objects->getSelectedTEValue( &func_auto_scale, value_bool ); base_key = std::string( LLMediaEntry::AUTO_SCALE_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Auto loop value_bool = default_media_data.getAutoLoop(); struct functor_getter_auto_loop : public LLSelectedTEGetFunctor< bool > { functor_getter_auto_loop(const LLMediaEntry& entry) : mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getAutoLoop(); return mMediaEntry.getAutoLoop(); }; const LLMediaEntry &mMediaEntry; } func_auto_loop(default_media_data); identical = selected_objects->getSelectedTEValue( &func_auto_loop, value_bool ); base_key = std::string( LLMediaEntry::AUTO_LOOP_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // width pixels (if not auto scaled) value_int = default_media_data.getWidthPixels(); struct functor_getter_width_pixels : public LLSelectedTEGetFunctor< int > { functor_getter_width_pixels(const LLMediaEntry& entry): mMediaEntry(entry) {} int get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getWidthPixels(); return mMediaEntry.getWidthPixels(); }; const LLMediaEntry &mMediaEntry; } func_width_pixels(default_media_data); identical = selected_objects->getSelectedTEValue( &func_width_pixels, value_int ); base_key = std::string( LLMediaEntry::WIDTH_PIXELS_KEY ); mMediaSettings[ base_key ] = value_int; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // height pixels (if not auto scaled) value_int = default_media_data.getHeightPixels(); struct functor_getter_height_pixels : public LLSelectedTEGetFunctor< int > { functor_getter_height_pixels(const LLMediaEntry& entry) : mMediaEntry(entry) {} int get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getHeightPixels(); return mMediaEntry.getHeightPixels(); }; const LLMediaEntry &mMediaEntry; } func_height_pixels(default_media_data); identical = selected_objects->getSelectedTEValue( &func_height_pixels, value_int ); base_key = std::string( LLMediaEntry::HEIGHT_PIXELS_KEY ); mMediaSettings[ base_key ] = value_int; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Enable Alt image value_bool = default_media_data.getAltImageEnable(); struct functor_getter_enable_alt_image : public LLSelectedTEGetFunctor< bool > { functor_getter_enable_alt_image(const LLMediaEntry& entry): mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getAltImageEnable(); return mMediaEntry.getAltImageEnable(); }; const LLMediaEntry &mMediaEntry; } func_enable_alt_image(default_media_data); identical = selected_objects->getSelectedTEValue( &func_enable_alt_image, value_bool ); base_key = std::string( LLMediaEntry::ALT_IMAGE_ENABLE_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Perms - owner interact value_bool = 0 != ( default_media_data.getPermsInteract() & LLMediaEntry::PERM_OWNER ); struct functor_getter_perms_owner_interact : public LLSelectedTEGetFunctor< bool > { functor_getter_perms_owner_interact(const LLMediaEntry& entry): mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return (0 != (object->getTE(face)->getMediaData()->getPermsInteract() & LLMediaEntry::PERM_OWNER)); return 0 != ( mMediaEntry.getPermsInteract() & LLMediaEntry::PERM_OWNER ); }; const LLMediaEntry &mMediaEntry; } func_perms_owner_interact(default_media_data); identical = selected_objects->getSelectedTEValue( &func_perms_owner_interact, value_bool ); base_key = std::string( LLPanelContents::PERMS_OWNER_INTERACT_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Perms - owner control value_bool = 0 != ( default_media_data.getPermsControl() & LLMediaEntry::PERM_OWNER ); struct functor_getter_perms_owner_control : public LLSelectedTEGetFunctor< bool > { functor_getter_perms_owner_control(const LLMediaEntry& entry) : mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return (0 != (object->getTE(face)->getMediaData()->getPermsControl() & LLMediaEntry::PERM_OWNER)); return 0 != ( mMediaEntry.getPermsControl() & LLMediaEntry::PERM_OWNER ); }; const LLMediaEntry &mMediaEntry; } func_perms_owner_control(default_media_data); identical = selected_objects ->getSelectedTEValue( &func_perms_owner_control, value_bool ); base_key = std::string( LLPanelContents::PERMS_OWNER_CONTROL_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Perms - group interact value_bool = 0 != ( default_media_data.getPermsInteract() & LLMediaEntry::PERM_GROUP ); struct functor_getter_perms_group_interact : public LLSelectedTEGetFunctor< bool > { functor_getter_perms_group_interact(const LLMediaEntry& entry): mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return (0 != (object->getTE(face)->getMediaData()->getPermsInteract() & LLMediaEntry::PERM_GROUP)); return 0 != ( mMediaEntry.getPermsInteract() & LLMediaEntry::PERM_GROUP ); }; const LLMediaEntry &mMediaEntry; } func_perms_group_interact(default_media_data); identical = selected_objects->getSelectedTEValue( &func_perms_group_interact, value_bool ); base_key = std::string( LLPanelContents::PERMS_GROUP_INTERACT_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Perms - group control value_bool = 0 != ( default_media_data.getPermsControl() & LLMediaEntry::PERM_GROUP ); struct functor_getter_perms_group_control : public LLSelectedTEGetFunctor< bool > { functor_getter_perms_group_control(const LLMediaEntry& entry): mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return (0 != (object->getTE(face)->getMediaData()->getPermsControl() & LLMediaEntry::PERM_GROUP)); return 0 != ( mMediaEntry.getPermsControl() & LLMediaEntry::PERM_GROUP ); }; const LLMediaEntry &mMediaEntry; } func_perms_group_control(default_media_data); identical = selected_objects->getSelectedTEValue( &func_perms_group_control, value_bool ); base_key = std::string( LLPanelContents::PERMS_GROUP_CONTROL_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Perms - anyone interact value_bool = 0 != ( default_media_data.getPermsInteract() & LLMediaEntry::PERM_ANYONE ); struct functor_getter_perms_anyone_interact : public LLSelectedTEGetFunctor< bool > { functor_getter_perms_anyone_interact(const LLMediaEntry& entry): mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return (0 != (object->getTE(face)->getMediaData()->getPermsInteract() & LLMediaEntry::PERM_ANYONE)); return 0 != ( mMediaEntry.getPermsInteract() & LLMediaEntry::PERM_ANYONE ); }; const LLMediaEntry &mMediaEntry; } func_perms_anyone_interact(default_media_data); identical = LLSelectMgr::getInstance()->getSelection()->getSelectedTEValue( &func_perms_anyone_interact, value_bool ); base_key = std::string( LLPanelContents::PERMS_ANYONE_INTERACT_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // Perms - anyone control value_bool = 0 != ( default_media_data.getPermsControl() & LLMediaEntry::PERM_ANYONE ); struct functor_getter_perms_anyone_control : public LLSelectedTEGetFunctor< bool > { functor_getter_perms_anyone_control(const LLMediaEntry& entry) : mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return (0 != (object->getTE(face)->getMediaData()->getPermsControl() & LLMediaEntry::PERM_ANYONE)); return 0 != ( mMediaEntry.getPermsControl() & LLMediaEntry::PERM_ANYONE ); }; const LLMediaEntry &mMediaEntry; } func_perms_anyone_control(default_media_data); identical = selected_objects->getSelectedTEValue( &func_perms_anyone_control, value_bool ); base_key = std::string( LLPanelContents::PERMS_ANYONE_CONTROL_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // security - whitelist enable value_bool = default_media_data.getWhiteListEnable(); struct functor_getter_whitelist_enable : public LLSelectedTEGetFunctor< bool > { functor_getter_whitelist_enable(const LLMediaEntry& entry) : mMediaEntry(entry) {} bool get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getWhiteListEnable(); return mMediaEntry.getWhiteListEnable(); }; const LLMediaEntry &mMediaEntry; } func_whitelist_enable(default_media_data); identical = selected_objects->getSelectedTEValue( &func_whitelist_enable, value_bool ); base_key = std::string( LLMediaEntry::WHITELIST_ENABLE_KEY ); mMediaSettings[ base_key ] = value_bool; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; // security - whitelist URLs std::vector<std::string> value_vector_str = default_media_data.getWhiteList(); struct functor_getter_whitelist_urls : public LLSelectedTEGetFunctor< std::vector<std::string> > { functor_getter_whitelist_urls(const LLMediaEntry& entry): mMediaEntry(entry) {} std::vector<std::string> get( LLViewerObject* object, S32 face ) { if ( object ) if ( object->getTE(face) ) if ( object->getTE(face)->getMediaData() ) return object->getTE(face)->getMediaData()->getWhiteList(); return mMediaEntry.getWhiteList(); }; const LLMediaEntry &mMediaEntry; } func_whitelist_urls(default_media_data); identical = selected_objects->getSelectedTEValue( &func_whitelist_urls, value_vector_str ); base_key = std::string( LLMediaEntry::WHITELIST_KEY ); mMediaSettings[ base_key ].clear(); std::vector< std::string >::iterator iter = value_vector_str.begin(); while( iter != value_vector_str.end() ) { std::string white_list_url = *iter; mMediaSettings[ base_key ].append( white_list_url ); ++iter; }; mMediaSettings[ base_key + std::string( LLPanelContents::TENTATIVE_SUFFIX ) ] = ! identical; } struct LLFloaterToolsCopyKeysFunctor : public LLSelectedObjectFunctor { LLFloaterToolsCopyKeysFunctor(std::string& strOut, std::string& strSep) : mOutput(strOut), mSep(strSep) {} virtual bool apply(LLViewerObject* object) { if (!mOutput.empty()) mOutput.append(mSep); mOutput.append(object->getID().asString()); return true; } private: std::string& mOutput; std::string& mSep; }; void LLFloaterTools::onClickBtnCopyKeys() { std::string separator = gSavedSettings.getString("FSCopyObjKeySeparator"); std::string stringKeys; MASK mask = gKeyboard->currentMask(FALSE); LLFloaterToolsCopyKeysFunctor copy_keys(stringKeys, separator); bool copied = false; if (mask == MASK_SHIFT) copied = LLSelectMgr::getInstance()->getSelection()->applyToObjects(&copy_keys); else if (mCheckSelectIndividual && mCheckSelectIndividual->get()) copied = LLSelectMgr::getInstance()->getSelection()->applyToObjects(&copy_keys); else copied = LLSelectMgr::getInstance()->getSelection()->applyToRootObjects(&copy_keys); if (copied) { LLView::getWindow()->copyTextToClipboard(utf8str_to_wstring(stringKeys)); } } void LLFloaterTools::onClickExpand() { BOOL show_more = !gSavedSettings.getBOOL("FSToolboxExpanded"); gSavedSettings.setBOOL("FSToolboxExpanded", show_more); LLButton* btnExpand = getChild<LLButton>("btnExpand"); if (show_more) { mTab->setVisible(TRUE); reshape( getRect().getWidth(), mExpandedHeight); translate( 0, mCollapsedHeight - mExpandedHeight ); btnExpand->setImageOverlay("Arrow_Up", btnExpand->getImageOverlayHAlign()); } else { mTab->setVisible(FALSE); reshape( getRect().getWidth(), mCollapsedHeight); translate( 0, mExpandedHeight - mCollapsedHeight ); btnExpand->setImageOverlay("Arrow_Down", btnExpand->getImageOverlayHAlign()); } } // <FS:Ansariel> FIRE-7802: Grass and tree selection in build tool template<class P> void build_plant_combo(const std::map<U32, P*>& list, LLComboBox* combo) { if (!combo || list.empty()) return; combo->removeall(); typename std::map<U32, P*>::const_iterator it = list.begin(); typename std::map<U32, P*>::const_iterator end = list.end(); for ( ; it != end; ++it ) { P* plant = (*it).second; if (plant) combo->addSimpleElement(plant->mName, ADD_BOTTOM); } } void LLFloaterTools::buildTreeGrassCombo() { if (!mTreeGrassCombo) return; // Rebuild the combo with the list we need, then select the last-known use // TODO: rebuilding this list continuously is probably not the best way LLPCode pcode = LLToolPlacer::getObjectType(); std::string type = LLStringUtil::null; // LL_PCODE_TREE_NEW seems to be "new" as in "dodo" switch (pcode) { case LL_PCODE_LEGACY_TREE: case LL_PCODE_TREE_NEW: build_plant_combo(LLVOTree::sSpeciesTable, mTreeGrassCombo); mTreeGrassCombo->addSimpleElement("Random", ADD_TOP); type = "Tree"; break; case LL_PCODE_LEGACY_GRASS: build_plant_combo(LLVOGrass::sSpeciesTable, mTreeGrassCombo); mTreeGrassCombo->addSimpleElement("Random", ADD_TOP); type = "Grass"; break; default: mTreeGrassCombo->setEnabled(false); break; } // select last selected if exists if (!type.empty()) { // Enable the options mTreeGrassCombo->setEnabled(true); // Set the last selection, or "Random" (old default) if there isn't one std::string last_selected = gSavedSettings.getString("LastSelected"+type); if (last_selected.empty()) { mTreeGrassCombo->selectByValue(LLSD(std::string("Random"))); } else { mTreeGrassCombo->selectByValue(LLSD(last_selected)); } } } void LLFloaterTools::onSelectTreeGrassCombo() { // Save the last-used selection std::string last_selected = mTreeGrassCombo->getValue().asString(); LLPCode pcode = LLToolPlacer::getObjectType(); std::string type = ""; switch (pcode) { case LL_PCODE_LEGACY_GRASS: type = "Grass"; break; case LL_PCODE_LEGACY_TREE: case LL_PCODE_TREE_NEW: type = "Tree"; break; default: break; } if (!type.empty()) { // Should never be an empty string gSavedSettings.setString("LastSelected"+type, last_selected); } } // </FS:Ansariel>
33.380579
148
0.708285
SaladDais
c60b0bcfdfdd3c00b24091dd02708ea8a1ba4d7c
2,410
hpp
C++
raygun/ui/text.hpp
maggo007/Raygun
f6be537c835976a9d6cc356ebe187feba6592847
[ "MIT" ]
null
null
null
raygun/ui/text.hpp
maggo007/Raygun
f6be537c835976a9d6cc356ebe187feba6592847
[ "MIT" ]
null
null
null
raygun/ui/text.hpp
maggo007/Raygun
f6be537c835976a9d6cc356ebe187feba6592847
[ "MIT" ]
null
null
null
// The MIT License (MIT) // // Copyright (c) 2019,2020 The Raygun Authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #pragma once #include "raygun/entity.hpp" #include "raygun/material.hpp" #include "raygun/render/model.hpp" namespace raygun::ui { struct Font { string name; std::array<std::shared_ptr<render::Mesh>, 128> charMap = {}; std::array<float, 128> charWidth = {}; }; enum class Alignment { TopLeft, TopCenter, TopRight, MiddleLeft, MiddleCenter, MiddleRight, BottomLeft, BottomCenter, BottomRight, }; class TextGenerator { public: TextGenerator(const Font& font, std::shared_ptr<Material> material, float letterPadding = 0.1f, float lineSpacing = 1.f); std::shared_ptr<Entity> text(string_view input, Alignment align = Alignment::TopLeft) const; std::pair<std::shared_ptr<Entity>, render::Mesh::Bounds> textWithBounds(string_view input, Alignment align = Alignment::TopLeft) const; private: std::array<std::shared_ptr<render::Model>, 128> m_charMap = {}; std::array<float, 128> m_charWidth = {}; float letterPadding, lineSpacing; std::shared_ptr<render::Model> letter(char c) const; std::pair<std::shared_ptr<Entity>, render::Mesh::Bounds> textInternal(string_view input) const; }; using UniqueTextGenerator = std::unique_ptr<TextGenerator>; } // namespace raygun::ui
33.943662
139
0.729461
maggo007
c60cc60ea1ac5e5c395514debfcdc3b911e171e2
530
cpp
C++
test/correctness/handle.cpp
mikeseven/Halide
739513cc290d0351b69cedd31829032788bc3a7e
[ "MIT" ]
1
2016-10-08T00:18:46.000Z
2016-10-08T00:18:46.000Z
test/correctness/handle.cpp
mikeseven/Halide
739513cc290d0351b69cedd31829032788bc3a7e
[ "MIT" ]
null
null
null
test/correctness/handle.cpp
mikeseven/Halide
739513cc290d0351b69cedd31829032788bc3a7e
[ "MIT" ]
null
null
null
#include <Halide.h> #include <stdio.h> using namespace Halide; HalideExtern_1(int, strlen, const char *); int main(int argc, char **argv) { const char *c_message = "Hello, world!"; Param<const char *> message; message.set(c_message); int result = evaluate<int>(strlen(message)); int correct = strlen(c_message); if (result != correct) { printf("strlen(%s) -> %d instead of %d\n", c_message, result, correct); return -1; } printf("Success!\n"); return 0; }
20.384615
50
0.598113
mikeseven
c60f924d37abe13cbd69c6b69256a0274790d738
944
cc
C++
greedy/fractional_knapsack.cc
knguyenc/algorithms
4f61d692c986f6200eb1a52de022366a172aaa6f
[ "MIT" ]
null
null
null
greedy/fractional_knapsack.cc
knguyenc/algorithms
4f61d692c986f6200eb1a52de022366a172aaa6f
[ "MIT" ]
null
null
null
greedy/fractional_knapsack.cc
knguyenc/algorithms
4f61d692c986f6200eb1a52de022366a172aaa6f
[ "MIT" ]
null
null
null
#include "fractional_knapsack.h" #include <algorithm> namespace algorithm { namespace greedy { bool FractionalKnapsackItemComparator( const std::tuple<unsigned int, unsigned int> a, const std::tuple<unsigned int, unsigned int> b) { return (std::get<1>(a) / std::get<0>(a)) > (std::get<1>(b) / std::get<0>(b)); } template <size_t N> unsigned int FractionalKnapsack( std::tuple<unsigned int, unsigned int> (&items)[N], unsigned int weight) { std::sort(items, items + N, FractionalKnapsackItemComparator); unsigned int maxValue = 0; for (std::tuple<unsigned int, unsigned int> item : items) { if (weight <= 0) { break; } if (weight < std::get<0>(item)) { maxValue += weight * std::get<1>(item) / std::get<0>(item); weight = 0; } else { maxValue += std::get<1>(item); weight -= std::get<0>(item); } } return maxValue; } } // namespace greedy } // namespace algorithm
26.222222
79
0.629237
knguyenc
c60fb9dbb1e4b8235ef275604a77ffb6b76ff501
2,801
cc
C++
src/qvi-group-mpi.cc
samuelkgutierrez/quo-vadis
2a93f1c2bbfece70a9cab4f1e2a2eb02a817560b
[ "BSD-3-Clause" ]
3
2021-12-09T19:16:02.000Z
2021-12-09T20:10:51.000Z
src/qvi-group-mpi.cc
samuelkgutierrez/quo-vadis
2a93f1c2bbfece70a9cab4f1e2a2eb02a817560b
[ "BSD-3-Clause" ]
14
2021-10-23T00:46:43.000Z
2022-03-15T20:53:04.000Z
src/qvi-group-mpi.cc
samuelkgutierrez/quo-vadis
2a93f1c2bbfece70a9cab4f1e2a2eb02a817560b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2020-2022 Triad National Security, LLC * All rights reserved. * * Copyright (c) 2020-2021 Lawrence Livermore National Security, LLC * All rights reserved. * * This file is part of the quo-vadis project. See the LICENSE file at the * top-level directory of this distribution. */ /** * @file qvi-group-mpi.cc * */ #include "qvi-common.h" #include "qvi-group-mpi.h" qvi_group_mpi_s::~qvi_group_mpi_s(void) { qvi_mpi_group_free(&mpi_group); } int qvi_group_mpi_s::create(void) { return qvi_mpi_group_new(&mpi_group); } int qvi_group_mpi_s::initialize( qvi_mpi_t *mpi ) { assert(mpi); if (!mpi) return QV_ERR_INTERNAL; this->mpi = mpi; return QV_SUCCESS; } int qvi_group_mpi_s::id(void) { return qvi_mpi_group_id(mpi_group); } int qvi_group_mpi_s::size(void) { return qvi_mpi_group_size(mpi_group); } int qvi_group_mpi_s::barrier(void) { return qvi_mpi_group_barrier(mpi_group); } int qvi_group_mpi_s::self( qvi_group_t **child ) { int rc = QV_SUCCESS; qvi_group_mpi_t *ichild = qvi_new qvi_group_mpi_t(); if (!ichild) { rc = QV_ERR_OOR; goto out; } // Initialize the child with the parent's MPI instance. rc = ichild->initialize(mpi); if (rc != QV_SUCCESS) goto out; // Create the underlying group using MPI_COMM_SELF. rc = qvi_mpi_group_create_from_mpi_comm( mpi, MPI_COMM_SELF, &ichild->mpi_group ); out: if (rc != QV_SUCCESS) { delete ichild; ichild = nullptr; } *child = ichild; return rc; } int qvi_group_mpi_s::split( int color, int key, qvi_group_t **child ) { int rc = QV_SUCCESS; qvi_group_mpi_t *ichild = qvi_new qvi_group_mpi_t(); if (!ichild) { rc = QV_ERR_OOR; goto out; } // Initialize the child with the parent's MPI instance. rc = ichild->initialize(mpi); if (rc != QV_SUCCESS) goto out; // Split this group using MPI. rc = qvi_mpi_group_create_from_split( mpi, mpi_group, color, key, &ichild->mpi_group ); out: if (rc != QV_SUCCESS) { delete ichild; ichild = nullptr; } *child = ichild; return rc; } int qvi_group_mpi_s::gather( qvi_bbuff_t *txbuff, int root, qvi_bbuff_t ***rxbuffs ) { return qvi_mpi_group_gather_bbuffs( mpi_group, txbuff, root, rxbuffs ); } int qvi_group_mpi_s::scatter( qvi_bbuff_t **txbuffs, int root, qvi_bbuff_t **rxbuff ) { return qvi_mpi_group_scatter_bbuffs( mpi_group, txbuffs, root, rxbuff ); } int qvi_group_mpi_s::comm_dup( MPI_Comm *comm ) { return qvi_mpi_group_comm_dup(mpi_group, comm); } /* * vim: ft=cpp ts=4 sts=4 sw=4 expandtab */
18.798658
74
0.637272
samuelkgutierrez
c6116c08f89617369f47b91304b38eb94548fe56
1,021
cpp
C++
src/Engine/Material/GGX.cpp
trygas/CGHomework
2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe
[ "MIT" ]
594
2019-02-19T01:09:27.000Z
2022-03-31T07:47:11.000Z
src/Engine/Material/GGX.cpp
Ricahrd-Li/ASAP_ARAP_Parameterization
c12d83605ce9ea9cac29efbd991d21e2b363e375
[ "MIT" ]
12
2020-02-19T07:11:14.000Z
2021-08-07T06:41:27.000Z
src/Engine/Material/GGX.cpp
Ricahrd-Li/ASAP_ARAP_Parameterization
c12d83605ce9ea9cac29efbd991d21e2b363e375
[ "MIT" ]
249
2020-02-01T08:14:36.000Z
2022-03-30T14:52:58.000Z
#include <Engine/Material/GGX.h> #include <Engine/Material/SurfCoord.h> using namespace Ubpa; float GGX::D(const normalf & wh) const { if (SurfCoord::CosTheta(wh) < 0) return 0.f; float alpha2 = alpha * alpha; float cos2Theta = SurfCoord::Cos2Theta(wh); float t = (alpha2 - 1) * cos2Theta + 1; return alpha2 / (PI<float> * t * t); } float GGX::Lambda(const normalf & w) const { auto absTanTheta = std::abs(SurfCoord::TanTheta(w)); if (std::isnan(absTanTheta)) return 98e8f; auto alpha2Tan2Theta = (alpha * absTanTheta) * (alpha * absTanTheta); return (-1.f + std::sqrt(1.f + alpha2Tan2Theta)) / 2.f; } const normalf GGX::Sample_wh() const { // sample const float Xi1 = Math::Rand_F(); const float Xi2 = Math::Rand_F(); // theta const auto cos2Theta = (1 - Xi1) / ((alpha*alpha - 1)*Xi1 + 1); const auto cosTheta = sqrt(cos2Theta); const auto sinTheta = sqrt(1 - cos2Theta); // phi const auto phi = 2 * PI<float> * Xi2; return SurfCoord::SphericalDirection(sinTheta, cosTheta, phi); }
23.204545
70
0.666993
trygas
c615c427ac9dc4d4f6623732fccd9c00da134b8d
3,580
cpp
C++
examples/primitives/shuffle.cpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
1,327
2018-01-25T21:23:47.000Z
2020-04-03T09:39:30.000Z
examples/primitives/shuffle.cpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
583
2020-04-04T02:37:25.000Z
2022-03-31T00:12:03.000Z
examples/primitives/shuffle.cpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
365
2018-01-29T16:12:36.000Z
2020-04-03T08:32:27.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. *******************************************************************************/ /// @example shuffle.cpp /// > Annotated version: @ref shuffle_example_cpp /// /// @page shuffle_example_cpp_short /// /// This C++ API example demonstrates how to create and execute a /// [Shuffle](@ref dev_guide_shuffle) primitive. /// /// Key optimizations included in this example: /// - Shuffle along axis 1 (channels). /// /// @page shuffle_example_cpp Shuffle Primitive Example /// @copydetails shuffle_example_cpp_short /// /// @include shuffle.cpp #include <algorithm> #include <cmath> #include <iostream> #include <string> #include <vector> #include "example_utils.hpp" #include "oneapi/dnnl/dnnl.hpp" using namespace dnnl; using tag = memory::format_tag; using dt = memory::data_type; void shuffle_example(dnnl::engine::kind engine_kind) { // Create execution dnnl::engine. dnnl::engine engine(engine_kind, 0); // Create dnnl::stream. dnnl::stream engine_stream(engine); // Tensor dimensions. const memory::dim N = 3, // batch size IC = 72, // channels IH = 227, // tensor height IW = 227; // tensor width // Source (src) and destination (dst) tensors dimensions. memory::dims src_dims = {N, IC, IH, IW}; // Allocate buffers. std::vector<float> src_data(product(src_dims)); std::vector<float> dst_data(product(src_dims)); // Initialize src. std::generate(src_data.begin(), src_data.end(), []() { static int i = 0; return std::cos(i++ / 10.f); }); // Shuffle axis and group size. const int shuffle_axis = 1; const int group_size = 4; // Create memory descriptor and memory objects for src and dst. auto src_md = memory::desc(src_dims, dt::f32, tag::nchw); auto src_mem = memory(src_md, engine); auto dst_mem = memory({src_dims, dt::f32, tag::abcd}, engine); // Write data to memory object's handle. write_to_dnnl_memory(src_data.data(), src_mem); // Create operation descriptor. auto shuffle_d = shuffle_forward::desc( prop_kind::forward_training, src_md, shuffle_axis, group_size); // Create primitive descriptor. auto shuffle_pd = shuffle_forward::primitive_desc(shuffle_d, engine); // Create the primitive. auto shuffle_prim = shuffle_forward(shuffle_pd); // Primitive arguments. std::unordered_map<int, memory> shuffle_args; shuffle_args.insert({DNNL_ARG_SRC, src_mem}); shuffle_args.insert({DNNL_ARG_DST, dst_mem}); // Primitive execution: shuffle. shuffle_prim.execute(engine_stream, shuffle_args); // Wait for the computation to finalize. engine_stream.wait(); // Read data from memory object. read_from_dnnl_memory(dst_data.data(), dst_mem); } int main(int argc, char **argv) { return handle_example_errors( shuffle_example, parse_engine_kind(argc, argv)); }
30.862069
80
0.659218
JackAKirk
c616ac7c50c630e1ec3184bb0247c6e7e6ee704e
768
cpp
C++
engine/calculators/source/unit_tests/TertiaryUnarmedCalculator_test.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
1
2020-05-24T22:44:03.000Z
2020-05-24T22:44:03.000Z
engine/calculators/source/unit_tests/TertiaryUnarmedCalculator_test.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
null
null
null
engine/calculators/source/unit_tests/TertiaryUnarmedCalculator_test.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" TEST(SW_Engine_Calculators_TertiaryUnarmedCalculator, calculate_knock_back_pct_chance) { CreaturePtr creature; TertiaryUnarmedCalculator tuc; EXPECT_EQ(0, tuc.calculate_knock_back_pct_chance(creature)); creature = CreaturePtr(new Creature()); Statistic str(1); creature->set_strength(str); EXPECT_EQ(0, tuc.calculate_knock_back_pct_chance(creature)); str.set_base_current(2); creature->set_strength(str); EXPECT_EQ(1, tuc.calculate_knock_back_pct_chance(creature)); str.set_base_current(12); creature->set_strength(str); EXPECT_EQ(6, tuc.calculate_knock_back_pct_chance(creature)); str.set_base_current(99); creature->set_strength(str); EXPECT_EQ(49, tuc.calculate_knock_back_pct_chance(creature)); }
24.774194
86
0.78776
sidav
723fb724e670b01b7142fb4ae0730ced229aa59a
343
cpp
C++
Exec/AMR-zoom/Nyx_error.cpp
Gosenca/axionyx_1.0
7e2a723e00e6287717d6d81b23db32bcf6c3521a
[ "BSD-3-Clause-LBNL" ]
6
2021-02-18T09:13:17.000Z
2022-03-22T21:27:46.000Z
Exec/AMR-zoom/Nyx_error.cpp
Gosenca/axionyx_1.0
7e2a723e00e6287717d6d81b23db32bcf6c3521a
[ "BSD-3-Clause-LBNL" ]
1
2020-10-12T08:54:31.000Z
2020-10-12T08:54:31.000Z
Exec/AMR-zoom/Nyx_error.cpp
Gosenca/axionyx_1.0
7e2a723e00e6287717d6d81b23db32bcf6c3521a
[ "BSD-3-Clause-LBNL" ]
3
2020-09-04T10:26:25.000Z
2022-03-14T23:51:51.000Z
#include "Nyx.H" #include "Nyx_error_F.H" using namespace amrex; void Nyx::error_setup() { err_list.add("total_density",1,ErrorRec::UseAverage, BL_FORT_PROC_CALL(TAG_OVERDENSITY, tag_overdensity)); } void Nyx::manual_tags_placement (TagBoxArray& tags, const Vector<IntVect>& bf_lev) { }
18.052632
70
0.653061
Gosenca
7244c846c394c7c8464423375111a5a45874fa10
4,229
cpp
C++
src/goto-symex/slice.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
143
2015-06-22T12:30:01.000Z
2022-03-21T08:41:17.000Z
src/goto-symex/slice.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
542
2017-06-02T13:46:26.000Z
2022-03-31T16:35:17.000Z
src/goto-symex/slice.cpp
shmarovfedor/esbmc
3226a3d68b009d44b9535a993ac0f25e1a1fbedd
[ "BSD-3-Clause" ]
81
2015-10-21T22:21:59.000Z
2022-03-24T14:07:55.000Z
/*******************************************************************\ Module: Slicer for symex traces Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ #include <goto-symex/slice.h> symex_slicet::symex_slicet(bool assume) : ignored(0), slice_assumes(assume), add_to_deps([this](const symbol2t &s) -> bool { return depends.insert(s.get_symbol_name()).second; }) { } bool symex_slicet::get_symbols( const expr2tc &expr, std::function<bool(const symbol2t &)> fn) { bool res = false; expr->foreach_operand([this, &fn, &res](const expr2tc &e) { if(!is_nil_expr(e)) res = get_symbols(e, fn) || res; return res; }); if(!is_symbol2t(expr)) return res; const symbol2t &tmp = to_symbol2t(expr); return fn(tmp) || res; } void symex_slicet::slice(std::shared_ptr<symex_target_equationt> &eq) { depends.clear(); for(symex_target_equationt::SSA_stepst::reverse_iterator it = eq->SSA_steps.rbegin(); it != eq->SSA_steps.rend(); it++) slice(*it); } void symex_slicet::slice(symex_target_equationt::SSA_stept &SSA_step) { switch(SSA_step.type) { case goto_trace_stept::ASSERT: get_symbols(SSA_step.guard, add_to_deps); get_symbols(SSA_step.cond, add_to_deps); break; case goto_trace_stept::ASSUME: if(slice_assumes) slice_assume(SSA_step); else { get_symbols(SSA_step.guard, add_to_deps); get_symbols(SSA_step.cond, add_to_deps); } break; case goto_trace_stept::ASSIGNMENT: slice_assignment(SSA_step); break; case goto_trace_stept::OUTPUT: break; case goto_trace_stept::RENUMBER: slice_renumber(SSA_step); break; default: assert(false); } } void symex_slicet::slice_assume(symex_target_equationt::SSA_stept &SSA_step) { auto check_in_deps = [this](const symbol2t &s) -> bool { return depends.find(s.get_symbol_name()) != depends.end(); }; if(!get_symbols(SSA_step.cond, check_in_deps)) { // we don't really need it SSA_step.ignore = true; ++ignored; } else { // If we need it, add the symbols to dependency get_symbols(SSA_step.guard, add_to_deps); get_symbols(SSA_step.cond, add_to_deps); } } void symex_slicet::slice_assignment(symex_target_equationt::SSA_stept &SSA_step) { assert(is_symbol2t(SSA_step.lhs)); auto check_in_deps = [this](const symbol2t &s) -> bool { return depends.find(s.get_symbol_name()) != depends.end(); }; if(!get_symbols(SSA_step.lhs, check_in_deps)) { // we don't really need it SSA_step.ignore = true; ++ignored; } else { get_symbols(SSA_step.guard, add_to_deps); get_symbols(SSA_step.rhs, add_to_deps); // Remove this symbol as we won't be seeing any references to it further // into the history. depends.erase(to_symbol2t(SSA_step.lhs).get_symbol_name()); } } void symex_slicet::slice_renumber(symex_target_equationt::SSA_stept &SSA_step) { assert(is_symbol2t(SSA_step.lhs)); auto check_in_deps = [this](const symbol2t &s) -> bool { return depends.find(s.get_symbol_name()) != depends.end(); }; if(!get_symbols(SSA_step.lhs, check_in_deps)) { // we don't really need it SSA_step.ignore = true; ++ignored; } // Don't collect the symbol; this insn has no effect on dependencies. } BigInt slice(std::shared_ptr<symex_target_equationt> &eq, bool slice_assumes) { symex_slicet symex_slice(slice_assumes); symex_slice.slice(eq); return symex_slice.ignored; } BigInt simple_slice(std::shared_ptr<symex_target_equationt> &eq) { BigInt ignored = 0; // just find the last assertion symex_target_equationt::SSA_stepst::iterator last_assertion = eq->SSA_steps.end(); for(symex_target_equationt::SSA_stepst::iterator it = eq->SSA_steps.begin(); it != eq->SSA_steps.end(); it++) if(it->is_assert()) last_assertion = it; // slice away anything after it symex_target_equationt::SSA_stepst::iterator s_it = last_assertion; if(s_it != eq->SSA_steps.end()) for(s_it++; s_it != eq->SSA_steps.end(); s_it++) { s_it->ignore = true; ++ignored; } return ignored; }
23.364641
80
0.659021
shmarovfedor
7244f40eed6c6a3b8c266b20909fccc2cf89c9f3
51,858
cpp
C++
project/c++/mri/src/PI-slim-napa/db/MySqlRecdClient.cpp
jia57196/code41
df611f84592afd453ccb2d22a7ad999ddb68d028
[ "Apache-2.0" ]
null
null
null
project/c++/mri/src/PI-slim-napa/db/MySqlRecdClient.cpp
jia57196/code41
df611f84592afd453ccb2d22a7ad999ddb68d028
[ "Apache-2.0" ]
null
null
null
project/c++/mri/src/PI-slim-napa/db/MySqlRecdClient.cpp
jia57196/code41
df611f84592afd453ccb2d22a7ad999ddb68d028
[ "Apache-2.0" ]
null
null
null
/* * MySqlRecdClient.cpp * * Created on: Jan 4, 2011 * Author: DS\one55379 */ #include "MySqlRecdClient.h" #include "DbUtils.h" //#include <my_global.h> #include <errmsg.h> #include <sstream> #include <string.h> MySqlRecdClient::MySqlRecdClient() : mpMysql(0), mDBName("recd"), mHost("localhost"), mUser("recd"), mPassword("recd"), mLoadCallTraceStr(""), mLoadTunnelStr(""), mLoadUeStr(""), mLoadUeUpdateStr(""), mLoadUeIpPartStr(""), mLoadIpStr(""), mLoadCallTraceEndStr(""), mLoadTunnelEndStr(""), mLoadApnStr(""), mLoadIpFlowStr("") { mLogId = LOG_ID("MySqlRecdClient"); mpMysql = new MYSQL(); if (!mysql_init(mpMysql)) { LOG_ERROR(mLogId,"Failure to initialize mysql using mysql_init."); delete mpMysql; mpMysql = 0; } } MySqlRecdClient::~MySqlRecdClient() { mysql_close(mpMysql); if (mpMysql != NULL) { delete mpMysql; } } int MySqlRecdClient::connect(const char *pHost, const char *pUser, const char *pPwd, const char *pDBName/*=0*/) { if (mpMysql != NULL) { if (NULL != pDBName) { mDBName = pDBName; } LOG_DEBUG(mLogId,"connect: db name = %s", mDBName.c_str()); if (!mysql_real_connect(mpMysql, pHost, pUser, pPwd, mDBName.c_str(), 0, NULL, CLIENT_MULTI_STATEMENTS)) { LOG_ERROR(mLogId,"Failure to connect to mysql using mysql_real_connect. Error: %s", mysql_error(mpMysql)); return(1); // error } // set option to reconnect if connection is idle too long // prior to version 5.1.6, documentation says to call mysql_options for RECONNECT after mysql_real_connect my_bool reconnect = 1; mysql_options(mpMysql,MYSQL_OPT_RECONNECT,&reconnect); } else { LOG_ERROR(mLogId,"Failure to connect to mysql, mpMysql is NULL - need to initialize."); return(1); // error } LOG_INFO(mLogId,"Successfully connected to mysql. db name = %s",mDBName.c_str()); return(0); // success } void MySqlRecdClient::disconnect() { mysql_close(mpMysql); } bool MySqlRecdClient::checkAndRepairTables(uint32_t partitionToCheck) { bool returnCode = true; // show tables to get all table names // skip: call_trace*, tunnel* MYSQL_RES *result; MYSQL_ROW row; int numFields = 0; // do the query string getAllNonPartitionedTables = "select table_name from INFORMATION_SCHEMA.TABLES where table_schema='" + mDBName + "' and table_name not like 'call_trace%' and table_name not like 'ue_ip_part%' and table_name not like 'tunnel%' and table_name not like 'ip_flow%'"; if (mysql_query(mpMysql,getAllNonPartitionedTables.c_str())) { LOG_ERROR(mLogId,"checkAndRepairTables: Failure to query: %s. Error: %s", getAllNonPartitionedTables.c_str(),mysql_error(mpMysql)); return false; } // note: result could be null if there are no rows. result = mysql_store_result(mpMysql); if (result == NULL) { LOG_ERROR(mLogId,"checkAndRepairTables: could not find any tables."); return false; } numFields = mysql_num_fields(result); while ((row = mysql_fetch_row(result))) { if (row[0] != NULL) { string tableName = row[0]; // check and repair the table returnCode = checkAndRepair(tableName); } } // end while tables to check // now check the partition tables LOG_TRACE(mLogId,"checkAndRepairTables: checking partition tables, previous partition = %d.",partitionToCheck); stringstream oss; oss << "tunnel_" << partitionToCheck; string tunnelTable = oss.str(); oss.str(""); oss.clear(); returnCode = checkAndRepair(tunnelTable); oss << "call_trace_" << partitionToCheck; string callTraceTable = oss.str(); oss.str(""); oss.clear(); returnCode = checkAndRepair(callTraceTable); oss << "call_trace_end_" << partitionToCheck; string callTraceEndTable = oss.str(); oss.str(""); oss.clear(); returnCode = checkAndRepair(callTraceEndTable); oss << "tunnel_end_" << partitionToCheck; string tunnelEndTable = oss.str(); oss.str(""); oss.clear(); returnCode = checkAndRepair(tunnelEndTable); oss << "ue_ip_part_" << partitionToCheck; string ueIpPartTable = oss.str(); oss.str(""); oss.clear(); returnCode = checkAndRepair(ueIpPartTable); oss << "ip_flow_" << partitionToCheck; string ipFlowTable = oss.str(); oss.str(""); oss.clear(); returnCode = checkAndRepair(ipFlowTable); mysql_free_result(result); return returnCode; } /* * These should be set in my.cnf. This is not being used now. */ void MySqlRecdClient::setGlobalServerVariables() { // variables affecting load data if (mysql_query(mpMysql,"SET GLOBAL bulk_insert_buffer_size = 1000000000")) { LOG_ERROR(mLogId,"Failure to set global variable. Error: %s", mysql_error(mpMysql)); } if (mysql_query(mpMysql,"SET GLOBAL myisam_sort_buffer_size = 1000000000")) { LOG_ERROR(mLogId,"Failure to set global variable. Error: %s", mysql_error(mpMysql)); } if (mysql_query(mpMysql,"SET GLOBAL key_buffer_size = 1000000000")) { LOG_ERROR(mLogId,"Failure to set global variable. Error: %s", mysql_error(mpMysql)); } } void MySqlRecdClient::sourceSqlFile(string& file) { string commandString = "mysql -uroot -pgizzy -e 'source " + file + "'"; system(commandString.c_str()); } void MySqlRecdClient::runSqlStatement(string& statement) { if(mysql_query(mpMysql,statement.c_str())) { LOG_ERROR(mLogId,"runSqlStatement(): query failed: %s", statement.c_str()); } } /* * initFileLoadCommands is called by the FileLoaderThread. */ void MySqlRecdClient::initFileLoadCommands(string& fileDir,DbFile* dbFile, uint32_t partition) { stringstream oss; string callTraceFile = DbFile::getFullFilePath(fileDir,DbFile::CALL_TRACE_FILENAME,partition); oss << "LOAD DATA CONCURRENT INFILE '" << callTraceFile << "' INTO TABLE call_trace_" << partition; mLoadCallTraceStr = oss.str(); LOG_INFO(mLogId,"initFileLoadCommands: mLoadCallTraceStr : %s", mLoadCallTraceStr.c_str()); oss.str(""); oss.clear(); string tunnelFile = DbFile::getFullFilePath(fileDir,DbFile::TUNNEL_FILENAME,partition); oss << "LOAD DATA CONCURRENT INFILE '" << tunnelFile << "' INTO TABLE tunnel_" << partition; mLoadTunnelStr = oss.str(); LOG_INFO(mLogId,"initFileLoadCommands: mLoadTunnelFileStr : %s", mLoadTunnelStr.c_str()); oss.str(""); oss.clear(); string ueFile = DbFile::getFullFilePath(fileDir,DbFile::UE_FILENAME,partition); oss << "LOAD DATA CONCURRENT INFILE '" << ueFile << "' INTO TABLE ue"; mLoadUeStr = oss.str(); LOG_INFO(mLogId,"initFileLoadCommands: mLoadUeFileStr : %s", mLoadUeStr.c_str()); oss.str(""); oss.clear(); string ueUpdateFile = DbFile::getFullFilePath(fileDir,DbFile::UE_UPDATE_FILENAME,partition); oss << "LOAD DATA CONCURRENT INFILE '" << ueFile << "' INTO TABLE ue_update"; mLoadUeUpdateStr = oss.str(); LOG_INFO(mLogId,"initFileLoadCommands: mLoadUeUpdateFileStr : %s", mLoadUeUpdateStr.c_str()); oss.str(""); oss.clear(); string ueIpPartFile = DbFile::getFullFilePath(fileDir,DbFile::UE_IP_FILENAME,partition); oss << "LOAD DATA CONCURRENT INFILE '" << ueIpPartFile << "' INTO TABLE ue_ip_part_" << partition; mLoadUeIpPartStr = oss.str(); LOG_INFO(mLogId,"initFileLoadCommands: mLoadUeIpPartStr : %s", mLoadUeIpPartStr.c_str()); oss.str(""); oss.clear(); string ipFile = DbFile::getFullFilePath(fileDir,DbFile::IP_FILENAME,partition); oss << "LOAD DATA CONCURRENT INFILE '" << ipFile << "' INTO TABLE ip"; mLoadIpStr = oss.str(); LOG_INFO(mLogId,"initFileLoadCommands: mLoadIpFileStr : %s", mLoadIpStr.c_str()); oss.str(""); oss.clear(); string callTraceEndFile = DbFile::getFullFilePath(fileDir,DbFile::CALL_TRACE_END_FILENAME,partition); oss << "LOAD DATA CONCURRENT INFILE '" << callTraceEndFile << "' INTO TABLE call_trace_end_" << partition; mLoadCallTraceEndStr = oss.str(); LOG_INFO(mLogId,"initFileLoadCommands: mLoadCallTraceEndStr : %s", mLoadCallTraceEndStr.c_str()); oss.str(""); oss.clear(); string tunnelEndFile = DbFile::getFullFilePath(fileDir,DbFile::TUNNEL_END_FILENAME,partition); oss << "LOAD DATA CONCURRENT INFILE '" << tunnelEndFile << "' INTO TABLE tunnel_end_" << partition; mLoadTunnelEndStr = oss.str(); LOG_INFO(mLogId,"initFileLoadCommands: mLoadTunnelEndStr : %s", mLoadTunnelEndStr.c_str()); oss.str(""); oss.clear(); string apnFile = DbFile::getFullFilePath(fileDir,DbFile::APN_FILENAME,partition); oss << "LOAD DATA CONCURRENT INFILE '" << apnFile << "' INTO TABLE apn"; mLoadApnStr = oss.str(); LOG_INFO(mLogId,"initFileLoadCommands: mLoadApnFileStr : %s", mLoadApnStr.c_str()); oss.str(""); oss.clear(); string ipFlowFile = DbFile::getFullFilePath(fileDir,DbFile::IP_FLOW_FILENAME,partition); oss << "LOAD DATA CONCURRENT INFILE '" << ipFlowFile << "' INTO TABLE ip_flow_" << partition; mLoadIpFlowStr = oss.str(); LOG_INFO(mLogId,"initFileLoadCommands: mLoadIpFlowStr : %s", mLoadIpFlowStr.c_str()); } /* * checkAndRepair a specific table. */ bool MySqlRecdClient::checkAndRepair(string& tableName) { bool returnCode = true; string checkTableStr = "CHECK TABLE " + tableName + " FAST QUICK"; MYSQL_RES *checkresult; MYSQL_ROW checkrow; int numCheckFields = 0; if (mysql_query(mpMysql,checkTableStr.c_str())) { LOG_ERROR(mLogId,"checkAndRepair: Failure to query: %s. Error: %s", checkTableStr.c_str(),mysql_error(mpMysql)); return false; } // note: result could be null if there are no rows. checkresult = mysql_store_result(mpMysql); if (checkresult == NULL) { LOG_ERROR(mLogId,"checkAndRepair: no results from check table: %s",tableName.c_str()); return false; } numCheckFields = mysql_num_fields(checkresult); // check result if ((checkrow = mysql_fetch_row(checkresult))) { if ((numCheckFields >= 4) && (checkrow[3] != NULL)) { string msgTextStr = checkrow[3]; if ((msgTextStr.compare("OK") == 0) || (msgTextStr.compare("Table is already up to date") == 0)) { // nothing to repair LOG_TRACE(mLogId,"checkAndRepair: Checked table: %s ,and it is OK",tableName.c_str()); } else { LOG_INFO(mLogId,"checkAndRepair: Attempting to Repair Table: %s",tableName.c_str()); //LOG_INFO(mLogId,"checkAndRepair: Flush Tables : %s",tableName.c_str()); //flushTables(tableName); // repair string repairTableStr = "REPAIR TABLE " + tableName + " QUICK"; MYSQL_RES *repairresult; MYSQL_ROW repairrow; int numRepairFields = 0; if (mysql_query(mpMysql,repairTableStr.c_str())) { LOG_ERROR(mLogId,"checkAndRepair: Failure to repair table query: %s. Error: %s", repairTableStr.c_str(),mysql_error(mpMysql)); return false; } // note: result could be null if there are no rows. repairresult = mysql_store_result(mpMysql); if (repairresult == NULL) { LOG_ERROR(mLogId,"checkAndRepair: no results from repair table: %s",tableName.c_str()); return false; } numRepairFields = mysql_num_fields(repairresult); // check result if ((repairrow = mysql_fetch_row(repairresult))) { if ((numRepairFields >= 4) && (repairrow[2] != NULL)) { string msgTypeStr = repairrow[2]; if (msgTypeStr.compare("error") == 0) { // try the USE_FRM option which recreates the .MYI file header based on the .frm file. LOG_INFO(mLogId,"checkAndRepair: Error during attempt to repair table: %s , Now attempting REPAIR USE_FRM option.",tableName.c_str()); string usefrmRepairTableStr = "REPAIR TABLE " + tableName + " USE_FRM"; MYSQL_RES *usefrmRepairresult; MYSQL_ROW usefrmRepairrow; int numUseFrmRepairFields = 0; if (mysql_query(mpMysql,usefrmRepairTableStr.c_str())) { LOG_ERROR(mLogId,"checkAndRepair: Failure to repair use_frm table query: %s. Error: %s", usefrmRepairTableStr.c_str(),mysql_error(mpMysql)); return false; } // note: result could be null if there are no rows. usefrmRepairresult = mysql_store_result(mpMysql); if (usefrmRepairresult == NULL) { LOG_ERROR(mLogId,"checkAndRepair: no results from repair use_frm table: %s",tableName.c_str()); return false; } numUseFrmRepairFields = mysql_num_fields(usefrmRepairresult); // check result if ((usefrmRepairrow = mysql_fetch_row(usefrmRepairresult))) { if ((numUseFrmRepairFields >= 4) && (usefrmRepairrow[3] != NULL)) { string msgTextStr = usefrmRepairrow[3]; if ((msgTextStr.compare("OK") == 0) || (msgTextStr.compare("Table is already up to date") == 0)) { // successful LOG_INFO(mLogId,"checkAndRepair: Successfully Repaired table: %s",tableName.c_str()); flushTables(tableName); LOG_INFO(mLogId,"checkAndRepair: Successfully Flushed table: %s",tableName.c_str()); } else { LOG_INFO(mLogId,"checkAndRepair: Failed to repair table: %s",tableName.c_str()); returnCode = false; } } } mysql_free_result(usefrmRepairresult); } else { // check if repair worked string msgFieldStr = repairrow[3]; if (msgFieldStr.compare("OK") != 0) { LOG_ERROR(mLogId,"checkAndRepair: Failed to repair table: %s",tableName.c_str()); returnCode = false; } else { LOG_INFO(mLogId,"checkAndRepair: Successfully Repaired table: %s",tableName.c_str()); flushTables(tableName); LOG_INFO(mLogId,"checkAndRepair: Successfully Flushed table: %s",tableName.c_str()); } } } } mysql_free_result(repairresult); } } } mysql_free_result(checkresult); return returnCode; } bool MySqlRecdClient::legacyipInsert(uint64_t id, bool is_ipv6, uint64_t ms_ip_addr, uint64_t ls_ip_addr) { stringstream oss; bool status = true; oss << "INSERT INTO ip (id,is_ipv6,ms_ip_addr,ls_ip_addr) VALUES (" << id << "," << is_ipv6 << "," << ms_ip_addr << "," << ls_ip_addr << ")"; string insertString = oss.str(); LOG_TRACE(mLogId,"ipInserts: insertString = %s", insertString.c_str()); if(mysql_query(mpMysql,insertString.c_str())) { LOG_ERROR(mLogId,"insertIp(): query failed: %s", insertString.c_str()); status=false; } return status; } bool MySqlRecdClient::legacyueIpInsert(uint64_t id, uint64_t ue_id, bool is_ipv6, uint64_t ms_ip_addr, uint64_t ls_ip_addr, int interface_type, time_t detect_time) { bool status = true; string mysqlTime; DbUtils::convertFromUnixTimeToMySqlString(detect_time, &mysqlTime); stringstream oss; oss << "INSERT INTO ue_ip (id,ue_id,is_ipv6,ms_ip_addr,ls_ip_addr,interface_type, detect_time) VALUES (" << id << "," << ue_id << "," << is_ipv6 << "," << ms_ip_addr << "," << ls_ip_addr << "," << interface_type << ",'" << mysqlTime << "')"; string insertString = oss.str(); LOG_TRACE(mLogId,"ueipInsert: insertString = %s", insertString.c_str()); if(mysql_query(mpMysql,insertString.c_str())) { LOG_ERROR(mLogId,"insertUeIp(): query failed: %s", insertString.c_str()); status = false; } return status; } bool MySqlRecdClient::legacyueIpPartInsert(uint64_t id, uint64_t ue_id,uint64_t call_trace_id, bool is_ipv6, uint64_t ms_ip_addr, uint64_t ls_ip_addr, int interface_type, time_t detect_time, uint64_t apn_id, int bearer_id, uint32_t partition) { bool status = true; string mysqlTime; DbUtils::convertFromUnixTimeToMySqlString(detect_time, &mysqlTime); stringstream oss; oss << "INSERT INTO ue_ip_part (id, ue_id,call_trace_id, is_ipv6, ms_ip_addr, ls_ip_addr, interface_type, detect_time, apn_id) VALUES (" << id << "," << ue_id << "," << call_trace_id << "," << is_ipv6 << "," << ms_ip_addr << "," << ls_ip_addr << "," << interface_type << ",'" << mysqlTime << "," << apn_id << "," << bearer_id << ")"; string insertString = oss.str(); LOG_TRACE(mLogId,"ueIpPartInsert: insertString = %s", insertString.c_str()); if(mysql_query(mpMysql,insertString.c_str())) { LOG_ERROR(mLogId,"ueIpPartInsert(): query failed: %s", insertString.c_str()); status = false; } return status; } bool MySqlRecdClient::legacyipFlowInsert(uint64_t id, time_t start_time, time_t end_time, int hwport, bool src_ip_is_ipv6, uint64_t ms_src_ip, uint64_t ls_src_ip, bool dst_ip_is_ipv6, uint64_t ms_dst_ip, uint64_t ls_dst_ip, int protocol, int src_port, int dst_port, int ip_tos, uint64_t src_bytes, uint64_t dst_bytes, uint64_t src_frames, uint64_t dst_frames, bool prev, bool next, uint32_t partition) { bool status = true; string startTime; DbUtils::convertFromUnixTimeToMySqlString(start_time, &startTime); string endTime; DbUtils::convertFromUnixTimeToMySqlString(end_time, &endTime); stringstream oss; oss << "INSERT INTO ip_flow (id, start_time, end_time, hwport, src_is_ipv6, ms_src_ip, ls_src_ip, dst_is_ipv6, ms_dst_ip, ls_dst_ip, " "protocol, src_port, dst_port, ip_tos, src_bytes, dst_bytes, src_frames, dst_frames, prev, next) VALUES (" << id << "," << startTime << "," << endTime << "," << hwport << "," << src_ip_is_ipv6 << "," << ms_src_ip << "," << ls_src_ip << "," << dst_ip_is_ipv6 << "," << ms_dst_ip << "," << ls_dst_ip << "," << protocol << "," << src_port << "," << dst_port << "," << ip_tos << "," << src_bytes << "," << dst_bytes << "," << src_frames << "," << dst_frames << "," << prev << "," << next << ")"; string insertString = oss.str(); LOG_TRACE(mLogId,"ipFlowInsert: insertString = %s", insertString.c_str()); if(mysql_query(mpMysql,insertString.c_str())) { LOG_ERROR(mLogId,"ipFlowInsert(): query failed: %s", insertString.c_str()); status = false; } return status; } bool MySqlRecdClient::legacyueInsert(uint64_t id, string imsi, string imei, string msisdn, time_t detect_time) { bool status = true; string mysqlTime; DbUtils::convertFromUnixTimeToMySqlString(detect_time, &mysqlTime); stringstream oss; oss << "INSERT INTO ue (id,imsi,imei,msisdn,detect_time) VALUES (" << id << ",'" << imsi << "','" << imei << "','" << msisdn << "','" << mysqlTime << "')"; string insertString = oss.str(); LOG_TRACE(mLogId,"ueInsert: insertString = %s", insertString.c_str()); if(mysql_query(mpMysql,insertString.c_str())) { LOG_ERROR(mLogId,"insertUe(): query failed: %s", insertString.c_str()); status = false; } return status; } bool MySqlRecdClient::legacyueUpdateInsert(uint64_t id,uint64_t ue_id,uint64_t new_ue_id, string imsi, string imei, string msisdn) { bool status = true; stringstream oss; oss << "INSERT INTO ue_update (id,ue_id,new_ue_id,imsi,imei,msisdn) VALUES (" << id << "," << ue_id << "," << new_ue_id << ",'" << imsi << "','" << imei << "','" << msisdn << "')"; string insertString = oss.str(); LOG_TRACE(mLogId,"ueUpdateInsert: insertString = %s", insertString.c_str()); if(mysql_query(mpMysql,insertString.c_str())) { LOG_ERROR(mLogId,"ueUpdateInsert(): query failed: %s", insertString.c_str()); status = false; } return status; } bool MySqlRecdClient::legacycallTraceInsert(uint64_t id, time_t start_time, uint64_t msg_list_on_disk, uint64_t ue_id, uint32_t partition) { bool status = true; string mysqlTime; DbUtils::convertFromUnixTimeToMySqlString(start_time, &mysqlTime); stringstream oss; oss << "INSERT INTO call_trace_" << partition << " (id,start_time,msg_list_on_disk,ue_id) VALUES (" << id << ",'" << mysqlTime << "'," << msg_list_on_disk << "," << ue_id << ")"; string insertString = oss.str(); LOG_TRACE(mLogId,"callTraceInsert: insertString = %s", insertString.c_str()); if(mysql_query(mpMysql,insertString.c_str())) { LOG_ERROR(mLogId,"insertCallTrace(): query failed: %s", insertString.c_str()); status = false; } return status; } bool MySqlRecdClient::legacycallTraceEndInsert(uint64_t id, uint16_t reason, time_t end_time, uint32_t partition) { bool status = true; string mysqlTime; DbUtils::convertFromUnixTimeToMySqlString(end_time, &mysqlTime); stringstream oss; oss << "INSERT INTO call_trace_end_" << partition << " (id,reason,end_time) VALUES (" << id << "," << reason << ",'" << mysqlTime << "')"; string insertString = oss.str(); LOG_TRACE(mLogId,"callTraceEndInsert: insertString = %s", insertString.c_str()); if(mysql_query(mpMysql,insertString.c_str())) { LOG_ERROR(mLogId,"insertCallTraceEnd(): query failed: %s", insertString.c_str()); status = false; } return status; } bool MySqlRecdClient::legacytunnelEndInsert(uint64_t id, uint16_t reason, time_t end_time, uint64_t teid, uint64_t call_trace_id, uint32_t partition) { bool status = true; string mysqlTime; DbUtils::convertFromUnixTimeToMySqlString(end_time, &mysqlTime); stringstream oss; oss << "INSERT INTO tunnel_end_" << partition << " (id,reason,end_time,teid,call_trace_id) VALUES (" << id << "," << reason << ",'" << mysqlTime << "'," << teid << "," << call_trace_id << ")"; string insertString = oss.str(); LOG_TRACE(mLogId,"tunnelEndInsert: insertString = %s", insertString.c_str()); if(mysql_query(mpMysql,insertString.c_str())) { LOG_ERROR(mLogId,"insertTunnelEnd(): query failed: %s", insertString.c_str()); status = false; } return status; } bool MySqlRecdClient::legacytunnelInsert(uint64_t id, uint64_t teid, uint64_t call_trace_id, uint64_t tunnel_ip_pair_id, int interface_type, time_t start_time, uint32_t partition) { bool status = true; string mysqlTime; DbUtils::convertFromUnixTimeToMySqlString(start_time, &mysqlTime); stringstream oss; oss << "INSERT INTO tunnel_" << partition << " (id,teid,call_trace_id,tunnel_ip_pair_id,interface_type,start_time) VALUES (" << id << "," << teid << "," << call_trace_id << "," << tunnel_ip_pair_id << "," << interface_type << ",'" << mysqlTime << "')"; string insertString = oss.str(); LOG_TRACE(mLogId,"tunnelInsert: insertString = %s", insertString.c_str()); if(mysql_query(mpMysql,insertString.c_str())) { LOG_ERROR(mLogId,"insertTunnel(): query failed: %s", insertString.c_str()); status = false; } return status; } bool MySqlRecdClient::legacyapnInsert( uint64_t id, string apn) { bool status = true; stringstream oss; oss << "INSERT INTO apn" << "( id, apn) VALUES (" << id << ",'" << apn << "')"; string insertString = oss.str(); LOG_TRACE(mLogId,"apnInsert: insertString = %s", insertString.c_str()); if(mysql_query( mpMysql, insertString.c_str())) { LOG_ERROR(mLogId,"apnInsert(): query failed: %s", insertString.c_str()); status = false; } return status; } // loadDataFromFile returns the number of rows inserted, or -1 if there was a failure for any of the file loads. // Note: The logs show that mysql_affected_rows is always -1 when there is a duplicate key failure. long MySqlRecdClient::loadDataFromFile() { long rowCount = 0; long returnCount = 0; long failure = 0; // load call_trace LOG_INFO(mLogId,"loadDataFromFile: About to load mLoadCallTraceStr. %s", mLoadCallTraceStr.c_str()); if (mysql_query(mpMysql,mLoadCallTraceStr.c_str())) { LOG_ERROR(mLogId,"loadDataFromFile: Failure during mysql_query for mLoadCallTraceStr. Error: %s", mysql_error(mpMysql)); failure = -1; } returnCount = mysql_affected_rows(mpMysql); if (returnCount >= 0) { rowCount += returnCount; } else { LOG_ERROR(mLogId,"loadDataFromFile: Negative return code from mysql_affected_rows."); } // load tunnel LOG_INFO(mLogId,"loadDataFromFile: About to load mLoadTunnelStr. %s", mLoadTunnelStr.c_str()); if (mysql_query(mpMysql,mLoadTunnelStr.c_str())) { LOG_ERROR(mLogId,"loadDataFromFile: Failure during mysql_query for mLoadTunnelStr. Error: %s", mysql_error(mpMysql)); failure = -1; } returnCount = mysql_affected_rows(mpMysql); if (returnCount >= 0) { rowCount += returnCount; } else { LOG_ERROR(mLogId,"loadDataFromFile: Negative return code from mysql_affected_rows."); } // load ue LOG_INFO(mLogId,"loadDataFromFile: About to load mLoadUeFileStr. %s", mLoadUeStr.c_str()); if (mysql_query(mpMysql,mLoadUeStr.c_str())) { LOG_ERROR(mLogId,"loadDataFromFile: Failure during mysql_query for mLoadUeStr. Error: %s", mysql_error(mpMysql)); failure = -1; } returnCount = mysql_affected_rows(mpMysql); if (returnCount >= 0) { rowCount += returnCount; } else { LOG_ERROR(mLogId,"loadDataFromFile: Negative return code from mysql_affected_rows."); } // load ue_update LOG_INFO(mLogId,"loadDataFromFile: About to load mLoadUeUpdateFileStr. %s", mLoadUeUpdateStr.c_str()); if (mysql_query(mpMysql,mLoadUeUpdateStr.c_str())) { LOG_ERROR(mLogId,"loadDataFromFile: Failure during mysql_query for mLoadUeUpdateStr. Error: %s", mysql_error(mpMysql)); failure = -1; } returnCount = mysql_affected_rows(mpMysql); if (returnCount >= 0) { rowCount += returnCount; } else { LOG_ERROR(mLogId,"loadDataFromFile: Negative return code from mysql_affected_rows."); } // load ue_ip_part LOG_INFO(mLogId,"loadDataFromFile: About to load mLoadUeIpPartStr. %s", mLoadUeIpPartStr.c_str()); if (mysql_query(mpMysql,mLoadUeIpPartStr.c_str())) { LOG_ERROR(mLogId,"loadDataFromFile: Failure during mysql_query for mLoadUeIpPartStr. Error: %s", mysql_error(mpMysql)); failure = -1; } returnCount = mysql_affected_rows(mpMysql); if (returnCount >= 0) { rowCount += returnCount; } else { LOG_ERROR(mLogId,"loadDataFromFile: Negative return code from mysql_affected_rows."); } // load ip LOG_INFO(mLogId,"loadDataFromFile: About to load mLoadIpStr. %s", mLoadIpStr.c_str()); if (mysql_query(mpMysql,mLoadIpStr.c_str())) { LOG_ERROR(mLogId,"loadDataFromFile: Failure during mysql_query for mLoadIpStr. Error: %s", mysql_error(mpMysql)); failure = -1; } returnCount = mysql_affected_rows(mpMysql); if (returnCount >= 0) { rowCount += returnCount; } else { LOG_ERROR(mLogId,"loadDataFromFile: Negative return code from mysql_affected_rows."); } // load call_trace_end LOG_INFO(mLogId,"loadDataFromFile: About to load mLoadCallTraceEndStr. %s", mLoadCallTraceEndStr.c_str()); if (mysql_query(mpMysql,mLoadCallTraceEndStr.c_str())) { LOG_ERROR(mLogId,"loadDataFromFile: Failure during mysql_query for mLoadCallTraceEndStr. Error: %s", mysql_error(mpMysql)); failure = -1; } returnCount = mysql_affected_rows(mpMysql); if (returnCount >= 0) { rowCount += returnCount; } else { LOG_ERROR(mLogId,"loadDataFromFile: Negative return code from mysql_affected_rows."); } // load tunnel_end LOG_INFO(mLogId,"loadDataFromFile: About to load mLoadTunnelEndStr. %s", mLoadTunnelEndStr.c_str()); if (mysql_query(mpMysql,mLoadTunnelEndStr.c_str())) { LOG_ERROR(mLogId,"loadDataFromFile: Failure during mysql_query for mLoadTunnelEndStr. Error: %s", mysql_error(mpMysql)); failure = -1; } returnCount = mysql_affected_rows(mpMysql); if (returnCount >= 0) { rowCount += returnCount; } else { LOG_ERROR(mLogId,"loadDataFromFile: Negative return code from mysql_affected_rows."); } // load apn LOG_INFO(mLogId,"loadDataFromFile: About to load mLoadApnStr. %s", mLoadApnStr.c_str()); if (mysql_query(mpMysql,mLoadApnStr.c_str())) { LOG_ERROR(mLogId,"loadDataFromFile: Failure during mysql_query for mLoadApnStr. Error: %s", mysql_error(mpMysql)); failure = -1; } returnCount = mysql_affected_rows(mpMysql); if (returnCount >= 0) { rowCount += returnCount; } else { LOG_ERROR(mLogId,"loadDataFromFile: Negative return code from mysql_affected_rows."); } // load ip_flow LOG_INFO(mLogId,"loadDataFromFile: About to load mLoadIpFlowStr. %s", mLoadIpFlowStr.c_str()); if (mysql_query(mpMysql,mLoadIpFlowStr.c_str())) { LOG_ERROR(mLogId,"loadDataFromFile: Failure during mysql_query for mLoadIpFlowStr. Error: %s", mysql_error(mpMysql)); failure = -1; } returnCount = mysql_affected_rows(mpMysql); if (returnCount >= 0) { rowCount += returnCount; } else { LOG_ERROR(mLogId,"loadDataFromFile: Negative return code from mysql_affected_rows."); } LOG_INFO(mLogId,"loadDataFromFile: total rowCount = %d, failure = %d", rowCount, failure); if (failure < 0) { return failure; } else { return rowCount; } } void MySqlRecdClient::truncateTable(const string& tableName) { string truncateCommand = "truncate table " + tableName; if (mysql_query(mpMysql,truncateCommand.c_str())) { LOG_ERROR(mLogId,"truncateTable: Failure to truncate table: %s. Error: %s", tableName.c_str(),mysql_error(mpMysql)); } } void MySqlRecdClient::flushTables(const string& tableName) { string flushCommand = "FLUSH TABLES " + tableName; if (mysql_query(mpMysql,flushCommand.c_str())) { LOG_ERROR(mLogId,"flushTables: Failure to flush tables: %s. Error: %s", tableName.c_str(),mysql_error(mpMysql)); } } uint32_t MySqlRecdClient::getRowCount(const string& tableName) { uint32_t rowCount = 0; string countQuery = "SELECT COUNT(*) FROM " + tableName; if (mysql_query(mpMysql,countQuery.c_str())) { LOG_ERROR(mLogId,"getRowCount: Failure count rows in table: %s. Error: %s", tableName.c_str(),mysql_error(mpMysql)); } else { MYSQL_RES *result = mysql_store_result(mpMysql); if (result) { MYSQL_ROW row = mysql_fetch_row(result); if (row && (row[0] != NULL)) { rowCount = atoi(row[0]); LOG_TRACE(mLogId,"getRowCount: tableName : %s, count: %u", tableName.c_str(),rowCount); } mysql_free_result(result); } } return(rowCount); } bool MySqlRecdClient::getAllUes(UeResultSet& resultSet) { MYSQL_RES *result; // do the query string getAllUeString = "SELECT id,imsi,imei,msisdn,UNIX_TIMESTAMP(detect_time) FROM ue"; if (mysql_query(mpMysql,getAllUeString.c_str())) { LOG_ERROR(mLogId,"getAllUes: Failure to query: %s. Error: %s", getAllUeString.c_str(),mysql_error(mpMysql)); return false; } // note: result could be null if there are no rows, this needs to be checked within UeResultSet. result = mysql_store_result(mpMysql); // set result buffer if (result == 0) { LOG_TRACE(mLogId,"getAllUes: No Rows found"); return false; } resultSet.setResultBuffer(result); return true; } bool MySqlRecdClient::getAllUeIps(UeIpResultSet& resultSet) { MYSQL_RES *result; // do the query string getAllUeIpString = "SELECT id,ue_id,is_ipv6,ms_ip_addr,ls_ip_addr,interface_type,UNIX_TIMESTAMP(detect_time),apn_id FROM ue_ip"; if (mysql_query(mpMysql,getAllUeIpString.c_str())) { LOG_ERROR(mLogId,"getAllUeIps: Failure to query: %s. Error: %s", getAllUeIpString.c_str(),mysql_error(mpMysql)); return false; } // note: result could be null if there are no rows. result = mysql_store_result(mpMysql); // set result buffer if (result == 0) { LOG_TRACE(mLogId,"getAllUeIps: No Rows found"); return false; } resultSet.setResultBuffer(result); return true; } bool MySqlRecdClient::getAllIps(IpResultSet& resultSet) { MYSQL_RES *result; // do the query string getAllIpString = "SELECT id,is_ipv6,ms_ip_addr,ls_ip_addr FROM ip"; if (mysql_query(mpMysql,getAllIpString.c_str())) { LOG_ERROR(mLogId,"getAllIps: Failure to query: %s. Error: %s", getAllIpString.c_str(),mysql_error(mpMysql)); return false; } // note: result could be null if there are no rows. result = mysql_store_result(mpMysql); if (result == 0) { LOG_TRACE(mLogId,"getAllIps: No Rows found"); return false; } // set result buffer resultSet.setResultBuffer(result); return true; } bool MySqlRecdClient::getAllTunnels(TunnelResultSet& resultSet) { MYSQL_RES *result; // do the query string getAllTunnelString = "SELECT id,teid,call_trace_id,tunnel_ip_pair_id,interface_type,UNIX_TIMESTAMP(start_time) FROM tunnel"; if (mysql_query(mpMysql,getAllTunnelString.c_str())) { LOG_ERROR(mLogId,"getAllTunnels: Failure to query: %s. Error: %s", getAllTunnelString.c_str(),mysql_error(mpMysql)); return false; } // note: result could be null if there are no rows. result = mysql_store_result(mpMysql); // set result buffer if (result == 0) { LOG_TRACE(mLogId,"getAllTunnels: No Rows found"); return false; } resultSet.setResultBuffer(result); return true; } bool MySqlRecdClient::getAllCallTraces(CallTraceResultSet& resultSet) { MYSQL_RES *result; // do the query string getAllCallTraceString = "SELECT id,UNIX_TIMESTAMP(start_time),msg_list_on_disk,ue_id FROM call_trace"; if (mysql_query(mpMysql,getAllCallTraceString.c_str())) { LOG_ERROR(mLogId,"getAllCallTraces: Failure to query: %s. Error: %s", getAllCallTraceString.c_str(),mysql_error(mpMysql)); return false; } // note: result could be null if there are no rows. result = mysql_store_result(mpMysql); // set result buffer if (result == 0) { LOG_TRACE(mLogId,"getAllCallTraces: No Rows found"); return false; } resultSet.setResultBuffer(result); return true; } bool MySqlRecdClient::getAllCallTraceEnds(CallTraceEndResultSet& resultSet) { MYSQL_RES *result; // do the query string getAllCallTraceEndString = "SELECT id,reason,UNIX_TIMESTAMP(end_time) FROM call_trace_end"; if (mysql_query(mpMysql,getAllCallTraceEndString.c_str())) { LOG_ERROR(mLogId,"getAllCallTraceEnds: Failure to query: %s. Error: %s", getAllCallTraceEndString.c_str(),mysql_error(mpMysql)); return false; } // note: result could be null if there are no rows. result = mysql_store_result(mpMysql); // set result buffer if (result == 0) { LOG_TRACE(mLogId,"getAllCallTraceEnds: No Rows found"); return false; } resultSet.setResultBuffer(result); return true; } bool MySqlRecdClient::getAllTunnelEnds(TunnelEndResultSet& resultSet) { MYSQL_RES *result; // do the query string getAllTunnelEndString = "SELECT id,reason,UNIX_TIMESTAMP(end_time),teid,call_trace_id FROM tunnel_end"; if (mysql_query(mpMysql,getAllTunnelEndString.c_str())) { LOG_ERROR(mLogId,"getAllTunnelEnds: Failure to query: %s. Error: %s", getAllTunnelEndString.c_str(),mysql_error(mpMysql)); return false; } // note: result could be null if there are no rows. result = mysql_store_result(mpMysql); // set result buffer if (result == 0) { LOG_TRACE(mLogId,"getAllTunnelEnds: No Rows found"); return false; } resultSet.setResultBuffer(result); return true; } /** * return the partition number that contains this start time */ uint32_t MySqlRecdClient::getPartition(time_t startTime) { MYSQL_RES *result; MYSQL_ROW row; uint32_t partition = 0; // convert to mysql time string mysqlStartTime; DbUtils::convertFromUnixTimeToMySqlString(startTime, &mysqlStartTime); string queryString = "SELECT partition FROM partition_map WHERE startTime<='" + mysqlStartTime + "' AND endTime>='" + mysqlStartTime + "'"; mysql_query(mpMysql, queryString.c_str()); result = mysql_store_result(mpMysql); if (result) { row = mysql_fetch_row(result); if (row) { if (NULL != row[0]) { partition = atoi(row[0]); } } } return partition; } bool MySqlRecdClient::foundPartition(uint32_t partition) { MYSQL_RES *result; MYSQL_ROW row; bool found = false; stringstream oss; oss << "SELECT * FROM partition_map WHERE partition = " << partition; string queryString = oss.str(); LOG_INFO(mLogId,"foundPartition: About to run this query: %s.", queryString.c_str()); mysql_query(mpMysql, queryString.c_str()); result = mysql_store_result(mpMysql); if (result) { row = mysql_fetch_row(result); if (row) { found = true; if (NULL != row[0]) { // could return all values if they were passed in by reference. } } } return found; } /* * adds to the partition_map db table */ void MySqlRecdClient::insertPartitionMap(uint32_t partition, time_t startTime, time_t endTime) { // add this partition to the table // convert to mysql time string mysqlStartTime; // convert time to mysql timestamp DbUtils::convertFromUnixTimeToMySqlString(startTime, &mysqlStartTime); string mysqlEndTime; // convert time to mysql timestamp DbUtils::convertFromUnixTimeToMySqlString(endTime, &mysqlEndTime); // build query string stringstream oss; oss << "INSERT INTO partition_map VALUES (" << partition << ",'" << mysqlStartTime << "','" << mysqlEndTime << "')"; string queryString = oss.str(); cout << "MySqlRecdClient::insertPartitionMap - queryString = " << queryString << endl; mysql_query(mpMysql,queryString.c_str()); uint32_t rowCount = mysql_affected_rows(mpMysql); cout << "MySqlRecdClient::insertPartitionMap - rowCount = " << rowCount << endl; if (rowCount != 1) { LOG_ERROR(mLogId,"insertPartitionMap: Failure during mysql_query for insert into partition map. Error: %s", mysql_error(mpMysql)); } } /* * delete the partition row from the partition_map db table. */ void MySqlRecdClient::deletePartitionMap(uint32_t partition) { // build query string stringstream oss; oss << "DELETE FROM partition_map WHERE partition=" << partition; string queryString = oss.str(); mysql_query(mpMysql,queryString.c_str()); uint32_t rowCount = mysql_affected_rows(mpMysql); //cout << "MySqlRecdClient::deletePartitionMap - rowCount = " << rowCount << endl; if (rowCount != 1) { LOG_ERROR(mLogId,"deletePartitionMap: Failure during mysql_query for delete from partition map. Query String = %s Error: %s",queryString.c_str(), mysql_error(mpMysql)); } } void MySqlRecdClient::deleteOldStats(time_t time) { // DRH: removed system stats from first release string sStatsTables[] = { "cpu_utilization", "mem_utilization", "disk_utilization", "network_utilization", "hardware_statistic", "port" }; string sStatsTables[] = { "hardware_statistic", "port", "port_changes" }; string sTime; DbUtils::convertFromUnixTimeToMySqlString(time, &sTime); for(uint8_t i = 0; i < sizeof(sStatsTables)/sizeof(string); i++) { stringstream ssQuery; ssQuery << "DELETE FROM " << sStatsTables[i] << " WHERE time <= '" << sTime << "'"; LOG_DEBUG(mLogId,"deleteOldStats(): delete query = %s", ssQuery.str().c_str()); if(mysql_query(mpMysql,ssQuery.str().c_str())) { LOG_ERROR(mLogId,"deleteOldStats(): query failed: %s", ssQuery.str().c_str()); } else { uint32_t rowCount; rowCount = mysql_affected_rows(mpMysql); // if (rowCount > 0) { LOG_DEBUG(mLogId,"deleteOldStats: deleted %d rows, query: %s", rowCount, ssQuery.str().c_str()); } } } } // called at startup uint32_t MySqlRecdClient::getNewestPartition() { MYSQL_RES *result; MYSQL_ROW row; uint32_t partition = 0; string maxStartTimeString; // first select MAX startTime mysql_query(mpMysql, "SELECT MAX(startTime) FROM partition_map"); result = mysql_store_result(mpMysql); if (result) { row = mysql_fetch_row(result); if (row) { if (NULL != row[0]) { maxStartTimeString = row[0]; //cout << "MySqlRecdClient::getNewestPartition - maxStartTimeString = " << maxStartTimeString << endl; mysql_free_result(result); string queryString = "SELECT partition FROM partition_map WHERE startTime='" + maxStartTimeString + "'"; LOG_DEBUG(mLogId,"getNewestPartition: Query string : %s", queryString.c_str()); mysql_query(mpMysql, queryString.c_str()); result = mysql_store_result(mpMysql); if (result) { row = mysql_fetch_row(result); if (row) { if (NULL != row[0]) { partition = atoi(row[0]); } } else { LOG_TRACE(mLogId,"getNewestPartition: no rows found in partition_map, returning 0"); } mysql_free_result(result); } } else { LOG_TRACE(mLogId,"getNewestPartition: empty table (null result) so returning 0"); mysql_free_result(result); } } else { LOG_TRACE(mLogId,"getNewestPartition: empty table (null result) so returning 0"); mysql_free_result(result); } } else { // empty table LOG_TRACE(mLogId,"getNewestPartition: empty table (null result) so returning 0"); } return partition; } // called at reap time uint32_t MySqlRecdClient::getOldestPartition(time_t* startTime, time_t* endTime) { MYSQL_RES *result; MYSQL_ROW row; uint32_t partition = 0; string minStartTimeString; // first select MIN startTime mysql_query(mpMysql, "SELECT MIN(startTime) FROM partition_map"); result = mysql_store_result(mpMysql); if (result) { row = mysql_fetch_row(result); if (row) { if (NULL != row[0]) { minStartTimeString = row[0]; cout << "MySqlRecdClient::getOldestPartition - minStartTimeString = " << minStartTimeString << endl; mysql_free_result(result); string queryString = "SELECT partition, UNIX_TIMESTAMP(startTime), UNIX_TIMESTAMP(endTime) FROM partition_map WHERE startTime='" + minStartTimeString + "'"; LOG_TRACE(mLogId,"getOldestPartition: Query string : %s", queryString.c_str()); mysql_query(mpMysql, queryString.c_str()); result = mysql_store_result(mpMysql); if (result) { row = mysql_fetch_row(result); if (row) { if (NULL != row[0]) { partition = atoi(row[0]); } if (NULL != row[1]) { //cout << "MySqlRecdClient::getOldestPartition : startTime = " << row[1] << endl; time_t stime = atoi(row[1]); //cout << "stime = " << stime << endl; if (startTime != NULL) { *startTime = stime; } } if (NULL != row[2]) { //cout << "MySqlRecdClient::getOldestPartition : endTime = " << row[2] << endl; time_t etime = atoi(row[2]); //cout << "etime = " << etime << endl; if (endTime != NULL) { *endTime = etime; } } } else { LOG_TRACE(mLogId,"getOldestPartition: no rows found in partition_map, returning 0"); } mysql_free_result(result); } } else { LOG_TRACE(mLogId,"getOldestPartition: empty table (null result) so returning 0"); mysql_free_result(result); } } else { LOG_TRACE(mLogId,"getOldestPartition: empty table (null result) so returning 0"); mysql_free_result(result); } } else { // empty table LOG_TRACE(mLogId,"getOldestPartition: empty table (null result) so returning 0"); } return partition; } uint64_t MySqlRecdClient::getLastIdFromTable(string& tableName) { uint64_t returnId = 0; MYSQL_RES *result; MYSQL_ROW row; // first select MAX id string queryMaxString = "SELECT MAX(id) FROM " + tableName; LOG_TRACE(mLogId,"getLastIdFromTable: Query string : %s", queryMaxString.c_str()); string idString; mysql_query(mpMysql,queryMaxString.c_str()); result = mysql_store_result(mpMysql); if (result) { row = mysql_fetch_row(result); if (row) { if (NULL != row[0]) { idString = row[0]; LOG_TRACE(mLogId,"getLastIdFromTable: tableName : %s id: %s", tableName.c_str(),idString.c_str()); returnId = strtoull(row[0],NULL,0); mysql_free_result(result); } else { LOG_TRACE(mLogId,"getLastIdFromTable: empty table (null result) so returning 0"); mysql_free_result(result); } } else { LOG_TRACE(mLogId,"getLastIdFromTable: empty table (null result) so returning 0"); mysql_free_result(result); } } else { // empty table LOG_TRACE(mLogId,"getLastIdFromTable: empty table (null result) so returning 0"); } return(returnId); } bool MySqlRecdClient::unit_test() { // connect if (connect("localhost","recd", "recd", "recd")) { LOG_TRACE(mLogId,"unit_test - connect error"); return false; } // get newest partition // disconnect disconnect(); return true; } /** * Test out this class */ /* int main( int argc, const char* argv[] ) { // Prints each argument on the command line. for( int i = 0; i < argc; i++ ) { printf( "arg %d: %s\n", i, argv[i] ); } uint32_t partition = pMysqlClient->getOldestPartition(); cout << "oldest partition = " << partition << endl; time_t startTime = 0; time_t endTime = 0; partition = pMysqlClient->getOldestPartition(&startTime,&endTime); cout << "main: startTime = " << startTime << " endTime = " << endTime << endl; delete pMysqlClient; } */
36.778723
274
0.589263
jia57196
72450180039d2bd1361a5fb3aaa237aea7a5aad4
4,093
cpp
C++
snippets/simple_read/snippets/lib.cpp
dejbug/protocasm
87bfc7ab9b555111d889b606da0d344a7c28eb9f
[ "MIT" ]
null
null
null
snippets/simple_read/snippets/lib.cpp
dejbug/protocasm
87bfc7ab9b555111d889b606da0d344a7c28eb9f
[ "MIT" ]
null
null
null
snippets/simple_read/snippets/lib.cpp
dejbug/protocasm
87bfc7ab9b555111d889b606da0d344a7c28eb9f
[ "MIT" ]
null
null
null
#include "lib.h" #include <assert.h> #include <string.h> lib::typ::bytes::bytes() : data(nullptr), capacity(0), good(0) { } lib::typ::bytes::bytes(size_t capacity) : data(nullptr), capacity(0), good(0) { if (!capacity) throw common::make_error("lib::typ::bytes::ctor : capacity must be >0 in this ctor"); grow(capacity); } lib::typ::bytes::~bytes() { free(); } lib::typ::bytes::bytes(lib::typ::bytes && other) { data = other.data; capacity = other.capacity; good = other.good; other.drop(); } void lib::typ::bytes::grow(size_t size) { if (!size) return; if (capacity >= size) return; free(); data = new char[capacity = size]; } void lib::typ::bytes::drop() { data = nullptr; capacity = good = 0; } void lib::typ::bytes::free() { if (data) delete[] data; drop(); } void lib::typ::bytes::fill(FILE * file) { if (!capacity) return; read(file, capacity); } void lib::typ::bytes::read(FILE * file, size_t size) { good = 0; if (size > capacity) throw common::make_error("lib::typ::bytes::read : not enough room for reading %d bytes from file at %08X: only %d bytes allocated", size, (size_t) file, capacity); good = fread(data, 1, size, file); if (good < size && !feof(file)) throw common::make_error("lib::typ::bytes::read : error while reading from file at %08X: only %d of %d bytes read", (size_t) file, good, size); } void lib::typ::bytes::read(FILE * file) { grow(10); for (size_t i = 0; i < capacity; ++i) { char byte[1]; lib::io::read(file, byte); data[i] = 0x7F & byte[0]; if (byte[0] & 0x80) continue; good = i + 1; return; } throw common::make_error("lib::typ::bytes::read : end of buffer reached at byte %d before varint fully read", capacity); } size_t lib::io::read(FILE * file, char * buffer, size_t size) { size_t const good = fread(buffer, sizeof(char), size, file); if (good < size && !feof(file)) throw common::make_error("lib::io::read : error while reading from file at %08X: only %d of %d bytes read", (size_t) file, good, size); return good; } void lib::io::dump(char const * buffer, size_t size) { for (size_t i=0; i<size; ++i) { if (i > 0) { if(i % 16 == 0) printf("\n"); else if(i % 4 == 0) printf (" "); } printf("%02X ", (unsigned char) buffer[i]); } printf("\n"); } void lib::io::dump(lib::typ::bytes & bytes) { lib::io::dump(bytes.data, bytes.good); } lib::io::file::file(char const * path) { handle = fopen(path, "rb"); if (!handle) throw common::make_error("lib::io::file::ctor : file not found %s", path); this->path = strdup(path); } lib::io::file::~file() { delete path; fclose(handle); } lib::typ::bytes lib::io::read(FILE * file, size_t size) { lib::typ::bytes out(size); out.read(file, size); return out; } lib::typ::bytes lib::io::read(FILE * file) { lib::typ::bytes out(10); out.read(file); return out; } void lib::io::read(FILE * file, lib::typ::i4 & out) { assert(sizeof(lib::typ::i4) == 4); lib::io::read(file, (char *) &out, 4); } void lib::io::read(FILE * file, lib::typ::i8 & out) { assert(sizeof(lib::typ::i8) == 8); lib::io::read(file, (char *) &out, 8); } #define SHL32(a, i) (((lib::typ::i4) (((unsigned char const *) a)[i])) << (24-i*8)) // #define SHL32(a, i, s) ((((unsigned char const *) a)[i]) << (s)) lib::typ::i4 lib::trans::flip(lib::typ::i4 value) { // TODO: ws2_32.dll's htonl() does this much more // efficiently, using only scratch registers . return SHL32(&value, 0) | SHL32(&value, 1) | SHL32(&value, 2) | SHL32(&value, 3); auto x = (unsigned char const *) &value; return (long) (unsigned long) (x[0] << 24) | (x[1] << 16) | (x[2] << 8) | x[3]; } #define SHL64(a, i) (((lib::typ::u8) (((unsigned char const *) a)[i])) << (56-i*8)) lib::typ::i8 lib::trans::flip(lib::typ::i8 value) { return SHL64(&value, 0) | SHL64(&value, 1) | SHL64(&value, 2) | SHL64(&value, 3) | SHL64(&value, 4) | SHL64(&value, 5) | SHL64(&value, 6) | SHL64(&value, 7); }
23.65896
166
0.582946
dejbug
7245d5fa565d541d564a68836ad54cd451038cde
3,556
cpp
C++
Example/Pods/librlottie/rlottie/src/vector/vdrawable.cpp
dotlottie/dotlottieR-ios
0531aaa427c969f5d89fea79f2dc6294414ba379
[ "MIT" ]
null
null
null
Example/Pods/librlottie/rlottie/src/vector/vdrawable.cpp
dotlottie/dotlottieR-ios
0531aaa427c969f5d89fea79f2dc6294414ba379
[ "MIT" ]
null
null
null
Example/Pods/librlottie/rlottie/src/vector/vdrawable.cpp
dotlottie/dotlottieR-ios
0531aaa427c969f5d89fea79f2dc6294414ba379
[ "MIT" ]
null
null
null
/* * Copyright (c) 2018 Samsung Electronics Co., Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "vdrawable.h" #include "vdasher.h" #include "vraster.h" VDrawable::VDrawable(VDrawable::Type type) { setType(type); } VDrawable::~VDrawable() { if (mStrokeInfo) { if (mType == Type::StrokeWithDash) { delete static_cast<StrokeWithDashInfo *>(mStrokeInfo); } else { delete mStrokeInfo; } } } void VDrawable::setType(VDrawable::Type type) { mType = type; if (mType == VDrawable::Type::Stroke) { mStrokeInfo = new StrokeInfo(); } else if (mType == VDrawable::Type::StrokeWithDash) { mStrokeInfo = new StrokeWithDashInfo(); } } void VDrawable::applyDashOp() { if (mStrokeInfo && (mType == Type::StrokeWithDash)) { auto obj = static_cast<StrokeWithDashInfo *>(mStrokeInfo); if (!obj->mDash.empty()) { VDasher dasher(obj->mDash.data(), obj->mDash.size()); mPath.clone(dasher.dashed(mPath)); } } } void VDrawable::preprocess(const VRect &clip) { if (mFlag & (DirtyState::Path)) { if (mType == Type::Fill) { mRasterizer.rasterize(std::move(mPath), mFillRule, clip); } else { applyDashOp(); mRasterizer.rasterize(std::move(mPath), mStrokeInfo->cap, mStrokeInfo->join, mStrokeInfo->width, mStrokeInfo->miterLimit, clip); } mPath = {}; mFlag &= ~DirtyFlag(DirtyState::Path); } } VRle VDrawable::rle() { return mRasterizer.rle(); } void VDrawable::setStrokeInfo(CapStyle cap, JoinStyle join, float miterLimit, float strokeWidth) { assert(mStrokeInfo); if ((mStrokeInfo->cap == cap) && (mStrokeInfo->join == join) && vCompare(mStrokeInfo->miterLimit, miterLimit) && vCompare(mStrokeInfo->width, strokeWidth)) return; mStrokeInfo->cap = cap; mStrokeInfo->join = join; mStrokeInfo->miterLimit = miterLimit; mStrokeInfo->width = strokeWidth; mFlag |= DirtyState::Path; } void VDrawable::setDashInfo(std::vector<float> &dashInfo) { assert(mStrokeInfo); assert(mType == VDrawable::Type::StrokeWithDash); auto obj = static_cast<StrokeWithDashInfo *>(mStrokeInfo); bool hasChanged = false; if (obj->mDash.size() == dashInfo.size()) { for (uint i = 0; i < dashInfo.size(); ++i) { if (!vCompare(obj->mDash[i], dashInfo[i])) { hasChanged = true; break; } } } else { hasChanged = true; } if (!hasChanged) return; obj->mDash = dashInfo; mFlag |= DirtyState::Path; } void VDrawable::setPath(const VPath &path) { mPath = path; mFlag |= DirtyState::Path; }
28
88
0.622328
dotlottie
7245e0d24c7d374058be5a7a3c5aa28bdb7ab7a9
3,667
hpp
C++
CmnIP/module/transform/inc/transform/color_normalization.hpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
CmnIP/module/transform/inc/transform/color_normalization.hpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
CmnIP/module/transform/inc/transform/color_normalization.hpp
Khoronus/CmnUniverse
9cf9b4297f2fcb49330126aa1047b422144045e1
[ "MIT" ]
null
null
null
/* @file color_normalization.hpp * @brief Class to perform the color normalization of a source of data. * * @section LICENSE * * 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 AUTHOR/AUTHORS 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. * * @author Alessandro Moro <alessandromoro.italy@gmail.com> * @bug No known bugs. * @version 0.1.0.0 * */ #ifndef CMNIP_TRANSFORM_COLORNORMALIZATION_HPP__ #define CMNIP_TRANSFORM_COLORNORMALIZATION_HPP__ #include <vector> #include <string> #include <algorithm> #include <iostream> #include <iterator> #include <fstream> #include <limits> #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" namespace CmnIP { namespace transform { /** @brief It performs the color normalization of a source data. It performs the color normalization of a source data. */ class ColorNormalization { public: /** @brief It performs the color normalization on the RGB components of the image. It performs the color normalization on the RGB components of the image. */ static void normalize_rgb(const cv::Mat &src, cv::Mat &out) { out = cv::Mat::zeros(src.size(), src.type()); for (int y = 0; y < src.rows; y++) { for (int x = 0; x < src.cols; x++) { float s = src.at<cv::Vec3b>(y, x)[0] + src.at<cv::Vec3b>(y, x)[1] + src.at<cv::Vec3b>(y, x)[2]; if (s > 0) { //float r = (float)src.at<cv::Vec3b>(y, x)[2] / s; //float g = (float)src.at<cv::Vec3b>(y, x)[1] / s; ////float b = (float)src.at<cv::Vec3b>(y, x)[0] / s; //out.at<cv::Vec3b>(y, x)[2] = (uchar)(r / g * src.at<cv::Vec3b>(y, x)[1]); //out.at<cv::Vec3b>(y, x)[1] = (uchar)(src.at<cv::Vec3b>(y, x)[1]); //out.at<cv::Vec3b>(y, x)[0] = (uchar)((1.0f - r - g) / g * src.at<cv::Vec3b>(y, x)[1]); for (int c = 0; c < 3; c++) { float v = (float)src.at<cv::Vec3b>(y, x)[c] / s; out.at<cv::Vec3b>(y, x)[c] = 255 * v; } } } } } /** @brief It performs the color normalization on the RGB components of the image. It performs the color normalization on the RGB components of the image. */ static void rg(const cv::Mat &src, cv::Mat &out) { out = cv::Mat::zeros(src.size(), src.type()); for (int y = 0; y < src.rows; y++) { for (int x = 0; x < src.cols; x++) { float s = src.at<cv::Vec3b>(y, x)[0] + src.at<cv::Vec3b>(y, x)[1] + src.at<cv::Vec3b>(y, x)[2]; if (s > 0) { float r = (float)src.at<cv::Vec3b>(y, x)[2] / s; float g = (float)src.at<cv::Vec3b>(y, x)[1] / s; //float b = (float)src.at<cv::Vec3b>(y, x)[0] / s; out.at<cv::Vec3b>(y, x)[2] = (uchar)(r / g * src.at<cv::Vec3b>(y, x)[1]); out.at<cv::Vec3b>(y, x)[1] = (uchar)(src.at<cv::Vec3b>(y, x)[1]); out.at<cv::Vec3b>(y, x)[0] = (uchar)((1.0f - r - g) / g * src.at<cv::Vec3b>(y, x)[1]); } } } } }; } // namespace transform } // namespace CmnIP #endif /* CMNIP_TRANSFORM_COLORNORMALIZATION_HPP__ */
29.336
93
0.620125
Khoronus
7246e9569e3a4062fda7f7b4dccffbf85d88467d
18,353
cpp
C++
src/mongo/db/pipeline/expression_object_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/pipeline/expression_object_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/pipeline/expression_object_test.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2019-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/bson/bsonmisc.h" #include "mongo/config.h" #include "mongo/db/exec/document_value/document.h" #include "mongo/db/exec/document_value/document_value_test_util.h" #include "mongo/db/exec/document_value/value_comparator.h" #include "mongo/db/jsobj.h" #include "mongo/db/json.h" #include "mongo/db/pipeline/expression.h" #include "mongo/db/pipeline/expression_context_for_test.h" #include "mongo/db/query/collation/collator_interface_mock.h" #include "mongo/dbtests/dbtests.h" #include "mongo/unittest/unittest.h" namespace mongo { namespace ExpressionTests { namespace { using boost::intrusive_ptr; using std::vector; namespace Object { using mongo::ExpressionObject; template <typename T> Document literal(T&& value) { return Document{{"$const", Value(std::forward<T>(value))}}; } // // Parsing. // TEST(ExpressionObjectParse, ShouldAcceptEmptyObject) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; auto object = ExpressionObject::parse(&expCtx, BSONObj(), vps); ASSERT_VALUE_EQ(Value(Document{}), object->serialize(false)); } TEST(ExpressionObjectParse, ShouldAcceptLiteralsAsValues) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; auto object = ExpressionObject::parse(&expCtx, BSON("a" << 5 << "b" << "string" << "c" << BSONNULL), vps); auto expectedResult = Value(Document{{"a", literal(5)}, {"b", literal("string"_sd)}, {"c", literal(BSONNULL)}}); ASSERT_VALUE_EQ(expectedResult, object->serialize(false)); } TEST(ExpressionObjectParse, ShouldAccept_idAsFieldName) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; auto object = ExpressionObject::parse(&expCtx, BSON("_id" << 5), vps); auto expectedResult = Value(Document{{"_id", literal(5)}}); ASSERT_VALUE_EQ(expectedResult, object->serialize(false)); } TEST(ExpressionObjectParse, ShouldAcceptFieldNameContainingDollar) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; auto object = ExpressionObject::parse(&expCtx, BSON("a$b" << 5), vps); auto expectedResult = Value(Document{{"a$b", literal(5)}}); ASSERT_VALUE_EQ(expectedResult, object->serialize(false)); } TEST(ExpressionObjectParse, ShouldAcceptNestedObjects) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; auto object = ExpressionObject::parse(&expCtx, fromjson("{a: {b: 1}, c: {d: {e: 1, f: 1}}}"), vps); auto expectedResult = Value(Document{{"a", Document{{"b", literal(1)}}}, {"c", Document{{"d", Document{{"e", literal(1)}, {"f", literal(1)}}}}}}); ASSERT_VALUE_EQ(expectedResult, object->serialize(false)); } TEST(ExpressionObjectParse, ShouldAcceptArrays) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; auto object = ExpressionObject::parse(&expCtx, fromjson("{a: [1, 2]}"), vps); auto expectedResult = Value(Document{{"a", vector<Value>{Value(literal(1)), Value(literal(2))}}}); ASSERT_VALUE_EQ(expectedResult, object->serialize(false)); } TEST(ObjectParsing, ShouldAcceptExpressionAsValue) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; auto object = ExpressionObject::parse(&expCtx, BSON("a" << BSON("$and" << BSONArray())), vps); ASSERT_VALUE_EQ(object->serialize(false), Value(Document{{"a", Document{{"$and", BSONArray()}}}})); } // // Error cases. // TEST(ExpressionObjectParse, ShouldRejectDottedFieldNames) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; ASSERT_THROWS(ExpressionObject::parse(&expCtx, BSON("a.b" << 1), vps), AssertionException); ASSERT_THROWS(ExpressionObject::parse(&expCtx, BSON("c" << 3 << "a.b" << 1), vps), AssertionException); ASSERT_THROWS(ExpressionObject::parse(&expCtx, BSON("a.b" << 1 << "c" << 3), vps), AssertionException); } TEST(ExpressionObjectParse, ShouldRejectDuplicateFieldNames) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; ASSERT_THROWS(ExpressionObject::parse(&expCtx, BSON("a" << 1 << "a" << 1), vps), AssertionException); ASSERT_THROWS(ExpressionObject::parse(&expCtx, BSON("a" << 1 << "b" << 2 << "a" << 1), vps), AssertionException); ASSERT_THROWS( ExpressionObject::parse(&expCtx, BSON("a" << BSON("c" << 1) << "b" << 2 << "a" << 1), vps), AssertionException); ASSERT_THROWS( ExpressionObject::parse(&expCtx, BSON("a" << 1 << "b" << 2 << "a" << BSON("c" << 1)), vps), AssertionException); } TEST(ExpressionObjectParse, ShouldRejectInvalidFieldName) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; ASSERT_THROWS(ExpressionObject::parse(&expCtx, BSON("$a" << 1), vps), AssertionException); ASSERT_THROWS(ExpressionObject::parse(&expCtx, BSON("" << 1), vps), AssertionException); ASSERT_THROWS(ExpressionObject::parse(&expCtx, BSON(std::string("a\0b", 3) << 1), vps), AssertionException); } TEST(ExpressionObjectParse, ShouldRejectInvalidFieldPathAsValue) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; ASSERT_THROWS(ExpressionObject::parse(&expCtx, BSON("a" << "$field."), vps), AssertionException); } TEST(ParseObject, ShouldRejectExpressionAsTheSecondField) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; ASSERT_THROWS( ExpressionObject::parse( &expCtx, BSON("a" << BSON("$and" << BSONArray()) << "$or" << BSONArray()), vps), AssertionException); } // // Evaluation. // TEST(ExpressionObjectEvaluate, EmptyObjectShouldEvaluateToEmptyDocument) { auto expCtx = ExpressionContextForTest{}; auto object = ExpressionObject::create(&expCtx, {}); ASSERT_VALUE_EQ(Value(Document()), object->evaluate(Document(), &(expCtx.variables))); ASSERT_VALUE_EQ(Value(Document()), object->evaluate(Document{{"a", 1}}, &(expCtx.variables))); ASSERT_VALUE_EQ(Value(Document()), object->evaluate(Document{{"_id", "ID"_sd}}, &(expCtx.variables))); } TEST(ExpressionObjectEvaluate, ShouldEvaluateEachField) { auto expCtx = ExpressionContextForTest{}; auto object = ExpressionObject::create(&expCtx, {{"a", ExpressionConstant::create(&expCtx, Value{1})}, {"b", ExpressionConstant::create(&expCtx, Value{5})}}); ASSERT_VALUE_EQ(Value(Document{{"a", 1}, {"b", 5}}), object->evaluate(Document(), &(expCtx.variables))); ASSERT_VALUE_EQ(Value(Document{{"a", 1}, {"b", 5}}), object->evaluate(Document{{"a", 1}}, &(expCtx.variables))); ASSERT_VALUE_EQ(Value(Document{{"a", 1}, {"b", 5}}), object->evaluate(Document{{"_id", "ID"_sd}}, &(expCtx.variables))); } TEST(ExpressionObjectEvaluate, OrderOfFieldsInOutputShouldMatchOrderInSpecification) { auto expCtx = ExpressionContextForTest{}; auto object = ExpressionObject::create(&expCtx, {{"a", ExpressionFieldPath::deprecatedCreate(&expCtx, "a")}, {"b", ExpressionFieldPath::deprecatedCreate(&expCtx, "b")}, {"c", ExpressionFieldPath::deprecatedCreate(&expCtx, "c")}}); ASSERT_VALUE_EQ( Value(Document{{"a", "A"_sd}, {"b", "B"_sd}, {"c", "C"_sd}}), object->evaluate(Document{{"c", "C"_sd}, {"a", "A"_sd}, {"b", "B"_sd}, {"_id", "ID"_sd}}, &(expCtx.variables))); } TEST(ExpressionObjectEvaluate, ShouldRemoveFieldsThatHaveMissingValues) { auto expCtx = ExpressionContextForTest{}; auto object = ExpressionObject::create( &expCtx, {{"a", ExpressionFieldPath::deprecatedCreate(&expCtx, "a.b")}, {"b", ExpressionFieldPath::deprecatedCreate(&expCtx, "missing")}}); ASSERT_VALUE_EQ(Value(Document{}), object->evaluate(Document(), &(expCtx.variables))); ASSERT_VALUE_EQ(Value(Document{}), object->evaluate(Document{{"a", 1}}, &(expCtx.variables))); } TEST(ExpressionObjectEvaluate, ShouldEvaluateFieldsWithinNestedObject) { auto expCtx = ExpressionContextForTest{}; auto object = ExpressionObject::create( &expCtx, {{"a", ExpressionObject::create( &expCtx, {{"b", ExpressionConstant::create(&expCtx, Value{1})}, {"c", ExpressionFieldPath::deprecatedCreate(&expCtx, "_id")}})}}); ASSERT_VALUE_EQ(Value(Document{{"a", Document{{"b", 1}}}}), object->evaluate(Document(), &(expCtx.variables))); ASSERT_VALUE_EQ(Value(Document{{"a", Document{{"b", 1}, {"c", "ID"_sd}}}}), object->evaluate(Document{{"_id", "ID"_sd}}, &(expCtx.variables))); } TEST(ExpressionObjectEvaluate, ShouldEvaluateToEmptyDocumentIfAllFieldsAreMissing) { auto expCtx = ExpressionContextForTest{}; auto object = ExpressionObject::create( &expCtx, {{"a", ExpressionFieldPath::deprecatedCreate(&expCtx, "missing")}}); ASSERT_VALUE_EQ(Value(Document{}), object->evaluate(Document(), &(expCtx.variables))); auto objectWithNestedObject = ExpressionObject::create(&expCtx, {{"nested", object}}); ASSERT_VALUE_EQ(Value(Document{{"nested", Document{}}}), objectWithNestedObject->evaluate(Document(), &(expCtx.variables))); } // // Dependencies. // TEST(ExpressionObjectDependencies, ConstantValuesShouldNotBeAddedToDependencies) { auto expCtx = ExpressionContextForTest{}; auto object = ExpressionObject::create(&expCtx, {{"a", ExpressionConstant::create(&expCtx, Value{5})}}); DepsTracker deps; object->addDependencies(&deps); ASSERT_EQ(deps.fields.size(), 0UL); } TEST(ExpressionObjectDependencies, FieldPathsShouldBeAddedToDependencies) { auto expCtx = ExpressionContextForTest{}; auto object = ExpressionObject::create( &expCtx, {{"x", ExpressionFieldPath::deprecatedCreate(&expCtx, "c.d")}}); DepsTracker deps; object->addDependencies(&deps); ASSERT_EQ(deps.fields.size(), 1UL); ASSERT_EQ(deps.fields.count("c.d"), 1UL); }; TEST(ExpressionObjectDependencies, VariablesShouldBeAddedToDependencies) { auto expCtx = ExpressionContextForTest{}; auto varID = expCtx.variablesParseState.defineVariable("var1"); auto fieldPath = ExpressionFieldPath::parse(&expCtx, "$$var1", expCtx.variablesParseState); DepsTracker deps; fieldPath->addDependencies(&deps); ASSERT_EQ(deps.vars.size(), 1UL); ASSERT_EQ(deps.vars.count(varID), 1UL); } TEST(ExpressionObjectDependencies, LocalLetVariablesShouldBeFilteredOutOfDependencies) { auto expCtx = ExpressionContextForTest{}; expCtx.variablesParseState.defineVariable("var1"); auto letSpec = BSON("$let" << BSON("vars" << BSON("var2" << "abc") << "in" << BSON("$multiply" << BSON_ARRAY("$$var1" << "$$var2")))); auto expressionLet = ExpressionLet::parse(&expCtx, letSpec.firstElement(), expCtx.variablesParseState); DepsTracker deps; expressionLet->addDependencies(&deps); ASSERT_EQ(deps.vars.size(), 1UL); ASSERT_EQ(expCtx.variablesParseState.getVariable("var1"), *deps.vars.begin()); } TEST(ExpressionObjectDependencies, LocalMapVariablesShouldBeFilteredOutOfDependencies) { auto expCtx = ExpressionContextForTest{}; expCtx.variablesParseState.defineVariable("var1"); auto mapSpec = BSON("$map" << BSON("input" << "$field1" << "as" << "var2" << "in" << BSON("$multiply" << BSON_ARRAY("$$var1" << "$$var2")))); auto expressionMap = ExpressionMap::parse(&expCtx, mapSpec.firstElement(), expCtx.variablesParseState); DepsTracker deps; expressionMap->addDependencies(&deps); ASSERT_EQ(deps.vars.size(), 1UL); ASSERT_EQ(expCtx.variablesParseState.getVariable("var1"), *deps.vars.begin()); } TEST(ExpressionObjectDependencies, LocalFilterVariablesShouldBeFilteredOutOfDependencies) { auto expCtx = ExpressionContextForTest{}; expCtx.variablesParseState.defineVariable("var1"); auto filterSpec = BSON("$filter" << BSON("input" << BSON_ARRAY(1 << 2 << 3) << "as" << "var2" << "cond" << BSON("$gt" << BSON_ARRAY("$$var1" << "$$var2")))); auto expressionFilter = ExpressionFilter::parse(&expCtx, filterSpec.firstElement(), expCtx.variablesParseState); DepsTracker deps; expressionFilter->addDependencies(&deps); ASSERT_EQ(deps.vars.size(), 1UL); ASSERT_EQ(expCtx.variablesParseState.getVariable("var1"), *deps.vars.begin()); } // // Optimizations. // TEST(ExpressionObjectOptimizations, OptimizingAnObjectShouldOptimizeSubExpressions) { // Build up the object {a: {$add: [1, 2]}}. auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; auto addExpression = ExpressionAdd::parse(&expCtx, BSON("$add" << BSON_ARRAY(1 << 2)).firstElement(), vps); auto object = ExpressionObject::create(&expCtx, {{"a", addExpression}}); ASSERT_EQ(object->getChildExpressions().size(), 1UL); auto optimized = object->optimize(); auto optimizedObject = dynamic_cast<ExpressionConstant*>(optimized.get()); ASSERT_TRUE(optimizedObject); ASSERT_VALUE_EQ(optimizedObject->evaluate(Document(), &(expCtx.variables)), Value(BSON("a" << 3))); }; TEST(ExpressionObjectOptimizations, OptimizingAnObjectWithAllConstantsShouldOptimizeToExpressionConstant) { auto expCtx = ExpressionContextForTest{}; VariablesParseState vps = expCtx.variablesParseState; // All constants should optimize to ExpressionConstant. auto objectWithAllConstants = ExpressionObject::parse(&expCtx, BSON("b" << 1 << "c" << 1), vps); auto optimizedToAllConstants = objectWithAllConstants->optimize(); auto constants = dynamic_cast<ExpressionConstant*>(optimizedToAllConstants.get()); ASSERT_TRUE(constants); // Not all constants should not optimize to ExpressionConstant. auto objectNotAllConstants = ExpressionObject::parse(&expCtx, BSON("b" << 1 << "input" << "$inputField"), vps); auto optimizedNotAllConstants = objectNotAllConstants->optimize(); auto shouldNotBeConstant = dynamic_cast<ExpressionConstant*>(optimizedNotAllConstants.get()); ASSERT_FALSE(shouldNotBeConstant); // Sub expression should optimize to constant expression. auto expressionWithConstantObject = ExpressionObject::parse( &expCtx, BSON("willBeConstant" << BSON("$add" << BSON_ARRAY(1 << 2)) << "alreadyConstant" << "string"), vps); auto optimizedWithConstant = expressionWithConstantObject->optimize(); auto optimizedObject = dynamic_cast<ExpressionConstant*>(optimizedWithConstant.get()); ASSERT_TRUE(optimizedObject); ASSERT_VALUE_EQ(optimizedObject->evaluate(Document(), &expCtx.variables), Value(BSON("willBeConstant" << 3 << "alreadyConstant" << "string"))); }; } // namespace Object } // namespace } // namespace ExpressionTests } // namespace mongo
45.204433
100
0.634447
benety
724b2939661c2895555f9dce4843cf761f15b5c2
25,921
cpp
C++
libs/StartExe/StartExe.cpp
kit-transue/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
2
2015-11-24T03:31:12.000Z
2015-11-24T16:01:57.000Z
libs/StartExe/StartExe.cpp
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
null
null
null
libs/StartExe/StartExe.cpp
radtek/software-emancipation-discover
bec6f4ef404d72f361d91de954eae9a3bd669ce3
[ "BSD-2-Clause" ]
1
2019-05-19T02:26:08.000Z
2019-05-19T02:26:08.000Z
/************************************************************************* * Copyright (c) 2015, Synopsys, Inc. * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are * * met: * * * * 1. Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * 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. * *************************************************************************/ // StartExe.cpp : Defines the entry point for the console application. // #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <sys/types.h> #include <sys/types.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> #include "nameServCalls.h" #ifdef _WIN32 #include <windows.h> #include <winsock.h> #include <ws2tcpip.h> // for socklen_t #include <io.h> #else #include <arpa/inet.h> #include <netinet/tcp.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #ifdef sun4 #include <poll.h> #include <time.h> #include <sys/time.h> #endif #ifdef irix6 #include <sys/poll.h> #endif #ifdef hp700 #include <sys/poll.h> #include <time.h> extern "C" int select(int, int*, int*, int*, const struct timeval*); #endif #endif #include "debug.h" #include "startproc.h" static int nClients = 0; #define REPLY_DELIM "\t" #ifndef _WIN32 #define closesocket(sock) close(sock) #endif typedef struct { int m_DriverAddress; int m_DriverPort; int m_DriverListeningSocket; } CConnectionDescriptor; static CConnectionDescriptor Connection; static int do_shutdown = 0; //############################################################################################ // This class represents the client record in the clients linked list. // Any client record contain client name, client TCP address and port and server TCP // address and port. //############################################################################################ class ClientDescriptor { public: ClientDescriptor(int id, int client_socket, int client_port, int client_tcp_addr); ~ClientDescriptor(); static void AddNewClient(ClientDescriptor *sd); static void RemoveClient(int id); static void RemoveClient(ClientDescriptor *p); static void RemoveAllClients(void); static ClientDescriptor *LookupID(int id); int m_ID; int m_ClientSocket; int m_ClientPort; int m_ClientTCP; ClientDescriptor *m_Next; static ClientDescriptor *sd_list; static ClientDescriptor *sd_list_last; }; ClientDescriptor *ClientDescriptor::sd_list = NULL; ClientDescriptor *ClientDescriptor::sd_list_last = NULL; int ProcessClientQuery(ClientDescriptor* client); void RequestsLoop(void); //------------------------------------------------------------------------------------------------------ // Constructor will create new client with the client name //------------------------------------------------------------------------------------------------------ ClientDescriptor::ClientDescriptor(int id, int client_socket, int client_port, int client_addr) { this->m_ID = id; this->m_ClientSocket = client_socket; this->m_ClientPort = client_port; this->m_ClientTCP = client_addr; this->m_Next = NULL; } //------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------ // Destructor will free the space allocated for the new client name //------------------------------------------------------------------------------------------------------ ClientDescriptor::~ClientDescriptor() { } //------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------ // This method will add new client to the clients linked list //------------------------------------------------------------------------------------------------------ void ClientDescriptor::AddNewClient(ClientDescriptor *sd) { if(sd_list == NULL){ sd_list = sd; sd_list_last = sd; } else { sd_list_last->m_Next = sd; sd_list_last = sd; } } //------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------ // This function will return a pointer to the client record in the clients linked list // or NULL of no client with the given name found. //------------------------------------------------------------------------------------------------------ ClientDescriptor *ClientDescriptor::LookupID(int id) { ClientDescriptor *cur = sd_list; while(cur != NULL){ if(cur->m_ID==id) return cur; cur = cur->m_Next; } return NULL; } //------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------ // This function will remove the client with the given name. //------------------------------------------------------------------------------------------------------ void ClientDescriptor::RemoveClient(int id) { ClientDescriptor *prev = NULL; ClientDescriptor *cur = sd_list; while(cur != NULL) { if(cur->m_ID == id) { closesocket(cur->m_ClientSocket); if(prev == NULL) sd_list = cur->m_Next; else prev->m_Next = cur->m_Next; if(sd_list_last == cur) sd_list_last = prev; delete cur; return; } prev = cur; cur = cur->m_Next; } } //------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------ // This function will remove client with the given address //------------------------------------------------------------------------------------------------------ void ClientDescriptor::RemoveClient(ClientDescriptor *p) { ClientDescriptor *prev = NULL; ClientDescriptor *cur = sd_list; while(cur != NULL) { if(p==cur) { closesocket(cur->m_ClientSocket); if(prev == NULL) sd_list = cur->m_Next; else prev->m_Next = cur->m_Next; if(sd_list_last == cur) sd_list_last = prev; delete cur; return; } prev = cur; cur = cur->m_Next; } } //------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------ // This function will remove client with the given address //------------------------------------------------------------------------------------------------------ void ClientDescriptor::RemoveAllClients(void) { ClientDescriptor *p; ClientDescriptor *cur = sd_list; while(cur != NULL) { p=cur; cur = cur->m_Next; closesocket(p->m_ClientSocket); delete p; } sd_list=sd_list_last=NULL; } //------------------------------------------------------------------------------------------------------ //-------------------------------------------------------------------------------------------- // This procedure will create a listen socket for client requests channel //-------------------------------------------------------------------------------------------- int CreateListener() { int sock; struct sockaddr_in name; /* Create the socket. */ sock = socket (PF_INET, SOCK_STREAM, 0); if (sock < 0) return -1; unsigned int set_option = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (const char *)&set_option, sizeof(set_option)); /* Give the socket a name. */ name.sin_family = AF_INET; name.sin_port = 0; name.sin_addr.s_addr = htonl(INADDR_ANY); if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) return -1; if(listen(sock, 5) < 0) return -1; return sock; } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- // This function will create new client record in the clients linked list. //-------------------------------------------------------------------------------------------- void CreateNewClient(int id, int client_socket, int client_port, int client_tcp) { ClientDescriptor* descr; descr = new ClientDescriptor(id,client_socket,client_port,client_tcp); descr->AddNewClient(descr); } //-------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Main function will register the editor service //--------------------------------------------------------------------------- int startExeMain(void) { socklen_t len; int i; int bNameServerStarted = 0; char serviceName[1024]; char* currentUser; char* dnStart; gethostname(serviceName,1024); if((dnStart = strchr(serviceName,'.'))>0) serviceName[dnStart-serviceName]=0; strcat(serviceName,":"); currentUser = getenv("USER"); if(currentUser!=NULL) { strcat(serviceName,currentUser); strcat(serviceName,":"); } strcat(serviceName,"STARTEXE"); _DBG(fprintf(log_fd,"Name of the service is : %s\n",serviceName)); // Checking if we have an instance of this driver and if we // have name server running at all int res = NameServerGetService(serviceName, Connection.m_DriverPort, Connection.m_DriverAddress); switch(res) { // No name server running case -1 : if(LaunchNameServer(START_SERVER)==0) return 0; _DBG(fprintf(log_fd,"Name server started.\n")); bNameServerStarted = 1; // No instance of this driver case 0 : // Any app which needs the editor service must request this socket. // It will create separate communication channel in responce Connection.m_DriverListeningSocket = CreateListener(); if(Connection.m_DriverListeningSocket < 0) { _DBG(fprintf(log_fd,"Unable to create clients requests socket.\n")); return 1; } _DBG(fprintf(log_fd,"Listening socket created.\n")); // This block will register MSDEV editor driver in our name server struct sockaddr_in assigned; len = sizeof(assigned); if(getsockname(Connection.m_DriverListeningSocket, (struct sockaddr *)&assigned, &len) == 0){ _DBG(fprintf(log_fd,"Registering StartEXE service.\n")); NameServerRegisterService(serviceName, ntohs(assigned.sin_port)); } for(i=0;i<200;i++) { if(NameServerGetService(serviceName,Connection.m_DriverPort,Connection.m_DriverAddress)==1) break; } if(i==200) { _DBG(fprintf(log_fd,"Unable to register this service.\n")); closesocket(Connection.m_DriverListeningSocket); return 2; } break; // This driver is already running case 1 : int first_part,second_part,third_part,fourth_part; first_part = Connection.m_DriverAddress/(256*256*256); Connection.m_DriverAddress -= 256*256*256*first_part; second_part = Connection.m_DriverAddress/(256*256); Connection.m_DriverAddress -= 256*256*second_part; third_part = Connection.m_DriverAddress/256; Connection.m_DriverAddress -= 256*third_part; fourth_part = Connection.m_DriverAddress; _DBG(fprintf(log_fd,"This driver is already running.\nPort is %d TCP address is %d.%d.%d.%d\nAborting launch procedure.\n",Connection.m_DriverPort,first_part,second_part,third_part,fourth_part)); return 3; } _DBG(fprintf(log_fd,"Ready to process requests.\n")); RequestsLoop(); if(bNameServerStarted == 1) { _DBG(fprintf(log_fd,"Closing nameserver.\n")); LaunchNameServer(STOP_SERVER); } else { _DBG(fprintf(log_fd,"Unregistering service %s.\n",serviceName)); NameServerUnRegisterService(serviceName); } _DBG(fprintf(log_fd,"Terminating driver.\n")); closesocket(Connection.m_DriverListeningSocket); return 0; } //-------------------------------------------------------------------------------------------- // This function will run every time the new client try to connect to the editor // It will create socket connection between the client and the currently // running pmod server and will start client log. //-------------------------------------------------------------------------------------------- void ConnectClient(int client_socket, sockaddr *addr) { static int ID_Counter = 0; int client_port = ((sockaddr_in *)addr)->sin_port; int client_tcp = ((sockaddr_in *)addr)->sin_addr.s_addr; // We will not use password right now, but we may in future CreateNewClient(ID_Counter++, client_socket, client_port, client_tcp); _DBG(fprintf(log_fd,"New client connected.\n")); } //-------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------------------ // This function will check if data available in the selected socket //------------------------------------------------------------------------------------------------------ int CheckSocket(int socket) { timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 0; fd_set sock_set; int nfsd = 0; #ifndef _WIN32 nfsd = FD_SETSIZE; #endif FD_ZERO(&sock_set); FD_SET(socket, &sock_set); #ifdef hp700 if(select(nfsd,(int *)&sock_set,NULL,NULL,&timeout)>0) { #else if(select(nfsd,&sock_set,NULL,NULL,&timeout)>0) { #endif return 1; } return 0; } //------------------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------------------ // This function will check if data available in the selected socket //------------------------------------------------------------------------------------------------------ int WaitSocket(int *sockets, int amount) { timeval timeout; timeout.tv_sec = 8; timeout.tv_usec = 0; fd_set sock_set; int nfsd = 0; #ifndef _WIN32 nfsd = FD_SETSIZE; #endif FD_ZERO(&sock_set); for(int i=0;i<amount;i++) { FD_SET(*(sockets+i), &sock_set); } #ifdef hp700 if(select(nfsd,(int *)&sock_set,NULL,NULL,&timeout)>0) { #else if(select(nfsd,&sock_set,NULL,NULL,&timeout)>0) { #endif return 1; } return 0; } //------------------------------------------------------------------------------------------------------ //-------------------------------------------------------------------------------------------- // This function will inspect clients list in order to determine which clients // need to query server. The data will be forwarded from the client socket // into model server socket and reply will be forwarded from model server socket // to the client socket. //-------------------------------------------------------------------------------------------- int MakeSocketsArray(int server, int *sockets) { static ClientDescriptor* hang; sockets[0]=server; int amount=1; ClientDescriptor *cur = ClientDescriptor::sd_list; while(ClientDescriptor::sd_list!=NULL && cur != NULL) { sockets[amount++]=cur->m_ClientSocket; cur = cur->m_Next; } return amount; } //-------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- // This function will inspect clients list in order to determine which clients // need to query server. The data will be forwarded from the client socket // into model server socket and reply will be forwarded from model server socket // to the client socket. //-------------------------------------------------------------------------------------------- void ProcessClients(void) { static ClientDescriptor* hang; _DBG(fprintf(log_fd,"Trying to process client request.\n")); ClientDescriptor *cur = ClientDescriptor::sd_list; while(ClientDescriptor::sd_list!=NULL && cur != NULL) { if(CheckSocket(cur->m_ClientSocket)) { // Processing client request if(ProcessClientQuery(cur)) break; } cur = cur->m_Next; } } //-------------------------------------------------------------------------------------------- //------------------------------------------------------------------------------------------- // Loop while not shutting down. Will listen clients socket and administrator socket, // will process clients and administrator requests if any. //------------------------------------------------------------------------------------------- void RequestsLoop(void) { int sockets[3000]; struct sockaddr s; socklen_t s_size = sizeof(s); do { int amount = MakeSocketsArray(Connection.m_DriverListeningSocket,sockets); WaitSocket(sockets,amount); if(CheckSocket(Connection.m_DriverListeningSocket)) { int cli_connection = accept(Connection.m_DriverListeningSocket, &s, &s_size); int tmp_switch = 1; setsockopt(cli_connection, IPPROTO_TCP, TCP_NODELAY, (char *)&tmp_switch, sizeof(tmp_switch)); if(cli_connection >= 0) { _DBG(fprintf(log_fd,"Connecting new client.\n")); ConnectClient(cli_connection, &s); continue; } } // Performing data translstion from the existing client sockets // to the existing model sockets ProcessClients(); } while(!do_shutdown); } //-------------------------------------------------------------------------------------------- bool ProcessEnvVars(char* cmd,char* expandedCmd) { int cmdLen = strlen(cmd); char* substrStart = cmd; char* firstDelim; char* secondDelim = cmd; char envVar[256]; char* pEnvVar; memset(envVar,0,256*sizeof(char)); do{ firstDelim = strchr(secondDelim,'%'); if(firstDelim!=NULL) { secondDelim = strchr(firstDelim+1,'%'); if(secondDelim==NULL) return false; strncat(expandedCmd,substrStart,firstDelim-substrStart); strncpy(envVar,firstDelim+1,secondDelim-firstDelim-1); pEnvVar = getenv(envVar); if(pEnvVar==NULL) return false; strcat(expandedCmd,pEnvVar); secondDelim++; substrStart = secondDelim; } }while((firstDelim!=NULL) && (secondDelim<(cmd+cmdLen))); strncat(expandedCmd,substrStart,firstDelim-substrStart); return true; } #ifndef _WIN32 const int ERROR_SUCCESS = 0; const int ERROR_ENVVAR_NOT_FOUND = -1; static int lastError = 0; void SetLastError(int errorCode) { lastError = errorCode; } int GetLastError() { return lastError; } char* FormatErrorMessage(int errorCode) { switch(errorCode) { case ERROR_SUCCESS: return (char *)"The operation completed successfully."; case ERROR_ENVVAR_NOT_FOUND: return (char *)"The system could not find the environment option that was entered."; default: return (char *)"The error code is unknown."; } } #endif bool StartProcess(char* exeName, char* params, char* outputFile,DWORD *retCode, int waitType) { char exeCmd[2048]; memset(exeCmd,0,2048*sizeof(char)); if(ProcessEnvVars(exeName,exeCmd)==false) { SetLastError(ERROR_ENVVAR_NOT_FOUND); return false; } strcat(exeCmd," "); if(ProcessEnvVars(params,exeCmd+strlen(exeCmd))==false) { SetLastError(ERROR_ENVVAR_NOT_FOUND); return false; } if(outputFile == NULL) *retCode = start_new_process(exeCmd,waitType); else { *retCode = start_new_process(exeCmd,outputFile); } return (*retCode)!=-1; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------- // This function will process given command with it's arguments and will send the reply //--------------------------------------------------------------------------------------------- int ProcessOneCommand(ClientDescriptor* client, char args[10][1000],int paramsCount) { int cmdType = START_NO_WAIT; DWORD exitCode; char* outputFile = NULL; char replyString[1024]; if(strcmp(args[0],"register")==0) { nClients++; SendString(client->m_ClientSocket, "done"); _DBG(fprintf(log_fd,"A new client has been registered.\n")); return 1; } if(strcmp(args[0],"unregister")==0) { nClients--; if(nClients<1){ do_shutdown = 1; } SendString(client->m_ClientSocket, "done"); _DBG(fprintf(log_fd,"A client has been unregistered.\n")); return 1; } // Starts detached process if(strcmp(args[0],"start")==0) { cmdType = START_NO_WAIT; _DBG(fprintf(log_fd,"Processing START_NO_WAIT command...\n")); } else { if(strcmp(args[0],"start_and_wait")==0) { cmdType = START_AND_WAIT; _DBG(fprintf(log_fd,"Processing START_AND_WAIT command...\n")); } else { if(strcmp(args[0],"start_wait_and_get_output")==0) { cmdType = START_AND_WAIT; outputFile = args[paramsCount-1]; _DBG(fprintf(log_fd,"Processing START_WAIT_AND_GET_OUTPUT command...\n")); } else { // We do not know this command sprintf(replyString,"Error%s0%sunknown command",REPLY_DELIM,REPLY_DELIM); SendString(client->m_ClientSocket,replyString); _DBG(fprintf(log_fd,"Unknown command %s.\n",args[0])); return 0; } } } if(StartProcess(args[1],args[2],outputFile,&exitCode,cmdType)==true) { sprintf(replyString,"Done%s%d%s",REPLY_DELIM,exitCode,REPLY_DELIM); _DBG(fprintf(log_fd,"Command successed. Return code %d\n",exitCode)); } else { #ifdef _WIN32 LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); // Save the error string. sprintf(replyString,"Error%s%d%s%s",REPLY_DELIM,&exitCode,REPLY_DELIM,(LPTSTR)lpMsgBuf); // Free the buffer. LocalFree( lpMsgBuf ); #else sprintf(replyString,"Error%s%d%s%s",REPLY_DELIM,&exitCode,REPLY_DELIM,FormatErrorMessage(GetLastError())); #endif _DBG(fprintf(log_fd,"Command FAILED. Return code %d. Error %s\n",exitCode,replyString)); } SendString(client->m_ClientSocket,replyString); return 1; } //---------------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------------- // Client send editor an operation request //-------------------------------------------------------------------------------------------- int ProcessClientQuery(ClientDescriptor* client) { char* command; int readed; char vals[10][1000]; // Redirecting query from the client to the server command = ReceiveString(client->m_ClientSocket); if(command == NULL) { _DBG(fprintf(log_fd,"Client disconnected. Removing dead client.\n")); ClientDescriptor::RemoveClient(client); return 1; } readed = strlen(command); _DBG(fprintf(log_fd,"Processing client query.\n")); // Tokenizing string query and placing all tokens into the // vals matrix char word[1000]; word[0]=0; int chcount=0; int lcount = 0; int i; for(i=0;i<readed;i++) { if(command[i]=='\t') { word[chcount] = 0; strcpy(vals[lcount++],word); chcount = 0; continue; } if(chcount<998) word[chcount++]=command[i]; } if(chcount>=0) { word[chcount] = 0; strcpy(vals[lcount++],word); } if(lcount>0) { ProcessOneCommand(client,vals,lcount); return 1; } return 0; } //--------------------------------------------------------------------------------------------
36.152022
200
0.521585
kit-transue
724ba9ffe8af322eb43cfdf327f9766188ee0bbe
5,167
cpp
C++
windows/feime/kor/ime2k/tip/fmode.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/feime/kor/ime2k/tip/fmode.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/feime/kor/ime2k/tip/fmode.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/**************************************************************************** FMODE.CPP : FMode class implementation which manage Full/Half shape mode button on the Cicero Toolbar History: 23-FEB-2000 CSLim Created ****************************************************************************/ #include "private.h" #include "globals.h" #include "common.h" #include "korimx.h" #include "fmode.h" #include "userex.h" #include "resource.h" // {D96498AF-0E46-446e-8F00-E113236FD22D} const GUID GUID_LBI_KORIMX_FMODE = { 0xd96498af, 0x0e46, 0x446e, { 0x8f, 0x0, 0xe1, 0x13, 0x23, 0x6f, 0xd2, 0x2d } }; /*--------------------------------------------------------------------------- FMode::FMode ---------------------------------------------------------------------------*/ FMode::FMode(CToolBar *ptb) { WCHAR szText[256]; m_pTb = ptb; // Set Add/Remove and tootip text LoadStringExW(g_hInst, IDS_TT_JUN_BAN, szText, sizeof(szText)/sizeof(WCHAR)); InitInfo(CLSID_KorIMX, GUID_LBI_KORIMX_FMODE, TF_LBI_STYLE_BTN_BUTTON | TF_LBI_STYLE_HIDDENBYDEFAULT | TF_LBI_STYLE_TEXTCOLORICON, 110, szText); SetToolTip(szText); // Set button text LoadStringExW(g_hInst, IDS_BUTTON_JUN_BAN, szText, sizeof(szText)/sizeof(WCHAR)); SetText(szText); } /*--------------------------------------------------------------------------- FMode::Release ---------------------------------------------------------------------------*/ STDAPI_(ULONG) FMode::Release() { long cr; cr = --m_cRef; Assert(cr >= 0); if (cr == 0) { delete this; } return cr; } /*--------------------------------------------------------------------------- FMode::GetIcon Get Button face Icon ---------------------------------------------------------------------------*/ STDAPI FMode::GetIcon(HICON *phIcon) { DWORD dwCM = GetCMode(); UINT uiIcon = 0; static const UINT uidIcons[2][2] = { { IDI_CMODE_BANJA, IDI_CMODE_BANJAW }, { IDI_CMODE_JUNJA, IDI_CMODE_JUNJAW } }; if (m_pTb->IsOn() && (m_pTb->GetConversionMode() & TIP_JUNJA_MODE)) uiIcon = 1; if (IsHighContrastBlack()) uiIcon = uidIcons[uiIcon][1]; else uiIcon = uidIcons[uiIcon][0]; *phIcon = (HICON)LoadImage(g_hInst, MAKEINTRESOURCE(uiIcon), IMAGE_ICON, 16, 16, LR_LOADMAP3DCOLORS); return S_OK; } /*--------------------------------------------------------------------------- FMode::InitMenu No need, this is just toggle button ---------------------------------------------------------------------------*/ STDAPI FMode::InitMenu(ITfMenu *pMenu) { return E_NOTIMPL; } /*--------------------------------------------------------------------------- FMode::OnMenuSelect No need, this is just toggle button ---------------------------------------------------------------------------*/ STDAPI FMode::OnMenuSelect(UINT wID) { return E_NOTIMPL; } //+--------------------------------------------------------------------------- // // OnLButtonUp // //---------------------------------------------------------------------------- HRESULT FMode::OnLButtonUp(const POINT pt, const RECT* prcArea) { DWORD dwConvMode; dwConvMode = GetCMode(); // Toggle Full/Half mode if (dwConvMode & TIP_JUNJA_MODE) dwConvMode &= ~TIP_JUNJA_MODE; else dwConvMode |= TIP_JUNJA_MODE; SetCMode(dwConvMode); return S_OK; } #if 0 //+--------------------------------------------------------------------------- // // OnRButtonUp // //---------------------------------------------------------------------------- HRESULT FMode::OnRButtonUp(const POINT pt, const RECT* prcArea) { HMENU hMenu; DWORD dwConvMode; CHAR szText[256]; UINT uiId; int nRet; hMenu = CreatePopupMenu(); dwConvMode = GetCMode(); if (dwConvMode & TIP_JUNJA_MODE) uiId = IDS_BANJA_MODE; else uiId = IDS_JUNJA_MODE; // Add Hangul/English mode menu LoadStringExA(g_hInst, uiId, szText, sizeof(szText)/sizeof(CHAR)); InsertMenu(hMenu, -1, MF_BYPOSITION | MF_STRING, 1, szText); // Add Cancel menu LoadStringExA(g_hInst, IDS_CANCEL, szText, sizeof(szText)/sizeof(CHAR)); InsertMenu(hMenu, -1, MF_BYPOSITION | MF_STRING, 0, szText); nRet = TrackPopupMenuEx(hMenu, TPM_LEFTBUTTON | TPM_NONOTIFY | TPM_RETURNCMD, pt.x, pt.y, m_pTb->GetOwnerWnd(), NULL); switch (nRet) { case 1: dwConvMode = GetCMode(); // Toggle Full/Half mode if (dwConvMode & TIP_JUNJA_MODE) dwConvMode &= ~TIP_JUNJA_MODE; else dwConvMode |= TIP_JUNJA_MODE; SetCMode(dwConvMode); break; } DestroyMenu(hMenu); return S_OK; } #endif
26.497436
106
0.444939
npocmaka
724c28ac4ffde7a6f6317182b5ba921c15074c2f
524
cpp
C++
GraphicsScene/Camera.cpp
Melody6149/Graphics-for-games-tutorial
8ad1ed15ab774c0bd93e87f5c937f1597d55509e
[ "MIT" ]
null
null
null
GraphicsScene/Camera.cpp
Melody6149/Graphics-for-games-tutorial
8ad1ed15ab774c0bd93e87f5c937f1597d55509e
[ "MIT" ]
null
null
null
GraphicsScene/Camera.cpp
Melody6149/Graphics-for-games-tutorial
8ad1ed15ab774c0bd93e87f5c937f1597d55509e
[ "MIT" ]
null
null
null
#include "Camera.h" #include <glm/ext.hpp> glm::mat4 Camera::getViewMatrix() { float yawRadians = glm::radians(m_yaw); float pitchRadians = glm::radians(m_pitch); glm::vec3 forward( cos(pitchRadians) * cos(yawRadians), sin(pitchRadians), cos(pitchRadians) * sin(yawRadians)); return glm::lookAt(m_position, m_position + forward, glm::vec3(0.0f, 1.0f, 0.0f)); } glm::mat4 Camera::getProjectionMatrix(float width, float height) { return glm::perspective(glm::pi<float>() * 0.25, width / height, 0.1, 1000.0f); }
26.2
83
0.70229
Melody6149
724defd8aa59d5474aa655bb87ae3227417e9cc7
3,328
cc
C++
support/conf/options.cc
ahamez/pnmc
cee5f2e01edc2130278ebfc13f0f859230d65680
[ "BSD-2-Clause" ]
5
2015-02-05T20:56:20.000Z
2022-01-29T01:20:24.000Z
support/conf/options.cc
ahamez/pnmc
cee5f2e01edc2130278ebfc13f0f859230d65680
[ "BSD-2-Clause" ]
null
null
null
support/conf/options.cc
ahamez/pnmc
cee5f2e01edc2130278ebfc13f0f859230d65680
[ "BSD-2-Clause" ]
null
null
null
/// @file /// @copyright The code is licensed under the BSD License /// <http://opensource.org/licenses/BSD-2-Clause>, /// Copyright (c) 2013-2015 Alexandre Hamez. /// @author Alexandre Hamez #include <map> #include <string> #include <utility> #include <boost/algorithm/string/join.hpp> #include <boost/range/adaptor/map.hpp> #include "support/conf/options.hh" #include "support/conf/pn_format.hh" #include "support/util/paths.hh" namespace pnmc { namespace conf { namespace po = boost::program_options; /*------------------------------------------------------------------------------------------------*/ static const auto pn_format_str = "format"; static const auto format_map = std::map<std::string, pn_format> { std::make_pair("ndr" , pn_format::ndr) , std::make_pair("net" , pn_format::net) , std::make_pair("nupn", pn_format::nupn) , std::make_pair("pnml", pn_format::pnml) }; static const auto possible_format_values = [] { using namespace boost::adaptors; return "Petri net format [" + boost::algorithm::join(format_map | map_keys, "|") + "]"; }(); /*------------------------------------------------------------------------------------------------*/ po::options_description pn_input_options() { po::options_description options{"Petri net file format options"}; options.add_options() (pn_format_str, po::value<std::string>()->default_value("net"), possible_format_values.c_str()); return options; } /*------------------------------------------------------------------------------------------------*/ static pn_format pn_format_from_options(const po::variables_map& vm) { const auto s = vm[pn_format_str].as<std::string>(); const auto search = format_map.find(s); if (search != end(format_map)) { return search->second; } else { throw po::error("Invalid input format " + s); } } /*------------------------------------------------------------------------------------------------*/ parsers::pn_configuration configure_pn_parser(const boost::program_options::variables_map& vm) { parsers::pn_configuration conf; if (vm["input-file"].as<std::string>() != "-") { conf.file = util::in_file(vm["input-file"].as<std::string>()); } conf.file_type = pn_format_from_options(vm); return conf; } /*------------------------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------------------------*/ static const auto properties_input_str = "properties-file"; po::options_description properties_input_options() { po::options_description options{"Properties file format options"}; options.add_options() (properties_input_str, po::value<std::string>(), "Path to properties file"); return options; } /*------------------------------------------------------------------------------------------------*/ parsers::properties_configuration configure_properties_parser(const boost::program_options::variables_map& vm) { parsers::properties_configuration conf; if (vm.count(properties_input_str)) { conf.file = util::in_file(vm[properties_input_str].as<std::string>()); } return conf; } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::conf
29.981982
100
0.534555
ahamez