hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
5d39b329b6f9e9289063542bde5f4441ce7baf59
11,919
cpp
C++
src/DeNoise.cpp
omi-lab/tp_image_utils_functions
5d02c634a87304eeb9c5b0828ebf8f18383aa91a
[ "MIT" ]
null
null
null
src/DeNoise.cpp
omi-lab/tp_image_utils_functions
5d02c634a87304eeb9c5b0828ebf8f18383aa91a
[ "MIT" ]
null
null
null
src/DeNoise.cpp
omi-lab/tp_image_utils_functions
5d02c634a87304eeb9c5b0828ebf8f18383aa91a
[ "MIT" ]
2
2019-01-30T14:02:44.000Z
2020-11-25T09:19:14.000Z
#include "tp_image_utils_functions/DeNoise.h" #include "tp_utils/DebugUtils.h" #include <memory.h> namespace tp_image_utils_functions { //################################################################################################## ByteRegions::ByteRegions(const tp_image_utils::ByteMap& src, bool addCorners) { w = src.width(); h = src.height(); if(w<1 || h<1) return; size_t ci=0; regions.resize(w*h); map.resize(w*h); int* done = new int[w*h]; auto partial = new std::pair<int, int>[w*h*8]; size_t partialCount=0; memset(done, 0, w*h*sizeof(int)); { const uint8_t* s = src.constData(); const uint8_t* sMax = s + (w*h); int* d = map.data(); for(; s<sMax; s++, d++) (*d) = (-int(*s))-1; } for(size_t y=0; y<h; y++) { for(size_t x=0; x<w; x++) { size_t offset = (y*w)+x; //Don't bother if we already have a count for this if(map[offset]>=0) continue; size_t i = ci; ci++; int color = map[offset]; map[offset] = int(i); ByteRegion& region = regions[i]; region.value=uint8_t(-1-color); region.count=0; partialCount=0; partial[partialCount]={int(x-1), int(y )}; partialCount++; partial[partialCount]={int(x+1), int(y )}; partialCount++; partial[partialCount]={int(x ), int(y-1)}; partialCount++; partial[partialCount]={int(x ), int(y+1)}; partialCount++; if(addCorners) { partial[partialCount]={int(x+1), int(y+1)}; partialCount++; partial[partialCount]={int(x+1), int(y-1)}; partialCount++; partial[partialCount]={int(x-1), int(y-1)}; partialCount++; partial[partialCount]={int(x-1), int(y+1)}; partialCount++; } while(partialCount>0) { partialCount--; auto px = size_t(partial[partialCount].first ); auto py = size_t(partial[partialCount].second); if(px>=w || py>=h) continue; size_t po = (py*w)+px; if(done[po]==int(i)) continue; done[po]=int(i); if(map[size_t(po)]!=color) continue; region.count++; map[po]=int(i); partial[partialCount]={int(px-1), int(py )}; partialCount++; partial[partialCount]={int(px+1), int(py )}; partialCount++; partial[partialCount]={int(px ), int(py-1)}; partialCount++; partial[partialCount]={int(px ), int(py+1)}; partialCount++; if(addCorners) { partial[partialCount]={int(px+1), int(py+1)}; partialCount++; partial[partialCount]={int(px+1), int(py-1)}; partialCount++; partial[partialCount]={int(px-1), int(py-1)}; partialCount++; partial[partialCount]={int(px-1), int(py+1)}; partialCount++; } } } } regions.resize(ci); delete[] done; delete[] partial; } //################################################################################################## void ByteRegions::calculateBoundingBoxes() { { ByteRegion* r = regions.data(); ByteRegion* rMax = r + regions.size(); for(; r<rMax; r++) { r->minX = w; r->minY = h; r->maxX = 0; r->maxY = 0; } } for(size_t y=0; y<h; y++) { for(size_t x=0; x<w; x++) { int index = map[(y*w)+x]; ByteRegion& region = regions[size_t(index)]; if(region.minX>x) region.minX=x; if(region.minY>y) region.minY=y; if(region.maxX<x) region.maxX=x; if(region.maxY<y) region.maxY=y; } } } //################################################################################################## tp_image_utils::ByteMap deNoise(const tp_image_utils::ByteMap& src, size_t minSize, bool addCorners, uint8_t solid, uint8_t space) { if(minSize<2) return src; size_t w = src.width(); size_t h = src.height(); if(w<1 || h<1) return src; tp_image_utils::ByteMap dst(w, h); ByteRegions regions(src, addCorners); uint8_t* d = dst.data(); for(size_t y=0; y<h; y++) { for(size_t x=0; x<w; x++) { auto index = size_t(regions.map[(y*w)+x]); const ByteRegion& region = regions.regions[index]; (*d) = (region.value==space || region.count<minSize)?space:solid; d++; } } return dst; } //################################################################################################## tp_image_utils::ByteMap deNoiseBlobs(const tp_image_utils::ByteMap& src, float minAspectRatio, float maxAspectRatio, float minDensity, float maxDensity, size_t minSize, size_t maxSize, bool addCorners, uint8_t solid, uint8_t space) { size_t w = src.width(); size_t h = src.height(); if(w<1 || h<1) return src; tp_image_utils::ByteMap dst(w, h); ByteRegions regions(src, addCorners); regions.calculateBoundingBoxes(); std::vector<int> erase; erase.resize(regions.regions.size()); { ByteRegion* r = regions.regions.data(); ByteRegion* rMax = r + regions.regions.size(); int* e = erase.data(); for(; r<rMax; r++, e++) { if(r->value==space) { (*e) = 1; continue; } (*e) = 0; size_t rw = (r->maxX - r->minX)+1; size_t rh = (r->maxY - r->minY)+1; float ar = (rw>rh)?(float(rh)/float(rw)):(float(rw)/float(rh)); float density = float(r->count) / float(rw*rh); if(ar<minAspectRatio || ar>maxAspectRatio) continue; if(density<minDensity || density>maxDensity) continue; if(rw<minSize || rw>maxSize) continue; if(rh<minSize || rh>maxSize) continue; (*e) = 1; } } uint8_t* d = dst.data(); for(size_t y=0; y<h; y++) { for(size_t x=0; x<w; x++) { auto index = size_t(regions.map[(y*w)+x]); (*d) = (erase[index])?space:solid; d++; } } return dst; } //################################################################################################## tp_image_utils::ByteMap deNoiseStripes(const tp_image_utils::ByteMap& src, size_t minSize, uint8_t solid, uint8_t space) { if(minSize<2) return src; size_t w = src.width(); size_t h = src.height(); if(w<1 || h<1) return src; tp_image_utils::ByteMap dst(w, h); //Search columns for(size_t x=0; x<w; x++) { size_t count=0; bool spaceFound=false; for(size_t y=0; y<h; y++) { if(src.pixel(x, y)==solid) count++; else { dst.setPixel(x, y, space); if(count>0) { uint8_t val = (spaceFound && count<minSize)?space:solid; for(size_t p=y-count; p<y; p++) dst.setPixel(x, p, val); count=0; } spaceFound=true; } } if(count>0) { uint8_t val = solid; for(size_t p=h-count; p<h; p++) dst.setPixel(x, p, val); } } //Search rows for(size_t y=0; y<h; y++) { size_t count=0; bool spaceFound=false; for(size_t x=0; x<w; x++) { if(dst.pixel(x, y)==solid) count++; else { dst.setPixel(x, y, space); if(count>0) { uint8_t val = (spaceFound && count<minSize)?space:solid; for(size_t p=x-count; p<x; p++) dst.setPixel(p, y, val); count=0; } spaceFound=true; } } if(count>0) { uint8_t val = solid; for(size_t p=w-count; p<w; p++) dst.setPixel(p, y, val); } } return dst; } //################################################################################################## tp_image_utils::ByteMap deNoiseKnoblets(const tp_image_utils::ByteMap& src, size_t knobletWidth, uint8_t solid, uint8_t space) { if(knobletWidth<1) return src; size_t w = src.width(); size_t h = src.height(); if(w<(knobletWidth+2) || h<(knobletWidth+2)) return src; tp_image_utils::ByteMap dst = src; size_t yMax = h-(knobletWidth+1); for(size_t y=1; y<yMax; y++) { uint8_t* d = dst.data()+(y*w)+1; uint8_t* dMax = d + (w-(knobletWidth+1)); for(; d<dMax; d++) { auto calcOnLine = [=](int xincx, int xincy, int yincy, int yincx) { auto val = [=](int x, int y) { size_t px = size_t(x*xincx) + size_t(y*yincx); size_t py = size_t(x*xincy) + size_t(y*yincy); return *(d + ((py*w) + px)); }; //Left side of the kernel if(val(-1, -1)!=space)return; if(val(-1, 0)!=space)return; if(val(-1, 1)!=solid)return; //Center of the kernel for(size_t i=0; i<=knobletWidth; i++) { if(val(int(i), -1)!=space)return; if(val(int(i), 1)!=solid)return; if(val(int(i), 0)==space) { (*d) = space; return; } } }; auto calcOnLeftCorner = [=](int xincx, int xincy, int yincy, int yincx) { auto val = [=](int x, int y) { size_t px = size_t(x*xincx) + size_t(y*yincx); size_t py = size_t(x*xincy) + size_t(y*yincy); return *(d + (py*w) + px); }; //Left side of the kernel if(val(-1, -1)!=space)return; if(val(-1, 0)!=space)return; if(val(-1, 1)!=space)return; //Center of the kernel for(size_t i=0; i<=knobletWidth; i++) { if(val(int(i), -1)!=space)return; if(val(int(i), 1)!=solid)return; if(val(int(i), 0)==space) { (*d) = space; return; } } }; auto calcOnRightCorner = [=](int xincx, int xincy, int yincy, int yincx) { auto val = [=](int x, int y) { size_t px = size_t(x*xincx) + size_t(y*yincx); size_t py = size_t(x*xincy) + size_t(y*yincy); return *(d + ((py*w) + px)); }; //Left side of the kernel if(val(-1, -1)!=space)return; if(val(-1, 0)!=space)return; if(val(-1, 1)!=solid)return; //Center of the kernel for(size_t i=0; i<=knobletWidth; i++) { if(val(int(i), -1)!=space)return; if(val(int(i), 0)==space) { if(val(int(i), 1)==space) (*d) = space; return; } if(val(-1, 1)!=solid)return; } }; if((*d)==space) continue; calcOnLine(1, 0, 1, 0); if((*d)==space) continue; calcOnLine(1, 0, -1, 0); if((*d)==space) continue; calcOnLine(0, 1, 0, 1); if((*d)==space) continue; calcOnLine(0, 1, 0, -1); if((*d)==space) continue; calcOnLeftCorner(1, 0, 1, 0); if((*d)==space) continue; calcOnLeftCorner(1, 0, -1, 0); if((*d)==space) continue; calcOnLeftCorner(0, 1, 0, 1); if((*d)==space) continue; calcOnLeftCorner(0, 1, 0, -1); if((*d)==space) continue; calcOnRightCorner(1, 0, 1, 0); if((*d)==space) continue; calcOnRightCorner(1, 0, -1, 0); if((*d)==space) continue; calcOnRightCorner(0, 1, 0, 1); if((*d)==space) continue; calcOnRightCorner(0, 1, 0, -1); } } return dst; } }
23.233918
100
0.466398
[ "vector", "solid" ]
5d3a26ae175ba7c31449745cdd3bd3e95e6a5876
2,237
cpp
C++
BUPT 2021 Winter Training #7/b.cpp
rakty/2022-spring-training
db36ad3838945d2bb3a951f9ccd8dfa6f0916d0d
[ "MIT" ]
1
2022-03-04T15:11:33.000Z
2022-03-04T15:11:33.000Z
BUPT 2021 Winter Training #7/b.cpp
rakty/2022-spring-training
db36ad3838945d2bb3a951f9ccd8dfa6f0916d0d
[ "MIT" ]
null
null
null
BUPT 2021 Winter Training #7/b.cpp
rakty/2022-spring-training
db36ad3838945d2bb3a951f9ccd8dfa6f0916d0d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define pb push_back #define all(x) (x).begin(), (x).end() #define um unordered_map #define pq priority_queue #define sz(x) ((int)(x).size()) #define x first #define y second #define endl '\n' typedef vector<int> vi; typedef long long ll; typedef unsigned long long ull; typedef pair<int, int> pii; mt19937 mrand(random_device{}()); const ll mod = 1000000007; int rnd(int x) { return mrand() % x;} ll mulmod(ll a, ll b) {ll res = 0; a %= mod; assert(b >= 0); for (; b; b >>= 1) {if (b & 1)res = (res + a) % mod; a = 2 * a % mod;} return res;} ll powmod(ll a, ll b) {ll res = 1; a %= mod; assert(b >= 0); for (; b; b >>= 1) {if (b & 1)res = res * a % mod; a = a * a % mod;} return res;} ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a;} //head vector<string> text; const string str_begin = "\\begin{thebibliography}{99}", str_end = "\\end{thebibliography}", str_cite = "\\cite"; void solve() { while (true) { string line; getline(cin, line); if (line == str_begin) break; text.push_back(line); } vector<string> order; for (auto &s : text) { for (int i = 0; i + 4 < s.length(); ++i) { if (s.substr(i, 5) == str_cite) { int l = s.find('{', i); int r = s.find('}', i); order.push_back(s.substr(l + 1, r - l - 1)); } } } vector< pair<string, string> > item; map<string, string> item_map; while (true) { string line; getline(cin, line); if (line == str_end) break; int l = line.find('{'); int r = line.find('}'); item.push_back({line.substr(l + 1, r - l - 1), line}); } bool correct = true; for (int i = 0; i < order.size(); ++i) { item_map[item[i].first] = item[i].second; if (order[i] != item[i].first) correct = false; } puts(correct ? "Correct" : "Incorrect"); if (correct) return; puts(str_begin.c_str()); for (int i = 0; i < order.size(); ++i) { puts(item_map[order[i]].c_str()); } puts(str_end.c_str()); } int main() { int t = 1; // cin >> t; while (t --) solve(); return 0; }
29.051948
144
0.52034
[ "vector" ]
5d44700d26c8cd5535144c8f5853635031be0170
11,582
cpp
C++
src/core/tree/list.cpp
alicemona/Smala
6f66c3b4bb111993a6bcf148e84c229fb3fa3534
[ "BSD-2-Clause" ]
null
null
null
src/core/tree/list.cpp
alicemona/Smala
6f66c3b4bb111993a6bcf148e84c229fb3fa3534
[ "BSD-2-Clause" ]
null
null
null
src/core/tree/list.cpp
alicemona/Smala
6f66c3b4bb111993a6bcf148e84c229fb3fa3534
[ "BSD-2-Clause" ]
null
null
null
/* * djnn v2 * * The copyright holders for the contents of this file are: * Ecole Nationale de l'Aviation Civile, France (2018) * See file "license.terms" for the rights and conditions * defined by copyright holders. * * * Contributors: * Mathieu Magnaudet <mathieu.magnaudet@enac.fr> * Mathieu Poirier <mathieu.poirier@enac.fr> * */ #include "list.h" #include "spike.h" #include "../control/coupling.h" #include "../execution/graph.h" #include <algorithm> #include "../execution/component_observer.h" #include "../serializer/serializer.h" #include "../error.h" namespace djnn { using namespace std; AbstractList::AbstractList () : Container () { _added = new RefProperty (nullptr); _removed = new RefProperty (nullptr); _size = new IntProperty (0); } AbstractList::AbstractList (Process* parent, const string& name) : Container (parent, name) { _added = new RefProperty (nullptr); _removed = new RefProperty (nullptr); _size = new IntProperty (0); } void AbstractList::dump (int level) { cout << (_parent ? _parent->find_component_name(this) : _name) << " [ index=" << _children.size () << " ]" << endl ; //FIXME: indent problem //for (auto c : _children) // c->dump(level); } void AbstractList::add_child (Process* c, const std::string& name) { if (c == nullptr) return; _children.push_back (c); finalize_child_insertion (c); } void AbstractList::insert (Process* c, const std::string& spec) { if (spec.compare (">") == 0) { add_child (c, ""); return; } std::vector<Process*>::iterator it; if (spec.compare ("<") == 0) { it = _children.begin (); it = _children.insert (it, c); finalize_child_insertion (c); return; } try { int index = std::stoi (spec.substr (1, string::npos)) - 1; if (spec.at (0) == '<') { it = _children.begin () + index; it = _children.insert (it, c); finalize_child_insertion (c); return; } else if (spec.at (0) == '>') { it = _children.begin () + index + 1; it = _children.insert (it, c); finalize_child_insertion (c); return; } else { goto label_error; } } catch (invalid_argument& arg) { goto label_error; } label_error: warning (this, "invalid specification '" + spec + "' for insertion in list '" + _name + "'"); } void AbstractList::remove_child (Process* c) { std::vector<Process*>::iterator newend = _children.end (); /* remove if 'c' is found in the vector */ newend = std::remove_if (_children.begin (), _children.end (), [c](std::vector<Process*>::iterator::value_type v) { return v == c; }); /* check if end has changed and erase if necessary */ if (newend != _children.end ()){ _children.erase(newend, _children.end ()); _removed->set_value (c, true); _size->set_value (_size->get_value () - 1, true); } } void AbstractList::remove_child (const std::string& name) { size_t index; try { /* from user index to internal index : -1 */ index = std::stoi (name, nullptr) - 1; if (index < _children.size ()) { Process* c = _children.at (index); remove_child (c); } else { /* we have to dispay index as the API user index */ warning (this, "index " + std::to_string(index+1) + " is out of bound for list '" + _name + "'"); } } catch (invalid_argument& arg) { warning (this, "invalid child name '" + name + "' for list '" +_name + "'"); } } List::List () : AbstractList () { } List::List (Process* parent, const string& name) : AbstractList (parent, name) { Process::finalize (); } List::~List () { _added = nullptr; _removed = nullptr; if (_added) {delete _added; _added = nullptr;} if (_removed) {delete _removed; _removed = nullptr;} if (_size) {delete _size; _size = nullptr;} } void List::finalize_child_insertion (Process *c) { c->set_parent (this); if (get_state () == activated && c->get_state () == deactivated) { c->activation (); } else if (get_state () == deactivated && c->get_state () == activated) { c->deactivation (); } _added->set_value (c, true); _size->set_value (_size->get_value () + 1, true); } Process* AbstractList::find_component (const string& path) { if (path.compare ("$added") == 0) return _added; else if (path.compare ("$removed") == 0) return _removed; else if (path.compare ("size") == 0) return _size; else { try { string::size_type sz; size_t index = std::stoi (path, &sz) - 1; if (index < _children.size ()) { Process* c = _children.at (index); if (path.length () > sz) { return c->find_component (path.substr (sz + 1)); } else return c; } else { /* we have to dispay index as the API user index */ warning (this, "index " + std::to_string(index+1) + " is out of bound for list \'" + _name + "\'"); } } catch (invalid_argument& arg) { warning (this, "invalid child path '" + path + "' for list '" + _name + "'"); } } return nullptr; } Process* List::clone () { List* clone = new List (); for (auto c: _children) { clone->add_child (c->clone (), ""); } return clone; } void List::serialize (const string& type) { AbstractSerializer::pre_serialize(this, type); AbstractSerializer::serializer->start ("core:list"); AbstractSerializer::serializer->text_attribute ("id", _name); for (auto c : _children) c->serialize (type); AbstractSerializer::serializer->end (); AbstractSerializer::post_serialize(this); } BidirectionalListIterator::IterAction::IterAction (Process *parent, const string& name, List *list, RefProperty *iter, IntProperty *index, bool forward) : Process (parent, name), _list (list), _iter (iter), _index (index), _forward (forward) { } void BidirectionalListIterator::IterAction::activate () { if (_parent->get_state () > activated) return; int index = _index->get_value (); if (_forward) { if (_list->size () > index) { _iter->set_value (_list->children ().at (index - 1), true); _index->set_value (index + 1, true); } } else { if (index >= 1) { _iter->set_value (_list->children ().at (index - 1), true); _index->set_value (index - 1, true); } } } BidirectionalListIterator::ResetAction::ResetAction (Process *parent, const string& name, IntProperty *index) : Process (parent, name), _index (index) { } void BidirectionalListIterator::ResetAction::activate () { if (_parent->get_state () > activated) return; _index->set_value (1, true); } BidirectionalListIterator::BidirectionalListIterator (Process *parent, const string& name, Process* list) : Process (parent, name) { _list = dynamic_cast<List*> (list); if (_list == nullptr) { warning (this, "list iterator must take a List as its third argument\n"); return; } _next = new Spike (this, "next"); _previous = new Spike (this, "previous"); _reset = new Spike (this, "reset"); _iter = new RefProperty (this, "iter", nullptr); _index = new IntProperty (this, "index", 1); _next_action = new IterAction (this, name + "_next_action", _list, _iter, _index, true); _previous_action = new IterAction (this, name + "_previous_action", _list, _iter, _index, false); _reset_action = new ResetAction (this, name + "_reset_action", _index); _c_next = new Coupling (_next, ACTIVATION, _next_action, ACTIVATION); _c_next->disable (); _c_previous = new Coupling (_previous, ACTIVATION, _previous_action, ACTIVATION); _c_previous->disable (); _c_reset = new Coupling (_reset, ACTIVATION, _reset_action, ACTIVATION); _c_next->disable (); Graph::instance ().add_edge (_next, _next_action); Graph::instance ().add_edge (_previous, _previous_action); Graph::instance ().add_edge (_reset, _reset_action); if (_parent && _parent->state_dependency () != nullptr) { Graph::instance ().add_edge (_parent->state_dependency (), _next_action); Graph::instance ().add_edge (_parent->state_dependency (), _previous_action); Graph::instance ().add_edge (_parent->state_dependency (), _reset_action); } Process::finalize (); } BidirectionalListIterator::~BidirectionalListIterator () { if (_parent && _parent->state_dependency () != nullptr) { Graph::instance ().remove_edge (_parent->state_dependency (), _next_action); Graph::instance ().remove_edge (_parent->state_dependency (), _previous_action); Graph::instance ().remove_edge (_parent->state_dependency (), _reset_action); } Graph::instance ().remove_edge (_next, _next_action); Graph::instance ().remove_edge (_previous, _previous_action); Graph::instance ().remove_edge (_reset, _reset_action); if (_c_reset) { delete _c_reset; _c_reset = nullptr;} if (_c_previous) { delete _c_previous; _c_previous = nullptr;} if (_c_next) { delete _c_next; _c_next = nullptr;} if (_reset_action) { delete _reset_action; _reset_action = nullptr;} if (_previous_action) { delete _previous_action; _previous_action = nullptr;} if (_next_action) { delete _next_action; _next_action = nullptr;} if (_index) { delete _index; _index = nullptr;} if (_iter) { delete _iter; _iter = nullptr;} if (_reset) { delete _reset; _reset = nullptr;} if (_previous) { delete _previous; _previous = nullptr;} if (_next) { delete _next; _next = nullptr;} } void BidirectionalListIterator::activate () { _c_next->enable (); _c_previous->enable (); _c_reset->enable (); } void BidirectionalListIterator::deactivate () { _c_next->disable (); _c_previous->disable (); _c_reset->disable (); } void BidirectionalListIterator::serialize (const string& type) { string buf; AbstractSerializer::pre_serialize(this, type); AbstractSerializer::serializer->start ("core:bidirectionallistiterator"); AbstractSerializer::serializer->text_attribute ("id", _name); AbstractSerializer::compute_path (get_parent (), _list, buf); AbstractSerializer::serializer->text_attribute ("list", buf); AbstractSerializer::serializer->end (); AbstractSerializer::post_serialize(this); } ListIterator::ListIterator (Process *parent, const string &name, Process *list, Process *action, bool model) : Process (parent, name, model), _action (action) { Container *l = dynamic_cast<Container*> (list); if (l == nullptr) error (this, "The list argument must be a List component in list iterator " + name); _list = l; Process::finalize (); } void ListIterator::activate () { for (auto p : _list->children ()) { _action->set_data (p); _action->activation (); } notify_activation (); } void ListIterator::post_activate () { _activation_state = deactivated; } }
29.697436
121
0.604386
[ "vector", "model" ]
5d47937e19833d140d4b4d9d7e6c38b01ba1b240
14,091
cpp
C++
src/plugins/georeferencer/qgstransformsettingsdialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/plugins/georeferencer/qgstransformsettingsdialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/plugins/georeferencer/qgstransformsettingsdialog.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgstransformsettingsdialog.cpp -------------------------------------- Date : 14-Feb-2010 Copyright : (C) 2010 by Jack R, Maxim Dubinin (GIS-Lab) Email : sim@gis-lab.info *************************************************************************** * * * 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. * * * ***************************************************************************/ #include <QFileDialog> #include <QFileInfo> #include <QMessageBox> #include "qgssettings.h" #include "qgsprojectionselectiontreewidget.h" #include "qgsapplication.h" #include "qgsfilewidget.h" #include "qgsrasterlayer.h" #include "qgstransformsettingsdialog.h" #include "qgscoordinatereferencesystem.h" QgsTransformSettingsDialog::QgsTransformSettingsDialog( const QString &raster, const QString &output, int countGCPpoints, QWidget *parent ) : QDialog( parent ) , mSourceRasterFile( raster ) , mCountGCPpoints( countGCPpoints ) { setupUi( this ); QgsSettings settings; restoreGeometry( settings.value( QStringLiteral( "/Plugin-GeoReferencer/TransformSettingsWindow/geometry" ) ).toByteArray() ); mOutputRaster->setStorageMode( QgsFileWidget::SaveFile ); if ( output.isEmpty() ) { mOutputRaster->setFilePath( generateModifiedRasterFileName( mSourceRasterFile ) ); } else { mOutputRaster->setFilePath( output ); } mOutputRaster->setFilter( tr( "TIF files" ) + " (*.tif *.tiff *.TIF *.TIFF)" ); mOutputRaster->setDialogTitle( tr( "Destination Raster" ) ); mOutputRaster->setDefaultRoot( settings.value( QStringLiteral( "UI/lastRasterFileFilterDir" ), QDir::homePath() ).toString() ); connect( mOutputRaster, &QgsFileWidget::fileChanged, this, [ = ] { QgsSettings settings; QFileInfo tmplFileInfo( mOutputRaster->filePath() ); settings.setValue( QStringLiteral( "UI/lastRasterFileFilterDir" ), tmplFileInfo.absolutePath() ); } ); mPdfMap->setStorageMode( QgsFileWidget::SaveFile ); mPdfMap->setFilter( tr( "PDF files" ) + " (*.pdf *.PDF)" ); mPdfMap->setDialogTitle( tr( "Save Map File As" ) ); mPdfMap->setDefaultRoot( settings.value( QStringLiteral( "/Plugin-GeoReferencer/lastPDFReportDir" ), QDir::homePath() ).toString() ); connect( mPdfMap, &QgsFileWidget::fileChanged, this, [ = ] { QgsSettings settings; QFileInfo tmplFileInfo( mPdfMap->filePath() ); settings.setValue( QStringLiteral( "Plugin-GeoReferencer/lastPDFReportDir" ), tmplFileInfo.absolutePath() ); } ); mPdfReport->setStorageMode( QgsFileWidget::SaveFile ); mPdfReport->setFilter( tr( "PDF files" ) + " (*.pdf *.PDF)" ); mPdfReport->setDialogTitle( tr( "Save Report File As" ) ); mPdfReport->setDefaultRoot( settings.value( QStringLiteral( "/Plugin-GeoReferencer/lastPDFReportDir" ), QDir::homePath() ).toString() ); connect( mPdfReport, &QgsFileWidget::fileChanged, this, [ = ] { QgsSettings settings; QFileInfo tmplFileInfo( mPdfReport->filePath() ); settings.setValue( QStringLiteral( "Plugin-GeoReferencer/lastPDFReportDir" ), tmplFileInfo.absolutePath() ); } ); connect( cmbTransformType, static_cast<void ( QComboBox::* )( const QString & )>( &QComboBox::currentIndexChanged ), this, &QgsTransformSettingsDialog::cmbTransformType_currentIndexChanged ); connect( mWorldFileCheckBox, &QCheckBox::stateChanged, this, &QgsTransformSettingsDialog::mWorldFileCheckBox_stateChanged ); cmbTransformType->addItem( tr( "Linear" ), static_cast<int>( QgsGeorefTransform::Linear ) ); cmbTransformType->addItem( tr( "Helmert" ), static_cast<int>( QgsGeorefTransform::Helmert ) ); cmbTransformType->addItem( tr( "Polynomial 1" ), static_cast<int>( QgsGeorefTransform::PolynomialOrder1 ) ); cmbTransformType->addItem( tr( "Polynomial 2" ), static_cast<int>( QgsGeorefTransform::PolynomialOrder2 ) ); cmbTransformType->addItem( tr( "Polynomial 3" ), static_cast<int>( QgsGeorefTransform::PolynomialOrder3 ) ); cmbTransformType->addItem( tr( "Thin Plate Spline" ), static_cast<int>( QgsGeorefTransform::ThinPlateSpline ) ); cmbTransformType->addItem( tr( "Projective" ), static_cast<int>( QgsGeorefTransform::Projective ) ); // Populate CompressionComboBox mListCompression.append( QStringLiteral( "None" ) ); mListCompression.append( QStringLiteral( "LZW" ) ); mListCompression.append( QStringLiteral( "PACKBITS" ) ); mListCompression.append( QStringLiteral( "DEFLATE" ) ); QStringList listCompressionTr; Q_FOREACH ( const QString &item, mListCompression ) { listCompressionTr.append( tr( item.toLatin1().data() ) ); } cmbCompressionComboBox->addItems( listCompressionTr ); cmbTransformType->setCurrentIndex( settings.value( QStringLiteral( "/Plugin-GeoReferencer/lasttransformation" ), -1 ).toInt() ); cmbResampling->setCurrentIndex( settings.value( QStringLiteral( "/Plugin-GeoReferencer/lastresampling" ), 0 ).toInt() ); cmbCompressionComboBox->setCurrentIndex( settings.value( QStringLiteral( "/Plugin-GeoReferencer/lastcompression" ), 0 ).toInt() ); QString targetCRSString = settings.value( QStringLiteral( "/Plugin-GeoReferencer/targetsrs" ) ).toString(); QgsCoordinateReferenceSystem targetCRS = QgsCoordinateReferenceSystem::fromOgcWmsCrs( targetCRSString ); mCrsSelector->setCrs( targetCRS ); mWorldFileCheckBox->setChecked( settings.value( QStringLiteral( "/Plugin-Georeferencer/word_file_checkbox" ), false ).toBool() ); cbxUserResolution->setChecked( settings.value( QStringLiteral( "/Plugin-Georeferencer/user_specified_resolution" ), false ).toBool() ); bool ok; dsbHorizRes->setValue( settings.value( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resx" ), .0 ).toDouble( &ok ) ); if ( !ok ) dsbHorizRes->setValue( 1.0 ); dsbVerticalRes->setValue( settings.value( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resy" ), -1.0 ).toDouble( &ok ) ); if ( !ok ) dsbHorizRes->setValue( -1.0 ); cbxZeroAsTrans->setChecked( settings.value( QStringLiteral( "/Plugin-GeoReferencer/zeroastrans" ), false ).toBool() ); cbxLoadInQgisWhenDone->setChecked( settings.value( QStringLiteral( "/Plugin-GeoReferencer/loadinqgis" ), false ).toBool() ); saveGcpCheckBox->setChecked( settings.value( QStringLiteral( "/Plugin-GeoReferencer/save_gcp_points" ), false ).toBool() ); } QgsTransformSettingsDialog::~QgsTransformSettingsDialog() { QgsSettings settings; settings.setValue( QStringLiteral( "Plugin-GeoReferencer/TransformSettingsWindow/geometry" ), saveGeometry() ); } void QgsTransformSettingsDialog::getTransformSettings( QgsGeorefTransform::TransformParametrisation &tp, QgsImageWarper::ResamplingMethod &rm, QString &comprMethod, QString &raster, QgsCoordinateReferenceSystem &proj, QString &pdfMapFile, QString &pdfReportFile, QString &gcpPoints, bool &zt, bool &loadInQgis, double &resX, double &resY ) { if ( cmbTransformType->currentIndex() == -1 ) tp = QgsGeorefTransform::InvalidTransform; else tp = ( QgsGeorefTransform::TransformParametrisation )cmbTransformType->currentData().toInt(); rm = ( QgsImageWarper::ResamplingMethod )cmbResampling->currentIndex(); comprMethod = mListCompression.at( cmbCompressionComboBox->currentIndex() ).toUpper(); if ( mWorldFileCheckBox->isChecked() ) { raster.clear(); } else { raster = mOutputRaster->filePath(); } proj = mCrsSelector->crs(); pdfMapFile = mPdfMap->filePath(); pdfReportFile = mPdfReport->filePath(); zt = cbxZeroAsTrans->isChecked(); loadInQgis = cbxLoadInQgisWhenDone->isChecked(); resX = 0.0; resY = 0.0; if ( cbxUserResolution->isChecked() ) { resX = dsbHorizRes->value(); resY = dsbVerticalRes->value(); } if ( saveGcpCheckBox->isChecked() ) { gcpPoints = mOutputRaster->filePath(); } } void QgsTransformSettingsDialog::resetSettings() { QgsSettings s; s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lasttransformation" ), -1 ); s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastresampling" ), 0 ); s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastcompression" ), 0 ); s.setValue( QStringLiteral( "/Plugin-GeoReferencer/targetsrs" ), QString() ); s.setValue( QStringLiteral( "/Plugin-GeoReferencer/zeroastrans" ), false ); s.setValue( QStringLiteral( "/Plugin-GeoReferencer/loadinqgis" ), false ); s.setValue( QStringLiteral( "/Plugin-GeoReferencer/save_gcp_points" ), false ); s.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resolution" ), false ); s.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resx" ), 1.0 ); s.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resy" ), -1.0 ); s.setValue( QStringLiteral( "/Plugin-GeoReferencer/word_file_checkbox" ), false ); s.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastPDFReportDir" ), QDir::homePath() ); } void QgsTransformSettingsDialog::changeEvent( QEvent *e ) { QDialog::changeEvent( e ); switch ( e->type() ) { case QEvent::LanguageChange: retranslateUi( this ); break; default: break; } } void QgsTransformSettingsDialog::accept() { if ( !mOutputRaster->filePath().isEmpty() ) { //if the file path is relative, make it relative to the raster file directory QString outputRasterName = mOutputRaster->filePath(); QFileInfo rasterFileInfo( mSourceRasterFile ); QFileInfo outputFileInfo( rasterFileInfo.absoluteDir(), outputRasterName ); if ( outputFileInfo.fileName().isEmpty() || !outputFileInfo.dir().exists() ) { QMessageBox::warning( this, tr( "Destination Raster" ), tr( "Invalid output file name." ) ); return; } if ( outputFileInfo.filePath() == mSourceRasterFile ) { //can't overwrite input file QMessageBox::warning( this, tr( "Destination Raster" ), tr( "Input raster can not be overwritten." ) ); return; } mOutputRaster->setFilePath( outputFileInfo.absoluteFilePath() ); } QgsSettings settings; settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/lasttransformation" ), cmbTransformType->currentIndex() ); settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastresampling" ), cmbResampling->currentIndex() ); settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/lastcompression" ), cmbCompressionComboBox->currentIndex() ); settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/targetsrs" ), mCrsSelector->crs().authid() ); settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/zeroastrans" ), cbxZeroAsTrans->isChecked() ); settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/loadinqgis" ), cbxLoadInQgisWhenDone->isChecked() ); settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resolution" ), cbxUserResolution->isChecked() ); settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resx" ), dsbHorizRes->value() ); settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/user_specified_resy" ), dsbVerticalRes->value() ); settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/word_file_checkbox" ), mWorldFileCheckBox->isChecked() ); settings.setValue( QStringLiteral( "/Plugin-GeoReferencer/save_gcp_points" ), saveGcpCheckBox->isChecked() ); QDialog::accept(); } void QgsTransformSettingsDialog::cmbTransformType_currentIndexChanged( const QString &text ) { if ( text == tr( "Linear" ) ) { mWorldFileCheckBox->setEnabled( true ); } else { mWorldFileCheckBox->setEnabled( false ); // reset world file checkbox when transformation differ from Linear mWorldFileCheckBox->setChecked( false ); } } void QgsTransformSettingsDialog::mWorldFileCheckBox_stateChanged( int state ) { bool enableOutputRaster = true; if ( state == Qt::Checked ) { enableOutputRaster = false; } label_2->setEnabled( enableOutputRaster ); mOutputRaster->setEnabled( enableOutputRaster ); } bool QgsTransformSettingsDialog::checkGCPpoints( int count, int &minGCPpoints ) { QgsGeorefTransform georefTransform; georefTransform.selectTransformParametrisation( ( QgsGeorefTransform::TransformParametrisation )count ); minGCPpoints = georefTransform.getMinimumGCPCount(); return ( mCountGCPpoints >= minGCPpoints ); } QString QgsTransformSettingsDialog::generateModifiedRasterFileName( const QString &raster ) { if ( raster.isEmpty() ) return QString(); QString modifiedFileName = raster; QFileInfo modifiedFileInfo( modifiedFileName ); int pos = modifiedFileName.size() - modifiedFileInfo.suffix().size() - 1; modifiedFileName.insert( pos, tr( "_modified", "Georeferencer:QgsOpenRasterDialog.cpp - used to modify a user given file name" ) ); pos = modifiedFileName.size() - modifiedFileInfo.suffix().size(); modifiedFileName.replace( pos, modifiedFileName.size(), QStringLiteral( "tif" ) ); return modifiedFileName; } // Note this code is duplicated from qgisapp.cpp because // I didn't want to make plugins on qgsapplication [TS] QIcon QgsTransformSettingsDialog::getThemeIcon( const QString &name ) { if ( QFile::exists( QgsApplication::activeThemePath() + name ) ) { return QIcon( QgsApplication::activeThemePath() + name ); } else if ( QFile::exists( QgsApplication::defaultThemePath() + name ) ) { return QIcon( QgsApplication::defaultThemePath() + name ); } else { QgsSettings settings; QString themePath = ":/icons/" + settings.value( QStringLiteral( "Themes" ) ).toString() + name; if ( QFile::exists( themePath ) ) { return QIcon( themePath ); } else { return QIcon( ":/icons/default" + name ); } } }
44.311321
193
0.705983
[ "geometry" ]
5d548feeee04ef513f1c24b2f1a72fa8b1c24ad3
6,582
cpp
C++
FileManager.cpp
hiraditya/cpp2cxx
36eb36b1fa04b54ee2be560bd86e8b4ac629d5a4
[ "Apache-2.0" ]
36
2015-02-16T19:35:45.000Z
2021-03-17T12:33:53.000Z
FileManager.cpp
hiraditya/cpp2cxx
36eb36b1fa04b54ee2be560bd86e8b4ac629d5a4
[ "Apache-2.0" ]
3
2015-12-04T01:37:50.000Z
2018-01-09T17:06:18.000Z
FileManager.cpp
hiraditya/cpp2cxx
36eb36b1fa04b54ee2be560bd86e8b4ac629d5a4
[ "Apache-2.0" ]
7
2015-04-09T16:50:27.000Z
2020-07-10T08:38:37.000Z
/** cpp2cxx is an open source software distributed under terms of the Apache2.0 licence. Copyrights remain with the original copyright holders. Use of this material is by permission and/or license. Copyright [2012] Aditya Kumar, Andrew Sutton, Bjarne Stroustrup 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 "Overseer.h" //observable #include "FileManager.h" #include "FileManagerScheme.h" #include "ExceptionHandler.h" FileManager::FileManager(FileManagerScheme const& fs, DemacroficationScheme const& ds) : fileManagerScheme(fs), demacroficationScheme(ds), inputFileIndex(0), outputFileIndex(0) { if(!SanityCheck()) throw ExceptionHandler("Failed Sanity Check in the File Manager"); PrepareMacroStatFile(); PrepareDemacrofiedMacroStatFile(); } void FileManager::Configure(FileManagerScheme const& fs) { //fileManagerScheme = fs; } std::vector<std::string>const& FileManager::OutputFiles() { return fileManagerScheme.outputFiles; } std::vector<std::string>const& FileManager::InputFiles() { return fileManagerScheme.inputFiles; } std::string const& FileManager::OutputDirectory() { return fileManagerScheme.outputDirectory; } std::string const& FileManager::InputDirectory() { return fileManagerScheme.inputDirectory; } //check whether this file is there in the list of output_files or not void FileManager::UpdateFile(std::ostream& fp, std::string const& file_str) { fp<<file_str; } void FileManager::UpdateFile(std::string const& file_str) { std::string output_file = GetOutputFile(); if(output_file.length()){ std::ofstream fp(output_file); if(fp.is_open()) { UpdateFile(fp,file_str); fp.close(); } else { std::string error_msg = "could not open the file " + fileManagerScheme.outputFiles[outputFileIndex] + " for writing"; WriteLog(error_msg); throw ExceptionHandler(error_msg); } } else { ///For no output file name output shall be ///redirected to the standard output"; std::string log_msg; log_msg = "for input file" + fileManagerScheme.inputFiles[outputFileIndex] + "no output file was found" + "output shall be redirected to the standard output"; WriteLog(log_msg); UpdateFile(std::cout,file_str); } } void FileManager::UpdateFile(Overseer const& overseer) { std::string output_file = GetOutputFile(); if(output_file.length()){ std::ofstream fp(output_file); if(fp.is_open()) { overseer.WriteOutputFile(fp); fp.close(); } else { /// @brief if output file is null then the output will be /// printed on the screen std::string error_msg = "could not open the file " + fileManagerScheme.outputFiles[outputFileIndex] + " for writing output shall be redirected to the standard output"; WriteLog(error_msg); overseer.WriteOutputFile(std::cout); } } else { ///For no output file name output shall be ///redirected to the standard output"; std::string log_msg; log_msg = "for input file" + fileManagerScheme.inputFiles[outputFileIndex] + "no output file was found" + "output shall be redirected to the standard output"; WriteLog(log_msg); overseer.WriteOutputFile(std::cout); } } std::string FileManager::GetOutputFile() { std::string output_file_name = fileManagerScheme.outputFiles[outputFileIndex]; ++outputFileIndex; return output_file_name; } std::vector<std::string> const& FileManager::GetSearchPaths() const { return fileManagerScheme.searchPaths; } std::vector<std::string> const& FileManager::GetInputFiles()const { return fileManagerScheme.inputFiles; } ///@todo perform checks bool FileManager::SanityCheck() { return true; } void FileManager::WriteLog(std::string const& str) { *(fileManagerScheme.pLogFile) << str << "\n"; } void FileManager::PrepareDemacrofiedMacroStatFile() { std::string header; if(demacroficationScheme.performCleanup){ header = "###################################################################\n" "#This file contains the details of each macro processed by the demacrofier\n" "#The file can be read by any yaml parser\n" "#The format is as follows:\n" "#file-name:" "# - id: identifier string\n" "###################################################################\n"; } else{ header = "###################################################################\n" "#This file contains the details of each macro processed by the demacrofier\n" "#The file can be read by any yaml parser\n" "#The format is as follows:\n" "#macro<count>\n" "# - id: identifier string\n" "# - category: macro_category\n" "# - header_guard_string: string\n" "###################################################################\n"; } GetDemacrofiedMacroStatFile()<<header; } void FileManager::PrepareMacroStatFile() { std::string header; header = "###################################################################\n" "#This file contains the details of each macro present in the files processed\n" "#The file can be read by any yaml parser\n" "#The format is as follows:\n" "#macro<count>\n" "# - m_id : identifier string\n" "# - m_cat: macro_category\n" "# - c_cat: if the replacement text maps to C++ expression then c_cat is complete otherwise partial\n" "# - d_cat: if the replacement text contains free variable(s) then d_cat is dependent otherwise closed\n" "###################################################################\n"; GetMacroStatFile()<<header; } std::ostream& FileManager::GetLogFile() { return *(fileManagerScheme.pLogFile); } std::ostream& FileManager::GetMacroStatFile() { return *(fileManagerScheme.pMacroStatFile); } std::ostream& FileManager::GetDemacrofiedMacroStatFile() { return *(fileManagerScheme.pDemacrofiedMacroStatFile); }
29.383929
112
0.646156
[ "vector" ]
5d56467b9b2c520a20eaf422d3e3bcd31deadba0
2,711
cpp
C++
cpp/source/zInterOp/functionSets/zUnrealFnMesh.cpp
venumb/zSpace
a85de6d29c9099fcbd3d2c67f5f1be315eed6dc4
[ "MIT" ]
1
2020-05-19T16:52:23.000Z
2020-05-19T16:52:23.000Z
cpp/source/zInterOp/functionSets/zUnrealFnMesh.cpp
GitZHCODE/zspace_toolsets
8bcc0c47bc74f2dde06f0f2de8bdb976b67fbe0a
[ "MIT" ]
1
2019-06-24T09:16:37.000Z
2019-06-26T18:21:36.000Z
cpp/source/zInterOp/functionSets/zUnrealFnMesh.cpp
GitZHCODE/zspace_toolsets
8bcc0c47bc74f2dde06f0f2de8bdb976b67fbe0a
[ "MIT" ]
null
null
null
// This file is part of zspace, a simple C++ collection of geometry data-structures & algorithms, // data analysis & visualization framework. // // Copyright (C) 2019 ZSPACE // // This Source Code Form is subject to the terms of the MIT License // If a copy of the MIT License was not distributed with this file, You can // obtain one at https://opensource.org/licenses/MIT. // // Author : Vishu Bhooshan <vishu.bhooshan@zaha-hadid.com> // #include<headers/zInterOp/functionSets/zUnrealFnMesh.h> #if defined(ZSPACE_UNREAL_INTEROP) namespace zSpace { //---- CONSTRUCTOR ZSPACE_INLINE zUnrealFnMesh::zUnrealFnMesh() {} ZSPACE_INLINE zUnrealFnMesh::zUnrealFnMesh(zObjMesh &_zspace_meshObj) { meshObj = &_zspace_meshObj;; } //---- DESTRUCTOR ZSPACE_INLINE zUnrealFnMesh::~zUnrealFnMesh() {} //---- INTEROP METHODS ZSPACE_INLINE void zUnrealFnMesh::toUnrealMesh(FDynamicMesh3 &unreal_mesh) { //int numVertices = unreal_mesh.VertexCount(); //int numFaces = unreal_mesh.TriangleCount(); //int numPolyConnects = 0; //zPointArray pos; //zIntArray polyCounts; //zIntArray polyConnects; //pos.assign(numVertices, zPoint()); //check(unreal_mesh.IsCompactV()); //for (int32 vid : unreal_mesh.VertexIndicesItr()) //{ // FVector3d Pos = unreal_mesh.GetVertex(vid); //} //for (int32 tid : unreal_mesh.TriangleIndicesItr()) //{ // FIndex3i Tri = unreal_mesh.GetTriangle(tid); //} //create(pos, polyCounts, polyConnects); } ZSPACE_INLINE void zUnrealFnMesh::toUnrealMesh(FDynamicMesh3 &unreal_mesh) { //// vertices //zVector* pos = getRawVertexPositions(); //for (int i = 0; i < numVertices(); i++) //{ // rhino_mesh.m_V.Append(ON_3fPoint(pos[i].x, pos[i].y, pos[i].z)); //} //// faces //for (zItMeshFace f(*meshObj); !f.end(); f++) //{ // zIntArray fVerts; // f.getVertices(fVerts); // if (fVerts.size() == 3 || fVerts.size() == 4) // { // ON_MeshFace r_face; // r_face.vi[0] = fVerts[0]; // r_face.vi[1] = fVerts[1]; // r_face.vi[2] = fVerts[2]; // if(fVerts.size() == 4) r_face.vi[3] = fVerts[3]; // else r_face.vi[3] = r_face.vi[2]; // rhino_mesh.m_F.Append(r_face); // } // else // { // int numT; // zIntArray tris; // f.getTriangles(numT, tris); // for (int i = 0; i < numT; i++) // { // ON_MeshFace r_face; // r_face.vi[0] = tris[i * 3 + 0]; // r_face.vi[1] = tris[i * 3 + 1]; // r_face.vi[2] = tris[i * 3 + 2]; // rhino_mesh.m_F.Append(r_face); // } // } //} //rhino_mesh.ComputeFaceNormals(); //rhino_mesh.ComputeVertexNormals(); //printf("\n RhinoMesh : v %i f%i ", rhino_mesh.VertexCount(), rhino_mesh.FaceCount()); } } #endif
22.781513
98
0.636297
[ "geometry" ]
5d5815d0f74583e863544e1c5c2fb288f299f429
3,411
cc
C++
src/profiling/symbolizer/breakpad_symbolizer.cc
ga-ram/perfetto
75dc39438ed158c39a3d0b4814327d36299f6033
[ "Apache-2.0" ]
null
null
null
src/profiling/symbolizer/breakpad_symbolizer.cc
ga-ram/perfetto
75dc39438ed158c39a3d0b4814327d36299f6033
[ "Apache-2.0" ]
null
null
null
src/profiling/symbolizer/breakpad_symbolizer.cc
ga-ram/perfetto
75dc39438ed158c39a3d0b4814327d36299f6033
[ "Apache-2.0" ]
1
2021-10-08T09:55:48.000Z
2021-10-08T09:55:48.000Z
/* * Copyright (C) 2021 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 "src/profiling/symbolizer/breakpad_symbolizer.h" #include "perfetto/ext/base/file_utils.h" #include "perfetto/ext/base/optional.h" #include "perfetto/ext/base/string_view.h" #include "perfetto/ext/base/string_writer.h" #include "src/profiling/symbolizer/breakpad_parser.h" namespace perfetto { namespace profiling { namespace { // Returns the file path for a breakpad symbol file with the given |build_id|. std::string MakeFilePath(const std::string& build_id, const std::string& symbol_dir_path) { char file_path[1000]; // The directory of the symbol file is stored in an environment variable. constexpr char kBreakpadSuffix[] = ".breakpad"; // Append file name to symbol directory path using |build_id| and // |kBreakpadSuffix|. base::StringWriter file_path_writer(file_path, base::ArraySize(file_path)); file_path_writer.AppendString(symbol_dir_path.c_str(), symbol_dir_path.size()); // TODO(uwemwilson): append a path separator here for file path. file_path_writer.AppendString(build_id.c_str(), build_id.size()); file_path_writer.AppendString(kBreakpadSuffix, strlen(kBreakpadSuffix)); return file_path_writer.GetStringView().ToStdString(); } } // namespace BreakpadSymbolizer::BreakpadSymbolizer(const std::string& symbol_dir_path) : symbol_dir_path_(symbol_dir_path) {} std::vector<std::vector<SymbolizedFrame>> BreakpadSymbolizer::Symbolize( const std::string&, const std::string& build_id, uint64_t, const std::vector<uint64_t>& address) { std::vector<std::vector<SymbolizedFrame>> result; size_t num_symbolized_frames = 0; result.reserve(address.size()); std::string file_path; // Check to see if the |file_path_for_testing_| member is populated. If it is, // this file must be used. if (file_path_for_testing_.empty()) { file_path = MakeFilePath(build_id, symbol_dir_path_).c_str(); } else { file_path = file_path_for_testing_; } BreakpadParser parser(file_path); if (!parser.ParseFile()) { PERFETTO_ELOG("Failed to parse file %s.", file_path.c_str()); PERFETTO_PLOG("Symbolized %zu of %zu frames.", num_symbolized_frames, address.size()); return result; } // Add each address's function name to the |result| vector in the same order. for (uint64_t addr : address) { SymbolizedFrame frame; base::Optional<std::string> opt_func_name = parser.GetSymbol(addr); if (opt_func_name) { frame.function_name = *opt_func_name; num_symbolized_frames++; } result.push_back({std::move(frame)}); } PERFETTO_PLOG("Symbolized %zu of %zu frames.", num_symbolized_frames, address.size()); return result; } } // namespace profiling } // namespace perfetto
35.905263
80
0.718264
[ "vector" ]
5d5a22f6a73218ca2e0b09a5a60a17069599c720
3,242
cpp
C++
TestsWithGL/test_fem_chm_s_1d_consolidation.cpp
MingAtUWA/SimpleMPM2
7a1d7c257c621123d85a0630e93d42ae25c70fb4
[ "MIT" ]
null
null
null
TestsWithGL/test_fem_chm_s_1d_consolidation.cpp
MingAtUWA/SimpleMPM2
7a1d7c257c621123d85a0630e93d42ae25c70fb4
[ "MIT" ]
null
null
null
TestsWithGL/test_fem_chm_s_1d_consolidation.cpp
MingAtUWA/SimpleMPM2
7a1d7c257c621123d85a0630e93d42ae25c70fb4
[ "MIT" ]
null
null
null
#include "TestsWithGL_pcp.h" #include "Model_S2D_CHM_s_FEM_uUp.h" #include "Step_S2D_CHM_s_FEM_uUp.h" #include "ModelDataOutput_S2D_CHM_s_FEM_uUp.h" #include "TimeHistoryOutput_S2D_CHM_s_FEM_uUp.h" #include "TimeHistoryOutput_ConsoleProgressBar.h" #include "test_sim_core.h" //#include "test_post_processor.h" //#include "GA_S2D_CHM_s.h" static size_t width = 1; static size_t len = 1; static double bgm_h = 1.0 / double(len); void test_fem_chm_s_1d_consolidation(void) { Model_S2D_CHM_s_FEM_uUp model; // background mesh model.init_mesh(bgm_h, width, len); model.init_mat_param(0.3, 2650.0, 1000.0, 1000.0, 0.25, 50000.0, 1.0e-4, 1.0); // traction bc model.ty_num = width; model.tys = new TractionBC_2DFEM[model.ty_num]; for (size_t i = 0; i < model.ty_num; i++) { TractionBC_2DFEM &ty = model.tys[i]; ty.elem_id = len - 1; ty.xi0 = -1.0; ty.xi1 = 1.0; ty.eta0 = 1.0; ty.eta1 = 1.0; ty.t0 = -1.0; ty.t1 = -1.0; } // velocity bc model.usy_num = width + 1; model.usys = new DisplacementBC[model.usy_num]; for (size_t bc_id = 0; bc_id < model.usy_num; ++bc_id) { DisplacementBC &dbc = model.usys[bc_id]; dbc.node_id = bc_id; dbc.u = 0.0; } model.usx_num = (len + 1) * 2; model.usxs = new DisplacementBC[model.usx_num]; model.ufx_num = model.usx_num; model.ufxs = new DisplacementBC[model.ufx_num]; for (size_t bc_id = 0; bc_id < len + 1; ++bc_id) { DisplacementBC &dbc1 = model.usxs[bc_id]; dbc1.node_id = (width + 1) * bc_id; dbc1.u = 0.0; DisplacementBC &dbc2 = model.usxs[len + 1 + bc_id]; dbc2.node_id = (width + 1) * (bc_id + 1) - 1; dbc2.u = 0.0; DisplacementBC &dbc3 = model.ufxs[bc_id]; dbc3.node_id = (width + 1) * bc_id; dbc3.u = 0.0; DisplacementBC &dbc4 = model.ufxs[len + 1 + bc_id]; dbc4.node_id = (width + 1) * (bc_id + 1) - 1; dbc4.u = 0.0; } model.ufy_num = width + 1; model.ufys = new DisplacementBC[model.ufy_num]; for (size_t bc_id = 0; bc_id < model.ufy_num; ++bc_id) { DisplacementBC &dbc1 = model.ufys[bc_id]; dbc1.node_id = bc_id; dbc1.u = 0.0; } // freely drainage bc model.pbc_num = width + 1; model.pbcs = new PressureBC[model.pbc_num]; for (size_t bc_id = 0; bc_id < model.pbc_num; ++bc_id) { PressureBC &pbc = model.pbcs[bc_id]; pbc.node_id = (width + 1) * len + bc_id; pbc.p = 0.0; } //ResultFile_PlainBin res_file_pb; //res_file_pb.init("mpm_me_up_res_1dbar.bin"); ResultFile_XML res_file_xml; res_file_xml.init("fem_chm_uup_res_1d_conso.xml"); // output model ModelDataOutput_S2D_CHM_s_FEM_uUp md; md.set_model(model); //md.set_res_file(res_file_pb); //md.output(); md.set_res_file(res_file_xml); md.output(); //TimeHistoryOutput_S2D_CHM_s_FEM_uUp out1; //out1.set_res_file(res_file_pb); //out1.set_interval_num(50); //out1.set_output_init_state(); TimeHistoryOutput_S2D_CHM_s_FEM_uUp out2; out2.set_res_file(res_file_xml); out2.set_interval_num(150); out2.set_output_init_state(); //TimeHistoryOutput_ConsoleProgressBar cpb; Step_S2D_CHM_s_FEM_uUp step; step.set_name("consolidation"); step.set_model(model); step.set_time(0.05); step.set_dtime(0.05); //step.add_time_history(out1); step.add_time_history(out2); //step.add_time_history(cpb); step.solve(); //system("pause"); }
26.793388
79
0.697409
[ "mesh", "model" ]
5d5b51f7a7b0a9f4bed221f9c3be47a4af444c9a
11,805
hpp
C++
src/gpu/jit/conv/utils.hpp
cfRod/oneDNN
7981216b8341b8603e54472f5a0dd7a12ef9cf67
[ "Apache-2.0" ]
1
2022-03-03T10:17:14.000Z
2022-03-03T10:17:14.000Z
src/gpu/jit/conv/utils.hpp
cfRod/oneDNN
7981216b8341b8603e54472f5a0dd7a12ef9cf67
[ "Apache-2.0" ]
null
null
null
src/gpu/jit/conv/utils.hpp
cfRod/oneDNN
7981216b8341b8603e54472f5a0dd7a12ef9cf67
[ "Apache-2.0" ]
1
2022-03-29T06:35:19.000Z
2022-03-29T06:35:19.000Z
/******************************************************************************* * Copyright 2021-2022 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. *******************************************************************************/ #ifndef GPU_JIT_CONV_UTILS_HPP #define GPU_JIT_CONV_UTILS_HPP #include <functional> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <type_traits> #include <unordered_map> #include <unordered_set> #include "common/utils.hpp" #include "gpu/compute/device_info.hpp" namespace dnnl { namespace impl { namespace gpu { namespace jit { namespace ir_utils { const int LOG_OFF = 0; const int LOG_WARNING = 100; const int LOG_INFO = 150; const int LOG_TRACE = 200; #ifdef GEN_CONV_DEBUG const int LOG_LEVEL = LOG_WARNING; #else const int LOG_LEVEL = LOG_OFF; #endif template <typename T> size_t get_hash(const T &t); template <typename T> size_t get_hash(const std::vector<T> &v); template <typename T> void get_hash_impl(size_t &h, const T &t) { h = hash_combine(h, get_hash(t)); } template <typename ArgHeadT, typename... ArgsT> void get_hash_impl(size_t &h, const ArgHeadT &head, const ArgsT &... args) { size_t h_head = get_hash(head); h = hash_combine(h, h_head); get_hash_impl(h, args...); } template <typename E> struct enum_hash_t { size_t operator()(const E &e) const noexcept { return std::hash<size_t>()((size_t)e); } }; template <typename T, typename = void> struct get_std_hash_helper_t { static size_t call(const T &t) { return std::hash<T>()(t); } }; template <typename T> struct get_std_hash_helper_t<T, typename std::enable_if<std::is_enum<T>::value>::type> { static size_t call(const T &t) { return enum_hash_t<T>()(t); } }; template <typename T, typename = void> struct get_hash_helper_t { static size_t call(const T &t) { return get_std_hash_helper_t<T>::call(t); } }; template <typename T> struct get_hash_helper_t<T, decltype(std::declval<T>().get_hash(), void())> { static size_t call(const T &t) { return t.get_hash(); } }; template <typename T> size_t get_hash(const T &t) { return get_hash_helper_t<T>::call(t); } template <typename T> size_t get_hash(const std::vector<T> &v) { size_t h = 0; for (auto &e : v) h = hash_combine(h, get_hash(e)); return h; } template <typename... ArgsT> size_t get_hash(const ArgsT &... args) { size_t h = 0; get_hash_impl(h, args...); return h; } template <typename T, typename U, typename = void> struct is_equal_helper_t { static bool call(const T &t, const U &u) { return t == u; } }; template <typename T, typename U> struct is_equal_helper_t<T, U, decltype(std::declval<T>().is_equal(std::declval<U>()), void())> { static bool call(const T &t, const U &u) { return t.is_equal(u); } }; // Checks equality of objects: // 1. Uses t.is_equal(u) if is_equal() is available // 2. Uses (t == u) otherwise template <typename T, typename U> bool is_equal(const T &t, const U &u) { return is_equal_helper_t<T, U>::call(t, u); } // Checks equality of vector elements. template <typename T, typename U> bool is_equal(const std::vector<T> &a, const std::vector<U> &b) { if (a.size() != b.size()) return false; for (size_t i = 0; i < a.size(); i++) if (!ir_utils::is_equal(a[i], b[i])) return false; return true; } // Checks equality of vector elements between each other. template <typename T> bool are_all_equal(const std::vector<T> &a) { if (a.empty()) return true; for (size_t i = 1; i < a.size(); i++) if (!ir_utils::is_equal(a[i], a[0])) return false; return true; } // Checks identity of vector elements. template <typename T, typename U> bool is_same(const std::vector<T> &a, const std::vector<U> &b) { if (a.size() != b.size()) return false; for (size_t i = 0; i < a.size(); i++) if (!a[i].is_same(b[i])) return false; return true; } class error_stream_t { public: error_stream_t(const char *file, int line, const char *assert_msg) : file_(file), line_(line) { out_ << "Assertion " << assert_msg << " failed at " << file_ << ":" << line_ << std::endl; } // This is to be able use a steam object in short-circuit evaluation with // booleans, see below. operator bool() const { return true; } template <typename T> error_stream_t &operator<<(const T &t) { out_ << t; return *this; } ~error_stream_t() { std::cerr << out_.str() << std::endl; abort(); } private: const char *file_; int line_; std::ostringstream out_; }; // Checks assertion and, in case of error, evaluates output operators to print // related messages. Usage: // ir_assert(condition) << "Error message" << ...; #ifndef NDEBUG #define ir_assert(cond) \ !(cond) \ && dnnl::impl::gpu::jit::ir_utils::error_stream_t( \ __FILE__, __LINE__, #cond) #else #define ir_assert(cond) \ (false) && !(cond) \ && dnnl::impl::gpu::jit::ir_utils::error_stream_t( \ __FILE__, __LINE__, #cond) #endif #define ir_error_not_expected() ir_assert(false) << "Not expected. " #define ir_error_not_implemented() ir_assert(false) << "Not implemented. " template <int level> class logger_t { public: logger_t(std::ostream &out = std::cout) : out_(out) {} operator bool() const { return true; } static bool is_enabled() { #ifdef GEN_CONV_DEBUG static int log_level = getenv_int("log_level", LOG_LEVEL); return log_level >= level; #else return LOG_LEVEL >= level; #endif } template <typename T> logger_t &operator<<(const T &obj) { maybe_print_header(); out_ << obj; return *this; } logger_t &operator<<(std::ostream &(*os)(std::ostream &)) { maybe_print_header(); out_ << os; return *this; } private: void maybe_print_header() { if (!is_first_print_) return; switch (level) { case LOG_WARNING: out_ << "[WARNING] "; break; default: break; } is_first_print_ = false; } std::ostream &out_; bool is_first_print_ = true; }; #define ir_info() \ ir_utils::logger_t<ir_utils::LOG_INFO>::is_enabled() \ && ir_utils::logger_t<ir_utils::LOG_INFO>() #define ir_warning() \ ir_utils::logger_t<ir_utils::LOG_WARNING>::is_enabled() \ && ir_utils::logger_t<ir_utils::LOG_WARNING>() #define ir_trace() \ ir_utils::logger_t<ir_utils::LOG_TRACE>::is_enabled() \ && ir_utils::logger_t<ir_utils::LOG_TRACE>() // Pretty printers for STL objects. template <typename KeyT, typename HashT, typename EqualT> inline std::ostream &operator<<( std::ostream &out, const std::unordered_set<KeyT, HashT, EqualT> &s) { out << "{"; for (auto it = s.begin(); it != s.end(); it++) { out << (it != s.begin() ? ", " : "") << *it; } out << "}"; return out; } template <typename KeyT, typename ValueT, typename HashT, typename EqualT> inline std::ostream &operator<<(std::ostream &out, const std::unordered_map<KeyT, ValueT, HashT, EqualT> &m) { out << "{"; for (auto it = m.begin(); it != m.end(); it++) { out << (it != m.begin() ? ", " : "") << it->first << ": " << it->second; } out << "}"; return out; } template <typename ContainerT> struct seq_print_helper_t { seq_print_helper_t(const ContainerT &v, const std::string &sep, int width) : v(v), sep(sep), width(width) {} const ContainerT &v; const std::string sep; int width; }; template <typename T> seq_print_helper_t<T> make_seq_print_helper( const T &v, const std::string &sep = ", ", int width = 0) { return seq_print_helper_t<T>(v, sep, width); } template <typename T> inline std::ostream &operator<<( std::ostream &out, const seq_print_helper_t<T> &seq) { for (auto it = seq.v.begin(); it != seq.v.end(); it++) { out << (it != seq.v.begin() ? seq.sep : "") << std::setw(seq.width) << *it; } return out; } template <typename T> inline std::ostream &operator<<(std::ostream &out, const std::vector<T> &v) { out << "["; out << make_seq_print_helper(v); out << "]"; return out; } inline bool getenv_bool(const char *s, bool def) { return getenv_int(s, def ? 1 : 0) == 1; } inline std::string getenv_str(const char *s, const std::string &def) { char buf[1024]; int ret = getenv(s, buf, sizeof(buf)); if (ret > 0) return buf; return def; } // Input is a comma separate list containing gpu_arch and optionally eu_count. inline compute::gpu_arch_t getenv_gpu(const char *s, compute::gpu_arch_t arch, int *eu_count = nullptr, size_t *max_wg_size = nullptr) { char buf[1024]; int ret = getenv(s, buf, sizeof(buf)); if (ret > 0) { char *arch_str = buf, *eu_str = nullptr; for (int i = 0; i < ret; i++) { if (buf[i] == ',') { buf[i] = 0; if (i < ret - 1) { eu_str = &buf[i + 1]; } break; } } arch = compute::str2gpu_arch(arch_str); if (eu_count && eu_str) { *eu_count = atoi(eu_str); } if (max_wg_size) { // Assume maximum wg size is basically the number of threads // available in a subslice with simd_size 16 const size_t max_eus_per_wg = compute::device_info_t::max_eus_per_wg(arch); const size_t simd_size = 16; const size_t thr_per_eu = utils::rnd_down_pow2( compute::device_info_t::threads_per_eu(arch)); *max_wg_size = simd_size * max_eus_per_wg * thr_per_eu; } } return arch; } inline std::string to_string(bool b) { return b ? "True" : "False"; } template <typename T> inline T max_divisor(T n, std::initializer_list<T> divisors) { T ret = -1; for (auto d : divisors) { if (n % d == 0) ret = std::max(ret, d); } ir_assert(ret != -1); return ret; } // Equivalent of BLSI instruction (extract lowest set isolated bit). template <typename T> inline T max_pow2_divisor(T n) { return n & ~(n - 1); } template <typename T, typename U> inline T safe_divide(T a, U b) { ir_assert(b != 0 && a % b == 0) << "Can't divide: " << a << " / " << b; return a / b; } template <typename ContainerT, typename T> inline int find_index(const ContainerT &c, const T &value) { for (int i = 0; i < int(c.size()); i++) { if (c[i] == value) return i; } return -1; } template <typename T, typename F> void for_each_impl(size_t pos, std::vector<T> &idx, const std::vector<T> &bounds, const F &f) { if (pos == bounds.size()) { f(idx); return; } for (T i = 0; i < bounds[pos]; i++) { idx[pos] = i; for_each_impl(pos + 1, idx, bounds, f); } } template <typename T, typename F> void for_each(const std::vector<T> &bounds, const F &f) { std::vector<T> idx(bounds.size()); for_each_impl(0, idx, bounds, f); } } // namespace ir_utils } // namespace jit } // namespace gpu } // namespace impl } // namespace dnnl #endif
27.841981
80
0.607539
[ "object", "vector" ]
5d621d13f36c8819edf7ff93193774477c422c38
41,254
cp
C++
Dev/Mod/Browser.cp
romiras/BlackBox-linux
3abf415f181024d3ce9456883910d4eb68c5a676
[ "BSD-2-Clause" ]
2
2016-03-17T08:27:55.000Z
2020-05-02T08:42:08.000Z
Dev/Mod/Browser.cp
romiras/BlackBox-linux
3abf415f181024d3ce9456883910d4eb68c5a676
[ "BSD-2-Clause" ]
null
null
null
Dev/Mod/Browser.cp
romiras/BlackBox-linux
3abf415f181024d3ce9456883910d4eb68c5a676
[ "BSD-2-Clause" ]
null
null
null
MODULE DevBrowser; (** OmInc, cas, bh 11 Oct 2000 **) (* bj 10.10.00 Change Init and SaveOptions to work with the registry instead of a file *) (* bj 02.10.00 Fixed Init so it reads the correct file. *) (* dg 29.08.00 bugfix in PutSelection *) (* dg 03.02.99 clientinterface and extensioninterface interfaces *) (* dg 09.12.98 hook interfaces (extensions of Kernel.Hook) and hook installations procedures are only shown if &-Option is provided *) (* bh 29.1.97 codefile browser *) (* bh 15.10.96 TypName changed *) (* bh 24.7.96 AliasType corrected *) (* bh 10.7.96 OPM.Close *) (* bh 10.6.96 correction in GetQualident *) (* cas 24.4.96 changed option handling *) (* bh 16.4.96 underscores *) (* bh 22.2.96 COM support adapted *) (* bh 5.3.96 open ruler *) (* bh 12.12.95 anypointer, anyrecord, longchar, & largeint support *) (* bh 25.9.95 COM support *) IMPORT Kernel, Files, Fonts, Dates, Ports, Stores, Views, Properties, Dialog, Documents, TextModels, TextMappers, TextRulers, TextViews, TextControllers, StdDialog, StdFolds, DevCPM, DevCPT, HostRegistry; CONST width = 170 * Ports.mm; (* view width *) height = 300 * Ports.mm; (* visibility *) internal = 0; external = 1; externalR = 2; inPar = 3; outPar = 4; (* object modes *) var = 1; varPar = 2; const = 3; field = 4; type = 5; lProc = 6; xProc = 7; cProc = 9; iProc = 10; mod = 11; head = 12; tProc = 13; ptrType = 31; (* structure forms *) undef = 0; bool = 2; sChar = 3; byte = 4; sInt = 5; int = 6; sReal = 7; real = 8; set = 9; sString = 10; nilTyp = 11; noTyp = 12; pointer = 13; procTyp = 14; comp = 15; char = 16; string = 17; lInt = 18; (* composite structure forms *) basic = 1; array = 2; dynArray = 3; record = 4; (* attribute flags (attr.adr, struct.attribute, proc.conval.setval) *) newAttr = 16; absAttr = 17; limAttr = 18; empAttr = 19; extAttr = 20; (* additional scanner types *) import = 100; module = 101; semicolon = 102; becomes = 103; comEnd = 104; modNotFoundKey = "#Dev:ModuleNotFound"; noSuchItemExportedKey = "#Dev:NoSuchItemExported"; noSuchExtItemExportedKey = "#Dev:NoSuchExtItemExported"; noModuleNameSelectedKey = "#Dev:NoModuleNameSelected"; noItemNameSelectedKey = "#Dev:NoItemNameSelected"; OptionsFile = "BrowOpt"; OptionsType = "opt"; regKey = "Dev\Browser\"; TYPE TProcList = POINTER TO RECORD fld: DevCPT.Object; attr: SET; (* newAttr *) next: TProcList END; VAR global: RECORD hints: BOOLEAN; (* display low-level hints such as field offsets *) flatten: BOOLEAN; (* include fields/bound procs of base types as well *) hideHooks: BOOLEAN; (* hide hook procedures and interfaces *) clientinterface, extensioninterface: BOOLEAN; sectAttr, keyAttr: TextModels.Attributes; (* formatting of section and other keywords *) level: SHORTINT; (* current indentation level *) gap: BOOLEAN; (* request for lazy Ln, issued with next Indent *) singleton: BOOLEAN; (* selectively display one object's definition *) thisObj: DevCPT.Name; (* singleton => selected object *) out: TextMappers.Formatter; (* formatter used to produce definition text *) systemUsed: BOOLEAN; comUsed: BOOLEAN; modUsed: ARRAY 127 OF BOOLEAN; pos: INTEGER END; inp: Files.Reader; imp: ARRAY 256 OF Kernel.Name; num, lev, max: INTEGER; options*: RECORD hints*: BOOLEAN; (* display low-level hints such as field offsets *) flatten*: BOOLEAN; (* include fields/bound procs of base types as well *) formatted*: BOOLEAN; shints, sflatten, sformatted: BOOLEAN; (* saved values *) END; PROCEDURE IsHook(typ: DevCPT.Struct): BOOLEAN; BEGIN WHILE ((typ.form = pointer) OR (typ.form = comp)) & (typ.BaseTyp # NIL) DO typ := typ.BaseTyp END; RETURN (DevCPT.GlbMod[typ.mno].name^ = "Kernel") & (typ.strobj.name^ = "Hook^"); END IsHook; (* auxilliary *) PROCEDURE GetSelection (VAR text: TextModels.Model; VAR beg, end: INTEGER); VAR c: TextControllers.Controller; BEGIN c := TextControllers.Focus(); IF (c # NIL) & c.HasSelection() THEN text := c.text; c.GetSelection(beg, end) ELSE text := NIL END END GetSelection; PROCEDURE GetQualIdent (VAR mod, ident: DevCPT.Name; VAR t: TextModels.Model); VAR s: TextMappers.Scanner; beg, end: INTEGER; i: SHORTINT; BEGIN GetSelection(t, beg, end); IF t # NIL THEN s.ConnectTo(t); s.SetOpts({7}); (* acceptUnderscores *) s.SetPos(beg); s.Scan; IF (s.type = TextMappers.string) & (s.len < LEN(mod)) THEN mod := SHORT(s.string$); s.Scan; IF (s.type = TextMappers.char) & (s.char = ".") & (s.Pos() <= end) THEN s.Scan; IF (s.type = TextMappers.string) & (s.len < LEN(ident)) THEN ident := SHORT(s.string$) ELSE mod[0] := 0X; ident[0] := 0X END ELSE ident[0] := 0X END ELSE mod[0] := 0X; ident[0] := 0X END ELSE mod[0] := 0X; ident[0] := 0X END END GetQualIdent; PROCEDURE Scan (VAR s: TextMappers.Scanner); BEGIN s.Scan; IF s.type = TextMappers.string THEN IF s.string = "IMPORT" THEN s.type := import ELSIF s.string = "MODULE" THEN s.type := module END ELSIF s.type = TextMappers.char THEN IF s.char = ";" THEN s.type := semicolon ELSIF s.char = ":" THEN IF s.rider.char = "=" THEN s.rider.Read; s.type := becomes END ELSIF s.char = "(" THEN IF s.rider.char = "*" THEN s.rider.Read; REPEAT Scan(s) UNTIL (s.type = TextMappers.eot) OR (s.type = comEnd); Scan(s) END ELSIF s.char = "*" THEN IF s.rider.char = ")" THEN s.rider.Read; s.type := comEnd END END END END Scan; PROCEDURE CheckModName (VAR mod: DevCPT.Name; t: TextModels.Model); VAR s: TextMappers.Scanner; BEGIN s.ConnectTo(t); s.SetPos(0); Scan(s); IF s.type = module THEN Scan(s); WHILE (s.type # TextMappers.eot) & (s.type # import) DO Scan(s) END; WHILE (s.type # TextMappers.eot) & (s.type # semicolon) & ((s.type # TextMappers.string) OR (s.string # mod)) DO Scan(s) END; IF s.type = TextMappers.string THEN Scan(s); IF s.type = becomes THEN Scan(s); IF s.type = TextMappers.string THEN mod := SHORT(s.string$) END END END END END CheckModName; PROCEDURE NewRuler (): TextRulers.Ruler; VAR ra: TextRulers.Attributes; p: TextRulers.Prop; BEGIN NEW(p); p.valid := {TextRulers.right, TextRulers.opts}; p.opts.val := {(*TextRulers.rightFixed*)}; p.opts.mask := p.opts.val; p.right := width; NEW(ra); ra.InitFromProp(p); RETURN TextRulers.dir.New(TextRulers.dir.NewStyle(ra)) END NewRuler; PROCEDURE Append (VAR d: ARRAY OF CHAR; s: ARRAY OF SHORTCHAR); VAR i, j: SHORTINT; ch: SHORTCHAR; BEGIN i := 0; WHILE d[i] # 0X DO INC(i) END; j := 0; REPEAT ch := s[j]; d[i] := ch; INC(i); INC(j) UNTIL ch = 0X END Append; PROCEDURE IsLegal (name: POINTER TO ARRAY OF SHORTCHAR): BOOLEAN; VAR i: SHORTINT; BEGIN IF name^ = "" THEN RETURN FALSE END; IF name[0] = "@" THEN RETURN global.hints END; i := 0; WHILE name[i] # 0X DO INC(i) END; RETURN name[i-1] # "^" END IsLegal; (* output formatting *) PROCEDURE Char (ch: SHORTCHAR); BEGIN global.out.WriteChar(ch) END Char; PROCEDURE String (s: ARRAY OF SHORTCHAR); BEGIN global.out.WriteSString(s) END String; PROCEDURE StringConst (s: ARRAY OF SHORTCHAR; long: BOOLEAN); VAR i, x, y: INTEGER; quoted, first: BOOLEAN; BEGIN IF long THEN i := 0; REPEAT DevCPM.GetUtf8(s, y, i) UNTIL (y = 0) OR (y >= 100H); IF y = 0 THEN global.out.WriteString("LONG(") END; END; i := 0; quoted := FALSE; first := TRUE; IF long THEN DevCPM.GetUtf8(s, x, i) ELSE x := ORD(s[i]); INC(i) END; WHILE x # 0 DO IF (x < ORD(" ")) OR (x >= 100H) THEN IF quoted THEN global.out.WriteChar('"') END; IF ~first THEN global.out.WriteString(" + ") END; IF x >= 0A00H THEN global.out.WriteIntForm(x, TextMappers.hexadecimal, 4, "0", FALSE) ELSIF x >= 0A0H THEN global.out.WriteIntForm(x, TextMappers.hexadecimal, 3, "0", FALSE) ELSE global.out.WriteIntForm(x, TextMappers.hexadecimal, 2, "0", FALSE) END; global.out.WriteChar("X"); quoted := FALSE ELSE IF ~quoted THEN IF ~first THEN global.out.WriteString(" + ") END; global.out.WriteChar('"') END; global.out.WriteChar(CHR(x)); quoted := TRUE END; IF long THEN DevCPM.GetUtf8(s, x, i) ELSE x := ORD(s[i]); INC(i) END; first := FALSE END; IF quoted THEN global.out.WriteChar('"') END; IF long & (y = 0) THEN global.out.WriteChar(")") END; END StringConst; PROCEDURE ProperString (s: ARRAY OF SHORTCHAR); VAR i: SHORTINT; BEGIN IF s # "" THEN i := 0; WHILE (s[i] # 0X) & (s[i] # "^") DO global.out.WriteChar(s[i]); INC(i) END END END ProperString; PROCEDURE Keyword (s: ARRAY OF SHORTCHAR); VAR a: TextModels.Attributes; BEGIN IF global.keyAttr # NIL THEN a := global.out.rider.attr; global.out.rider.SetAttr(global.keyAttr) END; global.out.WriteSString(s); IF global.keyAttr # NIL THEN global.out.rider.SetAttr(a) END END Keyword; PROCEDURE Section (VAR out: TextMappers.Formatter; s: ARRAY OF SHORTCHAR); VAR a: TextModels.Attributes; BEGIN IF global.sectAttr # NIL THEN a := out.rider.attr; out.rider.SetAttr(global.sectAttr) END; out.WriteSString(s); IF global.sectAttr # NIL THEN out.rider.SetAttr(a) END END Section; PROCEDURE Int (i: INTEGER); BEGIN global.out.WriteInt(i) END Int; PROCEDURE Hex (x, n: INTEGER); BEGIN IF n > 1 THEN Hex(x DIV 16, n - 1) END; x := x MOD 16; IF x >= 10 THEN global.out.WriteChar(SHORT(CHR(x + ORD("A") - 10))) ELSE global.out.WriteChar(SHORT(CHR(x + ORD("0")))) END END Hex; PROCEDURE Ln; BEGIN global.out.WriteLn END Ln; PROCEDURE Indent; VAR i: SHORTINT; BEGIN IF global.gap THEN global.gap := FALSE; Ln END; i := global.level; WHILE i > 0 DO global.out.WriteTab; DEC(i) END END Indent; PROCEDURE Guid (ext: DevCPT.ConstExt); BEGIN Char("{"); Hex(ORD(ext[2]) + 256 * ORD(ext[3]), 4); Hex(ORD(ext[0]) + 256 * ORD(ext[1]), 4); Char("-"); Hex(ORD(ext[4]) + 256 * ORD(ext[5]), 4); Char("-"); Hex(ORD(ext[6]) + 256 * ORD(ext[7]), 4); Char("-"); Hex(ORD(ext[8]), 2); Hex(ORD(ext[9]), 2); Char("-"); Hex(ORD(ext[10]), 2); Hex(ORD(ext[11]), 2); Hex(ORD(ext[12]), 2); Hex(ORD(ext[13]), 2); Hex(ORD(ext[14]), 2); Hex(ORD(ext[15]), 2); Char("}") END Guid; (* special marks *) PROCEDURE Hint (label: ARRAY OF SHORTCHAR; i: INTEGER; adj: BOOLEAN); BEGIN IF global.hints THEN Char("["); String(label); IF adj & (0 <= i) & (i < 10) THEN Char(TextModels.digitspace) END; Int(i); String("] ") END END Hint; PROCEDURE Hint3 (label1, label2, label3: ARRAY OF SHORTCHAR; i1, i2, i3: INTEGER); BEGIN IF global.hints THEN Char("["); String(label1); Int(i1); String(label2); Int(i2); String(label3); Int(i3); String("] ") END END Hint3; PROCEDURE Vis (i: INTEGER); BEGIN IF i # external THEN Char("-") END END Vis; PROCEDURE ProcSysFlag (flag: SHORTINT); BEGIN IF flag # 0 THEN String(" ["); IF flag = -10 THEN String("ccall") ELSE Int(flag) END; Char("]") END END ProcSysFlag; PROCEDURE ParSysFlag (flag: SHORTINT); VAR pos: INTEGER; BEGIN IF flag # 0 THEN String(" ["); pos := global.out.Pos(); IF ODD(flag) THEN String("nil") END; (* IF ODD(flag DIV 2) & (flag # 18) THEN IF global.out.Pos() # pos THEN String(", ") END; String("in") END; IF ODD(flag DIV 4) & (flag # 12) THEN IF global.out.Pos() # pos THEN String(", ") END; String("out") END; *) IF flag DIV 8 = 1 THEN IF global.out.Pos() # pos THEN String(", ") END; String("new") ELSIF flag DIV 8 = 2 THEN IF global.out.Pos() # pos THEN String(", ") END; String("iid") ELSIF flag DIV 8 # 0 THEN IF global.out.Pos() # pos THEN String(", ") END; Int(flag DIV 8 * 8) END; Char("]") END END ParSysFlag; PROCEDURE StructSysFlag (typ: DevCPT.Struct); VAR flag: SHORTINT; BEGIN flag := typ.sysflag; IF (flag # 0) & ((typ.form # pointer) OR (flag = 2)) THEN String(" ["); IF flag = 1 THEN String("untagged") ELSIF flag = 2 THEN String("handle") ELSIF flag = 3 THEN String("noalign") ELSIF flag = 4 THEN String("align2") ELSIF flag = 5 THEN String("align4") ELSIF flag = 6 THEN String("align8") ELSIF flag = 7 THEN String("union") ELSIF flag = 10 THEN IF typ.ext # NIL THEN Char('"'); String(typ.ext^); Char('"') ELSE String("interface") END ELSIF flag = 20 THEN String("som") ELSE Int(flag) END; Char("]") END END StructSysFlag; PROCEDURE SysStrings (obj: DevCPT.Object); BEGIN IF global.hints & ((obj.entry # NIL) OR (obj.library # NIL)) THEN String(' ["'); IF obj.library # NIL THEN String(obj.library^); String('", "') END; IF obj.entry # NIL THEN String(obj.entry^) END; String('"]') END END SysStrings; (* non-terminals *) PROCEDURE ^ Structure (typ: DevCPT.Struct); PROCEDURE Qualifier (mno: SHORTINT); BEGIN IF (mno > 1) OR (mno = 1) & global.singleton THEN global.modUsed[mno] := TRUE; String(DevCPT.GlbMod[mno].name^); Char(".") END END Qualifier; PROCEDURE LocalName (obj: DevCPT.Object); BEGIN Qualifier(0); String(obj.name^) END LocalName; PROCEDURE TypName (typ: DevCPT.Struct; force: BOOLEAN); BEGIN IF force OR IsLegal(typ.strobj.name) THEN IF (typ.mno > 1) OR (typ.mno = 1) & ((typ.form >= pointer) OR (typ.BaseTyp # DevCPT.undftyp)) & global.singleton THEN Qualifier(typ.mno); ELSIF typ = DevCPT.sysptrtyp THEN (* PTR is in SYSTEM *) String("SYSTEM."); global.systemUsed := TRUE ELSIF (typ = DevCPT.guidtyp) OR (typ = DevCPT.restyp) OR (typ = DevCPT.iunktyp) OR (typ = DevCPT.punktyp) THEN String("COM."); global.comUsed := TRUE END; IF force THEN ProperString(typ.strobj.name^) ELSE String(typ.strobj.name^) END ELSE Structure(typ) END END TypName; PROCEDURE ParList (VAR par: DevCPT.Object); BEGIN IF par.mode = varPar THEN IF par.vis = inPar THEN Keyword("IN") ELSIF par.vis = outPar THEN Keyword("OUT") ELSE Keyword("VAR") END; ParSysFlag(par.sysflag); Char(" ") END; String(par.name^); WHILE (par.link # NIL) & (par.link.typ = par.typ) & (par.link.mode = par.mode) & (par.link.vis = par.vis) & (par.link.sysflag = par.sysflag) DO par := par.link; String(", "); String(par.name^) END; String(": "); TypName(par.typ, FALSE) END ParList; PROCEDURE Signature (result: DevCPT.Struct; par: DevCPT.Object); VAR paren, res: BOOLEAN; BEGIN res := result # DevCPT.notyp; paren := res OR (par # NIL); IF paren THEN String(" (") END; IF par # NIL THEN ParList(par); par := par.link; WHILE par # NIL DO String("; "); ParList(par); par := par.link END END; IF paren THEN Char(")") END; IF res THEN String(": "); TypName(result, FALSE) END END Signature; PROCEDURE TProcs (rec: DevCPT.Struct; fld: DevCPT.Object; oldProcs: TProcList; VAR newProcs: TProcList); VAR receiver, old: DevCPT.Object; base: DevCPT.Struct; p, elem: TProcList; BEGIN IF fld # NIL THEN TProcs(rec, fld.left, oldProcs, newProcs); IF (fld.mode = tProc) & IsLegal(fld.name) THEN DevCPT.FindBaseField(fld.name^, rec, old); IF (old = NIL) OR (fld.typ # old.typ) OR (* (rec.attribute # 0) & *) (fld.conval.setval # old.conval.setval) THEN IF global.extensioninterface OR global.clientinterface THEN (* do not show methods with equal name *) p := oldProcs; WHILE (p # NIL) & (p.fld.name^ # fld.name^) DO p := p.next END; END; IF p = NIL THEN NEW(elem); elem.next := newProcs; newProcs := elem; elem.fld := fld; IF old = NIL THEN INCL(elem.attr, newAttr) END; IF absAttr IN fld.conval.setval THEN INCL(elem.attr, absAttr) ELSIF empAttr IN fld.conval.setval THEN INCL(elem.attr, empAttr) ELSIF extAttr IN fld.conval.setval THEN INCL(elem.attr, extAttr) END END END END; TProcs(rec, fld.right, oldProcs, newProcs) END END TProcs; (* PROCEDURE AdjustTProcs (typ: DevCPT.Struct; fld: DevCPT.Object); VAR receiver, old: DevCPT.Object; base: DevCPT.Struct; BEGIN IF fld # NIL THEN AdjustTProcs(typ, fld.left); IF (fld.mode = tProc) & IsLegal(fld.name) THEN DevCPT.FindBaseField(fld.name^, typ, old); IF old # NIL THEN IF fld.conval.setval * {absAttr, empAttr, extAttr} = {} THEN old.conval.setval := old.conval.setval - {absAttr, empAttr, extAttr} ELSIF (extAttr IN fld.conval.setval) & (empAttr IN old.conval.setval) THEN (* do not list methods which only change attribute from empty to extensible *) old.conval.setval := old.conval.setval + {extAttr} - {empAttr} END; IF fld.typ # old.typ THEN (* do not show base methods of covariant overwritten methods *) old.typ := fld.typ; old.conval.setval := {} END; END END; AdjustTProcs(typ, fld.right) END; IF (typ.BaseTyp # NIL) & (typ.BaseTyp # DevCPT.iunktyp) THEN AdjustTProcs(typ.BaseTyp, typ.BaseTyp.link) END END AdjustTProcs; *) PROCEDURE TypeboundProcs (typ: DevCPT.Struct; VAR cont: BOOLEAN; top: BOOLEAN; VAR list: TProcList; recAttr: INTEGER); VAR receiver: DevCPT.Object; new, p, q: TProcList; BEGIN IF (typ # NIL) & (typ # DevCPT.iunktyp) THEN TProcs(typ, typ.link, list, new); p := list; WHILE new # NIL DO q := new.next; new.next := p; p := new; new := q END; list := p; IF global.flatten THEN TypeboundProcs(typ.BaseTyp, cont, FALSE, list, recAttr); IF (typ.BaseTyp = NIL) OR (typ.BaseTyp = DevCPT.iunktyp) THEN (* IF global.extensioninterface & (recAttr IN {absAttr, extAttr}) THEN IF cont THEN Char(";") END; Ln; Indent; String("(a: ANYPTR) FINALIZE-, "); Keyword("NEW"); String(", "); Keyword("EMPTY"); cont := TRUE END *) END END; IF top THEN (* writeList *) WHILE list # NIL DO IF ~global.clientinterface & ~global.extensioninterface (* default *) OR global.clientinterface & (list.fld.vis = external) OR global.extensioninterface & (recAttr IN {absAttr, extAttr}) & (list.attr * {absAttr, empAttr, extAttr} # {}) THEN IF cont THEN Char(";") END; Ln; receiver := list.fld.link; Indent; Hint("entry ", list.fld.num, TRUE); (* Keyword("PROCEDURE"); String(" ("); *) Char("("); IF receiver.mode = varPar THEN IF receiver.vis = inPar THEN Keyword("IN") ELSE Keyword("VAR") END; Char(" ") END; String(receiver.name^); String(": "); IF IsLegal(receiver.typ.strobj.name) & (receiver.typ.mno = 1) THEN String(receiver.typ.strobj.name^) ELSE TypName(receiver.typ, FALSE) END; String(") "); String(list.fld.name^); Vis(list.fld.vis); SysStrings(list.fld); Signature(list.fld.typ, receiver.link); IF newAttr IN list.attr THEN String(", "); Keyword("NEW") END; IF absAttr IN list.attr THEN String(", "); Keyword("ABSTRACT") ELSIF empAttr IN list.attr THEN String(", "); Keyword("EMPTY"); ELSIF extAttr IN list.attr THEN String(", "); Keyword("EXTENSIBLE") END; cont := TRUE; END; list := list.next END END END END TypeboundProcs; PROCEDURE Flds (typ: DevCPT.Struct; VAR cont: BOOLEAN); VAR fld: DevCPT.Object; BEGIN fld := typ.link; WHILE (fld # NIL) & (fld.mode = field) DO IF IsLegal(fld.name) THEN IF cont THEN Char(";") END; Ln; Indent; Hint("offset ", fld.adr, TRUE); IF typ.mno > 1 THEN String("(* "); TypName(typ, TRUE); String(" *) ") END; String(fld.name^); WHILE (fld.link # NIL) & (fld.link.typ = fld.typ) & (fld.link.name # NIL) DO Vis(fld.vis); fld := fld.link; String(", "); String(fld.name^) END; Vis(fld.vis); String(": "); TypName(fld.typ, FALSE); cont := TRUE END; fld := fld.link END END Flds; PROCEDURE Fields (typ: DevCPT.Struct; VAR cont: BOOLEAN); BEGIN IF typ # NIL THEN IF global.flatten THEN Fields(typ.BaseTyp, cont) END; Flds(typ, cont) END END Fields; PROCEDURE BaseTypes (typ: DevCPT.Struct); BEGIN IF typ.BaseTyp # NIL THEN Char("("); TypName(typ.BaseTyp, TRUE); IF global.flatten THEN BaseTypes(typ.BaseTyp) END; Char(")") END END BaseTypes; PROCEDURE Structure (typ: DevCPT.Struct); VAR cont: BOOLEAN; p: TProcList; BEGIN INC(global.level); CASE typ.form OF pointer: Keyword("POINTER"); StructSysFlag(typ); Char(" "); Keyword("TO"); Char(" "); DEC(global.level); TypName(typ.BaseTyp, FALSE); INC(global.level) | procTyp: Keyword("PROCEDURE"); Signature(typ.BaseTyp, typ.link) | comp: CASE typ.comp OF array: Keyword("ARRAY"); StructSysFlag(typ); Char(" "); Int(typ.n); Char(" "); Keyword("OF"); Char(" "); TypName(typ.BaseTyp, FALSE) | dynArray: Keyword("ARRAY"); StructSysFlag(typ); Char(" "); Keyword("OF"); Char(" "); TypName(typ.BaseTyp, FALSE) | record: IF typ.attribute = absAttr THEN Keyword("ABSTRACT ") ELSIF typ.attribute = limAttr THEN Keyword("LIMITED ") ELSIF typ.attribute = extAttr THEN Keyword("EXTENSIBLE ") END; Keyword("RECORD"); StructSysFlag(typ); Char(" "); Hint3("tprocs ", ", size ", ", align ", typ.n, typ.size, typ.align); cont := FALSE; BaseTypes(typ); Fields(typ, cont); TypeboundProcs(typ, cont, TRUE, p, typ.attribute); IF cont THEN Ln; DEC(global.level); Indent; INC(global.level) ELSE Char (" ") END; Keyword("END") END ELSE IF (typ.BaseTyp # DevCPT.undftyp) THEN TypName(typ.BaseTyp, FALSE) END (* alias structures *) END; DEC(global.level) END Structure; PROCEDURE Const (obj: DevCPT.Object); VAR con: DevCPT.Const; s: SET; i: SHORTINT; x, y: INTEGER; r: REAL; BEGIN Indent; LocalName(obj); SysStrings(obj); String(" = "); con := obj.conval; CASE obj.typ.form OF bool: IF con.intval = 1 THEN String("TRUE") ELSE String("FALSE") END | sChar, char: IF con.intval >= 0A000H THEN Hex(con.intval, 5); Char("X") ELSIF con.intval >= 0100H THEN Hex(con.intval, 4); Char("X") ELSIF con.intval >= 0A0H THEN Hex(con.intval, 3); Char("X") ELSIF (con.intval >= 32) & (con.intval <= 126) THEN Char(22X); Char(SHORT(CHR(con.intval))); Char(22X) ELSE Hex(con.intval, 2); Char("X") END | byte, sInt, int: Int(con.intval) | lInt: y := SHORT(ENTIER((con.realval + con.intval) / 4294967296.0)); r := con.realval + con.intval - y * 4294967296.0; IF r > MAX(INTEGER) THEN r := r - 4294967296.0 END; x := SHORT(ENTIER(r)); Hex(y, 8); Hex(x, 8); Char("L") | set: Char("{"); i := 0; s := con.setval; WHILE i <= MAX(SET) DO IF i IN s THEN Int(i); EXCL(s, i); IF s # {} THEN String(", ") END END; INC(i) END; Char("}") | sReal, real: global.out.WriteReal(con.realval) | sString: StringConst(con.ext^, FALSE) | string: StringConst(con.ext^, TRUE) | nilTyp: Keyword("NIL") | comp: (* guid *) Char("{"); Guid(con.ext); Char("}") END; Char(";"); Ln END Const; PROCEDURE AliasType (typ: DevCPT.Struct); BEGIN IF global.singleton & IsLegal(typ.strobj.name) THEN WHILE typ.BaseTyp # DevCPT.undftyp DO Char(";"); Ln; Indent; String(typ.strobj.name^); SysStrings(typ.strobj); String(" = "); IF typ.form >= pointer THEN Structure(typ); typ := DevCPT.int16typ ELSE typ := typ.BaseTyp; TypName(typ, FALSE) END END END END AliasType; PROCEDURE NotExtRec(typ: DevCPT.Struct): BOOLEAN; BEGIN RETURN (typ.form = comp) & ((typ.comp # record) OR ~(typ.attribute IN {absAttr, extAttr})) OR (typ.form = procTyp) END NotExtRec; PROCEDURE Type (obj: DevCPT.Object); BEGIN IF global.hideHooks & IsHook(obj.typ) THEN RETURN END; IF global.extensioninterface (* & (obj.typ.strobj = obj) & ~((obj.typ.form < pointer) & (obj.typ.BaseTyp # DevCPT.undftyp)) *) & (NotExtRec(obj.typ) OR (obj.typ.form = pointer) & ~IsLegal(obj.typ.BaseTyp.strobj.name) & NotExtRec(obj.typ.BaseTyp) ) THEN IF global.singleton THEN RETURN END; global.out.rider.SetAttr(TextModels.NewColor(global.out.rider.attr, Ports.grey50)); IF global.pos < global.out.rider.Pos() THEN global.out.rider.Base().SetAttr(global.pos, global.out.rider.Pos()-1, global.out.rider.attr) END END; Indent; LocalName(obj); SysStrings(obj); String(" = "); IF obj.typ.strobj # obj THEN TypName(obj.typ, FALSE); AliasType(obj.typ) ELSIF (obj.typ.form < pointer) & (obj.typ.BaseTyp # DevCPT.undftyp) THEN TypName(obj.typ.BaseTyp, FALSE); AliasType(obj.typ.BaseTyp) ELSE Structure(obj.typ) END; Char(";"); Ln; global.gap := TRUE END Type; PROCEDURE PtrType (obj: DevCPT.Object); VAR base: DevCPT.Object; BEGIN Type(obj); base := obj.typ.BaseTyp.strobj; IF (base # NIL) & (base # DevCPT.anytyp.strobj) & (base # DevCPT.iunktyp.strobj) & (base.vis # internal) & (base.typ.strobj # NIL) & ~(global.hideHooks & IsHook(base.typ)) THEN (* show named record with pointer; avoid repetition *) IF global.extensioninterface & (base.typ.strobj = base) & ~((obj.typ.form < pointer) & (obj.typ.BaseTyp # DevCPT.undftyp)) & (NotExtRec(base.typ) OR (base.typ.form = pointer) & ~IsLegal(base.typ.BaseTyp.strobj.name) & NotExtRec(base.typ.BaseTyp) ) THEN IF global.singleton THEN IF global.pos < global.out.rider.Pos() THEN global.out.rider.Base().Delete(global.pos, global.out.rider.Pos()); global.out.rider.SetPos(global.pos) END; RETURN END; global.out.rider.SetAttr(TextModels.NewColor(global.out.rider.attr, Ports.grey50)); IF global.pos < global.out.rider.Pos() THEN global.out.rider.Base().SetAttr(global.pos, global.out.rider.Pos()-1, global.out.rider.attr) END END; global.gap := FALSE; Indent; String(base.name^); SysStrings(base); String(" = "); IF base.typ.strobj # base THEN TypName(base.typ, FALSE); AliasType(obj.typ) ELSIF (obj.typ.form < pointer) & (obj.typ.BaseTyp # DevCPT.undftyp) THEN TypName(obj.typ.BaseTyp, FALSE); AliasType(obj.typ.BaseTyp) ELSE Structure(base.typ) END; Char(";"); Ln; base.vis := internal; global.gap := TRUE END END PtrType; PROCEDURE Var (obj: DevCPT.Object); BEGIN IF global.hideHooks & IsHook(obj.typ) THEN RETURN END; Indent; LocalName(obj); Vis(obj.vis); SysStrings(obj); String(": "); TypName(obj.typ, FALSE); Char(";"); Ln END Var; PROCEDURE Proc (obj: DevCPT.Object); VAR ext: DevCPT.ConstExt; i, m: SHORTINT; BEGIN IF global.hideHooks & (obj.link # NIL) & (obj.link.link = NIL) & IsHook(obj.link.typ) THEN RETURN END; IF global.extensioninterface THEN RETURN END; Indent; Keyword("PROCEDURE"); (* Char(" "); *) IF obj.mode = cProc THEN String(" [code]") ELSIF obj.mode = iProc THEN String(" [callback]") ELSE ProcSysFlag(obj.sysflag) END; Char(" "); LocalName(obj); (*IF obj.mode # cProc THEN SysStrings(obj) END;*) SysStrings(obj); Signature(obj.typ, obj.link); IF (obj.mode = cProc) & global.hints THEN Ln; INC(global.level); Indent; ext := obj.conval.ext; m := ORD(ext^[0]); i := 1; WHILE i <= m DO global.out.WriteIntForm(ORD(ext^[i]), TextMappers.hexadecimal, 3, "0", TextMappers.showBase); IF i < m THEN String(", ") END; INC(i) END; DEC(global.level) END; Char(";"); Ln END Proc; (* tree traversal *) PROCEDURE Objects (obj: DevCPT.Object; mode: SET); VAR m: BYTE; a: TextModels.Attributes; BEGIN IF obj # NIL THEN INC(lev); INC(num); max := MAX(max, lev); Objects(obj.left, mode); m := obj.mode; IF (m = type) & (obj.typ.form = pointer) THEN m := ptrType END; IF (m IN mode) & (obj.vis # internal) & (obj.name # NIL) & (~global.singleton OR (obj.name^ = global.thisObj)) THEN global.pos := global.out.rider.Pos(); a := global.out.rider.attr; CASE m OF const: Const(obj) | type: Type(obj) | ptrType: PtrType(obj) | var: Var(obj) | xProc, cProc, iProc: Proc(obj) END; global.out.rider.SetAttr(a); END; Objects(obj.right, mode); DEC(lev); END END Objects; (* definition formatting *) PROCEDURE PutSection (VAR out: TextMappers.Formatter; s: ARRAY OF SHORTCHAR); VAR buf, def: TextModels.Model; i: INTEGER; BEGIN buf := global.out.rider.Base(); IF buf.Length() > 0 THEN IF ~global.singleton THEN Ln END; def := out.rider.Base(); out.SetPos(def.Length()); IF s # "" THEN (* prepend section keyword *) i := global.level - 1; WHILE i > 0 DO out.WriteTab; DEC(i) END; Section(out, s); out.WriteLn END; def.Append(buf); global.pos := 0; global.out.rider.SetPos(0); END; global.gap := FALSE END PutSection; PROCEDURE Scope (def: TextModels.Model; this: DevCPT.Name); VAR out: TextMappers.Formatter; i: SHORTINT; a: TextModels.Attributes; BEGIN global.gap := FALSE; global.thisObj := this; global.singleton := (this # ""); global.systemUsed := FALSE; global.comUsed := FALSE; i := 1; WHILE i < LEN(global.modUsed) DO global.modUsed[i] := FALSE; INC(i) END; out.ConnectTo(def); INC(global.level); IF ~(global.extensioninterface & global.singleton) THEN IF global.extensioninterface THEN a := global.out.rider.attr; global.out.rider.SetAttr(TextModels.NewColor(a, Ports.grey50)) END; Objects(DevCPT.GlbMod[1].right, {const}); IF global.extensioninterface THEN global.out.rider.SetAttr(a) END; PutSection(out, "CONST"); END; Objects(DevCPT.GlbMod[1].right, {ptrType}); Objects(DevCPT.GlbMod[1].right, {type}); PutSection(out, "TYPE"); IF ~global.extensioninterface THEN Objects(DevCPT.GlbMod[1].right, {var}); PutSection(out, "VAR"); END; DEC(global.level); num := 0; lev := 0; max := 0; Objects(DevCPT.GlbMod[1].right, {xProc, cProc}); PutSection(out, "") END Scope; PROCEDURE Modules; VAR i, j, n: SHORTINT; BEGIN n := 0; j := 2; IF global.systemUsed THEN INC(n) END; IF global.comUsed THEN INC(n) END; WHILE j < DevCPT.nofGmod DO IF global.modUsed[j] THEN INC(n) END; INC(j) END; IF n > 0 THEN Indent; Section(global.out, "IMPORT"); INC(global.level); IF n < 10 THEN Char(" ") ELSE Ln; Indent END; i := 0; j := 2; IF global.systemUsed THEN String("SYSTEM"); INC(i); IF i < n THEN String(", ") END END; IF global.comUsed THEN String("COM"); INC(i); IF i < n THEN String(", ") END END; WHILE i < n DO IF global.modUsed[j] THEN String(DevCPT.GlbMod[j].name^); INC(i); (* IF (DevCPT.GlbMod[j].strings # NIL) & (DevCPT.GlbMod[j].strings.ext # NIL) THEN String(' ["'); String(DevCPT.GlbMod[j].strings.ext^); String('"]') END; *) IF i < n THEN Char(","); IF i MOD 10 = 0 THEN Ln; Indent ELSE Char(" ") END END END; INC(j) END; Char(";"); Ln; Ln END END Modules; (* compiler interfacing *) PROCEDURE OpenCompiler (mod: DevCPT.Name; VAR noerr: BOOLEAN); VAR null: TextModels.Model; main: DevCPT.Name; BEGIN null := TextModels.dir.New(); DevCPM.Init(null.NewReader(NIL), null); (* DevCPT.Init({}); DevCPT.Open(mod); DevCPT.SelfName := "AvoidErr154"; *) DevCPT.Init({}); main := "@mainMod"; DevCPT.Open(main); DevCPT.processor := 0; (* accept all sym files *) DevCPT.Import("@notself", mod, noerr); IF ~DevCPM.noerr THEN noerr := FALSE END; END OpenCompiler; PROCEDURE CloseCompiler; BEGIN DevCPT.Close; DevCPM.Close END CloseCompiler; PROCEDURE Browse (ident: DevCPT.Name; opts: ARRAY OF CHAR; VAR view: Views.View; VAR title: Views.Title); VAR def, buf: TextModels.Model; v: TextViews.View; d: Documents.Document; h: BOOLEAN; noerr: BOOLEAN; p: Properties.BoundsPref; mod: DevCPT.Name; i: SHORTINT; str, str1: ARRAY 256 OF CHAR; BEGIN mod := DevCPT.GlbMod[1].name^$; i := 0; global.hints := FALSE; global.flatten := FALSE; global.hideHooks := TRUE; global.clientinterface := FALSE; global.extensioninterface := FALSE; global.keyAttr := NIL; global.sectAttr := NIL; IF opts[0] = '@' THEN IF options.hints THEN opts := opts + "+" END; IF options.flatten THEN opts := opts + "!" END; IF options.formatted THEN opts := opts + "/" END; END; WHILE opts[i] # 0X DO CASE opts[i] OF | '+': global.hints := TRUE | '!': global.flatten := TRUE | '&': global.hideHooks := FALSE | '/': (* global.keyAttr := TextModels.NewStyle(TextModels.dir.attr, {Fonts.underline}); *) global.keyAttr := TextModels.NewWeight(TextModels.dir.attr, Fonts.bold); global.sectAttr := TextModels.NewWeight(TextModels.dir.attr, Fonts.bold) | 'c': global.clientinterface := TRUE; | 'e' : global.extensioninterface := TRUE; ELSE END; INC(i) END; IF global.clientinterface & global.extensioninterface THEN global.clientinterface := FALSE; global.extensioninterface := FALSE END; IF global.extensioninterface THEN global.hideHooks := FALSE END; def := TextModels.dir.New(); buf := TextModels.dir.New(); global.out.ConnectTo(buf); IF ident # "" THEN h := global.hideHooks; global.hideHooks := FALSE; global.level := 0; Scope(def, ident); global.hideHooks := h; def.Append(buf); IF def.Length() > 0 THEN v := TextViews.dir.New(def); v.SetDefaults(NewRuler(), TextViews.dir.defAttr); p.w := Views.undefined; p.h := Views.undefined; Views.HandlePropMsg(v, p); title := mod$; Append(title, "."); Append(title, ident); view := Documents.dir.New(v, p.w, p.h) ELSE str := mod$; str1 := ident$; title := ""; IF global.extensioninterface THEN Dialog.ShowParamMsg(noSuchExtItemExportedKey, str, str1, "") ELSE Dialog.ShowParamMsg(noSuchItemExportedKey, str, str1, "") END END ELSE global.level := 1; Scope(def, ""); Section(global.out, "END"); Char(" "); String(mod); Char("."); Ln; def.Append(buf); Section(global.out, "DEFINITION"); Char(" "); String(mod); IF (DevCPT.GlbMod[1].library # NIL) THEN String(' ["'); String(DevCPT.GlbMod[1].library^); String('"]') ELSIF DevCPT.impProc # 0 THEN global.out.WriteTab; String("(* nonportable"); IF DevCPT.impProc = 10 THEN String(" (i386)") ELSIF DevCPT.impProc = 20 THEN String(" (68k)") END; String(" *)") END; Char(";"); Ln; Ln; Modules; buf.Append(def); v := TextViews.dir.New(buf); v.SetDefaults(NewRuler(), TextViews.dir.defAttr); title := mod$; view := Documents.dir.New(v, width, height) END; global.out.ConnectTo(NIL); global.keyAttr := NIL; global.sectAttr := NIL END Browse; PROCEDURE ShowInterface* (opts: ARRAY OF CHAR); VAR noerr: BOOLEAN; mod, ident: DevCPT.Name; v: Views.View; title: Views.Title; t: TextModels.Model; str: ARRAY 256 OF CHAR; BEGIN GetQualIdent(mod, ident, t); CheckModName(mod, t); IF mod # "" THEN OpenCompiler(mod, noerr); IF noerr & (DevCPT.GlbMod[1] # NIL) & (DevCPT.GlbMod[1].name^ = mod) THEN Browse(ident, opts, v, title); IF v # NIL THEN IF global.clientinterface THEN title := title + " (client interface)" ELSIF global.extensioninterface THEN title := title + " (extension interface)" END; Views.OpenAux(v, title) END ELSE str := mod$; Dialog.ShowParamMsg(modNotFoundKey, str, "", "") END; CloseCompiler ELSE Dialog.ShowMsg(noModuleNameSelectedKey) END; Kernel.Cleanup END ShowInterface; PROCEDURE ImportSymFile* (f: Files.File; OUT s: Stores.Store); VAR v: Views.View; title: Views.Title; noerr: BOOLEAN; BEGIN ASSERT(f # NIL, 20); DevCPM.file := f; OpenCompiler("@file", noerr); IF noerr THEN Browse("", "", v, title); s := v END; CloseCompiler; DevCPM.file := NIL; Kernel.Cleanup END ImportSymFile; (* codefile browser *) PROCEDURE RWord (VAR x: INTEGER); VAR b: BYTE; y: INTEGER; BEGIN inp.ReadByte(b); y := b MOD 256; inp.ReadByte(b); y := y + 100H * (b MOD 256); inp.ReadByte(b); y := y + 10000H * (b MOD 256); inp.ReadByte(b); x := y + 1000000H * b END RWord; PROCEDURE RNum (VAR x: INTEGER); VAR b: BYTE; s, y: INTEGER; BEGIN s := 0; y := 0; inp.ReadByte(b); WHILE b < 0 DO INC(y, ASH(b + 128, s)); INC(s, 7); inp.ReadByte(b) END; x := ASH((b + 64) MOD 128 - 64, s) + y END RNum; PROCEDURE RName (VAR name: ARRAY OF SHORTCHAR); VAR b: BYTE; i, n: INTEGER; BEGIN i := 0; n := LEN(name) - 1; inp.ReadByte(b); WHILE (i < n) & (b # 0) DO name[i] := SHORT(CHR(b)); INC(i); inp.ReadByte(b) END; WHILE b # 0 DO inp.ReadByte(b) END; name[i] := 0X END RName; PROCEDURE RLink; VAR x: INTEGER; BEGIN RNum(x); WHILE x # 0 DO RNum(x); RNum(x) END END RLink; PROCEDURE RShort (p: INTEGER; OUT x: INTEGER); VAR b0, b1: BYTE; BEGIN inp.ReadByte(b0); inp.ReadByte(b1); IF p = 10 THEN x := b0 MOD 256 + b1 * 256 (* little endian *) ELSE x := b1 MOD 256 + b0 * 256 (* big endian *) END END RShort; PROCEDURE ReadHeader (file: Files.File; VAR view: Views.View; VAR title: Views.Title); VAR ch, ch1: SHORTCHAR; n, i, p, fp, hs, ms, ds, cs, vs, m: INTEGER; name: Kernel.Name; first: BOOLEAN; text: TextModels.Model; v: TextViews.View; fold: StdFolds.Fold; d: Dates.Date; t: Dates.Time; str: ARRAY 64 OF CHAR; BEGIN text := TextModels.dir.New(); global.out.ConnectTo(text); inp := file.NewReader(NIL); inp.SetPos(0); RWord(n); IF n = 6F4F4346H THEN RWord(p); RWord(hs); RWord(ms); RWord(ds); RWord(cs); RWord(vs); RNum(n); RName(name); title := name$; i := 0; WHILE i < n DO RName(imp[i]); INC(i) END; String("MODULE "); String(name); Ln; String("processor: "); IF p = 10 THEN String("80x86") ELSIF p = 20 THEN String("68000") ELSIF p = 30 THEN String("PPC") ELSIF p = 40 THEN String("SH3") ELSE Int(p) END; Ln; String("meta size: "); Int(ms); Ln; String("desc size: "); Int(ds); Ln; String("code size: "); Int(cs); Ln; String("data size: "); Int(vs); Ln; inp.SetPos(hs + ms + 12); RShort(p, d.year); RShort(p, d.month); RShort(p, d.day); RShort(p, t.hour); RShort(p, t.minute); RShort(p, t.second); String("compiled: "); Dates.DateToString(d, Dates.short, str); global.out.WriteString(str); String(" "); Dates.TimeToString(t, str); global.out.WriteString(str); Ln; Int(n); String(" imports:"); Ln; inp.SetPos(hs + ms + ds + cs); RLink; RLink; RLink; RLink; RLink; RLink; i := 0; WHILE i < n DO global.out.WriteTab; String(imp[i]); global.out.WriteTab; RNum(p); IF p # 0 THEN fold := StdFolds.dir.New(StdFolds.expanded, "", TextModels.dir.New()); global.out.WriteView(fold); Char(" "); first := TRUE; WHILE p # 0 DO RName(name); RNum(fp); IF p = 2 THEN RNum(m) END; IF p # 1 THEN RLink END; IF name # "" THEN IF ~first THEN String(", ") END; first := FALSE; String(name) END; RNum(p) END; Char(" "); fold := StdFolds.dir.New(StdFolds.expanded, "", NIL); global.out.WriteView(fold); fold.Flip(); global.out.SetPos(text.Length()) END; INC(i); Ln END ELSE String("wrong file tag: "); Hex(n, 8) END; v := TextViews.dir.New(text); v.SetDefaults(NewRuler(), TextViews.dir.defAttr); view := Documents.dir.New(v, width, height); global.out.ConnectTo(NIL); inp := NIL END ReadHeader; PROCEDURE ShowCodeFile*; VAR t: TextModels.Model; f: Files.File; v: Views.View; title: Views.Title; mod, ident: DevCPT.Name; name: Files.Name; loc: Files.Locator; str: ARRAY 256 OF CHAR; BEGIN GetQualIdent(mod, ident, t); IF mod # "" THEN str := mod$; StdDialog.GetSubLoc(str, "Code", loc, name); f := Files.dir.Old(loc, name, Files.shared); IF f # NIL THEN ReadHeader(f, v, title); IF v # NIL THEN Views.OpenAux(v, title) END ELSE Dialog.ShowParamMsg(modNotFoundKey, str, "", "") END; ELSE Dialog.ShowMsg(noModuleNameSelectedKey) END END ShowCodeFile; PROCEDURE ImportCodeFile* (f: Files.File; OUT s: Stores.Store); VAR v: Views.View; title: Views.Title; BEGIN ASSERT(f # NIL, 20); ReadHeader(f, v, title); s := v END ImportCodeFile; PROCEDURE SaveOptions*; BEGIN HostRegistry.WriteBool(regKey + 'hints', options.hints); HostRegistry.WriteBool(regKey + 'flatten', options.flatten); HostRegistry.WriteBool(regKey + 'formatted', options.formatted); options.sflatten := options.flatten; options.shints := options.hints; options.sformatted := options.formatted END SaveOptions; PROCEDURE SaveGuard*(VAR par: Dialog.Par); BEGIN par.disabled := (options.sflatten = options.flatten) & (options.shints = options.hints) & (options.sformatted = options.formatted) END SaveGuard; PROCEDURE Init*; VAR res: INTEGER; BEGIN HostRegistry.ReadBool(regKey + 'hints', options.hints, res); IF res # 0 THEN options.hints := FALSE END; HostRegistry.ReadBool(regKey + 'flatten', options.flatten, res); IF res # 0 THEN options.flatten := TRUE END; HostRegistry.ReadBool(regKey + 'formatted', options.formatted, res); IF res # 0 THEN options.formatted := FALSE END; Dialog.Update(options); options.sflatten := options.flatten; options.shints := options.hints; options.sformatted := options.formatted END Init; BEGIN Init END DevBrowser. 
31.443598
132
0.635405
[ "object", "model" ]
5d6659559404dec93243e13c98065ba93e0d0ec9
2,773
cpp
C++
pytorch/torch/csrc/distributed/c10d/comm.cpp
raghavnauhria/whatmt
c20483a437c82936cb0fb8080925e37b9c4bba87
[ "MIT" ]
null
null
null
pytorch/torch/csrc/distributed/c10d/comm.cpp
raghavnauhria/whatmt
c20483a437c82936cb0fb8080925e37b9c4bba87
[ "MIT" ]
1
2019-07-22T09:48:46.000Z
2019-07-22T09:48:46.000Z
pytorch/torch/csrc/distributed/c10d/comm.cpp
raghavnauhria/whatmt
c20483a437c82936cb0fb8080925e37b9c4bba87
[ "MIT" ]
null
null
null
#include <torch/csrc/distributed/c10d/comm.h> #include <deque> #include <ATen/core/functional.h> #include <torch/csrc/distributed/c10d/reducer.h> #include <torch/csrc/utils/tensor_flatten.h> namespace c10d { namespace { class BroadcastWork { public: BroadcastWork( const std::shared_ptr<c10d::ProcessGroup>& process_group, std::vector<at::Tensor> bucket_tensors) : bucket_tensors_(std::move(bucket_tensors)), flat_tensor_({torch::utils::flatten_dense_tensors(bucket_tensors_)}), work_(process_group->broadcast(flat_tensor_)) {} void finish() { work_->wait(); // Copy the output of the broadcast operation back. auto output_tensors = torch::utils::unflatten_dense_tensors( flat_tensor_.front(), bucket_tensors_); AT_ASSERT(output_tensors.size() == bucket_tensors_.size()); for (size_t i = 0; i < output_tensors.size(); i++) { bucket_tensors_[i].copy_(output_tensors[i], /*non_blocking=*/true); } } protected: // The list of tensors to broadcast. They are guaranteed to be // placed on the same device and have the same dtype. std::vector<at::Tensor> bucket_tensors_; // The vector with a single flattened tensor containing the contents // of the tensors in bucket_tensors_. It must be stored in a vector // because c10d::ProcessGroup::broadcast takes a vector argument. std::vector<at::Tensor> flat_tensor_; // The broadcast work that is kicked off upon construction. std::shared_ptr<c10d::ProcessGroup::Work> work_; }; } // namespace // Broadcast many tensors to all processes in the process group. void broadcast_coalesced( std::shared_ptr<c10d::ProcessGroup> process_group, at::TensorList tensors, size_t buffer_size) { // Coalesce tensors into buckets taking into account the maximum buffer size. // This routine is multi-device aware, so the tensors can be split across // multiple devices and can contain a mix of CPU and CUDA tensors. const auto buckets = compute_bucket_assignment_by_size(tensors.vec(), {buffer_size}); // Returns tensor at specified index in input tensor list. const auto lookup = [&tensors](size_t index) { return tensors[index]; }; // We maintain a maximum of 2 in flight broadcast operations to avoid // allocating too much memory (in case the specified tensors are very large). std::deque<BroadcastWork> in_flight; constexpr auto max_in_flight = 2; for (const auto& bucket : buckets) { if (in_flight.size() >= max_in_flight) { in_flight.front().finish(); in_flight.pop_front(); } in_flight.emplace_back(process_group, c10::fmap(bucket, lookup)); } while (!in_flight.empty()) { in_flight.front().finish(); in_flight.pop_front(); } } } // namespace c10d
33.409639
79
0.713307
[ "vector" ]
5d7cb48847f48b9f1a6425b3f355f208c5abf7dd
2,980
hpp
C++
src/msa/zobrist.hpp
jinnaiyuu/15puzzle
142a6765123699a999c1b6414252bb30f8766c08
[ "MIT" ]
1
2017-12-18T07:57:42.000Z
2017-12-18T07:57:42.000Z
src/msa/zobrist.hpp
jinnaiyuu/15puzzle
142a6765123699a999c1b6414252bb30f8766c08
[ "MIT" ]
59
2015-01-01T13:50:25.000Z
2015-07-28T05:49:33.000Z
src/msa/zobrist.hpp
jinnaiyuu/Hash-Distributed-Astar
142a6765123699a999c1b6414252bb30f8766c08
[ "MIT" ]
null
null
null
/* * zobrist.h * * Created on: Jun 10, 2014 * Author: yuu */ #ifndef MSAZOBRIST_H_ #define MSAZOBRIST_H_ #include <cmath> #include <climits> #include <cstdlib> #include <math.h> #include <random> #include "../dist_hash.hpp" template<typename D> class MSAZobrist : public DistributionHash<D> { public: enum ABST { SINGLE = 1, FIVE = 5 // PAIR = 1, // LINE = 2, // BLOCK = 3, // TWO = 4, // ABSTRACTION = 123, // FAR_TILES = 1712, // FOURBLOCK_24 = 4024, // FOURABSTRACTION = 1234 }; // Should delete compatibility for performance. MSAZobrist(D &d, int abst = 1) : d(d), structure(abst) { initZobrist(structure); // dump_table(); } unsigned int dist_h(const typename D::State& s) const { unsigned int c = 0; for (unsigned int i = 0; i < map.size(); ++i) { c = c ^ map[i][s.sequence[i]]; } // printf("zbr = %u\n", c); return c; } /** * @param number: The number slided * @param from : Where the number is in parent node * @param to : Where the number is in child node * @return the value to XOR to the Zobrist value of parent. */ unsigned int inc_hash(const unsigned int previous, const int number, const int from, const int to, const char* const newBoard, const typename D::State s) const { unsigned int c = 0; for (unsigned int i = 0; i < map.size(); ++i) { c = c ^ map[i][s.sequence[i]]; } // printf("zbr = %u\n", c); return c; } unsigned int inc_hash(typename D::State s) const { return 0; } //#define RANDOM_ZOBRIST_INITIALIZATION private: void initZobrist(unsigned int abst) { map.resize(d.num_of_sequences); for (unsigned int i = 0; i < map.size(); ++i) { map[i].resize(d.sequences[i].size()); } gen = std::mt19937(rd()); // unsigned int max = std::numeric_limits<hashlength>::max(); // unsigned int max = UINT_MAX; dis = std::uniform_int_distribution<>(INT_MIN, INT_MAX); // Not sure I should initialize it by time as it randomize the results for each run. #ifdef RANDOM_ZOBRIST_INITIALIZATION srand(time(NULL)); #endif if (abst < 1000) { // ###### Abstraction abstraction(abst); } else { abstraction(abst % 1000, abst / 1000); } } void abstraction(unsigned int abst, unsigned int features = 100) { printf("abst = %u\n", abst); printf("features = %u\n", features); if (abst == 0) { ++abst; } for (unsigned int i = 0; i < map.size(); ++i) { if (i < features) { for (unsigned int j = 0; j < map[i].size(); j += abst) { unsigned int r = random(); for (unsigned int ab = 0; (ab < abst) && ((j + ab) < map[i].size()); ++ab) { map[i][j + ab] = r; } } } else { for (unsigned int j = 0; j < map[i].size(); ++j) { map[i][j] = 0; } } } } unsigned int random() { return dis(gen) + INT_MAX; } D& d; unsigned int structure; std::vector<std::vector<unsigned int> > map; std::random_device rd; std::mt19937 gen; std::uniform_int_distribution<> dis; }; #endif /* ZOBRIST_H_ */
22.575758
84
0.60906
[ "vector" ]
5d838032cf5969c483472b2489e1449e2411a009
54,924
cc
C++
JniTensorflow/jni/genfiles/tensorflow/core/protobuf/device_properties.pb.cc
Wenstery/TensorflowApp
e666b5908cb624e83d9084a842e7cbb105d6f23f
[ "Apache-2.0" ]
null
null
null
JniTensorflow/jni/genfiles/tensorflow/core/protobuf/device_properties.pb.cc
Wenstery/TensorflowApp
e666b5908cb624e83d9084a842e7cbb105d6f23f
[ "Apache-2.0" ]
null
null
null
JniTensorflow/jni/genfiles/tensorflow/core/protobuf/device_properties.pb.cc
Wenstery/TensorflowApp
e666b5908cb624e83d9084a842e7cbb105d6f23f
[ "Apache-2.0" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tensorflow/core/protobuf/device_properties.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "tensorflow/core/protobuf/device_properties.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace tensorflow { class DeviceProperties_EnvironmentEntryDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<DeviceProperties::DeviceProperties_EnvironmentEntry> { } _DeviceProperties_EnvironmentEntry_default_instance_; class DevicePropertiesDefaultTypeInternal : public ::google::protobuf::internal::ExplicitlyConstructed<DeviceProperties> { } _DeviceProperties_default_instance_; namespace protobuf_tensorflow_2fcore_2fprotobuf_2fdevice_5fproperties_2eproto { namespace { ::google::protobuf::Metadata file_level_metadata[2]; } // namespace PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTableField const TableStruct::entries[] = { {0, 0, 0, ::google::protobuf::internal::kInvalidMask, 0, 0}, }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::AuxillaryParseTableField const TableStruct::aux[] = { ::google::protobuf::internal::AuxillaryParseTableField(), }; PROTOBUF_CONSTEXPR_VAR ::google::protobuf::internal::ParseTable const TableStruct::schema[] = { { NULL, NULL, 0, -1, -1, false }, { NULL, NULL, 0, -1, -1, false }, }; const ::google::protobuf::uint32 TableStruct::offsets[] = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, vendor_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, model_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, frequency_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, num_cores_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, environment_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, num_registers_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, l1_cache_size_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, l2_cache_size_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, l3_cache_size_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, shared_memory_size_per_multiprocessor_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, memory_size_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(DeviceProperties, bandwidth_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] = { { 0, -1, sizeof(DeviceProperties)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&_DeviceProperties_EnvironmentEntry_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&_DeviceProperties_default_instance_), }; namespace { void protobuf_AssignDescriptors() { AddDescriptors(); ::google::protobuf::MessageFactory* factory = NULL; AssignDescriptors( "tensorflow/core/protobuf/device_properties.proto", schemas, file_default_instances, TableStruct::offsets, factory, file_level_metadata, NULL, NULL); file_level_metadata[0].reflection = DeviceProperties::DeviceProperties_EnvironmentEntry::CreateReflection(file_level_metadata[0].descriptor, _DeviceProperties_EnvironmentEntry_default_instance_.get_mutable()); } GOOGLE_ATTRIBUTE_NOINLINE void protobuf_AssignDescriptorsOnce() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 2); } } // namespace void TableStruct::Shutdown() { _DeviceProperties_default_instance_.Shutdown(); delete file_level_metadata[1].reflection; delete file_level_metadata[0].reflection; } void TableStruct::InitDefaultsImpl() { GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::internal::InitProtobufDefaults(); _DeviceProperties_EnvironmentEntry_default_instance_.DefaultConstruct(); _DeviceProperties_default_instance_.DefaultConstruct(); _DeviceProperties_EnvironmentEntry_default_instance_.get_mutable()->set_default_instance(_DeviceProperties_EnvironmentEntry_default_instance_.get_mutable()); _DeviceProperties_EnvironmentEntry_default_instance_.get_mutable()->InitAsDefaultInstance(); } GOOGLE_ATTRIBUTE_NOINLINE void InitDefaults() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &TableStruct::InitDefaultsImpl); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] = { "\n0tensorflow/core/protobuf/device_proper" "ties.proto\022\ntensorflow\"\220\003\n\020DevicePropert" "ies\022\014\n\004type\030\001 \001(\t\022\016\n\006vendor\030\002 \001(\t\022\r\n\005mod" "el\030\003 \001(\t\022\021\n\tfrequency\030\004 \001(\003\022\021\n\tnum_cores" "\030\005 \001(\003\022B\n\013environment\030\006 \003(\0132-.tensorflow" ".DeviceProperties.EnvironmentEntry\022\025\n\rnu" "m_registers\030\007 \001(\003\022\025\n\rl1_cache_size\030\010 \001(\003" "\022\025\n\rl2_cache_size\030\t \001(\003\022\025\n\rl3_cache_size" "\030\n \001(\003\022-\n%shared_memory_size_per_multipr" "ocessor\030\013 \001(\003\022\023\n\013memory_size\030\014 \001(\003\022\021\n\tba" "ndwidth\030\r \001(\003\0322\n\020EnvironmentEntry\022\013\n\003key" "\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001B\033B\026DevicePrope" "rtiesProtos\370\001\001b\006proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 502); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "tensorflow/core/protobuf/device_properties.proto", &protobuf_RegisterTypes); ::google::protobuf::internal::OnShutdown(&TableStruct::Shutdown); } GOOGLE_ATTRIBUTE_NOINLINE void AddDescriptors() { static GOOGLE_PROTOBUF_DECLARE_ONCE(once); ::google::protobuf::GoogleOnceInit(&once, &AddDescriptorsImpl); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_tensorflow_2fcore_2fprotobuf_2fdevice_5fproperties_2eproto // =================================================================== DeviceProperties::DeviceProperties_EnvironmentEntry::DeviceProperties_EnvironmentEntry() {} DeviceProperties::DeviceProperties_EnvironmentEntry::DeviceProperties_EnvironmentEntry(::google::protobuf::Arena* arena) : SuperType(arena) {} ::google::protobuf::Metadata DeviceProperties::DeviceProperties_EnvironmentEntry::GetMetadata() const { protobuf_tensorflow_2fcore_2fprotobuf_2fdevice_5fproperties_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_tensorflow_2fcore_2fprotobuf_2fdevice_5fproperties_2eproto::file_level_metadata[0]; } void DeviceProperties::DeviceProperties_EnvironmentEntry::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } void DeviceProperties::DeviceProperties_EnvironmentEntry::MergeFrom(const DeviceProperties_EnvironmentEntry& other) { MergeFromInternal(other); } #if PROTOBUF_INLINE_NOT_IN_HEADERS #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int DeviceProperties::kTypeFieldNumber; const int DeviceProperties::kVendorFieldNumber; const int DeviceProperties::kModelFieldNumber; const int DeviceProperties::kFrequencyFieldNumber; const int DeviceProperties::kNumCoresFieldNumber; const int DeviceProperties::kEnvironmentFieldNumber; const int DeviceProperties::kNumRegistersFieldNumber; const int DeviceProperties::kL1CacheSizeFieldNumber; const int DeviceProperties::kL2CacheSizeFieldNumber; const int DeviceProperties::kL3CacheSizeFieldNumber; const int DeviceProperties::kSharedMemorySizePerMultiprocessorFieldNumber; const int DeviceProperties::kMemorySizeFieldNumber; const int DeviceProperties::kBandwidthFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 DeviceProperties::DeviceProperties() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (GOOGLE_PREDICT_TRUE(this != internal_default_instance())) { protobuf_tensorflow_2fcore_2fprotobuf_2fdevice_5fproperties_2eproto::InitDefaults(); } SharedCtor(); // @@protoc_insertion_point(constructor:tensorflow.DeviceProperties) } DeviceProperties::DeviceProperties(::google::protobuf::Arena* arena) : ::google::protobuf::Message(), _internal_metadata_(arena), environment_(arena) { #ifdef GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER protobuf_tensorflow_2fcore_2fprotobuf_2fdevice_5fproperties_2eproto::InitDefaults(); #endif // GOOGLE_PROTOBUF_NO_STATIC_INITIALIZER SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:tensorflow.DeviceProperties) } DeviceProperties::DeviceProperties(const DeviceProperties& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), _cached_size_(0) { _internal_metadata_.MergeFrom(from._internal_metadata_); environment_.MergeFrom(from.environment_); type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.type().size() > 0) { type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.type(), GetArenaNoVirtual()); } vendor_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.vendor().size() > 0) { vendor_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.vendor(), GetArenaNoVirtual()); } model_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.model().size() > 0) { model_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.model(), GetArenaNoVirtual()); } ::memcpy(&frequency_, &from.frequency_, reinterpret_cast<char*>(&bandwidth_) - reinterpret_cast<char*>(&frequency_) + sizeof(bandwidth_)); // @@protoc_insertion_point(copy_constructor:tensorflow.DeviceProperties) } void DeviceProperties::SharedCtor() { type_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); vendor_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); model_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&frequency_, 0, reinterpret_cast<char*>(&bandwidth_) - reinterpret_cast<char*>(&frequency_) + sizeof(bandwidth_)); _cached_size_ = 0; } DeviceProperties::~DeviceProperties() { // @@protoc_insertion_point(destructor:tensorflow.DeviceProperties) SharedDtor(); } void DeviceProperties::SharedDtor() { ::google::protobuf::Arena* arena = GetArenaNoVirtual(); if (arena != NULL) { return; } type_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena); vendor_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena); model_.Destroy(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), arena); } void DeviceProperties::ArenaDtor(void* object) { DeviceProperties* _this = reinterpret_cast< DeviceProperties* >(object); (void)_this; } void DeviceProperties::RegisterArenaDtor(::google::protobuf::Arena* arena) { } void DeviceProperties::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* DeviceProperties::descriptor() { protobuf_tensorflow_2fcore_2fprotobuf_2fdevice_5fproperties_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_tensorflow_2fcore_2fprotobuf_2fdevice_5fproperties_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const DeviceProperties& DeviceProperties::default_instance() { protobuf_tensorflow_2fcore_2fprotobuf_2fdevice_5fproperties_2eproto::InitDefaults(); return *internal_default_instance(); } DeviceProperties* DeviceProperties::New(::google::protobuf::Arena* arena) const { return ::google::protobuf::Arena::CreateMessage<DeviceProperties>(arena); } void DeviceProperties::Clear() { // @@protoc_insertion_point(message_clear_start:tensorflow.DeviceProperties) environment_.Clear(); type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); vendor_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); model_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); ::memset(&frequency_, 0, reinterpret_cast<char*>(&bandwidth_) - reinterpret_cast<char*>(&frequency_) + sizeof(bandwidth_)); } bool DeviceProperties::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:tensorflow.DeviceProperties) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // string type = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_type())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->type().data(), this->type().length(), ::google::protobuf::internal::WireFormatLite::PARSE, "tensorflow.DeviceProperties.type")); } else { goto handle_unusual; } break; } // string vendor = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(18u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_vendor())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->vendor().data(), this->vendor().length(), ::google::protobuf::internal::WireFormatLite::PARSE, "tensorflow.DeviceProperties.vendor")); } else { goto handle_unusual; } break; } // string model = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(26u)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_model())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->model().data(), this->model().length(), ::google::protobuf::internal::WireFormatLite::PARSE, "tensorflow.DeviceProperties.model")); } else { goto handle_unusual; } break; } // int64 frequency = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &frequency_))); } else { goto handle_unusual; } break; } // int64 num_cores = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &num_cores_))); } else { goto handle_unusual; } break; } // map<string, string> environment = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(50u)) { DeviceProperties_EnvironmentEntry::Parser< ::google::protobuf::internal::MapField< DeviceProperties_EnvironmentEntry, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 >, ::google::protobuf::Map< ::std::string, ::std::string > > parser(&environment_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), parser.key().length(), ::google::protobuf::internal::WireFormatLite::PARSE, "tensorflow.DeviceProperties.EnvironmentEntry.key")); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.value().data(), parser.value().length(), ::google::protobuf::internal::WireFormatLite::PARSE, "tensorflow.DeviceProperties.EnvironmentEntry.value")); } else { goto handle_unusual; } break; } // int64 num_registers = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(56u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &num_registers_))); } else { goto handle_unusual; } break; } // int64 l1_cache_size = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(64u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &l1_cache_size_))); } else { goto handle_unusual; } break; } // int64 l2_cache_size = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(72u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &l2_cache_size_))); } else { goto handle_unusual; } break; } // int64 l3_cache_size = 10; case 10: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(80u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &l3_cache_size_))); } else { goto handle_unusual; } break; } // int64 shared_memory_size_per_multiprocessor = 11; case 11: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(88u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &shared_memory_size_per_multiprocessor_))); } else { goto handle_unusual; } break; } // int64 memory_size = 12; case 12: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(96u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &memory_size_))); } else { goto handle_unusual; } break; } // int64 bandwidth = 13; case 13: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(104u)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &bandwidth_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:tensorflow.DeviceProperties) return true; failure: // @@protoc_insertion_point(parse_failure:tensorflow.DeviceProperties) return false; #undef DO_ } void DeviceProperties::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:tensorflow.DeviceProperties) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string type = 1; if (this->type().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->type().data(), this->type().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "tensorflow.DeviceProperties.type"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->type(), output); } // string vendor = 2; if (this->vendor().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->vendor().data(), this->vendor().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "tensorflow.DeviceProperties.vendor"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->vendor(), output); } // string model = 3; if (this->model().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->model().data(), this->model().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "tensorflow.DeviceProperties.model"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->model(), output); } // int64 frequency = 4; if (this->frequency() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(4, this->frequency(), output); } // int64 num_cores = 5; if (this->num_cores() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->num_cores(), output); } // map<string, string> environment = 6; if (!this->environment().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), p->first.length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "tensorflow.DeviceProperties.EnvironmentEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), p->second.length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "tensorflow.DeviceProperties.EnvironmentEntry.value"); } }; if (output->IsSerializationDeterministic() && this->environment().size() > 1) { ::google::protobuf::scoped_array<SortItem> items( new SortItem[this->environment().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->environment().begin(); it != this->environment().end(); ++it, ++n) { items[n] = SortItem(&*it); } ::std::sort(&items[0], &items[n], Less()); ::google::protobuf::scoped_ptr<DeviceProperties_EnvironmentEntry> entry; for (size_type i = 0; i < n; i++) { entry.reset(environment_.NewEntryWrapper( items[i]->first, items[i]->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 6, *entry, output); if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(items[i]); } } else { ::google::protobuf::scoped_ptr<DeviceProperties_EnvironmentEntry> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->environment().begin(); it != this->environment().end(); ++it) { entry.reset(environment_.NewEntryWrapper( it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 6, *entry, output); if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(&*it); } } } // int64 num_registers = 7; if (this->num_registers() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(7, this->num_registers(), output); } // int64 l1_cache_size = 8; if (this->l1_cache_size() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(8, this->l1_cache_size(), output); } // int64 l2_cache_size = 9; if (this->l2_cache_size() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(9, this->l2_cache_size(), output); } // int64 l3_cache_size = 10; if (this->l3_cache_size() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(10, this->l3_cache_size(), output); } // int64 shared_memory_size_per_multiprocessor = 11; if (this->shared_memory_size_per_multiprocessor() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(11, this->shared_memory_size_per_multiprocessor(), output); } // int64 memory_size = 12; if (this->memory_size() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(12, this->memory_size(), output); } // int64 bandwidth = 13; if (this->bandwidth() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(13, this->bandwidth(), output); } // @@protoc_insertion_point(serialize_end:tensorflow.DeviceProperties) } ::google::protobuf::uint8* DeviceProperties::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:tensorflow.DeviceProperties) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string type = 1; if (this->type().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->type().data(), this->type().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "tensorflow.DeviceProperties.type"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->type(), target); } // string vendor = 2; if (this->vendor().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->vendor().data(), this->vendor().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "tensorflow.DeviceProperties.vendor"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->vendor(), target); } // string model = 3; if (this->model().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->model().data(), this->model().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "tensorflow.DeviceProperties.model"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->model(), target); } // int64 frequency = 4; if (this->frequency() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(4, this->frequency(), target); } // int64 num_cores = 5; if (this->num_cores() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->num_cores(), target); } // map<string, string> environment = 6; if (!this->environment().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), p->first.length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "tensorflow.DeviceProperties.EnvironmentEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), p->second.length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "tensorflow.DeviceProperties.EnvironmentEntry.value"); } }; if (deterministic && this->environment().size() > 1) { ::google::protobuf::scoped_array<SortItem> items( new SortItem[this->environment().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->environment().begin(); it != this->environment().end(); ++it, ++n) { items[n] = SortItem(&*it); } ::std::sort(&items[0], &items[n], Less()); ::google::protobuf::scoped_ptr<DeviceProperties_EnvironmentEntry> entry; for (size_type i = 0; i < n; i++) { entry.reset(environment_.NewEntryWrapper( items[i]->first, items[i]->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 6, *entry, deterministic, target); ; if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(items[i]); } } else { ::google::protobuf::scoped_ptr<DeviceProperties_EnvironmentEntry> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->environment().begin(); it != this->environment().end(); ++it) { entry.reset(environment_.NewEntryWrapper( it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 6, *entry, deterministic, target); ; if (entry->GetArena() != NULL) { entry.release(); } Utf8Check::Check(&*it); } } } // int64 num_registers = 7; if (this->num_registers() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(7, this->num_registers(), target); } // int64 l1_cache_size = 8; if (this->l1_cache_size() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(8, this->l1_cache_size(), target); } // int64 l2_cache_size = 9; if (this->l2_cache_size() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(9, this->l2_cache_size(), target); } // int64 l3_cache_size = 10; if (this->l3_cache_size() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(10, this->l3_cache_size(), target); } // int64 shared_memory_size_per_multiprocessor = 11; if (this->shared_memory_size_per_multiprocessor() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(11, this->shared_memory_size_per_multiprocessor(), target); } // int64 memory_size = 12; if (this->memory_size() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(12, this->memory_size(), target); } // int64 bandwidth = 13; if (this->bandwidth() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(13, this->bandwidth(), target); } // @@protoc_insertion_point(serialize_to_array_end:tensorflow.DeviceProperties) return target; } size_t DeviceProperties::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:tensorflow.DeviceProperties) size_t total_size = 0; // map<string, string> environment = 6; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->environment_size()); { ::google::protobuf::scoped_ptr<DeviceProperties_EnvironmentEntry> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->environment().begin(); it != this->environment().end(); ++it) { if (entry.get() != NULL && entry->GetArena() != NULL) { entry.release(); } entry.reset(environment_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } if (entry.get() != NULL && entry->GetArena() != NULL) { entry.release(); } } // string type = 1; if (this->type().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->type()); } // string vendor = 2; if (this->vendor().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->vendor()); } // string model = 3; if (this->model().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->model()); } // int64 frequency = 4; if (this->frequency() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->frequency()); } // int64 num_cores = 5; if (this->num_cores() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->num_cores()); } // int64 num_registers = 7; if (this->num_registers() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->num_registers()); } // int64 l1_cache_size = 8; if (this->l1_cache_size() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->l1_cache_size()); } // int64 l2_cache_size = 9; if (this->l2_cache_size() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->l2_cache_size()); } // int64 l3_cache_size = 10; if (this->l3_cache_size() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->l3_cache_size()); } // int64 shared_memory_size_per_multiprocessor = 11; if (this->shared_memory_size_per_multiprocessor() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->shared_memory_size_per_multiprocessor()); } // int64 memory_size = 12; if (this->memory_size() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->memory_size()); } // int64 bandwidth = 13; if (this->bandwidth() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->bandwidth()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void DeviceProperties::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:tensorflow.DeviceProperties) GOOGLE_DCHECK_NE(&from, this); const DeviceProperties* source = ::google::protobuf::internal::DynamicCastToGenerated<const DeviceProperties>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:tensorflow.DeviceProperties) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:tensorflow.DeviceProperties) MergeFrom(*source); } } void DeviceProperties::MergeFrom(const DeviceProperties& from) { // @@protoc_insertion_point(class_specific_merge_from_start:tensorflow.DeviceProperties) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; environment_.MergeFrom(from.environment_); if (from.type().size() > 0) { set_type(from.type()); } if (from.vendor().size() > 0) { set_vendor(from.vendor()); } if (from.model().size() > 0) { set_model(from.model()); } if (from.frequency() != 0) { set_frequency(from.frequency()); } if (from.num_cores() != 0) { set_num_cores(from.num_cores()); } if (from.num_registers() != 0) { set_num_registers(from.num_registers()); } if (from.l1_cache_size() != 0) { set_l1_cache_size(from.l1_cache_size()); } if (from.l2_cache_size() != 0) { set_l2_cache_size(from.l2_cache_size()); } if (from.l3_cache_size() != 0) { set_l3_cache_size(from.l3_cache_size()); } if (from.shared_memory_size_per_multiprocessor() != 0) { set_shared_memory_size_per_multiprocessor(from.shared_memory_size_per_multiprocessor()); } if (from.memory_size() != 0) { set_memory_size(from.memory_size()); } if (from.bandwidth() != 0) { set_bandwidth(from.bandwidth()); } } void DeviceProperties::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:tensorflow.DeviceProperties) if (&from == this) return; Clear(); MergeFrom(from); } void DeviceProperties::CopyFrom(const DeviceProperties& from) { // @@protoc_insertion_point(class_specific_copy_from_start:tensorflow.DeviceProperties) if (&from == this) return; Clear(); MergeFrom(from); } bool DeviceProperties::IsInitialized() const { return true; } void DeviceProperties::Swap(DeviceProperties* other) { if (other == this) return; if (GetArenaNoVirtual() == other->GetArenaNoVirtual()) { InternalSwap(other); } else { DeviceProperties* temp = New(GetArenaNoVirtual()); temp->MergeFrom(*other); other->CopyFrom(*this); InternalSwap(temp); if (GetArenaNoVirtual() == NULL) { delete temp; } } } void DeviceProperties::UnsafeArenaSwap(DeviceProperties* other) { if (other == this) return; GOOGLE_DCHECK(GetArenaNoVirtual() == other->GetArenaNoVirtual()); InternalSwap(other); } void DeviceProperties::InternalSwap(DeviceProperties* other) { environment_.Swap(&other->environment_); type_.Swap(&other->type_); vendor_.Swap(&other->vendor_); model_.Swap(&other->model_); std::swap(frequency_, other->frequency_); std::swap(num_cores_, other->num_cores_); std::swap(num_registers_, other->num_registers_); std::swap(l1_cache_size_, other->l1_cache_size_); std::swap(l2_cache_size_, other->l2_cache_size_); std::swap(l3_cache_size_, other->l3_cache_size_); std::swap(shared_memory_size_per_multiprocessor_, other->shared_memory_size_per_multiprocessor_); std::swap(memory_size_, other->memory_size_); std::swap(bandwidth_, other->bandwidth_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata DeviceProperties::GetMetadata() const { protobuf_tensorflow_2fcore_2fprotobuf_2fdevice_5fproperties_2eproto::protobuf_AssignDescriptorsOnce(); return protobuf_tensorflow_2fcore_2fprotobuf_2fdevice_5fproperties_2eproto::file_level_metadata[kIndexInFileMessages]; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // DeviceProperties // string type = 1; void DeviceProperties::clear_type() { type_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } const ::std::string& DeviceProperties::type() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.type) return type_.Get(); } void DeviceProperties::set_type(const ::std::string& value) { type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.type) } void DeviceProperties::set_type(const char* value) { GOOGLE_DCHECK(value != NULL); type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:tensorflow.DeviceProperties.type) } void DeviceProperties::set_type(const char* value, size_t size) { type_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:tensorflow.DeviceProperties.type) } ::std::string* DeviceProperties::mutable_type() { // @@protoc_insertion_point(field_mutable:tensorflow.DeviceProperties.type) return type_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::std::string* DeviceProperties::release_type() { // @@protoc_insertion_point(field_release:tensorflow.DeviceProperties.type) return type_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::std::string* DeviceProperties::unsafe_arena_release_type() { // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.DeviceProperties.type) GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); return type_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } void DeviceProperties::set_allocated_type(::std::string* type) { if (type != NULL) { } else { } type_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceProperties.type) } void DeviceProperties::unsafe_arena_set_allocated_type( ::std::string* type) { GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); if (type != NULL) { } else { } type_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), type, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.DeviceProperties.type) } // string vendor = 2; void DeviceProperties::clear_vendor() { vendor_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } const ::std::string& DeviceProperties::vendor() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.vendor) return vendor_.Get(); } void DeviceProperties::set_vendor(const ::std::string& value) { vendor_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.vendor) } void DeviceProperties::set_vendor(const char* value) { GOOGLE_DCHECK(value != NULL); vendor_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:tensorflow.DeviceProperties.vendor) } void DeviceProperties::set_vendor(const char* value, size_t size) { vendor_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:tensorflow.DeviceProperties.vendor) } ::std::string* DeviceProperties::mutable_vendor() { // @@protoc_insertion_point(field_mutable:tensorflow.DeviceProperties.vendor) return vendor_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::std::string* DeviceProperties::release_vendor() { // @@protoc_insertion_point(field_release:tensorflow.DeviceProperties.vendor) return vendor_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::std::string* DeviceProperties::unsafe_arena_release_vendor() { // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.DeviceProperties.vendor) GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); return vendor_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } void DeviceProperties::set_allocated_vendor(::std::string* vendor) { if (vendor != NULL) { } else { } vendor_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), vendor, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceProperties.vendor) } void DeviceProperties::unsafe_arena_set_allocated_vendor( ::std::string* vendor) { GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); if (vendor != NULL) { } else { } vendor_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), vendor, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.DeviceProperties.vendor) } // string model = 3; void DeviceProperties::clear_model() { model_.ClearToEmpty(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } const ::std::string& DeviceProperties::model() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.model) return model_.Get(); } void DeviceProperties::set_model(const ::std::string& value) { model_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.model) } void DeviceProperties::set_model(const char* value) { GOOGLE_DCHECK(value != NULL); model_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_char:tensorflow.DeviceProperties.model) } void DeviceProperties::set_model(const char* value, size_t size) { model_.Set(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string( reinterpret_cast<const char*>(value), size), GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_pointer:tensorflow.DeviceProperties.model) } ::std::string* DeviceProperties::mutable_model() { // @@protoc_insertion_point(field_mutable:tensorflow.DeviceProperties.model) return model_.Mutable(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::std::string* DeviceProperties::release_model() { // @@protoc_insertion_point(field_release:tensorflow.DeviceProperties.model) return model_.Release(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::std::string* DeviceProperties::unsafe_arena_release_model() { // @@protoc_insertion_point(field_unsafe_arena_release:tensorflow.DeviceProperties.model) GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); return model_.UnsafeArenaRelease(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } void DeviceProperties::set_allocated_model(::std::string* model) { if (model != NULL) { } else { } model_.SetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), model, GetArenaNoVirtual()); // @@protoc_insertion_point(field_set_allocated:tensorflow.DeviceProperties.model) } void DeviceProperties::unsafe_arena_set_allocated_model( ::std::string* model) { GOOGLE_DCHECK(GetArenaNoVirtual() != NULL); if (model != NULL) { } else { } model_.UnsafeArenaSetAllocated(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), model, GetArenaNoVirtual()); // @@protoc_insertion_point(field_unsafe_arena_set_allocated:tensorflow.DeviceProperties.model) } // int64 frequency = 4; void DeviceProperties::clear_frequency() { frequency_ = GOOGLE_LONGLONG(0); } ::google::protobuf::int64 DeviceProperties::frequency() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.frequency) return frequency_; } void DeviceProperties::set_frequency(::google::protobuf::int64 value) { frequency_ = value; // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.frequency) } // int64 num_cores = 5; void DeviceProperties::clear_num_cores() { num_cores_ = GOOGLE_LONGLONG(0); } ::google::protobuf::int64 DeviceProperties::num_cores() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.num_cores) return num_cores_; } void DeviceProperties::set_num_cores(::google::protobuf::int64 value) { num_cores_ = value; // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.num_cores) } // map<string, string> environment = 6; int DeviceProperties::environment_size() const { return environment_.size(); } void DeviceProperties::clear_environment() { environment_.Clear(); } const ::google::protobuf::Map< ::std::string, ::std::string >& DeviceProperties::environment() const { // @@protoc_insertion_point(field_map:tensorflow.DeviceProperties.environment) return environment_.GetMap(); } ::google::protobuf::Map< ::std::string, ::std::string >* DeviceProperties::mutable_environment() { // @@protoc_insertion_point(field_mutable_map:tensorflow.DeviceProperties.environment) return environment_.MutableMap(); } // int64 num_registers = 7; void DeviceProperties::clear_num_registers() { num_registers_ = GOOGLE_LONGLONG(0); } ::google::protobuf::int64 DeviceProperties::num_registers() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.num_registers) return num_registers_; } void DeviceProperties::set_num_registers(::google::protobuf::int64 value) { num_registers_ = value; // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.num_registers) } // int64 l1_cache_size = 8; void DeviceProperties::clear_l1_cache_size() { l1_cache_size_ = GOOGLE_LONGLONG(0); } ::google::protobuf::int64 DeviceProperties::l1_cache_size() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.l1_cache_size) return l1_cache_size_; } void DeviceProperties::set_l1_cache_size(::google::protobuf::int64 value) { l1_cache_size_ = value; // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.l1_cache_size) } // int64 l2_cache_size = 9; void DeviceProperties::clear_l2_cache_size() { l2_cache_size_ = GOOGLE_LONGLONG(0); } ::google::protobuf::int64 DeviceProperties::l2_cache_size() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.l2_cache_size) return l2_cache_size_; } void DeviceProperties::set_l2_cache_size(::google::protobuf::int64 value) { l2_cache_size_ = value; // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.l2_cache_size) } // int64 l3_cache_size = 10; void DeviceProperties::clear_l3_cache_size() { l3_cache_size_ = GOOGLE_LONGLONG(0); } ::google::protobuf::int64 DeviceProperties::l3_cache_size() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.l3_cache_size) return l3_cache_size_; } void DeviceProperties::set_l3_cache_size(::google::protobuf::int64 value) { l3_cache_size_ = value; // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.l3_cache_size) } // int64 shared_memory_size_per_multiprocessor = 11; void DeviceProperties::clear_shared_memory_size_per_multiprocessor() { shared_memory_size_per_multiprocessor_ = GOOGLE_LONGLONG(0); } ::google::protobuf::int64 DeviceProperties::shared_memory_size_per_multiprocessor() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.shared_memory_size_per_multiprocessor) return shared_memory_size_per_multiprocessor_; } void DeviceProperties::set_shared_memory_size_per_multiprocessor(::google::protobuf::int64 value) { shared_memory_size_per_multiprocessor_ = value; // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.shared_memory_size_per_multiprocessor) } // int64 memory_size = 12; void DeviceProperties::clear_memory_size() { memory_size_ = GOOGLE_LONGLONG(0); } ::google::protobuf::int64 DeviceProperties::memory_size() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.memory_size) return memory_size_; } void DeviceProperties::set_memory_size(::google::protobuf::int64 value) { memory_size_ = value; // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.memory_size) } // int64 bandwidth = 13; void DeviceProperties::clear_bandwidth() { bandwidth_ = GOOGLE_LONGLONG(0); } ::google::protobuf::int64 DeviceProperties::bandwidth() const { // @@protoc_insertion_point(field_get:tensorflow.DeviceProperties.bandwidth) return bandwidth_; } void DeviceProperties::set_bandwidth(::google::protobuf::int64 value) { bandwidth_ = value; // @@protoc_insertion_point(field_set:tensorflow.DeviceProperties.bandwidth) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace tensorflow // @@protoc_insertion_point(global_scope)
38.651654
209
0.700732
[ "object", "model" ]
5d8a6937822879874dd367d99a376bddc338ee9c
7,278
cpp
C++
src/framework/io/MeshBinaryIO.cpp
poelzi/efficient-sparse-voxel-octrees.
39e186a07cc12630b3b70231d61dcf2ac631a9b4
[ "BSD-3-Clause" ]
51
2016-09-27T19:13:57.000Z
2021-12-13T03:44:12.000Z
src/framework/io/MeshBinaryIO.cpp
Neo-Zhixing/efficient-sparse-voxel-octrees
d5ee9c494c08e595870b3b2b627a695c747bf2cc
[ "BSD-3-Clause" ]
null
null
null
src/framework/io/MeshBinaryIO.cpp
Neo-Zhixing/efficient-sparse-voxel-octrees
d5ee9c494c08e595870b3b2b627a695c747bf2cc
[ "BSD-3-Clause" ]
18
2016-11-24T11:33:18.000Z
2022-03-20T01:19:21.000Z
/* * Copyright (c) 2009-2011, NVIDIA Corporation * 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 NVIDIA Corporation nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "io/MeshBinaryIO.hpp" #include "3d/Mesh.hpp" #include "io/Stream.hpp" #include "io/ImageBinaryIO.hpp" using namespace FW; //------------------------------------------------------------------------ MeshBase* FW::importBinaryMesh(InputStream& stream) { MeshBase* mesh = new MeshBase; // MeshHeader. char formatID[9]; stream.readFully(formatID, 8); formatID[8] = '\0'; if (String(formatID) != "BinMesh ") setError("Not a binary mesh file!"); S32 version; stream >> version; int numTex; switch (version) { case 1: numTex = 0; break; case 2: numTex = MeshBase::TextureType_Alpha + 1; break; case 3: numTex = MeshBase::TextureType_Displacement + 1; break; case 4: numTex = MeshBase::TextureType_Environment + 1; break; default: numTex = 0; setError("Unsupported binary mesh version!"); break; } S32 numAttribs, numVertices, numSubmeshes, numTextures = 0; stream >> numAttribs >> numVertices >> numSubmeshes; if (version >= 2) stream >> numTextures; if (numAttribs < 0 || numVertices < 0 || numSubmeshes < 0 || numTextures < 0) setError("Corrupt binary mesh data!"); // Array of AttribSpec. for (int i = 0; i < numAttribs && !hasError(); i++) { S32 type, format, length; stream >> type >> format >> length; if (type < 0 || format < 0 || format >= MeshBase::AttribFormat_Max || length < 1 || length > 4) setError("Corrupt binary mesh data!"); else mesh->addAttrib((MeshBase::AttribType)type, (MeshBase::AttribFormat)format, length); } // Array of Vertex. if (!hasError()) { mesh->resetVertices(numVertices); stream.readFully(mesh->getMutableVertexPtr(), numVertices * mesh->vertexStride()); } // Array of Texture. Array<Texture> textures(NULL, numTextures); for (int i = 0; i < numTextures && !hasError(); i++) { String id; stream >> id; Image* image = importBinaryImage(stream); textures[i] = Texture::find(id); if (textures[i].exists()) delete image; else textures[i] = Texture(image, id); } // Array of Submesh. for (int i = 0; i < numSubmeshes && !hasError(); i++) { mesh->addSubmesh(); MeshBase::Material& mat = mesh->material(i); Vec3f ambient; stream >> ambient >> mat.diffuse >> mat.specular >> mat.glossiness; if (version >= 3) stream >> mat.displacementCoef >> mat.displacementBias; for (int j = 0; j < numTex; j++) { S32 texIdx; stream >> texIdx; if (texIdx < -1 || texIdx >= numTextures) setError("Corrupt binary mesh data!"); else if (texIdx != -1) mat.textures[j] = textures[texIdx]; } S32 numTriangles; stream >> numTriangles; if (numTriangles < 0) setError("Corrupt binary mesh data!"); else { Array<Vec3i>& inds = mesh->mutableIndices(i); inds.reset(numTriangles); stream.readFully(inds.getPtr(), inds.getNumBytes()); } } // Handle errors. if (hasError()) { delete mesh; return NULL; } return mesh; } //------------------------------------------------------------------------ void FW::exportBinaryMesh(OutputStream& stream, const MeshBase* mesh) { FW_ASSERT(mesh); // Collapse duplicate textures. int numTex = MeshBase::TextureType_Environment + 1; Array<Texture> textures; Hash<const Image*, S32> texHash; texHash.add(NULL, -1); for (int i = 0; i < mesh->numSubmeshes(); i++) { const MeshBase::Material& mat = mesh->material(i); for (int j = 0; j < numTex; j++) { const Image* key = mat.textures[j].getImage(); if (texHash.contains(key)) continue; texHash.add(key, textures.getSize()); textures.add(mat.textures[j]); } } // MeshHeader. stream.write("BinMesh ", 8); stream << (S32)4 << (S32)mesh->numAttribs() << (S32)mesh->numVertices() << (S32)mesh->numSubmeshes() << (S32)textures.getSize(); // Array of AttribSpec. for (int i = 0; i < mesh->numAttribs(); i++) { const MeshBase::AttribSpec& spec = mesh->attribSpec(i); stream << (S32)spec.type << (S32)spec.format << spec.length; } // Array of Vertex. stream.write(mesh->getVertexPtr(), mesh->numVertices() * mesh->vertexStride()); // Array of Texture. for (int i = 0; i < textures.getSize(); i++) { stream << textures[i].getID(); exportBinaryImage(stream, textures[i].getImage()); } // Array of Submesh. for (int i = 0; i < mesh->numSubmeshes(); i++) { const Array<Vec3i>& inds = mesh->indices(i); const MeshBase::Material& mat = mesh->material(i); stream << Vec3f(0.0f) << mat.diffuse << mat.specular << mat.glossiness; stream << mat.displacementCoef << mat.displacementBias; for (int j = 0; j < numTex; j++) stream << texHash[mat.textures[j].getImage()]; stream << (S32)inds.getSize(); stream.write(inds.getPtr(), inds.getNumBytes()); } } //------------------------------------------------------------------------
33.694444
133
0.568975
[ "mesh", "3d" ]
5d93614b3425fc7a194b0e5b8c8c12d97d70bd0e
5,888
cpp
C++
MyDebugger/main.cpp
gmh5225/GleeBug
63a6668514e79bf689b9fec395c4c017e9d71adb
[ "MIT" ]
1,068
2015-12-28T15:43:43.000Z
2022-01-21T05:01:23.000Z
MyDebugger/main.cpp
gmh5225/GleeBug
63a6668514e79bf689b9fec395c4c017e9d71adb
[ "MIT" ]
58
2015-12-16T10:50:45.000Z
2021-07-19T13:13:05.000Z
MyDebugger/main.cpp
gmh5225/GleeBug
63a6668514e79bf689b9fec395c4c017e9d71adb
[ "MIT" ]
36
2016-02-09T12:30:38.000Z
2022-03-31T15:32:41.000Z
#include <cstdio> #include "MyDebugger.h" #include "GleeBug/Static.File.h" #include "GleeBug/Static.Pe.h" #include "GleeBug/Static.BufferFile.h" static void testDebugger() { #ifdef _WIN64 wchar_t szFilePath[256] = L"c:\\MembpTest_x64.exe"; #else //x86 wchar_t szFilePath[256] = L"c:\\MembpTest_x32.exe"; #endif //_WIN64 wchar_t szCommandLine[256] = L""; wchar_t szCurrentDir[256] = L"c:\\"; MyDebugger dbg; if (dbg.Init(szFilePath, szCommandLine, szCurrentDir)) { puts("Debugger::Init success!"); dbg.Start(); puts("Debugger::Start finished!"); } else { puts("Debugger::Init failed!"); } } template<typename T> static void printRegion(const char* str, Region<T> region, bool newline = true) { printf("\n%s (offset: 0x%X, size: 0x%X, v: %s, e: %s)", str, region.Offset(), region.Size(), region.Valid() ? "true" : "false", region.Empty() ? "true" : "false"); if (newline) puts(""); } template<typename T> static void printNtHeaders(T inth) { printRegion("NT Headers:", inth); printf(" Signature: %08X\n", inth->Signature); auto ifh = &inth->FileHeader; puts("\n File Header:"); printf(" Machine : %04X\n", ifh->Machine); printf(" NumberOfSections : %04X\n", ifh->NumberOfSections); printf(" TimeDateStamp : %08X\n", ifh->TimeDateStamp); printf(" SizeOfOptionalHeader: %04X\n", ifh->SizeOfOptionalHeader); auto ioh = &inth->OptionalHeader; puts("\n Optional Header:"); printf(" Magic : %04X\n", ioh->Magic); printf(" EntryPoint: %08X\n", ioh->AddressOfEntryPoint); printf(" ImageBase : %llX\n", (uint64_t)ioh->ImageBase); printf(" Subsystem : %04X\n", ioh->Subsystem); } static bool testPeFile(const wchar_t* szFileName, bool dumpData = true) { using namespace GleeBug; auto result = false; File diskFile(szFileName, File::ReadOnly); if (diskFile.Open()) { auto diskSize = diskFile.GetSize(); std::vector<uint8> diskData(diskSize); if (diskFile.Read(0, diskData.data(), diskSize)) { BufferFile file(diskData.data(), diskSize); Pe pe(file); auto parseError = pe.Parse(true); if (parseError == Pe::ErrorOk) { result = true; if (!dumpData) return result; auto idh = pe.GetDosHeader(); printRegion("DOS Header:", idh); printf(" e_magic: %02X\n", idh->e_magic); printf(" e_lfanew: %08X\n", idh->e_lfanew); auto afterDosData = pe.GetAfterDosData(); printRegion("After DOS Data", afterDosData); if (pe.IsPe64()) printNtHeaders(pe.GetNtHeaders64()); else printNtHeaders(pe.GetNtHeaders32()); auto afterOptionalData = pe.GetAfterOptionalData(); printRegion("After Optional Data", afterOptionalData); auto ish = pe.GetSectionHeaders(); printRegion("Section Headers", ish, false); auto afterSectionHeadersData = pe.GetAfterSectionHeadersData(); printRegion("After Section Headers Data", afterSectionHeadersData); auto sections = pe.GetSections(); for (const auto & section : sections) { if (section.GetIndex()) puts(""); printf(" Section %d:\n", section.GetIndex()); auto cur = section.GetHeader(); char name[9] = ""; memcpy(name, cur.Name, sizeof(cur.Name)); printf(" Name : %s\n", name); printf(" VSize: %08X\n", cur.Misc.VirtualSize); printf(" VAddr: %08X\n", cur.VirtualAddress); printf(" RSize: %08X\n", cur.SizeOfRawData); printf(" RAddr: %08X", cur.PointerToRawData); printRegion(" Before Data", section.GetBeforeData(), false); printRegion(" Data", section.GetData()); } printf("\nOffset -> Section:\n"); for (auto range : pe.GetOffsetSectionMap()) { printf(" %08llX:%08llX -> %d\n", range.first.first, range.first.second, range.second); } printf("\nRva -> Section:\n"); for (auto range : pe.GetRvaSectionMap()) { printf(" %08llX:%08llX -> %d\n", range.first.first, range.first.second, range.second); } } else printf("Pe::Parse failed (%s)!\n", pe.ErrorText(parseError)); } else puts("File::Read failed!"); } else puts("File::Open failed!"); return result; } static void testCorkami() { #include "PeTests.h" wchar_t szBasePath[MAX_PATH] = L"c:\\!exclude\\pe\\bin\\"; int okCount = 0; for (auto i = 0; i < _countof(peTestFiles); i++) { std::wstring fileName(szBasePath); fileName += peTestFiles[i]; if (testPeFile(fileName.c_str(), false)) okCount++; else { printf("file: %ws\n\n", fileName.c_str()); } } printf("\n%d/%zu parsed OK!\n", okCount, _countof(peTestFiles)); } int main() { //testDebugger(); testCorkami(); //testPeFile(L"c:\\!exclude\\pe\\bin\\appendedhdr.exe"); puts(""); system("pause"); return 0; }
34.635294
108
0.512908
[ "vector" ]
5d980e2cfc68ba7d709f108650c7258bc574aa6b
2,165
cpp
C++
CONTRIB/LLVM/_Demo/Lib_GZ/Gfx/Dispacher.cpp
Cwc-Test/CpcdosOS2.1
d52c170be7f11cc50de38ef536d4355743d21706
[ "Apache-2.0" ]
1
2021-05-05T20:42:24.000Z
2021-05-05T20:42:24.000Z
CONTRIB/LLVM/_Demo/Lib_GZ/Gfx/Dispacher.cpp
Cwc-Test/CpcdosOS2.1
d52c170be7f11cc50de38ef536d4355743d21706
[ "Apache-2.0" ]
null
null
null
CONTRIB/LLVM/_Demo/Lib_GZ/Gfx/Dispacher.cpp
Cwc-Test/CpcdosOS2.1
d52c170be7f11cc50de38ef536d4355743d21706
[ "Apache-2.0" ]
null
null
null
//This file is part of "GZE - GroundZero Engine" //The permisive licence allow to use GZE for free or commercial project (Apache License, Version 2.0). //For conditions of distribution and use, see copyright notice in Licence.txt, this license must be included with any distribution of the code. //Though not required by the license agreement, please consider the following will be greatly appreciated: //- We would like to hear about projects where GZE is used. //- Include an attribution statement somewhere in your project. //- If you want to see GZE evolve please help us with a donation. #include "Lib_GZ/Gfx/Dispacher.h" #include "Lib_GZ/Gfx/Object.h" #include "Lib_GZ/Gfx/Buffer.h" #include "Lib_GZ/Gfx/Root.h" #include "Lib_GZ/Sys/Debug.h" #include "Lib_GZ/Class.h" #include "Lib_GZ/ThreadMsg.h" namespace Lib_GZ{namespace Gfx{namespace Dispacher{ ////// Current Lib Access //// //// Current Static Access //// #undef _ #define _ Dispacher void Ini_Class(){ } #ifdef GZ_tHaveCallStack gzFuncStack zFuncName[] = {{0,"Dispacher"},{0,"fAddChild"},{0,"fDispatchUpdate"},{0,"fDispatchRender"},{0,"fDispatchContextResume"}}; #endif /////////////////////////////// } GZ_mCppClass(Dispacher) cDispacher::cDispacher(Lib_GZ::cBase* _parent) : Lib_GZ::cClass(_parent){ } void cDispacher::Ini_cDispacher(){ gz_(0) } void cDispacher::fAddChild(Lib_GZ::Gfx::cRoot* _oObj){ gz_(1) qaChild.fPush(gzSCastSelf<Lib_GZ::Gfx::cRoot>(_oObj)); } void cDispacher::fDispatchUpdate(){ gz_(2) gzFOR_EACH_QArrayNew(qaChild, _qe_oChild, gzSp<Lib_GZ::Gfx::cRoot>){ Lib_GZ::Gfx::cRoot* _oChild = _qe_oChild.val()->get(); _oChild->fUpdateRoot(); gzEND_QArray(_qe_oChild)} } void cDispacher::fDispatchRender(){ gz_(3) gzFOR_EACH_QArrayNew(qaChild, _qe_oChild, gzSp<Lib_GZ::Gfx::cRoot>){ Lib_GZ::Gfx::cRoot* _oChild = _qe_oChild.val()->get(); _oChild->fRender(); gzEND_QArray(_qe_oChild)} } void cDispacher::fDispatchContextResume(){ gz_(4) gzFOR_EACH_QArrayNew(qaChild, _qe_oChild, gzSp<Lib_GZ::Gfx::cRoot>){ Lib_GZ::Gfx::cRoot* _oChild = _qe_oChild.val()->get(); _oChild->fContextResume(); gzEND_QArray(_qe_oChild)} } cDispacher::~cDispacher(){ } }}
29.256757
143
0.727483
[ "object" ]
4b6b8a601ddcc816a5ecca7413b8b070ced34882
9,931
cpp
C++
VectorTest/VectorTest.cpp
aykSpace/GanimedDeorbitation
1de8ed7a84a25866d81f3f0843ac01991862b549
[ "MIT" ]
null
null
null
VectorTest/VectorTest.cpp
aykSpace/GanimedDeorbitation
1de8ed7a84a25866d81f3f0843ac01991862b549
[ "MIT" ]
null
null
null
VectorTest/VectorTest.cpp
aykSpace/GanimedDeorbitation
1de8ed7a84a25866d81f3f0843ac01991862b549
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "Date_Time.h" #include "Date_Time.cpp" #include "Atmosphera.h" #include "Atmosphera.cpp" #include "OrbitElements.h" #include "OrbitElements.cpp" #include "Vector.h" #include "Vector.cpp" #include "Spacecraft.h" #include "Spacecraft.cpp" #include "Soyuz.h" #include "Soyuz.cpp" #include "Engine.h" #include "Engine.cpp" #include "Printer.h" #include "Printer.cpp" #include "Matrix.hpp" #include "GanimedLandModule.h" #include "GanimedLandModule.cpp" #include "ZoneRadioVision.h" #include "ZoneRadioVision.cpp" #include "GroundStation.h" #include "GroundStation.cpp" class TestVector : public testing::Test { protected: void SetUp() { Vector::f = 110; Vector::ap = 16; Date_Time DataTime(2011,10,05); vect = new Vector(1816, 70500, -4887.4796260, -1988.8661830, 4242.4879740, -0.536599240, -6.3971388400, -3.612259210, 0.04158185, DataTime); soyuz = new Soyuz(*vect, 6746.0, 1158.0, 2886.0, 115.20, 0.385080, -0.036830, 0.0, 0.008234, 273.0, 6, 1, 2); Engine skd(1,"SKD", 300, 302); soyuz->AddEngine(skd); } void TearDown() override { delete vect; delete soyuz; } Vector* vect; Soyuz* soyuz; }; /* TEST_F(TestVector, gpz36x36_is_working) { Vector::f = 110; Vector::ap = 16; Date_Time DataTime(2014,10,05); Vector vectorAsn(2, 47519.0, 4877.474915, 810.551593, 4485.757142, -3.800656006, 5.567955078, 3.124009521, 0.03, DataTime); vectorAsn.Prognoz((unsigned int)3); ASSERT_NEAR(vect->h, 383.39854, 0.0001); }*/ /* TEST_F(TestVector, test_readingGpzAndNorm_is_OK) { Printer::ReadFileName = "..\\dpz_norm4-36.txt"; double ** c = vect->CreateSquareMatrix(37); double ** d = vect->CreateSquareMatrix(37); double norm[37][37]; Printer::ReadGpzFromFile(c,d); int delta = 0; int k = 0; double res [1300]; long double koef1; long double koef2; double koef3; for (int i = 2; i < 37; i++) { for (int j = 0; j <= i; j++) { j == 0 ? delta = 1 : delta = 2; koef1 = vect->factorial(i - j); koef2 = vect->factorial(i+j); norm[i][j] = sqrt((delta*(2 * i + 1)* (koef1))/koef2); res[k] = c[i][j]; k ++ ; } } Printer::OutFileName = "..\\gpzN1.txt"; Printer::Precision = 10; Printer::PrintDoubleToFile(res, k); vect->DeleteSquareMatrix(37, c); vect->DeleteSquareMatrix(37, d); SUCCEED(); }*/ /* TEST_F(TestVector, test_readingGpzAndNorm_is_OK) { Printer::ReadFileName = "..\\dpz4-36.txt"; double c[665]; double d[665]; double c0[35]; Printer::ReadGpzFromFile2(c0,c,d); auto i = 1; }*/ /* TEST_F(TestVector, test_polinom_is_working) { bool kk = false; int n = 7; double* a = new double[n]; double res; double mass[500]; double mass1[500]; int countStr; Printer::ReadFileName = "C:\\PROG_ASN\\asn.003"; Printer::OutFileName = "..\\resultAsn.txt"; Printer::Precision = 11; Printer::ReadDoublesFromFile(1,4,mass, mass1, countStr); double * resMass = new double [countStr]; for (int i = 0; i < countStr; i++) { vect->Polinom(kk, n, countStr, mass, mass1, mass[i], a, res); resMass[i] = fabs(mass1[i]) - fabs(res); //resMass[i] = res; } Printer::PrintDoubleToFile(mass, resMass, countStr); delete [] resMass; delete [] a; ASSERT_EQ(countStr, 408); } */ TEST_F(TestVector, Kepler_To_Vector) { double M0 = 0; double e = 0.00045; double a = 2831.2; double omega = 0 * M_PI / 180.0; double i = M_PI / 2; double omega1 = 0 * M_PI / 180.0; double n = sqrt(mu_g/(a*a*a)); Date_Time dateTime(2015, 02, 20, 00, 00, 00); Date_Time dateTimeStart(1997, 01, 16, 00, 00, 00); OrbitElements oe (1, dateTimeStart.GetSecOfDay(), a, e, omega, i, omega1, M0, n,dateTimeStart); Vector vect = oe.KeplerToVector(dateTime); n = 1.016e-5; M0 = 192.417; e = 0.0013; a = 1070400; omega = 192.417 * PI / 180.0; i = 0.177 * M_PI / 180; omega1 = 63.552 * M_PI / 180; OrbitElements oe1 (1, dateTime.GetSecOfDay(), a, e, omega, i, omega1, M0, n, dateTime); Vector vect1 = oe1.KeplerToVector(dateTime); int ii = 0; ASSERT_NEAR(vect.x, 2829.9211857915025, 0.0000001); ASSERT_NEAR(vect.y, 0.00000000000000031835908591289033, 0.000001); ASSERT_NEAR(vect.z, 5.1993701472998666, 0.0000001); ASSERT_NEAR(vect.Vx, -0.003433531336410129, 0.000001); ASSERT_NEAR(vect.Vy, 0.00000000000000011447918295357312, 0.0000001); ASSERT_NEAR(vect.Vz, 1.8696486850039278 , 0.000001); } TEST_F(TestVector, kepler_is_working) { Date_Time DataTime(2015,02,20); Vector nu(1, DataTime.GetSecOfDay(), 2829.9211857915025, 0.00000000000000031835908591289033, 5.1993701472998666, -0.003433531336410129, 0.00000000000000011447918295357312, 1.8696486850039278, 0, DataTime); OrbitElements oe = OrbitElements::Kepler(nu); ASSERT_NEAR(oe.Hmax(), 201.27403999999933, 1e-4); ASSERT_NEAR(oe.Hmin(), 198.725960000001, 1e-4); ASSERT_NEAR(oe.I(), 1.5707963267948966, 1e-4); ASSERT_NEAR(oe.e(), 0.000449999999999862, 1e-4); ASSERT_NEAR(oe.A(), 2831.1999999999998, 1e-4); ASSERT_NEAR(oe.omega(), 6.2831853071795862, 1e-4); ASSERT_NEAR(oe.Omega(), 1.8636941088196963e-35, 1e-4); ASSERT_NEAR(oe.T(), 9518.8637263964065, 1e-4); ASSERT_NEAR(oe.Tau(), -2.7809311670630898, 1e-4); } TEST_F(TestVector, spacecraft_ganimedDeorb) { GanimedLandModule landingModule; Engine mainEngine(1,"KTD", 600, 320); Engine secondEngine(2,"DMP", 120, 298); landingModule.AddEngine(mainEngine); landingModule.AddEngine(secondEngine); vector<Spacecraft> result = landingModule.BalDeorb(); ASSERT_NEAR(result[0].h, 2, 1e-1); ASSERT_NEAR(result[1].h, 0, 0e-1); } TEST_F(TestVector, spacecraft_removeEngines) { Date_Time DataTime(2011,10,05); Vector vvk(1816, 70500, -4887.4796260, -1988.8661830, 4242.4879740, -0.536599240, -6.3971388400, -3.612259210, 0.04158185, DataTime); vvk.Perevod(); vvk.Predict20(86380); vvk.Perevod(); Spacecraft testsSpCr(*vect, 6746.0, 1158.0, 2886.0, 115.20, 0.385080, -0.036830, 0.0, 0.008234, 273.0, 6, 1, 2); Engine skd(1,"SKD", 300, 302); Engine skd2(2,"SKD2", 300, 302); testsSpCr.AddEngine(skd); testsSpCr.AddEngine(skd2); ASSERT_EQ(testsSpCr.CountOfEngines(), 2); testsSpCr.RemoveEngine(2); ASSERT_EQ(testsSpCr.CountOfEngines(), 1); Engine dpo(2,"DPO", 49, 302); testsSpCr.AddEngine(dpo); ASSERT_EQ(testsSpCr.CountOfEngines(), 2); testsSpCr.RemoveEngine(dpo); ASSERT_EQ(testsSpCr.CountOfEngines(), 1); } TEST_F(TestVector, soyuz_controlledDeorbitation) { ASSERT_EQ(6, soyuz->TestRef()); vector<Spacecraft> result = soyuz->ControlledDeorb(1819); ASSERT_GT(result.size(), (unsigned int)0); /*//active part ending ASSERT_NEAR(84290.593, result[1].t, 0.01); ASSERT_NEAR(3962.798, result[1][1], 0.03); ASSERT_NEAR(-3257.793, result[1][2], 0.03); ASSERT_NEAR(-4392.766, result[1][3], 0.03); //division ASSERT_NEAR(85699.0773, result[2].t, 0.06); ASSERT_NEAR(5291.3042, result[2][1], 0.3); ASSERT_NEAR(2203.8246, result[2][2], 0.3); ASSERT_NEAR(3093.30753, result[2][3], 0.3); //start atmosphere part ASSERT_NEAR(85904.6220, result[3].t, 0.14); ASSERT_NEAR(4207.9380, result[3][1], 0.9); ASSERT_NEAR(2892.3440, result[3][2], 0.9); ASSERT_NEAR(3975.1020, result[3][3], 0.9); ASSERT_NEAR(-1.45640, result[3].Tet()*PerRadGrad, 0.0014); //start guidance part ASSERT_NEAR(86019.063, result[4].t, 0.3); ASSERT_NEAR(3497.10424, result[4][1], 2.0); ASSERT_NEAR(3216.07155, result[4][2], 2.0); ASSERT_NEAR(4362.23860, result[4][3], 2.0); ASSERT_NEAR(81.6013000, result[4].h, 0.07); //rotation ASSERT_NEAR(86280.339, result[5].t, 0.25); ASSERT_NEAR(1864.2230, result[5][1], 1.6); ASSERT_NEAR(3687.5830, result[5][2], 0.9); ASSERT_NEAR(4902.4850, result[5][3], 0.9); ASSERT_NEAR(45.911000, result[5].h, 0.07); //parachute open ASSERT_NEAR(86463.770, result[6].t, 0.25); ASSERT_NEAR(1541.3570, result[6][1], 1.6); ASSERT_NEAR(3742.4620, result[6][2], 0.9); ASSERT_NEAR(4926.7130, result[6][3], 0.9); ASSERT_NEAR(10.700000, result[6].h, 0.001);*/ ASSERT_NEAR(50.67, result[6][8], 0.07); ASSERT_NEAR(67.33, result[6][9], 0.2); ASSERT_NEAR(10.700000, result[6].h, 0.001); SUCCEED(); } TEST_F(TestVector, soyuz_ballisticDeorbitation) { Date_Time DataTime(2011,10,05); Vector *vect = new Vector(1816, 70500, -4887.4796260, -1988.8661830, 4242.4879740, -0.536599240, -6.3971388400, -3.612259210, 0.04158185, DataTime); Spacecraft testsSpCr(*vect, 6746.0, 1158.0, 2886.0, 115.20, 0.385080, -0.036830, 0.0, 0.008234, 273.0, 6, 1, 2); Engine skd(1,"SKD", 300, 302); testsSpCr.AddEngine(skd); vector<Spacecraft> result = testsSpCr.BalDeorb(1819); ASSERT_NEAR(86356, result.back().t, 1.0); ASSERT_NEAR(63, result.back()[9], 0.0166667); ASSERT_NEAR(1881.38985, result.back()[1], 0.00001); } TEST_F(TestVector, z_eq_zero) { vect->Prognoz(static_cast<unsigned int>(1817)); double z = vect->operator[](3); double x = vect->operator[](1); double y = vect->operator[](2); ASSERT_NEAR(0, z, 0.0001); ASSERT_NEAR(4651.9107, x, 0.001); ASSERT_NEAR(4906.6039, y, 0.001); } TEST_F(TestVector, soyuz_aerodynamic_case_1) { double s = 0; double s1 = 0; double b = 0; soyuz->Perevod(); soyuz->Aerodynamic(5.0, s, s1, b); // case 3 max > 6 && h > 130 ASSERT_NEAR(s,8.38046713413349, 0.000001); ASSERT_NEAR(s1,8.63614637837593, 0.000001); ASSERT_NEAR(b,2.08585591123745, 0.000001); } TEST_F(TestVector, soyuz_aerodynamic_case_2) { double s = 0; double s1 = 0; double b = 0; soyuz->Perevod(); soyuz->h = 65.0; soyuz->Aerodynamic(8.5, s, s1, b); // case 2 max > 6 && 30 <= h < 90 ASSERT_NEAR(s,8.51175843173862, 0.000001); ASSERT_NEAR(s1,8.75920062379871, 0.000001); ASSERT_NEAR(b,2.06726001453181, 0.000001); } TEST_F(TestVector, soyuz_aerodynamic_case_3) { double s = 0; double s1 = 0; double b = 0; soyuz->Perevod(); soyuz->Aerodynamic(30.0, s, s1, b); // case 3 max > 6 && h > 130 ASSERT_NEAR(s,14.2968545546068, 0.000001); ASSERT_NEAR(s1,14.3173726619517, 0.000001); ASSERT_NEAR(b,0.766230895763406, 0.000001); } int maint (int argc, char *argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
28.953353
149
0.687947
[ "vector" ]
4b6cb93ed18f78a88d87809add44acb166e6fee9
1,028
cpp
C++
011 Largest product in a grid.cpp
satvik007/ProjectEuler
6044cebe03672412d385a62bef827b28f0943cb6
[ "MIT" ]
null
null
null
011 Largest product in a grid.cpp
satvik007/ProjectEuler
6044cebe03672412d385a62bef827b28f0943cb6
[ "MIT" ]
null
null
null
011 Largest product in a grid.cpp
satvik007/ProjectEuler
6044cebe03672412d385a62bef827b28f0943cb6
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector <int> vi; int dr[] = {0, 1, -1, 1}; int dc[] = {1, 0, 1, 1}; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); vector <vi> a(20, vi(20)); int n = 20; for(int i=0; i<n; i++) for(int j=0; j<n; j++) cin >> a[i][j]; int max1 = 0; for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ int tx, ty; for(int k=0; k<4; k++){ int res = 1, cnt = 0; for(int m=0; m<4; m++){ tx = i + m * dr[k]; ty = j + m * dc[k]; if(tx >= 0 && ty >= 0 && tx < 20 && ty < 20){ res *= a[tx][ty]; cnt++; }else break; } if(cnt == 4){ max1 = max(max1, res); } } } } cout << max1 << "\n"; return 0; }
27.052632
65
0.366732
[ "vector" ]
4b724679c25299e080cfae659f29d15d0bb3c24a
2,211
cxx
C++
Modules/Filtering/Statistics/test/otbStreamingCompareImageFilter.cxx
heralex/OTB
c52b504b64dc89c8fe9cac8af39b8067ca2c3a57
[ "Apache-2.0" ]
317
2015-01-19T08:40:58.000Z
2022-03-17T11:55:48.000Z
Modules/Filtering/Statistics/test/otbStreamingCompareImageFilter.cxx
guandd/OTB
707ce4c6bb4c7186e3b102b2b00493a5050872cb
[ "Apache-2.0" ]
18
2015-07-29T14:13:45.000Z
2021-03-29T12:36:24.000Z
Modules/Filtering/Statistics/test/otbStreamingCompareImageFilter.cxx
guandd/OTB
707ce4c6bb4c7186e3b102b2b00493a5050872cb
[ "Apache-2.0" ]
132
2015-02-21T23:57:25.000Z
2022-03-25T16:03:16.000Z
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "itkMacro.h" #include "itkShiftScaleImageFilter.h" #include "otbStreamingCompareImageFilter.h" #include "otbImageFileReader.h" #include "otbImage.h" #include <fstream> #include "otbStreamingTraits.h" int otbStreamingCompareImageFilter(int itkNotUsed(argc), char* argv[]) { const char* infname = argv[1]; const char* outfname = argv[2]; const unsigned int Dimension = 2; typedef double PixelType; typedef otb::Image<PixelType, Dimension> ImageType; typedef otb::ImageFileReader<ImageType> ReaderType; typedef otb::StreamingCompareImageFilter<ImageType> StreamingCompareImageFilterType; typedef itk::ShiftScaleImageFilter<ImageType, ImageType> ShiftFilterType; // Instantiating object StreamingCompareImageFilterType::Pointer filter = StreamingCompareImageFilterType::New(); ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(infname); ShiftFilterType::Pointer shiftFilter = ShiftFilterType::New(); shiftFilter->SetInput(reader->GetOutput()); shiftFilter->SetScale(1); shiftFilter->SetShift(10); filter->SetInput1(reader->GetOutput()); filter->SetInput2(shiftFilter->GetOutput()); filter->Update(); std::ofstream file; file.open(outfname); file << "MSE: " << filter->GetMSE() << std::endl; file << "MAE: " << filter->GetMAE() << std::endl; file << "PSNR: " << filter->GetPSNR() << std::endl; file << "Count: " << filter->GetDiffCount() << std::endl; file.close(); return EXIT_SUCCESS; }
31.585714
91
0.721393
[ "object" ]
4b77947e520cc432361fbdf53c7735178b423350
15,694
cpp
C++
src/mongo/db/commands/list_indexes.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/commands/list_indexes.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/commands/list_indexes.cpp
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2018-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 <memory> #include <utility> #include "mongo/bson/bsonobjbuilder.h" #include "mongo/db/auth/authorization_session.h" #include "mongo/db/catalog/index_key_validate.h" #include "mongo/db/catalog/list_indexes.h" #include "mongo/db/clientcursor.h" #include "mongo/db/commands.h" #include "mongo/db/curop.h" #include "mongo/db/curop_failpoint_helpers.h" #include "mongo/db/cursor_manager.h" #include "mongo/db/db_raii.h" #include "mongo/db/exec/queued_data_stage.h" #include "mongo/db/exec/working_set.h" #include "mongo/db/index/index_descriptor.h" #include "mongo/db/list_indexes_gen.h" #include "mongo/db/query/cursor_request.h" #include "mongo/db/query/cursor_response.h" #include "mongo/db/query/find_common.h" #include "mongo/db/query/plan_executor_factory.h" #include "mongo/db/service_context.h" #include "mongo/db/storage/durable_catalog.h" #include "mongo/db/storage/storage_engine.h" #include "mongo/db/timeseries/catalog_helper.h" #include "mongo/db/timeseries/timeseries_index_schema_conversion_functions.h" #include "mongo/logv2/log.h" #include "mongo/util/uuid.h" #define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kCommand namespace mongo { namespace { // The allowed fields have to be in sync with those defined in 'src/mongo/db/list_indexes.idl'. static std::set<StringData> allowedFieldNames = { ListIndexesReplyItem::k2dsphereIndexVersionFieldName, ListIndexesReplyItem::kBackgroundFieldName, ListIndexesReplyItem::kBitsFieldName, ListIndexesReplyItem::kBucketSizeFieldName, ListIndexesReplyItem::kBuildUUIDFieldName, ListIndexesReplyItem::kClusteredFieldName, ListIndexesReplyItem::kCoarsestIndexedLevelFieldName, ListIndexesReplyItem::kCollationFieldName, ListIndexesReplyItem::kDefault_languageFieldName, ListIndexesReplyItem::kDropDupsFieldName, ListIndexesReplyItem::kExpireAfterSecondsFieldName, ListIndexesReplyItem::kFinestIndexedLevelFieldName, ListIndexesReplyItem::kHiddenFieldName, ListIndexesReplyItem::kIndexBuildInfoFieldName, ListIndexesReplyItem::kKeyFieldName, ListIndexesReplyItem::kLanguage_overrideFieldName, ListIndexesReplyItem::kMaxFieldName, ListIndexesReplyItem::kMinFieldName, ListIndexesReplyItem::kNameFieldName, ListIndexesReplyItem::kNsFieldName, ListIndexesReplyItem::kOriginalSpecFieldName, ListIndexesReplyItem::kPartialFilterExpressionFieldName, ListIndexesReplyItem::kPrepareUniqueFieldName, ListIndexesReplyItem::kSparseFieldName, ListIndexesReplyItem::kSpecFieldName, ListIndexesReplyItem::kStorageEngineFieldName, ListIndexesReplyItem::kTextIndexVersionFieldName, ListIndexesReplyItem::kUniqueFieldName, ListIndexesReplyItem::kVFieldName, ListIndexesReplyItem::kWeightsFieldName, ListIndexesReplyItem::kWildcardProjectionFieldName}; /** * Returns index specs, with resolved namespace, from the catalog for this listIndexes request. */ using IndexSpecsWithNamespaceString = std::pair<std::list<BSONObj>, NamespaceString>; IndexSpecsWithNamespaceString getIndexSpecsWithNamespaceString(OperationContext* opCtx, const ListIndexes& cmd) { const auto& origNssOrUUID = cmd.getNamespaceOrUUID(); bool buildUUID = cmd.getIncludeBuildUUIDs().value_or(false); bool indexBuildInfo = cmd.getIncludeIndexBuildInfo().value_or(false); invariant(!(buildUUID && indexBuildInfo)); ListIndexesInclude additionalInclude = buildUUID ? ListIndexesInclude::BuildUUID : indexBuildInfo ? ListIndexesInclude::IndexBuildInfo : ListIndexesInclude::Nothing; // Since time-series collections don't have UUIDs, we skip the time-series lookup // if the target collection is specified as a UUID. if (const auto& origNss = origNssOrUUID.nss()) { auto isCommandOnTimeseriesBucketNamespace = cmd.getIsTimeseriesNamespace() && *cmd.getIsTimeseriesNamespace(); if (auto timeseriesOptions = timeseries::getTimeseriesOptions( opCtx, *origNss, !isCommandOnTimeseriesBucketNamespace)) { auto bucketsNss = isCommandOnTimeseriesBucketNamespace ? *origNss : origNss->makeTimeseriesBucketsNamespace(); AutoGetCollectionForReadCommandMaybeLockFree autoColl(opCtx, bucketsNss); const CollectionPtr& coll = autoColl.getCollection(); uassert(ErrorCodes::NamespaceNotFound, str::stream() << "ns does not exist: " << bucketsNss, coll); return std::make_pair( timeseries::createTimeseriesIndexesFromBucketsIndexes( *timeseriesOptions, listIndexesInLock(opCtx, coll, bucketsNss, additionalInclude)), bucketsNss.getTimeseriesViewNamespace()); } } AutoGetCollectionForReadCommandMaybeLockFree autoColl(opCtx, origNssOrUUID); const auto& nss = autoColl.getNss(); const CollectionPtr& coll = autoColl.getCollection(); uassert( ErrorCodes::NamespaceNotFound, str::stream() << "ns does not exist: " << nss.ns(), coll); return std::make_pair(listIndexesInLock(opCtx, coll, nss, additionalInclude), nss); } /** * Lists the indexes for a given collection. * If 'includeBuildUUIDs' is true, then the index build uuid is also returned alongside the index * spec for in-progress index builds only. * If 'includeIndexBuildInfo' is true, then the index spec is returned in the spec subdocument, and * index build info is returned alongside the index spec for in-progress index builds only. * includeBuildUUIDs and includeIndexBuildInfo cannot both be set to true. * * Format: * { * listIndexes: <collection name>, * includeBuildUUIDs: <boolean>, * includeIndexBuildInfo: <boolean> * } * * Return format: * { * indexes: [ * <index>, * ... * ] * } * * Where '<index>' is the index spec if either the index is ready or 'includeBuildUUIDs' is false. * If the index is in-progress and 'includeBuildUUIDs' is true then '<index>' has the following * format: * { * spec: <index spec>, * buildUUID: <index build uuid> * } * * If 'includeIndexBuildInfo' is true, then for in-progress indexes, <index> has the following * format: * { * spec: <index spec>, * indexBuildInfo: { * buildUUID: <index build uuid> * } * } * And for complete (not in-progress) indexes: * { * spec: <index spec> * } */ class CmdListIndexes final : public ListIndexesCmdVersion1Gen<CmdListIndexes> { public: AllowedOnSecondary secondaryAllowed(ServiceContext*) const final { return AllowedOnSecondary::kOptIn; } bool maintenanceOk() const final { return false; } bool adminOnly() const final { return false; } bool collectsResourceConsumptionMetrics() const final { return true; } std::string help() const final { return "list indexes for a collection"; } class Invocation final : public InvocationBaseGen { public: using InvocationBaseGen::InvocationBaseGen; bool supportsWriteConcern() const final { return false; } NamespaceString ns() const final { auto nss = request().getNamespaceOrUUID(); if (nss.uuid()) { // UUID requires opCtx to resolve, settle on just the dbname. return NamespaceString(request().getDbName(), ""); } invariant(nss.nss()); return nss.nss().get(); } void doCheckAuthorization(OperationContext* opCtx) const final { AuthorizationSession* authzSession = AuthorizationSession::get(opCtx->getClient()); auto& cmd = request(); uassert( ErrorCodes::Unauthorized, "Unauthorized", authzSession->isAuthorizedToParseNamespaceElement(request().getNamespaceOrUUID())); const auto nss = CollectionCatalog::get(opCtx)->resolveNamespaceStringOrUUID( opCtx, cmd.getNamespaceOrUUID()); uassert(ErrorCodes::Unauthorized, str::stream() << "Not authorized to list indexes on collection:" << nss.ns(), authzSession->isAuthorizedForActionsOnResource( ResourcePattern::forExactNamespace(nss), ActionType::listIndexes)); } ListIndexesReply typedRun(OperationContext* opCtx) final { CommandHelpers::handleMarkKillOnClientDisconnect(opCtx); const auto& cmd = request(); bool buildUUID = cmd.getIncludeBuildUUIDs().value_or(false); bool indexBuildInfo = cmd.getIncludeIndexBuildInfo().value_or(false); uassert(ErrorCodes::InvalidOptions, "The includeBuildUUIDs flag and includeBuildIndexInfo flag cannot both be set " "to true", !(buildUUID && indexBuildInfo)); auto indexSpecsWithNss = getIndexSpecsWithNamespaceString(opCtx, cmd); const auto& indexList = indexSpecsWithNss.first; const auto& nss = indexSpecsWithNss.second; return ListIndexesReply(_makeCursor(opCtx, indexList, nss)); } private: /** * Constructs a cursor that iterates the index specs found in 'indexSpecsWithNss'. * This function does not hold any locks because it does not access in-memory * or on-disk data. */ ListIndexesReplyCursor _makeCursor(OperationContext* opCtx, const std::list<BSONObj>& indexList, const NamespaceString& nss) { auto& cmd = request(); long long batchSize = std::numeric_limits<long long>::max(); if (cmd.getCursor() && cmd.getCursor()->getBatchSize()) { batchSize = *cmd.getCursor()->getBatchSize(); } auto expCtx = make_intrusive<ExpressionContext>( opCtx, std::unique_ptr<CollatorInterface>(nullptr), nss); auto ws = std::make_unique<WorkingSet>(); auto root = std::make_unique<QueuedDataStage>(expCtx.get(), ws.get()); for (auto&& indexSpec : indexList) { WorkingSetID id = ws->allocate(); WorkingSetMember* member = ws->get(id); member->keyData.clear(); member->recordId = RecordId(); member->resetDocument(SnapshotId(), indexSpec.getOwned()); member->transitionToOwnedObj(); root->pushBack(id); } auto exec = uassertStatusOK( plan_executor_factory::make(expCtx, std::move(ws), std::move(root), &CollectionPtr::null, PlanYieldPolicy::YieldPolicy::NO_YIELD, false, /* whether returned BSON must be owned */ nss)); std::vector<mongo::ListIndexesReplyItem> firstBatch; size_t bytesBuffered = 0; for (long long objCount = 0; objCount < batchSize; objCount++) { BSONObj nextDoc; PlanExecutor::ExecState state = exec->getNext(&nextDoc, nullptr); if (state == PlanExecutor::IS_EOF) { break; } invariant(state == PlanExecutor::ADVANCED); nextDoc = index_key_validate::repairIndexSpec(nss, nextDoc, allowedFieldNames); // If we can't fit this result inside the current batch, then we stash it for // later. if (!FindCommon::haveSpaceForNext(nextDoc, objCount, bytesBuffered)) { exec->stashResult(nextDoc); break; } try { firstBatch.push_back(ListIndexesReplyItem::parse( IDLParserErrorContext("ListIndexesReplyItem"), nextDoc)); } catch (const DBException& exc) { LOGV2_ERROR(5254500, "Could not parse catalog entry while replying to listIndexes", "entry"_attr = nextDoc, "error"_attr = exc); uasserted(5254501, fmt::format("Could not parse catalog entry while replying to " "listIndexes. Entry: '{}'. Error: '{}'.", nextDoc.toString(), exc.toString())); } bytesBuffered += nextDoc.objsize(); } if (exec->isEOF()) { return ListIndexesReplyCursor(0 /* cursorId */, nss, std::move(firstBatch)); } exec->saveState(); exec->detachFromOperationContext(); // Global cursor registration must be done without holding any locks. auto pinnedCursor = CursorManager::get(opCtx)->registerCursor( opCtx, {std::move(exec), nss, AuthorizationSession::get(opCtx->getClient())->getAuthenticatedUserNames(), APIParameters::get(opCtx), opCtx->getWriteConcern(), repl::ReadConcernArgs::get(opCtx), ReadPreferenceSetting::get(opCtx), cmd.toBSON({}), {Privilege(ResourcePattern::forExactNamespace(nss), ActionType::listIndexes)}}); pinnedCursor->incNBatches(); pinnedCursor->incNReturnedSoFar(firstBatch.size()); return ListIndexesReplyCursor( pinnedCursor.getCursor()->cursorid(), nss, std::move(firstBatch)); } }; } cmdListIndexes; } // namespace } // namespace mongo
41.850667
99
0.635593
[ "vector" ]
4b8e3d4b832454c448701f898a14afadbc6a772c
21,653
hpp
C++
libobs-for-HQ-Windows/UI/window-basic-main.hpp
jayliu1989/HQ
470d9919742412795447c81c3f160278b4418ba7
[ "MIT" ]
45
2019-01-09T01:50:12.000Z
2021-08-09T20:51:22.000Z
libobs-for-HQ-Windows/UI/window-basic-main.hpp
jayliu1989/HQ
470d9919742412795447c81c3f160278b4418ba7
[ "MIT" ]
8
2019-01-14T10:30:55.000Z
2021-06-16T11:38:39.000Z
libobs-for-HQ-Windows/UI/window-basic-main.hpp
jayliu1989/HQ
470d9919742412795447c81c3f160278b4418ba7
[ "MIT" ]
24
2019-02-15T17:24:23.000Z
2021-09-09T23:45:19.000Z
/****************************************************************************** Copyright (C) 2013-2014 by Hugh Bailey <obs.jim@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ #pragma once #include <QBuffer> #include <QAction> #include <QSystemTrayIcon> #include <obs.hpp> #include <vector> #include <memory> #include "window-main.hpp" #include "window-basic-interaction.hpp" #include "window-basic-properties.hpp" #include "window-basic-transform.hpp" #include "window-basic-adv-audio.hpp" #include "window-basic-filters.hpp" #include <obs-frontend-internal.hpp> #include <util/platform.h> #include <util/threading.h> #include <util/util.hpp> #include <QPointer> class QMessageBox; class QListWidgetItem; class VolControl; class QNetworkReply; class OBSBasicStats; #include "ui_OBSBasic.h" #define DESKTOP_AUDIO_1 Str("DesktopAudioDevice1") #define DESKTOP_AUDIO_2 Str("DesktopAudioDevice2") #define AUX_AUDIO_1 Str("AuxAudioDevice1") #define AUX_AUDIO_2 Str("AuxAudioDevice2") #define AUX_AUDIO_3 Str("AuxAudioDevice3") #define SIMPLE_ENCODER_X264 "x264" #define SIMPLE_ENCODER_X264_LOWCPU "x264_lowcpu" #define SIMPLE_ENCODER_QSV "qsv" #define SIMPLE_ENCODER_NVENC "nvenc" #define SIMPLE_ENCODER_AMD "amd" #define PREVIEW_EDGE_SIZE 10 struct BasicOutputHandler; struct AgoraOutputHandler; enum class QtDataRole { OBSRef = Qt::UserRole, OBSSignals, }; enum class ProjectorType { Source, Preview, StudioProgram, Multiview }; struct QuickTransition { QPushButton *button = nullptr; OBSSource source; obs_hotkey_id hotkey = 0; int duration = 0; int id = 0; inline QuickTransition() {} inline QuickTransition(OBSSource source_, int duration_, int id_) : source (source_), duration (duration_), id (id_) {} }; class OBSBasic : public OBSMainWindow { Q_OBJECT friend class OBSBasicPreview; friend class OBSBasicStatusBar; friend class OBSBasicSourceSelect; friend class OBSBasicSettings; friend struct OBSStudioAPI; enum class MoveDir { Up, Down, Left, Right }; enum DropType { DropType_RawText, DropType_Text, DropType_Image, DropType_Media, DropType_Html }; private: obs_frontend_callbacks *api = nullptr; std::vector<VolControl*> volumes; std::vector<OBSSignal> signalHandlers; std::vector<std::string> projectorArray; std::vector<int> studioProgramProjectorArray; std::vector<int> multiviewProjectorArray; std::vector<int> previewProjectorArray; bool loaded = false; long disableSaving = 1; bool projectChanged = false; bool previewEnabled = true; bool fullscreenInterface = false; const char *copyString; const char *copyFiltersString; bool copyVisible = true; QPointer<QThread> updateCheckThread; QPointer<QThread> logUploadThread; QPointer<OBSBasicInteraction> interaction; QPointer<OBSBasicProperties> properties; QPointer<OBSBasicTransform> transformWindow; QPointer<OBSBasicAdvAudio> advAudioWindow; QPointer<OBSBasicFilters> filters; QPointer<QTimer> cpuUsageTimer; os_cpu_usage_info_t *cpuUsageInfo = nullptr; OBSService service; std::unique_ptr<BasicOutputHandler> outputHandler; bool streamingStopping = false; bool recordingStopping = false; bool replayBufferStopping = false; gs_vertbuffer_t *box = nullptr; gs_vertbuffer_t *boxLeft = nullptr; gs_vertbuffer_t *boxTop = nullptr; gs_vertbuffer_t *boxRight = nullptr; gs_vertbuffer_t *boxBottom = nullptr; gs_vertbuffer_t *circle = nullptr; bool sceneChanging = false; bool ignoreSelectionUpdate = false; int previewX = 0, previewY = 0; int previewCX = 0, previewCY = 0; float previewScale = 0.0f; ConfigFile basicConfig; QPointer<QWidget> projectors[10]; QList<QPointer<QWidget>> windowProjectors; QPointer<QWidget> stats; QPointer<QMenu> startStreamMenu; QPointer<QPushButton> replayBufferButton; QPointer<QSystemTrayIcon> trayIcon; QPointer<QAction> sysTrayStream; QPointer<QAction> sysTrayRecord; QPointer<QAction> sysTrayReplayBuffer; QPointer<QAction> showHide; QPointer<QAction> exit; QPointer<QMenu> trayMenu; void DrawBackdrop(float cx, float cy); void SetupEncoders(); void CreateFirstRunSources(); void CreateDefaultScene(bool firstStart); void UpdateVolumeControlsDecayRate(); void ClearVolumeControls(); void UploadLog(const char *file); void Save(const char *file); void Load(const char *file); void InitHotkeys(); void CreateHotkeys(); void ClearHotkeys(); bool InitService(); bool InitBasicConfigDefaults(); bool InitBasicConfig(); void InitOBSCallbacks(); void InitPrimitives(); OBSSceneItem GetSceneItem(QListWidgetItem *item); OBSSceneItem GetCurrentSceneItem(); bool QueryRemoveSource(obs_source_t *source); void TimedCheckForUpdates(); void CheckForUpdates(bool manualUpdate); void GetFPSCommon(uint32_t &num, uint32_t &den) const; void GetFPSInteger(uint32_t &num, uint32_t &den) const; void GetFPSFraction(uint32_t &num, uint32_t &den) const; void GetFPSNanoseconds(uint32_t &num, uint32_t &den) const; void GetConfigFPS(uint32_t &num, uint32_t &den) const; void UpdatePreviewScalingMenu(); void UpdateSources(OBSScene scene); void InsertSceneItem(obs_sceneitem_t *item); void LoadSceneListOrder(obs_data_array_t *array); obs_data_array_t *SaveSceneListOrder(); void ChangeSceneIndex(bool relative, int idx, int invalidIdx); void TempFileOutput(const char *path, int vBitrate, int aBitrate); void TempStreamOutput(const char *url, const char *key, int vBitrate, int aBitrate); void CreateInteractionWindow(obs_source_t *source); void CreatePropertiesWindow(obs_source_t *source); void CreateFiltersWindow(obs_source_t *source); void CloseDialogs(); void ClearSceneData(); void Nudge(int dist, MoveDir dir); void OpenProjector(obs_source_t *source, int monitor, bool window, QString title = nullptr, ProjectorType type = ProjectorType::Source); void GetAudioSourceFilters(); void GetAudioSourceProperties(); void VolControlContextMenu(); void AddSceneCollection(bool create_new); void RefreshSceneCollections(); void ChangeSceneCollection(); void LogScenes(); void LoadProfile(); void ResetProfileData(); bool AddProfile(bool create_new, const char *title, const char *text, const char *init_text = nullptr); void DeleteProfile(const char *profile_name, const char *profile_dir); void RefreshProfiles(); void ChangeProfile(); void CheckForSimpleModeX264Fallback(); void SaveProjectNow(); QListWidgetItem *GetTopSelectedSourceItem(); obs_hotkey_pair_id streamingHotkeys, recordingHotkeys, replayBufHotkeys; obs_hotkey_id forceStreamingStopHotkey; void InitDefaultTransitions(); void InitTransition(obs_source_t *transition); obs_source_t *FindTransition(const char *name); OBSSource GetCurrentTransition(); obs_data_array_t *SaveTransitions(); void LoadTransitions(obs_data_array_t *transitions); obs_source_t *fadeTransition; void CreateProgramDisplay(); void CreateProgramOptions(); void AddQuickTransitionId(int id); void AddQuickTransition(); void AddQuickTransitionHotkey(QuickTransition *qt); void RemoveQuickTransitionHotkey(QuickTransition *qt); void LoadQuickTransitions(obs_data_array_t *array); obs_data_array_t *SaveQuickTransitions(); void ClearQuickTransitionWidgets(); void RefreshQuickTransitions(); void CreateDefaultQuickTransitions(); QMenu *CreatePerSceneTransitionMenu(); QuickTransition *GetQuickTransition(int id); int GetQuickTransitionIdx(int id); QMenu *CreateTransitionMenu(QWidget *parent, QuickTransition *qt); void ClearQuickTransitions(); void QuickTransitionClicked(); void QuickTransitionChange(); void QuickTransitionChangeDuration(int value); void QuickTransitionRemoveClicked(); void SetPreviewProgramMode(bool enabled); void ResizeProgram(uint32_t cx, uint32_t cy); void SetCurrentScene(obs_scene_t *scene, bool force = false, bool direct = false); static void RenderProgram(void *data, uint32_t cx, uint32_t cy); std::vector<QuickTransition> quickTransitions; QPointer<QWidget> programOptions; QPointer<OBSQTDisplay> program; OBSWeakSource lastScene; OBSWeakSource swapScene; OBSWeakSource programScene; bool editPropertiesMode = false; bool sceneDuplicationMode = true; bool swapScenesMode = true; volatile bool previewProgramMode = false; obs_hotkey_id togglePreviewProgramHotkey = 0; obs_hotkey_id transitionHotkey = 0; int quickTransitionIdCounter = 1; bool overridingTransition = false; int programX = 0, programY = 0; int programCX = 0, programCY = 0; float programScale = 0.0f; int disableOutputsRef = 0; inline void OnActivate(); inline void OnDeactivate(); void AddDropSource(const char *file, DropType image); void dragEnterEvent(QDragEnterEvent *event) override; void dragLeaveEvent(QDragLeaveEvent *event) override; void dragMoveEvent(QDragMoveEvent *event) override; void dropEvent(QDropEvent *event) override; void ReplayBufferClicked(); bool sysTrayMinimizeToTray(); void EnumDialogs(); QList<QDialog*> visDialogs; QList<QDialog*> modalDialogs; QList<QMessageBox*> visMsgBoxes; QList<QPoint> visDlgPositions; QByteArray startingDockLayout; obs_data_array_t *SaveProjectors(); void LoadSavedProjectors(obs_data_array_t *savedProjectors); obs_data_array_t *SavePreviewProjectors(); void LoadSavedPreviewProjectors( obs_data_array_t *savedPreviewProjectors); obs_data_array_t *SaveStudioProgramProjectors(); void LoadSavedStudioProgramProjectors( obs_data_array_t *savedStudioProgramProjectors); obs_data_array_t *SaveMultiviewProjectors(); void LoadSavedMultiviewProjectors( obs_data_array_t *savedMultiviewProjectors); public slots: void StartStreaming(); void StopStreaming(); void ForceStopStreaming(); void StreamDelayStarting(int sec); void StreamDelayStopping(int sec); void StreamingStart(); void StreamStopping(); void StreamingStop(int errorcode, QString last_error); void StartRecording(); void StopRecording(); void RecordingStart(); void RecordStopping(); void RecordingStop(int code); void StartReplayBuffer(); void StopReplayBuffer(); void ReplayBufferStart(); void ReplayBufferSave(); void ReplayBufferStopping(); void ReplayBufferStop(int code); void SaveProjectDeferred(); void SaveProject(); void SetTransition(OBSSource transition); void TransitionToScene(OBSScene scene, bool force = false, bool direct = false); void TransitionToScene(OBSSource scene, bool force = false, bool direct = false, bool quickTransition = false); void SetCurrentScene(OBSSource scene, bool force = false, bool direct = false); private slots: void AddSceneItem(OBSSceneItem item); void RemoveSceneItem(OBSSceneItem item); void AddScene(OBSSource source); void RemoveScene(OBSSource source); void RenameSources(OBSSource source, QString newName, QString prevName); void SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select); void ActivateAudioSource(OBSSource source); void DeactivateAudioSource(OBSSource source); void DuplicateSelectedScene(); void RemoveSelectedScene(); void RemoveSelectedSceneItem(); void ToggleAlwaysOnTop(); void ReorderSources(OBSScene scene); void ProcessHotkey(obs_hotkey_id id, bool pressed); void AddTransition(); void RenameTransition(); void TransitionClicked(); void TransitionStopped(); void TransitionFullyStopped(); void TriggerQuickTransition(int id); void SetDeinterlacingMode(); void SetDeinterlacingOrder(); void SetScaleFilter(); void IconActivated(QSystemTrayIcon::ActivationReason reason); void SetShowing(bool showing); void ToggleShowHide(); void HideAudioControl(); void UnhideAllAudioControls(); void ToggleHideMixer(); void MixerRenameSource(); void on_mixerScrollArea_customContextMenuRequested(); void on_actionCopySource_triggered(); void on_actionPasteRef_triggered(); void on_actionPasteDup_triggered(); void on_actionCopyFilters_triggered(); void on_actionPasteFilters_triggered(); private: /* OBS Callbacks */ static void SceneReordered(void *data, calldata_t *params); static void SceneItemAdded(void *data, calldata_t *params); static void SceneItemRemoved(void *data, calldata_t *params); static void SceneItemSelected(void *data, calldata_t *params); static void SceneItemDeselected(void *data, calldata_t *params); static void SourceLoaded(void *data, obs_source_t *source); static void SourceRemoved(void *data, calldata_t *params); static void SourceActivated(void *data, calldata_t *params); static void SourceDeactivated(void *data, calldata_t *params); static void SourceRenamed(void *data, calldata_t *params); static void RenderMain(void *data, uint32_t cx, uint32_t cy); void ResizePreview(uint32_t cx, uint32_t cy); void AddSource(const char *id); QMenu *CreateAddSourcePopupMenu(); void AddSourcePopupMenu(const QPoint &pos); void copyActionsDynamicProperties(); static void HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed); public: OBSSource GetProgramSource(); OBSScene GetCurrentScene(); void SysTrayNotify(const QString &text, QSystemTrayIcon::MessageIcon n); inline OBSSource GetCurrentSceneSource() { OBSScene curScene = GetCurrentScene(); return OBSSource(obs_scene_get_source(curScene)); } obs_service_t *GetService(); void SetService(obs_service_t *service); inline bool IsPreviewProgramMode() const { return os_atomic_load_bool(&previewProgramMode); } bool StreamingActive() const; bool Active() const; void ResetUI(); int ResetVideo(); bool ResetAudio(); void ResetOutputs(); void ResetAudioDevice(const char *sourceId, const char *deviceId, const char *deviceDesc, int channel); void NewProject(); void LoadProject(); inline void GetDisplayRect(int &x, int &y, int &cx, int &cy) { x = previewX; y = previewY; cx = previewCX; cy = previewCY; } inline double GetCPUUsage() const { return os_cpu_usage_info_query(cpuUsageInfo); } void SaveService(); bool LoadService(); inline void EnableOutputs(bool enable) { if (enable) { if (--disableOutputsRef < 0) disableOutputsRef = 0; } else { disableOutputsRef++; } } void ReorderSceneItem(obs_sceneitem_t *item, size_t idx); QMenu *AddDeinterlacingMenu(obs_source_t *source); QMenu *AddScaleFilteringMenu(obs_sceneitem_t *item); void CreateSourcePopupMenu(QListWidgetItem *item, bool preview); void UpdateTitleBar(); void UpdateSceneSelection(OBSSource source); void SystemTrayInit(); void SystemTray(bool firstStarted); void OpenSavedProjectors(); void RemoveSavedProjectors(int monitor); protected: virtual void closeEvent(QCloseEvent *event) override; virtual void changeEvent(QEvent *event) override; private slots: void on_actionFullscreenInterface_triggered(); void on_actionShow_Recordings_triggered(); void on_actionRemux_triggered(); void on_action_Settings_triggered(); void on_actionAdvAudioProperties_triggered(); void on_advAudioProps_clicked(); void on_advAudioProps_destroyed(); void on_actionShowLogs_triggered(); void on_actionUploadCurrentLog_triggered(); void on_actionUploadLastLog_triggered(); void on_actionViewCurrentLog_triggered(); void on_actionCheckForUpdates_triggered(); void on_actionEditTransform_triggered(); void on_actionCopyTransform_triggered(); void on_actionPasteTransform_triggered(); void on_actionRotate90CW_triggered(); void on_actionRotate90CCW_triggered(); void on_actionRotate180_triggered(); void on_actionFlipHorizontal_triggered(); void on_actionFlipVertical_triggered(); void on_actionFitToScreen_triggered(); void on_actionStretchToScreen_triggered(); void on_actionCenterToScreen_triggered(); void on_scenes_currentItemChanged(QListWidgetItem *current, QListWidgetItem *prev); void on_scenes_customContextMenuRequested(const QPoint &pos); void on_actionAddScene_triggered(); void on_actionRemoveScene_triggered(); void on_actionSceneUp_triggered(); void on_actionSceneDown_triggered(); void on_sources_itemSelectionChanged(); void on_sources_customContextMenuRequested(const QPoint &pos); void on_sources_itemDoubleClicked(QListWidgetItem *item); void on_scenes_itemDoubleClicked(QListWidgetItem *item); void on_actionAddSource_triggered(); void on_actionRemoveSource_triggered(); void on_actionInteract_triggered(); void on_actionSourceProperties_triggered(); void on_actionSourceUp_triggered(); void on_actionSourceDown_triggered(); void on_actionMoveUp_triggered(); void on_actionMoveDown_triggered(); void on_actionMoveToTop_triggered(); void on_actionMoveToBottom_triggered(); void on_actionLockPreview_triggered(); void on_scalingMenu_aboutToShow(); void on_actionScaleWindow_triggered(); void on_actionScaleCanvas_triggered(); void on_actionScaleOutput_triggered(); void on_streamButton_clicked(); void on_recordButton_clicked(); void on_settingsButton_clicked(); void on_actionHelpPortal_triggered(); void on_actionWebsite_triggered(); void on_preview_customContextMenuRequested(const QPoint &pos); void on_program_customContextMenuRequested(const QPoint &pos); void on_previewDisabledLabel_customContextMenuRequested( const QPoint &pos); void on_actionNewSceneCollection_triggered(); void on_actionDupSceneCollection_triggered(); void on_actionRenameSceneCollection_triggered(); void on_actionRemoveSceneCollection_triggered(); void on_actionImportSceneCollection_triggered(); void on_actionExportSceneCollection_triggered(); void on_actionNewProfile_triggered(); void on_actionDupProfile_triggered(); void on_actionRenameProfile_triggered(); void on_actionRemoveProfile_triggered(); void on_actionImportProfile_triggered(); void on_actionExportProfile_triggered(); void on_actionShowSettingsFolder_triggered(); void on_actionShowProfileFolder_triggered(); void on_actionAlwaysOnTop_triggered(); void on_toggleListboxToolbars_toggled(bool visible); void on_toggleStatusBar_toggled(bool visible); void on_transitions_currentIndexChanged(int index); void on_transitionAdd_clicked(); void on_transitionRemove_clicked(); void on_transitionProps_clicked(); void on_modeSwitch_clicked(); void on_autoConfigure_triggered(); void on_stats_triggered(); void on_resetUI_triggered(); void on_lockUI_toggled(bool lock); void on_agoraPKButton_clicked(); void logUploadFinished(const QString &text, const QString &error); void updateCheckFinished(); void AddSourceFromAction(); void MoveSceneToTop(); void MoveSceneToBottom(); void EditSceneName(); void EditSceneItemName(); void SceneNameEdited(QWidget *editor, QAbstractItemDelegate::EndEditHint endHint); void SceneItemNameEdited(QWidget *editor, QAbstractItemDelegate::EndEditHint endHint); void OpenSceneFilters(); void OpenFilters(); void EnablePreviewDisplay(bool enable); void TogglePreview(); void NudgeUp(); void NudgeDown(); void NudgeLeft(); void NudgeRight(); void OpenStudioProgramProjector(); void OpenPreviewProjector(); void OpenSourceProjector(); void OpenMultiviewProjector(); void OpenSceneProjector(); void OpenStudioProgramWindow(); void OpenPreviewWindow(); void OpenSourceWindow(); void OpenMultiviewWindow(); void OpenSceneWindow(); public slots: void on_actionResetTransform_triggered(); public: explicit OBSBasic(QWidget *parent = 0); virtual ~OBSBasic(); virtual void OBSInit() override; virtual config_t *Config() const override; virtual int GetProfilePath(char *path, size_t size, const char *file) const override; private: std::unique_ptr<Ui::OBSBasic> ui; public: //agora obs_service_t *GetAgoraService(); void InitAgoraService(); void InitAgoraServiceSettings(); void SetAgoraService(obs_service_t* service); void ResetAgoraOutput(); static void AgoraFirstRemoteVideoDecoded(void *data, calldata_t *params); static void AgoraUserJoined(void *data, calldata_t *params); static void AgoraUserOffline(void *data, calldata_t *params); void CreateAgoraRemoteVideo(); private: OBSService agoraService; std::unique_ptr<AgoraOutputHandler> agoraOutputHandler; std::string agoraColorFormat = "I420"; std::string obsColorFormatReplacedByAgora = "NV12"; QWidget* remoteVideo = nullptr; std::list<uint32_t> m_lstUids; void SetPreviewPK(bool bPK); uint32_t remote_uid = 0; uint32_t loacal_uid = 0; private slots: void SetupRempteVideo(long long uid); void OnUserOffline(long long uid); void OnUserJoined(long long uid); static void obsVideoCallback(uint8_t* data, void* param); static void obsAudioCallback(struct encoder_frame* data, int planes, void* param); // end agora };
28.157347
83
0.770609
[ "vector", "transform" ]
4b8e7f81374582151e1fd0b8ce7f29fdca48fadb
2,587
cpp
C++
aegisub/reporter/platform_unix_osx.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
1
2018-02-12T02:44:57.000Z
2018-02-12T02:44:57.000Z
aegisub/reporter/platform_unix_osx.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
null
null
null
aegisub/reporter/platform_unix_osx.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
2
2018-02-12T03:46:24.000Z
2018-02-12T14:36:07.000Z
// Copyright (c) 2009, Amar Takhar <verm@aegisub.org> // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // // $Id$ /// @file platform_unix_bsd.cpp /// @brief BSD Platform extensions. /// @ingroup unix #ifndef R_PRECOMP #include <wx/string.h> #endif extern "C" { #include <sys/types.h> #include <sys/sysctl.h> } #include "include/platform.h" #include "platform_unix.h" #include "platform_unix_osx.h" std::string PlatformUnixOSX::CPUId() { char id[300]; size_t len = sizeof(id); sysctlbyname("machdep.cpu.brand_string", &id, &len, NULL, 0); return wxString::Format("%s", id).ToStdString(); }; std::string PlatformUnixOSX::CPUSpeed() { uint64_t speed; size_t len = sizeof(speed); sysctlbyname("hw.cpufrequency_max", &speed, &len, NULL, 0); return wxString::Format("%d", speed / (1000*1000)).ToStdString(); }; int PlatformUnixOSX::CPUCores() { return 0; }; int PlatformUnixOSX::CPUCount() { int proc; size_t len = sizeof(proc); sysctlbyname("hw.ncpu", &proc, &len, NULL, 0); return proc; }; std::string PlatformUnixOSX::CPUFeatures() { char feat[300]; size_t len = sizeof(feat); sysctlbyname("machdep.cpu.features", &feat, &len, NULL, 0); return wxString::Format("%s", feat).ToStdString(); }; std::string PlatformUnixOSX::CPUFeatures2() { char feat[128]; size_t len = sizeof(feat); sysctlbyname("machdep.cpu.extfeatures", &feat, &len, NULL, 0); return wxString::Format("%s", feat).ToStdString(); }; uint64_t PlatformUnixOSX::Memory() { uint64_t memory; size_t len = sizeof(memory); sysctlbyname("hw.memsize", &memory, &len, NULL, 0); return memory; }; std::string PlatformUnixOSX::UnixLibraries() { return ""; }; std::string PlatformUnixOSX::PatchLevel() { return ""; } std::string PlatformUnixOSX::HardwareModel() { char model[300]; size_t len = sizeof(model); sysctlbyname("hw.model", &model, &len, NULL, 0); return wxString::Format("%s", model).ToStdString(); }
26.947917
75
0.713181
[ "model" ]
4b9108933cc17377e2580d96b79ec7e55312c5be
5,469
cpp
C++
Programs/TestBed/Sources/Tests/OverdrawTest/OverdrawTesterRenderObject.cpp
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Programs/TestBed/Sources/Tests/OverdrawTest/OverdrawTesterRenderObject.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Programs/TestBed/Sources/Tests/OverdrawTest/OverdrawTesterRenderObject.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
#include "OverdrawTesterRenderObject.h" #include "Base/BaseTypes.h" #include "Engine/Engine.h" #include "Functional/Function.h" #include "Render/2D/Systems/VirtualCoordinatesSystem.h" #include "Render/Renderer.h" #include "Render/Material/NMaterial.h" #include "Render/Highlevel/RenderBatch.h" #include "Render/DynamicBufferAllocator.h" #include "Functional/Function.h" #include "UI/UIControlSystem.h" namespace OverdrawPerformanceTester { using DAVA::NMaterial; using DAVA::RenderBatch; using DAVA::Vector2; using DAVA::Vector3; using DAVA::uint8; using DAVA::uint16; using DAVA::uint32; using DAVA::int32; using DAVA::float32; using DAVA::DynamicBufferAllocator::AllocResultVB; using DAVA::DynamicBufferAllocator::AllocResultIB; using DAVA::Camera; using DAVA::Size2i; namespace { DAVA::Array<uint16, 6> indices = { 0, 3, 1, 1, 3, 2 }; } OverdrawTesterRenderObject::OverdrawTesterRenderObject(float32 addOverdrawPercent_, uint32 maxStepsCount_, uint16 textureResolution_) : addOverdrawPercentNormalized(addOverdrawPercent_ * 0.01f) , textureResolution(textureResolution_) { AddFlag(RenderObject::ALWAYS_CLIPPING_VISIBLE); AddFlag(RenderObject::CUSTOM_PREPARE_TO_RENDER); rhi::VertexLayout layout; layout.AddElement(rhi::VS_POSITION, 0, rhi::VDT_FLOAT, 3); layout.AddElement(rhi::VS_TEXCOORD, 0, rhi::VDT_FLOAT, 2); uint32 layoutId = rhi::VertexLayout::UniqueId(layout); vertexStride = (3 + 2) * sizeof(float); GenerateIndexBuffer(); for (uint32 i = 0; i < maxStepsCount_; i++) { GenerateQuad(i, layoutId); } bbox.AddPoint(Vector3(1.0f, 1.0f, 1.0f)); DAVA::Renderer::GetSignals().needRestoreResources.Connect(this, &OverdrawTesterRenderObject::Restore); } OverdrawTesterRenderObject::~OverdrawTesterRenderObject() { for (DAVA::RenderBatch* batch : quads) { if (batch->vertexBuffer.IsValid()) rhi::DeleteVertexBuffer(batch->vertexBuffer); DAVA::SafeRelease(batch); } quads.clear(); if (iBuffer.IsValid()) rhi::DeleteIndexBuffer(iBuffer); DAVA::Renderer::GetSignals().needRestoreResources.Disconnect(this); } void OverdrawTesterRenderObject::PrepareToRender(Camera* camera) { activeRenderBatchArray.clear(); if (material == nullptr || currentStepsCount == 0) return; activeVerts.clear(); for (uint32 i = 0; i < currentStepsCount; i++) activeRenderBatchArray.push_back(quads[i]); } void OverdrawTesterRenderObject::RecalculateWorldBoundingBox() { worldBBox = bbox; } void OverdrawTesterRenderObject::BindDynamicParameters(Camera* camera, DAVA::RenderBatch* batch) { DAVA::Renderer::GetDynamicBindings().SetDynamicParam(DAVA::DynamicBindings::PARAM_WORLD, &DAVA::Matrix4::IDENTITY, reinterpret_cast<DAVA::pointer_size>(&DAVA::Matrix4::IDENTITY)); } void OverdrawTesterRenderObject::GenerateQuad(uint32 index, uint32 layoutId) { auto quad = GetQuadVerts(index); rhi::VertexBuffer::Descriptor desc; desc.usage = rhi::USAGE_STATICDRAW; desc.size = 4 * sizeof(QuadVertex); desc.initialData = quad.data(); rhi::HVertexBuffer vBuffer = rhi::CreateVertexBuffer(desc); RenderBatch* renderBatch = new RenderBatch(); renderBatch->SetRenderObject(this); renderBatch->vertexLayoutId = layoutId; renderBatch->vertexBuffer = vBuffer; renderBatch->indexBuffer = iBuffer; renderBatch->indexCount = 6; renderBatch->vertexCount = 4; quads.push_back(renderBatch); } DAVA::Vector<OverdrawTesterRenderObject::QuadVertex> OverdrawTesterRenderObject::GetQuadVerts(uint32 index) { static const float32 threshold = 0.999f; // This threshold prevent quad from drawing in positions like 0.9999-1.9999 except 0-0.1, and force last quad right edge to be drawn at 1.0. float32 xStart = addOverdrawPercentNormalized * index; xStart = xStart - static_cast<int32>(xStart); xStart = xStart < threshold ? xStart : 0.0f; xStart = xStart * 2 - 1.0f; float32 xEnd = xStart + 2.0f * addOverdrawPercentNormalized; xEnd = xEnd < threshold ? xEnd : 1.0f; // Try to keep 2pix - 1tex ratio. Size2i size = DAVA::GetEngineContext()->uiControlSystem->vcs->GetPhysicalScreenSize(); float32 maxX = size.dx * 0.5f / textureResolution; float32 maxY = size.dy * 0.5f / textureResolution; float32 uvStart = (xStart * 0.5f + 0.5f) * maxX; float32 uvEnd = (xEnd * 0.5f + 0.5f) * maxX; return { { { { xStart, -1.0f, 1.0f }, { uvStart, 0.0f } }, { { xStart, 1.0f, 1.0f }, { uvStart, maxY } }, { { xEnd, 1.0f, 1.0f }, { uvEnd, maxY } }, { { xEnd, -1.0f, 1.0f }, { uvEnd, 0.0f } } } }; } void OverdrawTesterRenderObject::GenerateIndexBuffer() { rhi::IndexBuffer::Descriptor iDesc; iDesc.indexSize = rhi::INDEX_SIZE_16BIT; iDesc.size = 6 * sizeof(uint16); iDesc.usage = rhi::USAGE_STATICDRAW; iDesc.initialData = indices.data(); iBuffer = rhi::CreateIndexBuffer(iDesc); } void OverdrawTesterRenderObject::Restore() { if (rhi::NeedRestoreIndexBuffer(iBuffer)) rhi::UpdateIndexBuffer(iBuffer, indices.data(), 0, static_cast<DAVA::uint32>(indices.size() * sizeof(uint16))); for (size_t i = 0; i < quads.size(); i++) { if (rhi::NeedRestoreVertexBuffer(quads[i]->vertexBuffer)) rhi::UpdateVertexBuffer(quads[i]->vertexBuffer, GetQuadVerts(static_cast<DAVA::uint32>(i)).data(), 0, static_cast<DAVA::uint32>(4 * sizeof(QuadVertex))); } } }
32.748503
185
0.705613
[ "render", "vector" ]
4b96872c6a45288ccb3834e3351c889b8082c046
11,374
hpp
C++
src/Magma/String.hpp
RiscadoA/Magma-Streams
a51821609ec6d80e1ac45660068e0a216f65624b
[ "BSD-3-Clause" ]
null
null
null
src/Magma/String.hpp
RiscadoA/Magma-Streams
a51821609ec6d80e1ac45660068e0a216f65624b
[ "BSD-3-Clause" ]
null
null
null
src/Magma/String.hpp
RiscadoA/Magma-Streams
a51821609ec6d80e1ac45660068e0a216f65624b
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <stdexcept> #include <vector> namespace Magma { class InvalidStringError : public std::runtime_error { public: using std::runtime_error::runtime_error; }; /// <summary> /// Class that wraps a C string. This class uses the UTF-8 encoding. /// </summary> class String { public: /// <summary> /// Constructs an empty string /// </summary> String(); ~String() noexcept; /// <summary> /// Constructs a string from a UTF-8 C string /// </summary> /// <param name="cstring">UTF-8 C string</param> /// <exception cref="InvalidStringError">Thrown if C string contains invalid UTF-8</exception> String(const char* utf8CString); /// <summary> /// Constructs a string from another string (copy constructor) /// </summary> /// <param name="string">String to copy</param> String(const String& string); /// <summary> /// Constructs a string from another string, inutilizing the other string (move constructor) /// </summary> /// <param name="string">String to move</param> String(String&& string) noexcept; /// <summary> /// Copies a UTF-8 C string into this string /// </summary> /// <param name="utf8CString">UTF-8 C string</param> /// <exception cref="InvalidStringError">Thrown if C string contains invalid UTF-8</exception> /// <returns>This</returns> String& operator=(const char* utf8CString); /// <summary> /// Copies a string into this string (copy assignment operator) /// </summary> /// <param name="string">String to copy</param> /// <returns>This</returns> String& operator=(const String& string); /// <summary> /// Moves a string into this string (move assignment operator) /// </summary> /// <param name="string">String to move</param> /// <returns>This</returns> String& operator=(String&& string) noexcept; /// <summary> /// Gets the underlying C string (char array) from this string /// </summary> /// <returns>Char array used in this string</returns> inline const char* CString() const { return m_data; } /// <summary> /// Appends a unicode character to this string /// </summary> /// <param name="character">Character unicode point</param> /// <exception cref="InvalidCharacterError">Thrown if unicode character is invalid</exception> void AppendChar(char32_t character); /// <summary> /// Appends a UTF-8 character to this string and returns the character size in bytes /// </summary> /// <param name="character">UTF-8 character address</param> /// <exception cref="InvalidCharacterError">Thrown if UTF-8 character is invalid</exception> /// <returns>UTF-8 character size</returns> size_t AppendChar(const char* character); /// <summary> /// Appends a UTF-8 C string to this string /// </summary> /// <param name="utf8CString">UTF-8 C string to append</param> /// <exception cref="InvalidStringError">Thrown if C string contains invalid UTF-8</exception> void AppendString(const char* utf8CString); /// <summary> /// Appends a string to this string /// </summary> /// <param name="string">String to append</param> void AppendString(const String& string); /// <summary> /// Removes the last character in the string /// </summary> /// <exception cref="std::out_of_range">Thrown when the string is already empty</exception> void Pop(); /// <summary> /// Clears the string /// </summary> void Clear(); /// <summary> /// Appends this string and another, and returns the result /// </summary> /// <param name="rhs">String to append</param> /// <returns>Appended strings</returns> String operator+(const String& rhs) const; /// <summary> /// Appends a string to this string /// </summary> /// <param name="rhs">String to append</param> /// <returns>This</returns> String& operator+=(const String& rhs); /// <summary> /// Appends this string and a UTF-8 C string, and returns the result /// </summary> /// <param name="rhs">UTF-8 C string to append</param> /// <exception cref="InvalidStringError">Thrown if C string contains invalid UTF-8</exception> /// <returns>Appended strings</returns> String operator+(const char* rhs) const; /// <summary> /// Appends a UTF-8 C string to this string /// </summary> /// <param name="rhs">UTF-8 C string to append</param> /// <exception cref="InvalidStringError">Thrown if C string contains invalid UTF-8</exception> /// <returns>This</returns> String& operator+=(const char* rhs); /// <summary> /// Gets a substring of this string /// </summary> /// <param name="index">Substring starting index</param> /// <param name="length">Substring length</param> /// <exception cref="std::out_of_bounds">Thrown if index + length is bigger than this string's length</exception> /// <returns>The substring</returns> String Substring(size_t index, size_t length) const; /// <summary> /// Splits this string into many /// </summary> /// <param name="delimeter">Delimiter between substrings</param> /// <returns>Vector of substrings</returns> std::vector<String> Split(char32_t delimeter) const; /// <summary> /// Splits this string into many /// </summary> /// <param name="delimeter">Delimiter between substrings</param> /// <returns>Vector of substrings</returns> std::vector<String> Split(const String& delimeter) const; /// <summary> /// Gets a character in this string /// </summary> /// <param name="index">Character index</param> /// <exception cref="std::out_of_bounds">Thrown if index is out of range</exception> /// <returns>Character unicode point</returns> char32_t At(size_t index) const; /// <summary> /// Sets a character in this string /// </summary> /// <param name="index">Character index</param> /// <param name="character">Character unicode point</param> /// <exception cref="std::out_of_bounds">Thrown if index is out of range</exception> void Set(size_t index, char32_t character); /// <summary> /// Erases a character from this string /// </summary> /// <param name="index">Character index</param> /// <exception cref="std::out_of_bounds">Thrown if index is out of range</exception> void Erase(size_t index); /// <summary> /// Erases a substring from this string /// </summary> /// <param name="index">Substring index</param> /// <param name="length">Substring length</param> /// <exception cref="std::out_of_bounds">Thrown if substring index + substring length is bigger than string length</exception> void Erase(size_t index, size_t length); /// <summary> /// Inserts a character into this string /// </summary> /// <param name="index">Index where character will be inserted</param> /// <param name="character">Character unicode point</param> /// <exception cref="std::out_of_bounds">Thrown if index is out of range</exception> void Insert(size_t index, char32_t character); /// <summary> /// Inserts a substring into this string /// </summary> /// <param name="index">Substring index</param> /// <param name="substring">Substring</param> /// <exception cref="std::out_of_bounds">Thrown if index is bigger than string length</exception> void Insert(size_t index, const String& substring); /// <summary> /// Gets this string length in characters /// </summary> /// <returns>String length in characters</returns> inline size_t Length() const noexcept { return m_length; } /// <summary> /// Gets this string size in bytes /// </summary> /// <returns></returns> inline size_t Size() const noexcept { return m_size; } /// <summary> /// Checks if this string is empty /// </summary> /// <returns>True if empty, otherwise false</returns> inline bool Empty() const noexcept { return m_length == 0; } /// <summary> /// Checks if this string starts with a substring /// </summary> /// <param name="substring">Substring to check</param> /// <returns>True if starts, otherwise false</returns> bool StartsWith(const String& substring) const; /// <summary> /// Checks if this string ends with a substring /// </summary> /// <param name="substring">Substring to check</param> /// <returns>True if ends, otherwise false</returns> bool EndsWith(const String& substring) const; /// <summary> /// Compares this string with another /// </summary> /// <param name="rhs">String to compare</param> /// <returns>True if they are equal, otherwise false</returns> bool operator==(const String& rhs) const; /// <summary> /// Compares this string with another /// </summary> /// <param name="rhs">String to compare</param> /// <returns>False if they are equal, otherwise true</returns> inline bool operator!=(const String& rhs) const { return !(*this == rhs); } private: size_t m_length; size_t m_size; char* m_data; }; namespace UTF8 { class InvalidCharacterError : public std::runtime_error { public: using std::runtime_error::runtime_error; }; /// <summary> /// Checks if unicode point is valid /// </summary> /// <param name="character">Unicode point</param> /// <returns>True if valid, otherwise false</returns> bool IsValid(char32_t character); /// <summary> /// Checks if a UTF-8 C string is valid /// </summary> /// <param name="utf8String">UTF-8 C string to check</param> /// <returns>True if valid, otherwise false</returns> bool IsValid(const char* utf8String); /// <summary> /// Gets the size a unicode character would have if encoded in UTF-8 /// </summary> /// <param name="character">Character to check</param> /// <exception cref="InvalidCharacterError">Thrown if unicode character is invalid</exception> /// <returns>Character UTF-8 size</returns> size_t GetCharSize(char32_t character); /// <summary> /// Gets the size of an UTF-8 character /// </summary> /// <param name="utf8Char">Address of UTF-8 character</param> /// <exception cref="InvalidCharacterError">Thrown if UTF-8 character has invalid prefix</exception> /// <returns>Character size</returns> size_t GetCharSize(const char* utf8Char); /// <summary> /// Gets the length of an UTF-8 C string (in characters, not bytes) /// </summary> /// <param name="utf8String">C String address</param> /// <exception cref="InvalidCharacterError">Thrown if a UTF-8 character has invalid prefix</exception> /// <returns>C String length</returns> size_t GetStringLength(const char* utf8String); /// <summary> /// Converts a UTF-8 character to a unicode character /// </summary> /// <param name="utf8Char">Address of UTF-8 character</param> /// <exception cref="InvalidCharacterError">Thrown if UTF-8 character has invalid prefix</exception> /// <seealso cref="FromUnicode"/> /// <returns>Unicode character</returns> char32_t ToUnicode(const char* utf8Char); /// <summary> /// Converts a unicode character to a UTF-8 character /// </summary> /// <param name="character">Character to be converted</param> /// <param name="utf8Char">UTF-8 character output address (maximum character size is 4 bytes)</param> /// <exception cref="InvalidCharacterError">Thrown if unicode character is invalid</exception> /// <seealso cref="ToUnicode"/> /// <returns>UTF-8 character size</returns> size_t FromUnicode(char32_t character, char* utf8Char); } }
34.466667
128
0.672147
[ "vector" ]
4ba421e148c4ea2f1216c264bb8cdd98c6783bd1
4,238
cpp
C++
projects/acommandline/test/parse_test.cpp
agnesoft/adev
e2515ff85c169b529423828cd9afacdfb74e56e2
[ "Apache-2.0" ]
5
2022-03-14T13:08:01.000Z
2022-03-30T20:31:29.000Z
projects/acommandline/test/parse_test.cpp
agnesoft/adev
e2515ff85c169b529423828cd9afacdfb74e56e2
[ "Apache-2.0" ]
318
2020-10-26T11:51:09.000Z
2022-03-31T15:42:30.000Z
projects/acommandline/test/parse_test.cpp
agnesoft/adev
e2515ff85c169b529423828cd9afacdfb74e56e2
[ "Apache-2.0" ]
1
2021-01-26T19:16:56.000Z
2021-01-26T19:16:56.000Z
import atest; import acommandline; using ::atest::expect; using ::atest::suite; using ::atest::test; static const auto S = suite("CommandLine::parse()", [] { // NOLINT(cert-err58-cpp) test("long and short mix", [] { std::stringstream stream; ::acommandline::CommandLine commandLine{stream}; bool value = false; std::string option; std::int64_t another = 0; std::string positional; constexpr int argc = 6; commandLine.option().long_name("value").short_name('v').description("").bind_to(&value); commandLine.option().long_name("option").short_name('o').description("").bind_to(&option); commandLine.option().long_name("yetanother").description("").bind_to(&another); commandLine.option().positional().description("").bind_to(&positional); expect(commandLine.parse(argc, std::array<const char *, argc>{"./app", "-v", "-o=file", "--yetanother", "1", "somefile"}.data())).to_be(true); expect(value).to_be(true); expect(option).to_be("file"); expect(another).to_be(1); expect(positional).to_be("somefile"); }); test("quoted", [] { std::stringstream stream; ::acommandline::CommandLine commandLine{stream}; std::string value; commandLine.option().long_name("value").description("").bind_to(&value); expect(commandLine.parse(3, std::array<const char *, 3>{"./app", "--value", "\"my long quoted value\""}.data())).to_be(true); expect(value).to_be("my long quoted value"); }); test("one quote", [] { std::stringstream stream; ::acommandline::CommandLine commandLine{stream}; std::string value; commandLine.option().long_name("value").description("").bind_to(&value); expect(commandLine.parse(3, std::array<const char *, 3>{"./app", "--value", "\""}.data())).to_be(true); expect(value).to_be("\""); }); test("wrongly quoted", [] { std::stringstream stream; ::acommandline::CommandLine commandLine{stream}; std::string value; commandLine.option().long_name("value").description("").bind_to(&value); expect(commandLine.parse(3, std::array<const char *, 3>{"./app", "--value", "\"wrongly \"quoted"}.data())).to_be(true); expect(value).to_be("\"wrongly \"quoted"); }); test("single, missing, defaulted and repeated options", [] { std::stringstream stream; ::acommandline::CommandLine commandLine{stream}; std::vector<int64_t> parameters; bool flag = true; std::string output; std::vector<std::string> paths; constexpr int argc = 6; commandLine.option().long_name("param").short_name('p').description("").bind_to(&parameters); commandLine.option().long_name("flag").short_name('f').description("").bind_to(&flag); commandLine.option().positional().required().description("").bind_to(&output); commandLine.option().long_name("include").short_name('I').default_value(std::vector<std::string>{"c:/path/with spaces/", "//"}).description("").bind_to(&paths); expect(commandLine.parse(argc, std::array<const char *, argc>{"a", "-p=1", "-p=2", "--param", "3", "output_option"}.data())).to_be(true); expect(parameters).to_be(std::vector<std::int64_t>{1, 2, 3}); expect(flag).to_be(true); expect(output).to_be("output_option"); expect(paths).to_be(std::vector<std::string>{"c:/path/with spaces/", "//"}); }); test("no arguments", [] { std::stringstream stream; ::acommandline::CommandLine commandLine{stream}; expect([&] { static_cast<void>(commandLine.parse(0, std::array<const char *, 0>{}.data())); }) .to_throw<std::logic_error>("Missing mandatory first command line argument."); }); test("unmatched argument", [] { std::stringstream stream; ::acommandline::CommandLine commandLine{stream}; expect([&] { static_cast<void>(commandLine.parse(2, std::array<const char *, 2>{"./app", "-v"}.data())); }) .to_throw<std::runtime_error>("Unmatched argument '-v'."); }); });
38.880734
168
0.601935
[ "vector" ]
4ba66054dcddde8493d854be07c643b7902033c8
3,595
cpp
C++
cpp/model/GetAccountsResponse.cpp
havenmoney/platform-clients
60a2553bde73c1f8a2b02e76ad7adcdf04283cd3
[ "Apache-2.0" ]
null
null
null
cpp/model/GetAccountsResponse.cpp
havenmoney/platform-clients
60a2553bde73c1f8a2b02e76ad7adcdf04283cd3
[ "Apache-2.0" ]
null
null
null
cpp/model/GetAccountsResponse.cpp
havenmoney/platform-clients
60a2553bde73c1f8a2b02e76ad7adcdf04283cd3
[ "Apache-2.0" ]
null
null
null
/** * Haven Money API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0 * * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2. * https://openapi-generator.tech * Do not edit the class manually. */ #include "GetAccountsResponse.h" namespace dev { namespace haven { namespace client { namespace model { GetAccountsResponse::GetAccountsResponse() { } GetAccountsResponse::~GetAccountsResponse() { } void GetAccountsResponse::validate() { // TODO: implement validation } web::json::value GetAccountsResponse::toJson() const { web::json::value val = web::json::value::object(); { std::vector<web::json::value> jsonArray; for( auto& item : m_Accounts ) { jsonArray.push_back(ModelBase::toJson(item)); } val[utility::conversions::to_string_t("accounts")] = web::json::value::array(jsonArray); } return val; } void GetAccountsResponse::fromJson(const web::json::value& val) { { m_Accounts.clear(); std::vector<web::json::value> jsonArray; for( auto& item : val.at(utility::conversions::to_string_t("accounts")).as_array() ) { if(item.is_null()) { m_Accounts.push_back( std::shared_ptr<ApiAccount>(nullptr) ); } else { std::shared_ptr<ApiAccount> newItem(new ApiAccount()); newItem->fromJson(item); m_Accounts.push_back( newItem ); } } } } void GetAccountsResponse::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } { std::vector<web::json::value> jsonArray; for( auto& item : m_Accounts ) { jsonArray.push_back(ModelBase::toJson(item)); } multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("accounts"), web::json::value::array(jsonArray), utility::conversions::to_string_t("application/json"))); } } void GetAccountsResponse::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } { m_Accounts.clear(); web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("accounts")))); for( auto& item : jsonArray.as_array() ) { if(item.is_null()) { m_Accounts.push_back( std::shared_ptr<ApiAccount>(nullptr) ); } else { std::shared_ptr<ApiAccount> newItem(new ApiAccount()); newItem->fromJson(item); m_Accounts.push_back( newItem ); } } } } std::vector<std::shared_ptr<ApiAccount>>& GetAccountsResponse::getAccounts() { return m_Accounts; } void GetAccountsResponse::setAccounts(const std::vector<std::shared_ptr<ApiAccount>>& value) { m_Accounts = value; } } } } }
26.240876
200
0.618359
[ "object", "vector", "model" ]
4bb0673b020d4a3cb8a3e132becad81f88f8a9c2
2,064
cc
C++
src/nojs_vm.cc
Flameeyes/nojs
b386fe707f651ffb2000d52560bc60bc3c0b2f1b
[ "BSD-3-Clause" ]
78
2016-05-29T09:17:00.000Z
2020-12-27T16:16:23.000Z
src/nojs_vm.cc
Flameeyes/nojs
b386fe707f651ffb2000d52560bc60bc3c0b2f1b
[ "BSD-3-Clause" ]
4
2016-06-02T00:47:34.000Z
2016-06-21T15:25:09.000Z
src/nojs_vm.cc
Flameeyes/nojs
b386fe707f651ffb2000d52560bc60bc3c0b2f1b
[ "BSD-3-Clause" ]
3
2016-06-16T08:17:16.000Z
2020-03-31T19:33:17.000Z
#include "uv.h" #include "v8.h" #include "nojs_validate_arguments.h" #include "nojs_thread_context_inl.h" #include "nojs_object_inl.h" #include "nojs_uv_request.h" #include "nojs_string.h" namespace NoJS { typedef Validation::And< Validation::Length<4>, Validation::And< Validation::And< Validation::Or< Validation::Slot<0, Validation::IsString>, Validation::Slot<0, Validation::IsArrayBufferView> >, Validation::Slot<1, Validation::IsString> >, Validation::And< Validation::Slot<2, Validation::IsNumber>, Validation::Slot<3, Validation::IsNumber> > > > RunScriptValidator; static v8::Local<v8::Value> CreateStringView(const v8::Local<v8::Value>& in) { return in; } // content, filename, line, column void RunScriptInContext(const v8::FunctionCallbackInfo<v8::Value>& args) { ThreadContext* tc = ThreadContext::From(args); v8::Isolate* isolate(tc->GetIsolate()); v8::HandleScope scope(isolate); v8::MaybeLocal<v8::Value> err = RunScriptValidator::Check(tc, args); if (!err.IsEmpty()) { isolate->ThrowException( err.ToLocalChecked() ); return; } v8::Local<v8::String> code = ( args[0]->IsString() ? args[0] : CreateStringView(args[0]) ).As<v8::String>(); v8::ScriptOrigin origin(args[1], args[2].As<v8::Integer>(), args[3].As<v8::Integer>()); v8::MaybeLocal<v8::Script> script = v8::Script::Compile( isolate->GetCurrentContext(), code, &origin ); if (script.IsEmpty()) { args.GetReturnValue().Set(v8::Null(isolate)); return; } v8::MaybeLocal<v8::Value> value = script.ToLocalChecked()->Run( isolate->GetCurrentContext() ); if (value.IsEmpty()) { args.GetReturnValue().Set(v8::Null(isolate)); return; } args.GetReturnValue().Set(value.ToLocalChecked()); } namespace VM { void ContributeToBridge (ThreadContext* tc, v8::Local<v8::Object> bridge) { v8::Isolate* isolate(tc->GetIsolate()); v8::HandleScope scope(isolate); tc->SetMethod(bridge, "run", RunScriptInContext); } } }
23.191011
89
0.661822
[ "object" ]
4bbb70cf5e561d42f46e768ee0f604edf5bd49fc
5,116
cpp
C++
src/P12218319/parallel/Task.cpp
p12218319/Parallel
10bf916b8c63064521df909fa09f8b6128f7a1e8
[ "Apache-2.0" ]
null
null
null
src/P12218319/parallel/Task.cpp
p12218319/Parallel
10bf916b8c63064521df909fa09f8b6128f7a1e8
[ "Apache-2.0" ]
null
null
null
src/P12218319/parallel/Task.cpp
p12218319/Parallel
10bf916b8c63064521df909fa09f8b6128f7a1e8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016 Adam Smith - P12218319 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. email : p12218319@myemail.dmu.ac.uk */ #include <mutex> #include <vector> #include <atomic> #include <map> #include "P12218319\parallel\Nesting.hpp" #include "P12218319\parallel\Task.hpp" namespace P12218319 { namespace Tasks { enum { WORKER_THREAD_COUNT = P12218319_DEFAULT_THREAD_COUNT }; struct TaskData { uint64_t ID; implementation::Task* Task; std::thread::id SourceThread; TaskData() throw() : ID(0), Task(nullptr), SourceThread(std::this_thread::get_id()) {} TaskData(const uint64_t aID, implementation::Task& aTask, const std::thread::id aSourceThread) throw() : ID(aID), Task(&aTask), SourceThread(aSourceThread) {} inline operator bool() const throw() { return Task ? true : false; } }; std::condition_variable TASK_ADDED_CONDITION; std::condition_variable TASK_COMPLETED_CONDITION; std::vector<TaskData> TASK_LIST; thread_local std::vector<std::vector<TaskID>> TASK_GROUPS; std::mutex TASK_LIST_LOCK; std::thread WORKER_THREADS[WORKER_THREAD_COUNT]; TaskData WORKER_TASKS[WORKER_THREAD_COUNT]; std::atomic_bool EXIT_FLAG = false; uint64_t ID_BASE = 0; void P12218319_CALL TaskWorker(const uint32_t aID) { TaskData& taskData = WORKER_TASKS[aID]; taskData.Task = nullptr; while(! EXIT_FLAG) { { std::unique_lock<std::mutex> lock(TASK_LIST_LOCK); TASK_ADDED_CONDITION.wait_for(lock, std::chrono::milliseconds(5)); if(! TASK_LIST.empty()) { taskData = TASK_LIST.back(); TASK_LIST.pop_back(); } } if(taskData) { taskData.Task->operator()(); delete taskData.Task; taskData.Task = nullptr; TASK_COMPLETED_CONDITION.notify_all(); } } } void LaunchWorkers() throw() { static bool THREADS_LAUNCHED = false; if(! THREADS_LAUNCHED) { THREADS_LAUNCHED = true; P12218319::implementation::IncrementParallelDepth(); std::atexit([](){ EXIT_FLAG = true; for(uint32_t i = 0; i < WORKER_THREAD_COUNT; ++i) WORKER_THREADS[i].join(); P12218319::implementation::DecrementParallelDepth(); }); for(uint32_t i = 0; i < WORKER_THREAD_COUNT; ++i) { WORKER_THREADS[i] = std::thread(TaskWorker, i); } } } namespace implementation { TaskID P12218319_CALL Schedule(Task& aTask) throw() { LaunchWorkers(); std::vector<TaskID>* group = TASK_GROUPS.empty() ? nullptr : &TASK_GROUPS.back(); TASK_LIST_LOCK.lock(); const TaskID id = ++ID_BASE; TASK_LIST.push_back(TaskData(id, aTask, std::this_thread::get_id())); TASK_LIST_LOCK.unlock(); TASK_ADDED_CONDITION.notify_one(); if(group) group->push_back(id); return id; } // Task P12218319_CALL Task::~Task() { } } template<class F> void P12218319_CALL WaitImplementation(const F aCheckList) throw() { bool wait = true; { std::lock_guard<std::mutex> lock(TASK_LIST_LOCK); wait = ! aCheckList(); } while(wait) { { std::unique_lock<std::mutex> lock(TASK_LIST_LOCK); TASK_COMPLETED_CONDITION.wait(lock); wait = ! aCheckList(); } } } void P12218319_CALL Wait(const TaskID* const aBegin, const TaskID* const aEnd) throw() { WaitImplementation<>([=]()->bool { for(const TaskData& i : TASK_LIST) for(const TaskID* j = aBegin; j != aEnd; ++j) if (i && i.ID == *j) return false; for(const TaskData& i : WORKER_TASKS) for(const TaskID* j = aBegin; j != aEnd; ++j) if (i && i.ID == *j) return false; return true; }); } void P12218319_CALL Wait(const TaskID aID) throw() { WaitImplementation<>([=]()->bool { for(const TaskData& i : TASK_LIST) if(i && i.ID == aID) return false; for(const TaskData& i : WORKER_TASKS) if(i && i.ID == aID) return false; return true; }); } void P12218319_CALL WaitThread() throw() { const std::thread::id id = std::this_thread::get_id(); WaitImplementation<>([=]()->bool { for(const TaskData& i : TASK_LIST) if(i && i.SourceThread == id) return false; for(const TaskData& i : WORKER_TASKS) if(i && i.SourceThread == id) return false; return true; }); } void P12218319_CALL WaitGlobal() throw() { WaitImplementation<>([]()->bool{ for(const TaskData& i : TASK_LIST) if(i) return false; for(const TaskData& i : WORKER_TASKS) if(i) return false; return true; }); } void P12218319_CALL BeginGroup() throw() { TASK_GROUPS.push_back(std::vector<TaskID>()); } bool P12218319_CALL EndGroup() throw() { if(TASK_GROUPS.empty()) return false; const std::vector<TaskID>& group = TASK_GROUPS.back(); Wait(&group[0], &group[0] + group.size()); TASK_GROUPS.pop_back(); return true; } }}
27.956284
121
0.688233
[ "vector" ]
4bbd7ec5a4cd91d2436e85d00e232bac9cf70348
3,961
cpp
C++
src/macosx/EstEID.tokend/EstEID/EstEIDRecord.cpp
kaidokert/old-esteid-stack
0391bbf600556dc8527c4f87eed2c95afc878ab4
[ "BSD-3-Clause" ]
null
null
null
src/macosx/EstEID.tokend/EstEID/EstEIDRecord.cpp
kaidokert/old-esteid-stack
0391bbf600556dc8527c4f87eed2c95afc878ab4
[ "BSD-3-Clause" ]
null
null
null
src/macosx/EstEID.tokend/EstEID/EstEIDRecord.cpp
kaidokert/old-esteid-stack
0391bbf600556dc8527c4f87eed2c95afc878ab4
[ "BSD-3-Clause" ]
null
null
null
/* * EstEID.tokend * * Copyright (C) 2009 Kaido Kert <kaidokert@gmail.com> * * 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 * */ // $Revision$ // $Date$ // $Author$ /* * EstEIDRecord.cpp */ #include "EstEIDRecord.h" #include "EstEIDError.h" #include "EstEIDToken.h" #include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacTypes.h> #include <Security/SecKey.h> #include <tokend/Attribute.h> #include <tokend/MetaAttribute.h> #include <tokend/MetaRecord.h> #include <security_cdsa_client/aclclient.h> #include "EstEID_utility.h" EstEIDRecord::EstEIDRecord(const char *description) : mDescription(description) { secdebug("tok_esteid","EstEIDRecord '%s' created",mDescription); } const char *EstEIDRecord::description() { secdebug("tok_esteid","EstEIDRecord::description '%s'",mDescription); return mDescription; } // // EstEIDRecord // EstEIDRecord::~EstEIDRecord() { } EstEIDKeyRecord::EstEIDKeyRecord( const char *description, const Tokend::MetaRecord &metaRecord, bool signOnly) : EstEIDRecord(description), mSignOnly(signOnly) { FLOG; attributeAtIndex(metaRecord.metaAttribute(kSecKeyDecrypt).attributeIndex(), new Tokend::Attribute(!signOnly)); attributeAtIndex(metaRecord.metaAttribute(kSecKeyUnwrap).attributeIndex(), new Tokend::Attribute(!signOnly)); attributeAtIndex(metaRecord.metaAttribute(kSecKeySign).attributeIndex(), new Tokend::Attribute(signOnly)); } EstEIDKeyRecord::~EstEIDKeyRecord() {} void EstEIDKeyRecord::getAcl(const char *tag, uint32 &count, AclEntryInfo *&acls) { FLOG; // @@@ Key 1 has any acl for sign, key 2 has pin1 acl, and key3 has pin1 // acl with auto-lock which we express as a prompted password subject. if (!mAclEntries) { mAclEntries.allocator(Allocator::standard()); // Anyone can read the DB record for this key (which is a reference // CSSM_KEY) mAclEntries.add(CssmClient::AclFactory::AnySubject( mAclEntries.allocator()), AclAuthorizationSet(CSSM_ACL_AUTHORIZATION_DB_READ, 0)); // Using this key to sign or decrypt will require PIN1 mAclEntries.add(CssmClient::AclFactory::PinSubject( mAclEntries.allocator(), 1), AclAuthorizationSet((mSignOnly ? CSSM_ACL_AUTHORIZATION_SIGN : CSSM_ACL_AUTHORIZATION_DECRYPT), 0)); } count = mAclEntries.size(); acls = mAclEntries.entries(); } EstEIDCertRecord::~EstEIDCertRecord() {} Tokend::Attribute *EstEIDCertRecord::getDataAttribute(Tokend::TokenContext *tokenContext) { FLOG; secdebug("tok_esteid","getDAtaAttribute, tokenContext = %p",tokenContext); EstEIDToken &token = dynamic_cast<EstEIDToken &>(*tokenContext); //return NULL; CssmData data; if (token.cachedObject(0, mDescription, data)) { Tokend::Attribute *attribute = new Tokend::Attribute(data.Data, data.Length); free(data.Data); return attribute; } try { std::vector<unsigned char> arrCert = token.getCard().getAuthCert(); data.Data = &arrCert[0]; data.Length = arrCert.size(); } catch (std::exception &err) { secdebug("tok_esteid","exception thrown in *EstEIDCertRecord::getDataAttribute '%s'",err.what()); return NULL; } token.cacheObject(0, mDescription, data); return new Tokend::Attribute(data.Data, data.Length); }
29.781955
99
0.729866
[ "vector" ]
4bce55f66bafce9b08f230da11d3cbae487ed04c
2,966
cpp
C++
Antiplagiat/Antiplagiat/bin/Debug/5534.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
1
2015-07-04T14:45:32.000Z
2015-07-04T14:45:32.000Z
Antiplagiat/Antiplagiat/bin/Debug/5534.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
null
null
null
Antiplagiat/Antiplagiat/bin/Debug/5534.cpp
DmitryTheFirst/AntiplagiatVkCup
556d3fe2e5a630d06a7aa49f2af5dcb28667275a
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <iostream> #include <stack> #include <queue> #include <deque> #include <map> #include <set> #include <vector> #include <string> #include <cstring> #include <math.h> #include <algorithm> #include <complex> #include <ctime> #include <iomanip> #include <cassert> #include <sstream> #include <iterator> using namespace std; #define file "file" #define mp make_pair #define pb push_back #define xx real() #define yy imag() typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; typedef vector<int> vi; typedef complex<double> point; const int MAXN = 20 + 5; const int MASK = 33; const ll BASE = 21; int p[MAXN]; int a[MAXN]; int n,m; int r[MAXN],c[MAXN]; vi good[MAXN]; int was; int ans[MAXN]; map<pair<ll,ll>,int> dp; ll hash_code(int col){ ll ans = 0; for(int i = 0;i < n;i++){ ans *= BASE; ans += a[i]; } ans *= BASE; ans += col; return ans; } void precalc(){ for(int mask = 0;mask < (1 << n);mask++){ int block = 0; int last = 0; for(int i = 0;i < n;i++){ if(mask & (1 << i)){ if(!last) block++; last = 1; } else{ last = 0; } } good[block].pb(mask); } } void rec_sol(int col,int prev){ if(was) return; if(col == m){ for(int i = 0;i < n;i++){ if(r[i] != a[i]){ return; } } was = 1; for(int i = 0;i < m;i++){ ans[i] = p[i]; } return; } ll code = hash_code(col); if(dp.find(mp(code,prev)) != dp.end()) return; dp[mp(code,prev)] = 1; for(int i = 0;i < n;i++){ if(a[i] > r[i]){ return; } } int a2[5]; for(int i = 0;i < n;i++){ a2[i] = a[i]; } for(int i = 0;i < (int) good[c[col]].size();i++){ int nxt = good[c[col]][i]; for(int j = 0;j < n;j++){ if(nxt & (1 << j)){ if(!(prev & (1 << j))){ a[j]++; } } } int t = p[col]; p[col] = nxt; rec_sol(col + 1,nxt); p[col] = t; if(was) return; for(int j = 0;j < n;j++) a[j] = a2[j]; } } void solve(){ scanf("%d%d",&n,&m); for(int i = 0;i < n;i++){ scanf("%d",&r[i]); } for(int i = 0;i < m;i++){ scanf("%d",&c[i]); } precalc(); rec_sol(0,0); for(int i = 0;i < n;i++){ for(int j = 0;j < m;j++){ if(ans[j] & (1 << i)) printf("*"); else printf("."); } printf("\n"); } } int main() { #ifndef ONLINE_JUDGE assert(freopen("input.txt","r",stdin)); assert(freopen("output.txt","w",stdout)); #else //assert(freopen(file".in","r",stdin)); assert(freopen(file".out","w",stdout)); #endif int t = 1; while(t--){ solve(); } return 0; }
19.513158
83
0.45145
[ "vector" ]
4bcf096301eb08ab9fd9d7e2a163f52274f154f3
25,551
cpp
C++
src/disasm/disasm_i8086.cpp
madmoose/chani
567e6c1a5769d050220f990b437f099198f1f8f1
[ "MIT" ]
11
2021-05-30T21:02:55.000Z
2022-03-19T16:22:34.000Z
src/disasm/disasm_i8086.cpp
madmoose/chani
567e6c1a5769d050220f990b437f099198f1f8f1
[ "MIT" ]
3
2021-06-06T08:37:04.000Z
2021-10-06T18:40:12.000Z
src/disasm/disasm_i8086.cpp
madmoose/chani
567e6c1a5769d050220f990b437f099198f1f8f1
[ "MIT" ]
3
2021-06-04T19:53:18.000Z
2021-06-06T14:02:26.000Z
#include "disasm/disasm_i8086.h" enum { NONE, MODRM, GROUP, }; struct opcode_t { const char *mnemonic; byte flags; arg_type_e arg_1; arg_type_e arg_2; }; /* * Checked against http://mlsite.net/8086/ */ const opcode_t i8086_opcode_table[256] = { /* 00 */ { "add", MODRM, PARAM_RM8, PARAM_REG8 }, /* 01 */ { "add", MODRM, PARAM_RM16, PARAM_REG16 }, /* 02 */ { "add", MODRM, PARAM_REG8, PARAM_RM8 }, /* 03 */ { "add", MODRM, PARAM_REG16, PARAM_RM16 }, /* 04 */ { "add", 0, PARAM_IMM8 }, /* 05 */ { "add", 0, PARAM_IMM16 }, /* 06 */ { "push", 0, PARAM_ES }, /* 07 */ { "pop", 0, PARAM_ES }, /* 08 */ { "or", MODRM, PARAM_RM8, PARAM_REG8 }, /* 09 */ { "or", MODRM, PARAM_RM16, PARAM_REG16 }, /* 0a */ { "or", MODRM, PARAM_REG8, PARAM_RM8 }, /* 0b */ { "or", MODRM, PARAM_REG16, PARAM_RM16 }, /* 0c */ { "or", 0, PARAM_IMM8 }, /* 0d */ { "or", 0, PARAM_IMM16 }, /* 0e */ { "push", 0, PARAM_CS }, /* 0f */ { "pop", 0, PARAM_CS }, /* 10 */ { "adc", MODRM, PARAM_RM8, PARAM_REG8 }, /* 11 */ { "adc", MODRM, PARAM_RM16, PARAM_REG16 }, /* 12 */ { "adc", MODRM, PARAM_REG8, PARAM_RM8 }, /* 13 */ { "adc", MODRM, PARAM_REG16, PARAM_RM16 }, /* 14 */ { "adc", 0, PARAM_IMM8 }, /* 15 */ { "adc", 0, PARAM_IMM16 }, /* 16 */ { "push", 0, PARAM_SS }, /* 17 */ { "pop", 0, PARAM_SS }, /* 18 */ { "sbb", MODRM, PARAM_RM8, PARAM_REG8 }, /* 19 */ { "sbb", MODRM, PARAM_RM16, PARAM_REG16 }, /* 1a */ { "sbb", MODRM, PARAM_REG8, PARAM_RM8 }, /* 1b */ { "sbb", MODRM, PARAM_REG16, PARAM_RM16 }, /* 1c */ { "sbb", 0, PARAM_IMM8 }, /* 1d */ { "sbb", 0, PARAM_IMM16 }, /* 1e */ { "push", 0, PARAM_DS }, /* 1f */ { "pop", 0, PARAM_DS }, /* 20 */ { "and", MODRM, PARAM_RM8, PARAM_REG8 }, /* 21 */ { "and", MODRM, PARAM_RM16, PARAM_REG16 }, /* 22 */ { "and", MODRM, PARAM_REG8, PARAM_RM8 }, /* 23 */ { "and", MODRM, PARAM_REG16, PARAM_RM16 }, /* 24 */ { "and", 0, PARAM_IMM8 }, /* 25 */ { "and", 0, PARAM_IMM16 }, /* 26 */ { }, /* 27 */ { "daa" }, /* 28 */ { "sub", MODRM, PARAM_RM8, PARAM_REG8 }, /* 29 */ { "sub", MODRM, PARAM_RM16, PARAM_REG16 }, /* 2a */ { "sub", MODRM, PARAM_REG8, PARAM_RM8 }, /* 2b */ { "sub", MODRM, PARAM_REG16, PARAM_RM16 }, /* 2c */ { "sub", 0, PARAM_IMM8 }, /* 2d */ { "sub", 0, PARAM_IMM16 }, /* 2e */ { }, /* 2f */ { "das" }, /* 30 */ { "xor", MODRM, PARAM_RM8, PARAM_REG8 }, /* 31 */ { "xor", MODRM, PARAM_RM16, PARAM_REG16 }, /* 32 */ { "xor", MODRM, PARAM_REG8, PARAM_RM8 }, /* 33 */ { "xor", MODRM, PARAM_REG16, PARAM_RM16 }, /* 34 */ { "xor", 0, PARAM_IMM8 }, /* 35 */ { "xor", 0, PARAM_IMM16 }, /* 36 */ { }, /* 37 */ { "aaa" }, /* 38 */ { "cmp", MODRM, PARAM_RM8, PARAM_REG8 }, /* 39 */ { "cmp", MODRM, PARAM_RM16, PARAM_REG16 }, /* 3a */ { "cmp", MODRM, PARAM_REG8, PARAM_RM8 }, /* 3b */ { "cmp", MODRM, PARAM_REG16, PARAM_RM16 }, /* 3c */ { "cmp", 0, PARAM_IMM8 }, /* 3d */ { "cmp", 0, PARAM_IMM16 }, /* 3e */ { }, /* 3f */ { "aas" }, /* 40 */ { "inc", 0, PARAM_AX }, /* 41 */ { "inc", 0, PARAM_CX }, /* 42 */ { "inc", 0, PARAM_DX }, /* 43 */ { "inc", 0, PARAM_BX }, /* 44 */ { "inc", 0, PARAM_SP }, /* 45 */ { "inc", 0, PARAM_BP }, /* 46 */ { "inc", 0, PARAM_SI }, /* 47 */ { "inc", 0, PARAM_DI }, /* 48 */ { "dec", 0, PARAM_AX }, /* 49 */ { "dec", 0, PARAM_CX }, /* 4a */ { "dec", 0, PARAM_DX }, /* 4b */ { "dec", 0, PARAM_BX }, /* 4c */ { "dec", 0, PARAM_SP }, /* 4d */ { "dec", 0, PARAM_BP }, /* 4e */ { "dec", 0, PARAM_SI }, /* 4f */ { "dec", 0, PARAM_DI }, /* 50 */ { "push", 0, PARAM_AX }, /* 51 */ { "push", 0, PARAM_CX }, /* 52 */ { "push", 0, PARAM_DX }, /* 53 */ { "push", 0, PARAM_BX }, /* 54 */ { "push", 0, PARAM_SP }, /* 55 */ { "push", 0, PARAM_BP }, /* 56 */ { "push", 0, PARAM_SI }, /* 57 */ { "push", 0, PARAM_DI }, /* 58 */ { "pop", 0, PARAM_AX }, /* 59 */ { "pop", 0, PARAM_CX }, /* 5a */ { "pop", 0, PARAM_DX }, /* 5b */ { "pop", 0, PARAM_BX }, /* 5c */ { "pop", 0, PARAM_SP }, /* 5d */ { "pop", 0, PARAM_BP }, /* 5e */ { "pop", 0, PARAM_SI }, /* 5f */ { "pop", 0, PARAM_DI }, /* 60 */ { }, /* 61 */ { }, /* 62 */ { }, /* 63 */ { }, /* 64 */ { }, /* 65 */ { }, /* 66 */ { }, /* 67 */ { }, /* 68 */ { }, /* 69 */ { }, /* 6a */ { }, /* 6b */ { }, /* 6c */ { }, /* 6d */ { }, /* 6e */ { }, /* 6f */ { }, /* 70 */ { "jo", 0, PARAM_REL8 }, /* 71 */ { "jno", 0, PARAM_REL8 }, /* 72 */ { "jb", 0, PARAM_REL8 }, /* 73 */ { "jnb", 0, PARAM_REL8 }, /* 74 */ { "jz", 0, PARAM_REL8 }, /* 75 */ { "jnz", 0, PARAM_REL8 }, /* 76 */ { "jbe", 0, PARAM_REL8 }, /* 77 */ { "ja", 0, PARAM_REL8 }, /* 78 */ { "js", 0, PARAM_REL8 }, /* 79 */ { "jns", 0, PARAM_REL8 }, /* 7a */ { "jpe", 0, PARAM_REL8 }, /* 7b */ { "jpo", 0, PARAM_REL8 }, /* 7c */ { "jl", 0, PARAM_REL8 }, /* 7d */ { "jge", 0, PARAM_REL8 }, /* 7e */ { "jle", 0, PARAM_REL8 }, /* 7f */ { "jg", 0, PARAM_REL8 }, /* 80 */ { 0, GROUP, PARAM_RM8, PARAM_IMM8 }, /* 81 */ { 0, GROUP, PARAM_RM16, PARAM_IMM16 }, /* 82 */ { 0, GROUP, PARAM_RM8, PARAM_IMM8 }, /* 83 */ { 0, GROUP, PARAM_RM16, PARAM_IMM8 }, /* 84 */ { "test", MODRM, PARAM_REG8, PARAM_RM8 }, /* 85 */ { "test", MODRM, PARAM_REG16, PARAM_RM16 }, /* 86 */ { "xchg", MODRM, PARAM_REG8, PARAM_RM8 }, /* 87 */ { "xchg", MODRM, PARAM_REG16, PARAM_RM16 }, /* 88 */ { "mov", MODRM, PARAM_RM8, PARAM_REG8 }, /* 89 */ { "mov", MODRM, PARAM_RM16, PARAM_REG16 }, /* 8a */ { "mov", MODRM, PARAM_REG8, PARAM_RM8 }, /* 8b */ { "mov", MODRM, PARAM_REG16, PARAM_RM16 }, /* 8c */ { "mov", MODRM, PARAM_RM16, PARAM_SREG }, /* 8d */ { "lea", MODRM, PARAM_REG16, PARAM_MEM16 }, /* 8e */ { "mov", MODRM, PARAM_SREG, PARAM_RM16 }, /* 8f */ { "pop", MODRM, PARAM_RM16 }, /* 90 */ { "nop" }, /* 91 */ { "xchg", 0, PARAM_CX, PARAM_AX }, /* 92 */ { "xchg", 0, PARAM_DX, PARAM_AX }, /* 93 */ { "xchg", 0, PARAM_BX, PARAM_AX }, /* 94 */ { "xchg", 0, PARAM_SP, PARAM_AX }, /* 95 */ { "xchg", 0, PARAM_BP, PARAM_AX }, /* 96 */ { "xchg", 0, PARAM_SI, PARAM_AX }, /* 97 */ { "xchg", 0, PARAM_DI, PARAM_AX }, /* 98 */ { "cbw" }, /* 99 */ { "cwd" }, /* 9a */ { "call", 0, PARAM_IMEM32 }, /* 9b */ { "wait" }, /* 9c */ { "pushf" }, /* 9d */ { "popf" }, /* 9e */ { "sahf" }, /* 9f */ { "lahf" }, /* a0 */ { "mov", 0, PARAM_AL, PARAM_IMEM8 }, /* a1 */ { "mov", 0, PARAM_AX, PARAM_IMEM16 }, /* a2 */ { "mov", 0, PARAM_IMEM8, PARAM_AL }, /* a3 */ { "mov", 0, PARAM_IMEM16, PARAM_AX }, /* a4 */ { "movsb" }, /* a5 */ { "movsw" }, /* a6 */ { "cmpsb" }, /* a7 */ { "cmpsw" }, /* a8 */ { "test", 0, PARAM_AL, PARAM_IMM8 }, /* a9 */ { "test", 0, PARAM_AX, PARAM_IMM16 }, /* aa */ { "stosb" }, /* ab */ { "stosw" }, /* ac */ { "lodsb" }, /* ad */ { "lodsw" }, /* ae */ { "scasb" }, /* af */ { "scasw" }, /* b0 */ { "mov", 0, PARAM_AL, PARAM_IMM8 }, /* b1 */ { "mov", 0, PARAM_CL, PARAM_IMM8 }, /* b2 */ { "mov", 0, PARAM_DL, PARAM_IMM8 }, /* b3 */ { "mov", 0, PARAM_BL, PARAM_IMM8 }, /* b4 */ { "mov", 0, PARAM_AH, PARAM_IMM8 }, /* b5 */ { "mov", 0, PARAM_CH, PARAM_IMM8 }, /* b6 */ { "mov", 0, PARAM_DH, PARAM_IMM8 }, /* b7 */ { "mov", 0, PARAM_BH, PARAM_IMM8 }, /* b8 */ { "mov", 0, PARAM_AX, PARAM_IMM16 }, /* b9 */ { "mov", 0, PARAM_CX, PARAM_IMM16 }, /* ba */ { "mov", 0, PARAM_DX, PARAM_IMM16 }, /* bb */ { "mov", 0, PARAM_BX, PARAM_IMM16 }, /* bc */ { "mov", 0, PARAM_SP, PARAM_IMM16 }, /* bd */ { "mov", 0, PARAM_BP, PARAM_IMM16 }, /* be */ { "mov", 0, PARAM_SI, PARAM_IMM16 }, /* bf */ { "mov", 0, PARAM_DI, PARAM_IMM16 }, /* c0 */ { }, /* c1 */ { }, /* c2 */ { "ret", 0, PARAM_IMM16 }, /* c3 */ { "ret" }, /* c4 */ { "les", MODRM, PARAM_REG16, PARAM_MEM32 }, /* c5 */ { "lds", MODRM, PARAM_REG16, PARAM_MEM32 }, /* c6 */ { "mov", MODRM, PARAM_RM8, PARAM_IMM8 }, /* c7 */ { "mov", MODRM, PARAM_RM16, PARAM_IMM16 }, /* c8 */ { }, /* c9 */ { }, /* ca */ { "retf", 0, PARAM_IMM16 }, /* cb */ { "retf" }, /* cc */ { "int", 0, PARAM_3 }, /* cd */ { "int", 0, PARAM_IMM8 }, /* ce */ { "into" }, /* cf */ { "iret" }, /* d0 */ { 0, GROUP, PARAM_RM8, PARAM_1 }, /* d1 */ { 0, GROUP, PARAM_RM16, PARAM_1 }, /* d2 */ { 0, GROUP, PARAM_RM8, PARAM_CL }, /* d3 */ { 0, GROUP, PARAM_RM16, PARAM_CL }, /* d4 */ { "aam", 0, PARAM_IMM8 }, /* d5 */ { "aad", 0, PARAM_IMM8 }, /* d6 */ { }, /* d7 */ { "xlat" }, /* d8 */ { }, /* d9 */ { }, /* da */ { }, /* db */ { }, /* dc */ { }, /* dd */ { }, /* de */ { }, /* df */ { }, /* e0 */ { "loopnz", 0, PARAM_REL8 }, /* e1 */ { "loopz", 0, PARAM_REL8 }, /* e2 */ { "loop", 0, PARAM_REL8 }, /* e3 */ { "jcxz", 0, PARAM_REL8 }, /* e4 */ { "in", 0, PARAM_AL, PARAM_IMM8 }, /* e5 */ { "in", 0, PARAM_AX, PARAM_IMM8 }, /* e6 */ { "out", 0, PARAM_IMM8, PARAM_AL }, /* e7 */ { "out", 0, PARAM_IMM8, PARAM_AX }, /* e8 */ { "call", 0, PARAM_REL16 }, /* e9 */ { "jmp", 0, PARAM_REL16 }, /* ea */ { "jmp", 0, PARAM_IMEM32 }, /* eb */ { "jmp", 0, PARAM_REL8 }, /* ec */ { "in", 0, PARAM_AL, PARAM_DX }, /* ed */ { "in", 0, PARAM_AX, PARAM_DX }, /* ee */ { "out", 0, PARAM_DX, PARAM_AL }, /* ef */ { "out", 0, PARAM_DX, PARAM_AX }, /* f0 */ { "lock" }, /* f1 */ { }, /* f2 */ { }, /* f3 */ { }, /* f4 */ { "hlt" }, /* f5 */ { "cmc" }, /* f6 */ { 0, GROUP, PARAM_RM8, PARAM_IMM8 }, /* f7 */ { 0, GROUP, PARAM_RM16, PARAM_IMM16 }, /* f8 */ { "clc" }, /* f9 */ { "stc" }, /* fa */ { "cli" }, /* fb */ { "sti" }, /* fc */ { "cld" }, /* fd */ { "std" }, /* fe */ { 0, GROUP, PARAM_RM8 }, /* ff */ { 0, GROUP, PARAM_RM16 }, }; const opcode_t i8086_opcode_table_grp_1[8] = { { "add" }, { "or" }, { "adc" }, { "sbb" }, { "and" }, { "sub" }, { "xor" }, { "cmp" }, }; const opcode_t i8086_opcode_table_grp_ff[8] = { { "inc", 0, PARAM_RM8 }, { "dec", 0, PARAM_RM8 }, { "call", 0, PARAM_RM8 }, { "call", 0, PARAM_RM16 }, { "jmp", 0, PARAM_RM8 }, { "jmp", 0, PARAM_RM16 }, { "push" }, }; const opcode_t i8086_opcode_table_grp_2[8] = { { "rol" }, { "ror" }, { "rcl" }, { "rcr" }, { "shl" }, { "shr" }, { "sal" }, { "sar" }, }; const opcode_t i8086_opcode_table_grp_3[8] = { {"test" }, {"test" }, {"not", 0, PARAM_INHERIT, PARAM_NONE }, {"neg", 0, PARAM_INHERIT, PARAM_NONE }, {"mul", 0, PARAM_INHERIT, PARAM_NONE }, {"imul", 0, PARAM_INHERIT, PARAM_NONE }, {"div", 0, PARAM_INHERIT, PARAM_NONE }, {"idiv", 0, PARAM_INHERIT, PARAM_NONE }, }; const opcode_t i8086_opcode_table_grp_4[8] = { { "inc" }, { "dec" }, }; const opcode_t i8086_opcode_table_grp_5[8] = { { "inc" }, { "dec" }, { "call" }, { "call", PARAM_MEM32 }, { "jmp" }, { "jmp", PARAM_MEM32 }, { "push" }, { 0 }, }; byte disasm_i8086_t::read8(uint16_t seg, uint16_t ofs) { uint32_t ea = 0x10 * seg + ofs; byte v = read(MEM, ea, W8); return v; } uint16_t disasm_i8086_t::read16(uint16_t seg, uint16_t ofs) { uint32_t ea = 0x10 * seg + ofs; uint16_t v = read(MEM, ea, W16); return v; } byte disasm_i8086_t::fetch8() { byte v = read8(cs, ip); ip += 1; return v; } uint16_t disasm_i8086_t::fetch16() { uint16_t v = read16(cs, ip); ip += 2; return v; } static bool needs_modrm(const opcode_t &opcode) { return opcode.flags == MODRM || opcode.flags == GROUP; } static opcode_t inherit(const opcode_t op_detail, const opcode_t grp) { return opcode_t { .mnemonic = op_detail.mnemonic, .flags = op_detail.flags, .arg_1 = op_detail.arg_1 ? op_detail.arg_1 : grp.arg_1, .arg_2 = op_detail.arg_2 ? op_detail.arg_2 : grp.arg_2, }; } static bool is_mem_arg(arg_type_e arg, byte modrm) { switch (arg) { case PARAM_IMEM8: case PARAM_IMEM16: case PARAM_IMEM32: case PARAM_MEM8: case PARAM_MEM16: case PARAM_MEM32: return true; case PARAM_RM8: case PARAM_RM16: return modrm < 0xc0; default:; } return false; } static int needs_width_for_mem(arg_type_e arg) { switch (arg) { case PARAM_INHERIT: case PARAM_NONE: case PARAM_IMM8: case PARAM_IMM16: return true; default:; } return false; } void disasm_i8086_t::disassemble(uint16_t a_cs, uint16_t *a_ip, const char **s) { cs = a_cs; op_ip = ip = *a_ip; sreg_ovr = 0; flag_f2 = false; flag_f3 = false; flag_lock = false; op = 0; modrm = 0; sreg_ovr = 0; strbuf.clear(); for (;;) { op = fetch8(); // Handle prefixes switch (op) { case 0x2e: sreg_ovr = op; break; // CS case 0x36: sreg_ovr = op; break; // SS case 0x3e: sreg_ovr = op; break; // DS case 0x26: sreg_ovr = op; break; // ES case 0xf0: // LOCK flag_lock = true; break; case 0xf2: // REPNE flag_f2 = true; flag_f3 = false; break; case 0xf3: // REP flag_f3 = true; flag_f2 = false; break; default: goto opcode; } } opcode: opcode_t opcode = i8086_opcode_table[op]; if (needs_modrm(opcode)) { modrm = fetch8(); } #define REG ((modrm >> 3) & 0b111) switch (op) { case 0x80: case 0x81: case 0x82: case 0x83: opcode = inherit(i8086_opcode_table_grp_1[REG], opcode); break; case 0xd0: case 0xd1: case 0xd2: case 0xd3: opcode = inherit(i8086_opcode_table_grp_2[REG], opcode); break; case 0xf6: case 0xf7: opcode = inherit(i8086_opcode_table_grp_3[REG], opcode); break; case 0xfe: opcode = inherit(i8086_opcode_table_grp_4[REG], opcode); break; case 0xff: opcode = inherit(i8086_opcode_table_grp_5[REG], opcode); break; } #undef REG strbuf.sprintf("%04x:%04x\t", cs, op_ip); if (!opcode.mnemonic) { strbuf.sprintf("db\t%s", str_imm(op)); } else { if (flag_lock) { strbuf.sprintf("lock "); } if (flag_f2) { switch (op) { case 0xa6: // cmpsb case 0xa7: // cmpsw strbuf.sprintf("repne "); break; case 0xae: // scasb case 0xaf: // scasw strbuf.sprintf("repne "); break; } } else if (flag_f3) { switch (op) { case 0xa4: // movsb case 0xa5: // movsw strbuf.sprintf("rep "); break; case 0xa6: // cmpsb case 0xa7: // cmpsw strbuf.sprintf("repe "); break; case 0xaa: // stosb case 0xab: // stosw strbuf.sprintf("rep "); break; case 0xac: // lodsb case 0xad: // lodsw strbuf.sprintf("rep "); break; case 0xae: // scasb case 0xaf: // scasw strbuf.sprintf("repe "); break; } } bool has_mem_arg = is_mem_arg(opcode.arg_1, modrm) || is_mem_arg(opcode.arg_2, modrm); bool needs_mem_width = has_mem_arg && (needs_width_for_mem(opcode.arg_1) || needs_width_for_mem(opcode.arg_2)); show_mem_width = always_show_mem_width || needs_mem_width; /* * If we have a segment override but no memory * argument to put it in front of, put it before * the mnemonic. */ if (sreg_ovr) { if (!has_mem_arg) { strbuf.sprintf("%s", str_sreg_ovr(sreg_ovr)); } } strbuf.sprintf("%s", opcode.mnemonic); if (opcode.arg_1) { strbuf.sprintf("\t"); handle_param(opcode.arg_1); } if (opcode.arg_2) { strbuf.sprintf(", "); handle_param(opcode.arg_2); } } *a_ip = this->ip; if (s) { *s = strbuf.cstr(); } } const char *disasm_i8086_t::str_imm(uint16_t imm) { static char s[16]; uint16_t t = imm; while (t > 0xf) { t >>= 4; } sprintf(s, "%s%X%s", t > 9 ? "0" : "", imm, imm < 10 ? "" : "h"); return s; } const char *disasm_i8086_t::str_reg(byte reg, bool w) { const char *regnames = "al\0cl\0dl\0bl\0ah\0ch\0dh\0bh\0ax\0cx\0dx\0bx\0sp\0bp\0si\0di"; byte index = (((byte)w << 3) | reg); return &regnames[3 * index]; } const char *disasm_i8086_t::str_sreg(byte reg) { const char *regnames = "es\0cs\0ss\0ds"; return &regnames[3 * reg]; } const char *disasm_i8086_t::str_sreg_ovr(byte sreg_ovr) { switch (sreg_ovr) { case 0x26: return "es:"; case 0x2e: return "cs:"; case 0x36: return "ss:"; case 0x3e: return "ds:"; } return ""; } #define REG ((modrm >> 3) & 0b111) void disasm_i8086_t::handle_param(arg_type_e arg) { switch (arg) { case PARAM_INHERIT: case PARAM_NONE: break; case PARAM_1: strbuf.sprintf("1"); break; case PARAM_3: strbuf.sprintf("3"); break; case PARAM_AL: strbuf.sprintf("al"); break; case PARAM_CL: strbuf.sprintf("cl"); break; case PARAM_DL: strbuf.sprintf("dl"); break; case PARAM_BL: strbuf.sprintf("bl"); break; case PARAM_AH: strbuf.sprintf("ah"); break; case PARAM_CH: strbuf.sprintf("ch"); break; case PARAM_DH: strbuf.sprintf("dh"); break; case PARAM_BH: strbuf.sprintf("bh"); break; case PARAM_AX: strbuf.sprintf("ax"); break; case PARAM_CX: strbuf.sprintf("cx"); break; case PARAM_DX: strbuf.sprintf("dx"); break; case PARAM_BX: strbuf.sprintf("bx"); break; case PARAM_SP: strbuf.sprintf("sp"); break; case PARAM_BP: strbuf.sprintf("bp"); break; case PARAM_SI: strbuf.sprintf("si"); break; case PARAM_DI: strbuf.sprintf("di"); break; case PARAM_ES: strbuf.sprintf("es"); break; case PARAM_CS: strbuf.sprintf("cs"); break; case PARAM_SS: strbuf.sprintf("ss"); break; case PARAM_DS: strbuf.sprintf("ds"); break; case PARAM_REG8: strbuf.sprintf("%s", str_reg(REG, false)); break; case PARAM_REG16: strbuf.sprintf("%s", str_reg(REG, true)); break; case PARAM_SREG: strbuf.sprintf("%s", str_sreg(REG)); break; case PARAM_IMM8: strbuf.sprintf("%s", str_imm(fetch8())); break; case PARAM_IMM16: strbuf.sprintf("%s", str_imm(fetch16())); break; case PARAM_REL8: { uint16_t inc = fetch8(); strbuf.sprintf("%s", str_imm(ip + inc)); } break; case PARAM_REL16: { uint16_t inc = fetch16(); strbuf.sprintf("%s", str_imm(ip + inc)); } break; case PARAM_IMEM8: case PARAM_IMEM16: strbuf.sprintf("%s[%s]", str_sreg_ovr(sreg_ovr), str_imm(fetch16())); break; case PARAM_IMEM32: { uint16_t ofs = fetch16(); uint16_t seg = fetch16(); strbuf.sprintf("%s[%s:%s]", str_sreg_ovr(sreg_ovr), str_imm(seg), str_imm(ofs)); } break; case PARAM_MEM8: case PARAM_MEM16: case PARAM_MEM32: case PARAM_RM8: case PARAM_RM16: { byte mod = (modrm >> 6); byte rm = (modrm >> 0) & 0b111; bool w = (arg == PARAM_RM16) || (arg == PARAM_MEM16); ; if (mod == 0b11) { if (arg == PARAM_MEM8 || arg == PARAM_MEM8 || arg == PARAM_MEM32) { strbuf.sprintf("invalid"); } else { strbuf.sprintf("%s", str_reg(rm, w)); } } else { if (show_mem_width) { switch (arg) { case PARAM_MEM8: case PARAM_RM8: strbuf.sprintf("byte ptr "); break; case PARAM_RM16: case PARAM_MEM16: strbuf.sprintf("word ptr "); break; case PARAM_MEM32: strbuf.sprintf("far ptr "); break; default:; } } strbuf.sprintf("%s", str_sreg_ovr(sreg_ovr)); strbuf.sprintf("["); switch (rm) { case 0b000: strbuf.sprintf("bx+si"); break; case 0b001: strbuf.sprintf("bx+di"); break; case 0b010: strbuf.sprintf("bp+si"); break; case 0b011: strbuf.sprintf("bp+di"); break; case 0b100: strbuf.sprintf("si"); break; case 0b101: strbuf.sprintf("di"); break; case 0b110: if (mod) { strbuf.sprintf("bp"); } else { strbuf.sprintf("%s", str_imm(fetch16())); } break; case 0b111: strbuf.sprintf("bx"); break; } int disp; switch (mod) { case 0b01: disp = fetch8(); if (disp & 0x80) { strbuf.sprintf("-%s", str_imm((disp ^ 0xff) + 1)); } else { strbuf.sprintf("+%s", str_imm(disp)); } break; case 0b10: strbuf.sprintf("+%s", str_imm(fetch16())); break; } strbuf.sprintf("]"); } } break; } }
35.536857
89
0.411608
[ "3d" ]
4bd882fe43b58b85adbfa7d1824bccda879381d3
2,922
cpp
C++
rapp_qr_detection/tests/qr_detection/unit_tests.cpp
DEVX1/NAOrapp-Pythonlib
d07d7fe304556cad24e7e138df4e41376eacb6a7
[ "Apache-2.0" ]
null
null
null
rapp_qr_detection/tests/qr_detection/unit_tests.cpp
DEVX1/NAOrapp-Pythonlib
d07d7fe304556cad24e7e138df4e41376eacb6a7
[ "Apache-2.0" ]
null
null
null
rapp_qr_detection/tests/qr_detection/unit_tests.cpp
DEVX1/NAOrapp-Pythonlib
d07d7fe304556cad24e7e138df4e41376eacb6a7
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** Copyright 2015 RAPP 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 <gtest/gtest.h> #include <qr_detection/qr_detector.h> #include <ros/package.h> /** * @class QrDetectionTest * @brief Utilizes gtest in order to provide unit tests for qr detection */ class QrDetectionTest : public ::testing::Test { protected: /** * @brief Default constructor */ QrDetectionTest() { } /** * @brief Sets up stuff before each unit test call */ virtual void SetUp() { qr_detector_ = new QrDetector; } /** * @brief Clears up stuff after each unit test call */ virtual void TearDown() { delete qr_detector_; } /**< The QrDetector object, used to test its functions */ QrDetector *qr_detector_; }; /** * @brief Tests QR detection with an image containing face. Should return 0 qrs */ TEST_F(QrDetectionTest, lenna_test) { std::string path = ros::package::getPath("rapp_testing_tools"); std::string s = path + std::string("/test_data/Lenna.png"); std::vector<QrCode> qrs; qrs = qr_detector_->findQrs(s); EXPECT_EQ(0, qrs.size()); } /** * @brief Tests QR detection with an image containing a qr. Should return 1 qr */ TEST_F(QrDetectionTest, qr_test) { std::string path = ros::package::getPath("rapp_testing_tools"); std::string s = path + std::string("/test_data/qr_code_rapp.jpg"); std::vector<QrCode> qrs; qrs = qr_detector_->findQrs(s); EXPECT_EQ(1, qrs.size()); } /** * @brief Tests QR detection with a non-existent image. Should return 0 qrs */ TEST_F(QrDetectionTest, file_not_exists_test) { std::string path = ros::package::getPath("rapp_testing_tools"); std::string s = path + std::string("/test_data/file_not_exists.jpg"); std::vector<QrCode> qrs; qrs = qr_detector_->findQrs(s); EXPECT_EQ(0, qrs.size()); } /** * @brief Tests QR detection with a zero-sized image. Should return 0 qrs */ TEST_F(QrDetectionTest, zero_sized_image_test) { cv::Mat tmp_img(0, 0, CV_8UC1); std::vector<QrCode> qrs; qrs = qr_detector_->detectQrs(tmp_img); EXPECT_EQ(0, qrs.size()); } /** * @brief The main function. Initializes the unit tests */ int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
25.631579
79
0.654346
[ "object", "vector" ]
4be41d96ba97bfb0f3e7be49489cb32328697978
678
cpp
C++
Leetcode1964.cpp
dezhonger/LeetCode
70de054be5af3a0749dce0625fefd75e176e59f4
[ "Apache-2.0" ]
1
2020-06-28T06:29:05.000Z
2020-06-28T06:29:05.000Z
Leetcode1964.cpp
dezhonger/LeetCode
70de054be5af3a0749dce0625fefd75e176e59f4
[ "Apache-2.0" ]
null
null
null
Leetcode1964.cpp
dezhonger/LeetCode
70de054be5af3a0749dce0625fefd75e176e59f4
[ "Apache-2.0" ]
null
null
null
const int N = 100010; //f[i]: 长度为i的LIS数组的最小结尾数字 int f[N]; class Solution { public: vector<int> longestObstacleCourseAtEachPosition(vector<int>& obstacles) { int len = 0, n = obstacles.size(); vector<int> res(n); memset(f, 0, sizeof f); f[0] = -2e9; for (int i = 0; i < n; i++) { int x = obstacles[i]; int l = 0, r = len; while (l < r) { int mid = l + r + 1 >> 1; if (f[mid] <= x) l = mid; else r = mid - 1; } f[l + 1] = x; len = max(len, l + 1); res[i] = l + 1; } return res; } };
25.111111
77
0.405605
[ "vector" ]
4be42ca0942c22876de46edcaf03ea1f46f39c8f
4,620
cxx
C++
Code/Modules/Functional/test/MahalanobisFunctionalTest.cxx
xiaochengcike/RegSeg
e2cff93ef4f195bfd59c518e047cf8f37560b6a8
[ "MIT" ]
14
2016-05-16T08:47:04.000Z
2022-01-07T14:57:16.000Z
Code/Modules/Functional/test/MahalanobisFunctionalTest.cxx
xiaochengcike/RegSeg
e2cff93ef4f195bfd59c518e047cf8f37560b6a8
[ "MIT" ]
5
2016-01-24T02:52:55.000Z
2017-10-18T02:13:15.000Z
Code/Modules/Functional/test/MahalanobisFunctionalTest.cxx
oesteban/RegSeg
e2cff93ef4f195bfd59c518e047cf8f37560b6a8
[ "MIT" ]
8
2015-12-24T21:13:43.000Z
2022-03-25T00:06:35.000Z
// This file is part of RegSeg // // Copyright 2014-2017, Oscar Esteban <code@oscaresteban.es> // // 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. #ifndef TEST_DATA_DIR #define TEST_DATA_DIR "./" // data source http://code.google.com/p/v3dsolver/source/browse/data/ #endif #include <itkVector.h> #include <itkVectorImage.h> #include <itkImage.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkQuadEdgeMesh.h> #include <itkVTKPolyDataReader.h> #include <itkVTKPolyDataWriter.h> #include <itkVectorImageToImageAdaptor.h> #include "MahalanobisFunctional.h" #include "DisplacementFieldFileWriter.h" using namespace rstk; int main(int argc, char *argv[]) { typedef itk::Vector<float, 1u> VectorPixelType; typedef itk::Image<VectorPixelType, 3u> ImageType; typedef MahalanobisFunctional<ImageType> FunctionalType; typedef FunctionalType::ContourType ContourType; typedef ContourType::Pointer ContourDisplacementFieldPointer; typedef FunctionalType::PointType PointType; typedef FunctionalType::MeanType MeanType; typedef FunctionalType::CovarianceType CovarianceType; typedef FunctionalType::DeformationFieldType DeformationFieldType; typedef itk::VTKPolyDataReader< ContourType > ReaderType; typedef itk::VTKPolyDataWriter< ContourType > WriterType; typedef itk::ImageFileReader<ImageType> ImageReader; typedef itk::ImageFileWriter<ImageType> ImageWriter; typedef rstk::DisplacementFieldFileWriter<DeformationFieldType> Writer; typedef itk::VectorImageToImageAdaptor<double,3u> VectorToImage; ImageReader::Pointer r = ImageReader::New(); r->SetFileName( std::string( TEST_DATA_DIR ) + "ellipse.nii.gz" ); r->Update(); ImageType::Pointer im = r->GetOutput(); ReaderType::Pointer polyDataReader = ReaderType::New(); polyDataReader->SetFileName( std::string( TEST_DATA_DIR ) + "ellipse.vtk" ); polyDataReader->Update(); ContourDisplacementFieldPointer ellipse = polyDataReader->GetOutput(); typename ContourType::PointsContainerPointer points = ellipse->GetPoints(); typename ContourType::PointsContainerIterator u_it = points->Begin(); PointType zero = itk::NumericTraits<PointType>::Zero; while( u_it != points->End() ) { ellipse->SetPointData( u_it.Index(),zero); ++u_it; } MeanType mean1; mean1.Fill(127); MeanType mean2; mean2.Fill(255); CovarianceType cov; cov.SetIdentity(); DeformationFieldType::Pointer df = DeformationFieldType::New(); DeformationFieldType::SizeType size = im->GetLargestPossibleRegion().GetSize(); double factor = 0.25; for( size_t i=0;i<3;i++) size[i]=(unsigned int) (size[i] * factor); DeformationFieldType::SpacingType spacing = im->GetSpacing(); spacing=spacing/factor; df->SetRegions( size ); df->SetSpacing( spacing ); df->SetDirection( im->GetDirection() ); df->Allocate(); df->FillBuffer( itk::NumericTraits<DeformationFieldType::PixelType>::Zero ); std::cout << "Number Of Parameters=" << df->GetLargestPossibleRegion().GetNumberOfPixels() << std::endl; FunctionalType::Pointer ls = FunctionalType::New(); ls->SetReferenceImage( im ); //typename FunctionalType::ParametersType params; //params.mean[0] = 255; //params.mean[1] = 127; //params.cov = cov; //params.iCovariance[2] = cov; ls->AddShapePrior( ellipse ); Writer::Pointer writer = Writer::New(); writer->SetFileName( std::string( TEST_DATA_DIR ) + "shapegradientmap.nii.gz" ); writer->SetInput( ls->GetShapeGradients() ); writer->Update(); }
38.823529
105
0.736364
[ "vector" ]
4beaab1fb4d62fdef8f33d5b540ef2f37d1f01b9
2,816
cpp
C++
src/mcmc.cpp
halasadi/eems2
92c6b54cdd2cf30c0c363fa716487f4ace584fd3
[ "MIT" ]
20
2017-10-20T15:47:11.000Z
2022-03-30T17:25:11.000Z
src/mcmc.cpp
halasadi/eems2
92c6b54cdd2cf30c0c363fa716487f4ace584fd3
[ "MIT" ]
9
2018-01-05T16:42:54.000Z
2021-03-04T09:41:02.000Z
src/mcmc.cpp
halasadi/eems2
92c6b54cdd2cf30c0c363fa716487f4ace584fd3
[ "MIT" ]
3
2019-04-09T09:07:01.000Z
2020-12-01T14:31:57.000Z
#include "mcmc.hpp" MCMC::MCMC(const Params &params) { numMCMCIter = params.numMCMCIter; numBurnIter = params.numBurnIter; numThinIter = params.numThinIter; currIter = 0; numTypes = 12; finished = false; okayMoves = vector<double>(numTypes,0); totalMoves = vector<double>(numTypes,0); } MCMC::~MCMC( ) { } int MCMC::num_iters_to_save( ) const { int a = (numMCMCIter - numBurnIter) / (numThinIter + 1); return (a); } int MCMC::to_save_iteration( ) const { if (currIter>numBurnIter) { int a = (currIter - numBurnIter) / (numThinIter + 1); int b = (currIter - numBurnIter) % (numThinIter + 1); if (b==0) { return (a-1); } } return (-1); } ostream& operator<<(ostream& out, const MCMC& mcmc) { for ( int i = 0 ; i < mcmc.numTypes ; i++ ) { double a = mcmc.okayMoves.at(i); double A = mcmc.totalMoves.at(i); out << setprecision(2) << "\t(" << (int)a << "/" << (int)A << ") = " << 100.0*(a/A) << "% for type "; switch (i) { case Q_VORONOI_RATE_UPDATE: out << "\"qTileRate\"" << endl; break; case Q_VORONOI_POINT_MOVE: out << "\"qTileMove\"" << endl; break; case Q_VORONOI_BIRTH_DEATH: out << "\"qBirthDeath\"" << endl; break; case M_VORONOI_RATE_UPDATE: out << "\"mTileRate\"" << endl; break; case M_MEAN_RATE_UPDATE: out << "\"mMeanRate\"" << endl; break; case M_VORONOI_POINT_MOVE: out << "\"mTileMove\"" << endl; break; case M_VORONOI_BIRTH_DEATH: out << "\"mBirthDeath\"" << endl; break; case Q_MEAN_RATE_UPDATE: out << "\"qMeanRate\"" << endl; break; case OMEGAM_UPDATE: out << "\"omegaM\"" << endl; break; case OMEGAQ_UPDATE: out << "\"omegaQ\"" << endl; break; case EMBAR_UPDATE: out << "\"eqBar\"" << endl; break; case EQBAR_UPDATE: out << "\"emBar\"" << endl; break; default: cerr << "[RJMCMC] Unknown move type" << endl; exit(1); } } return out; } void MCMC::end_iteration( ) { if (++currIter==numMCMCIter) { finished = true; } if (!(currIter%1000)) { cerr << "Iteration " << currIter << " of " << numMCMCIter << "..." << endl; } } void MCMC::add_to_okay_moves(const int type) { okayMoves[type]++; } void MCMC::add_to_total_moves(const int type) { totalMoves[type]++; }
31.288889
109
0.478338
[ "vector" ]
4bfa758f9840cb4b55686dae74e199b5bc0874c2
8,303
cpp
C++
src/coordinates.cpp
faizol/tilemaker
763200664db2319079e97cc8134c41deffb41f0d
[ "MIT" ]
null
null
null
src/coordinates.cpp
faizol/tilemaker
763200664db2319079e97cc8134c41deffb41f0d
[ "MIT" ]
null
null
null
src/coordinates.cpp
faizol/tilemaker
763200664db2319079e97cc8134c41deffb41f0d
[ "MIT" ]
null
null
null
#include "coordinates.h" #include <math.h> using namespace std; namespace geom = boost::geometry; TileCoordinates_::TileCoordinates_() { this->x = 0; this->y = 0; } TileCoordinates_::TileCoordinates_(TileCoordinate x, TileCoordinate y) { this->x = x; this->y = y; } double deg2rad(double deg) { return (M_PI/180.0) * deg; } double rad2deg(double rad) { return (180.0/M_PI) * rad; } // Project latitude (spherical Mercator) // (if calling with raw coords, remember to divide/multiply by 10000000.0) static inline double clamp(double value, double limit) { return (value < -limit ? -limit : (value > limit ? limit : value)); } double lat2latp(double lat) { return rad2deg(log(tan(deg2rad(clamp(lat,85.06)+90.0)/2.0))); } double latp2lat(double latp) { return rad2deg(atan(exp(deg2rad(latp)))*2.0)-90.0; } // Tile conversions double lon2tilexf(double lon, uint z) { return scalbn((lon+180.0) * (1/360.0), (int)z); } double latp2tileyf(double latp, uint z) { return scalbn((180.0-latp) * (1/360.0), (int)z); } double lat2tileyf(double lat, uint z) { return latp2tileyf(lat2latp(lat), z); } uint lon2tilex(double lon, uint z) { return lon2tilexf(lon, z); } uint latp2tiley(double latp, uint z) { return latp2tileyf(latp, z); } uint lat2tiley(double lat, uint z) { return lat2tileyf(lat, z); } double tilex2lon(uint x, uint z) { return scalbn(x, -(int)z) * 360.0 - 180.0; } double tiley2latp(uint y, uint z) { return 180.0 - scalbn(y, -(int)z) * 360.0; } double tiley2lat(uint y, uint z) { return latp2lat(tiley2latp(y, z)); } // Get a tile index TileCoordinates latpLon2index(LatpLon ll, uint baseZoom) { return TileCoordinates(lon2tilex(ll.lon /10000000.0, baseZoom), latp2tiley(ll.latp/10000000.0, baseZoom)); } // Convert to actual length double degp2meter(double degp, double latp) { return RadiusMeter * deg2rad(degp) * cos(deg2rad(latp2lat(latp))); } double meter2degp(double meter, double latp) { return rad2deg((1/RadiusMeter) * (meter / cos(deg2rad(latp2lat(latp))))); } // the range between smallest y and largest y is filled, for each x void fillCoveredTiles(unordered_set<TileCoordinates> &tileSet) { vector<TileCoordinates> tileList(tileSet.begin(), tileSet.end()); sort(tileList.begin(), tileList.end(), TileCoordinatesCompare()); TileCoordinate prevX = 0, prevY = static_cast<TileCoordinate>(-2); for (TileCoordinates index: tileList) { TileCoordinate tileX = index.x, tileY = index.y; if (tileX == prevX) { // this loop has no effect at the first iteration for (TileCoordinate fillY = prevY+1; fillY < tileY; fillY++) { tileSet.insert(TileCoordinates(tileX, fillY)); } } prevX = tileX, prevY = tileY; } } // ------------------------------------------------------ // Helper class for dealing with spherical Mercator tiles TileBbox::TileBbox(TileCoordinates i, uint z, bool h) { zoom = z; index = i; hires = h; minLon = tilex2lon(i.x ,zoom); minLat = tiley2lat(i.y+1,zoom); maxLon = tilex2lon(i.x+1,zoom); maxLat = tiley2lat(i.y ,zoom); minLatp = lat2latp(minLat); maxLatp = lat2latp(maxLat); xmargin = (maxLon -minLon )/200.0; ymargin = (maxLatp-minLatp)/200.0; xscale = (maxLon -minLon )/(hires ? 8192.0 : 4096.0); yscale = (maxLatp-minLatp)/(hires ? 8192.0 : 4096.0); clippingBox = Box(geom::make<Point>(minLon-xmargin, minLatp-ymargin), geom::make<Point>(maxLon+xmargin, maxLatp+ymargin)); } pair<int,int> TileBbox::scaleLatpLon(double latp, double lon) const { int x = floor( (lon - minLon) / xscale ); int y = floor( (maxLatp - latp) / yscale ); return pair<int,int>(x,y); } pair<double, double> TileBbox::floorLatpLon(double latp, double lon) const { auto p = scaleLatpLon(latp, lon); return std::make_pair( -(p.second * yscale - maxLatp), p.first * xscale + minLon); } Box TileBbox::getTileBox() const { double xmargin = (maxLon -minLon )/8192.0; double ymargin = (maxLatp-minLatp)/8192.0; return Box(geom::make<Point>(minLon+xmargin, minLatp+ymargin), geom::make<Point>(maxLon-xmargin, maxLatp-ymargin)); } Box TileBbox::getExtendBox() const { return Box( geom::make<Point>( minLon-(maxLon-minLon)*2.0, minLatp-(maxLatp-minLatp)*(8191.0/8192.0)), geom::make<Point>( maxLon+(maxLon-minLon)*(8191.0/8192.0), maxLatp+(maxLatp-minLatp)*2.0)); } MultiPolygon round_coordinates(TileBbox const &bbox, MultiPolygon const &mp) { MultiPolygon combined_mp; for(auto new_p: mp) { for(auto &i: new_p.outer()) { auto round_i = bbox.floorLatpLon(i.y(), i.x()); i = Point(round_i.second, round_i.first); } for(auto &r: new_p.inners()) { for(auto &i: r) { auto round_i = bbox.floorLatpLon(i.y(), i.x()); i = Point(round_i.second, round_i.first); } } boost::geometry::remove_spikes(new_p); simplify_combine(combined_mp, std::move(new_p)); } return combined_mp; } template<typename T> void impl_insertIntermediateTiles(T const &points, uint baseZoom, std::unordered_set<TileCoordinates> &tileSet) { Point p2(0, 0); for (auto it = points.begin(); it != points.end(); ++it) { // Line is from p1 to p2 Point p1 = p2; p2 = *it; // Calculate p2 tile, and mark it double tileXf2 = lon2tilexf(p2.x(), baseZoom), tileYf2 = latp2tileyf(p2.y(), baseZoom); TileCoordinate tileX2 = static_cast<TileCoordinate>(tileXf2), tileY2 = static_cast<TileCoordinate>(tileYf2); tileSet.insert(TileCoordinates(tileX2, tileY2)); if (it == points.begin()) continue; // first point, so no line // Calculate p1 tile double tileXf1 = lon2tilexf(p1.x(), baseZoom), tileYf1 = latp2tileyf(p1.y(), baseZoom); TileCoordinate tileX1 = static_cast<TileCoordinate>(tileXf1), tileY1 = static_cast<TileCoordinate>(tileYf1); tileSet.insert(TileCoordinates(tileX1,tileY1)); // Supercover line algorithm from http://eugen.dedu.free.fr/projects/bresenham/ int i; // loop counter int ystep, xstep; // the step on y and x axis int error; // the error accumulated during the increment int errorprev; // *vision the previous value of the error variable int y = tileY1, x = tileX1; // the line points int ddy, ddx; // compulsory variables: the double values of dy and dx int dx = tileX2 - tileX1; int dy = tileY2 - tileY1; if (dy < 0) { ystep = -1; dy = -dy; } else { ystep = 1; } if (dx < 0) { xstep = -1; dx = -dx; } else { xstep = 1; } ddy = 2 * dy; // work with double values for full precision ddx = 2 * dx; if (ddx >= ddy) { // first octant (0 <= slope <= 1) // compulsory initialization (even for errorprev, needed when dx==dy) errorprev = error = dx; // start in the middle of the square for (i=0 ; i < dx ; i++) { // do not use the first point (already done) x += xstep; error += ddy; if (error > ddx){ // increment y if AFTER the middle ( > ) y += ystep; error -= ddx; // three cases (octant == right->right-top for directions below): if (error + errorprev < ddx) // bottom square also tileSet.insert(TileCoordinates(x, y-ystep)); else if (error + errorprev > ddx) // left square also tileSet.insert(TileCoordinates(x-xstep, y)); else { // corner: bottom and left squares also tileSet.insert(TileCoordinates(x, y-ystep)); tileSet.insert(TileCoordinates(x-xstep, y)); } } tileSet.insert(TileCoordinates(x, y)); errorprev = error; } } else { // the same as above errorprev = error = dy; for (i=0 ; i < dy ; i++){ y += ystep; error += ddx; if (error > ddy){ x += xstep; error -= ddy; if (error + errorprev < ddy) tileSet.insert(TileCoordinates(x-xstep, y)); else if (error + errorprev > ddy) tileSet.insert(TileCoordinates(x, y-ystep)); else{ tileSet.insert(TileCoordinates(x-xstep, y)); tileSet.insert(TileCoordinates(x, y-ystep)); } } tileSet.insert(TileCoordinates(x, y)); errorprev = error; } } } } void insertIntermediateTiles(Linestring const &points, uint baseZoom, std::unordered_set<TileCoordinates> &tileSet) { impl_insertIntermediateTiles(points, baseZoom, tileSet); } void insertIntermediateTiles(Ring const &points, uint baseZoom, std::unordered_set<TileCoordinates> &tileSet) { impl_insertIntermediateTiles(points, baseZoom, tileSet); }
36.577093
116
0.6647
[ "geometry", "vector" ]
4bfaec1d428974c25c3d5645bfd8d1900516961a
952
cc
C++
blaze/blaze/operator/op/not_op.cc
Ru-Xiang/x-deeplearning
04cc0497150920c64b06bb8c314ef89977a3427a
[ "Apache-2.0" ]
4,071
2018-12-13T04:17:38.000Z
2022-03-30T03:29:35.000Z
blaze/blaze/operator/op/not_op.cc
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
359
2018-12-21T01:14:57.000Z
2022-02-15T07:18:02.000Z
blaze/blaze/operator/op/not_op.cc
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
1,054
2018-12-20T09:57:42.000Z
2022-03-29T07:16:53.000Z
/* * \file not_op.cc * \desc The not operator */ #include "blaze/operator/op/not_op.h" namespace blaze { template <typename DType> void NotKernel(const NotParam<DType>& params) { for (size_t k = 0; k < params.size; ++k) { params.y[k] = params.x[k] == 0 ? 1 : 0; } } template <> bool NotOp<CPUContext>::RunOnDevice() { Blob* X = this->Input(0); Blob* Y = this->Output(0); TYPE_SWITCH(X->data_type(), DType, { // Reshape Y->Reshape(X->shape()); // lauch cpu kernel NotParam<DType> params(X->as<DType>(), X->size(), Y->as<DType>()); NotKernel(params); }); return true; } REGISTER_CPU_OPERATOR(Not, NotOp<CPUContext>); // Input: X Output: Y OPERATOR_SCHEMA(Not) .NumInputs(1) .NumOutputs(1) .AllowInplace({{0, 0}}) .IdenticalTypeOfInput(0) .SetDoc(R"DOC( Sigmoid activation. )DOC") .Input(0, "X", "1D input tensor") .Output(0, "Y", "1D output tensor"); } // namespace blaze
20.255319
70
0.609244
[ "shape" ]
4bfbeeb078b01d56ab38a5f1fba3c278eb92a644
1,318
cpp
C++
AdvancedLevel_C++/1142. Maximal Clique (25) .cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
107
2019-10-25T07:46:59.000Z
2022-03-29T11:10:56.000Z
AdvancedLevel_C++/1142. Maximal Clique (25) .cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
1
2021-08-13T05:42:27.000Z
2021-08-13T05:42:27.000Z
AdvancedLevel_C++/1142. Maximal Clique (25) .cpp
upupming/algorithm
44edcffe886eaf4ce8c7b27a8db50d7ed5d29ef1
[ "MIT" ]
18
2020-12-09T14:24:22.000Z
2022-03-30T06:56:01.000Z
#include <iostream> #include <vector> using namespace std; int e[210][210]; int main() { int nv, ne, m, ta, tb, k; scanf("%d %d", &nv, &ne); for (int i = 0; i < ne; i++) { scanf("%d %d", &ta, &tb); e[ta][tb] = e[tb][ta] = 1; } scanf("%d", &m); for (int i = 0; i < m; i++) { scanf("%d", &k); vector<int> v(k); int hash[210] = {0}, isclique = 1, isMaximal = 1; for (int j = 0; j < k; j++) { scanf("%d", &v[j]); hash[v[j]] = 1; } for (int j = 0; j < k; j++) { if (isclique == 0) break; for (int l = j + 1; l < k; l++) { if (e[v[j]][v[l]] == 0) { isclique = 0; printf("Not a Clique\n"); break; } } } if (isclique == 0) continue; for (int j = 1; j <= nv; j++) { if (hash[j] == 0) { for (int l = 0; l < k; l++) { if (e[v[l]][j] == 0) break; if (l == k - 1) isMaximal = 0; } } if (isMaximal == 0) { printf("Not Maximal\n"); break; } } if (isMaximal == 1) printf("Yes\n"); } return 0; }
28.042553
57
0.326252
[ "vector" ]
4bff46f9209abe4ef783dc4b69719886f0d438a7
7,217
cpp
C++
WindowsConsoleGame/Tester.cpp
Joefficial/WindowsConsoleGame
0ec4df55fb119be0903f9d589a3b4e1fb83d0234
[ "MIT" ]
null
null
null
WindowsConsoleGame/Tester.cpp
Joefficial/WindowsConsoleGame
0ec4df55fb119be0903f9d589a3b4e1fb83d0234
[ "MIT" ]
null
null
null
WindowsConsoleGame/Tester.cpp
Joefficial/WindowsConsoleGame
0ec4df55fb119be0903f9d589a3b4e1fb83d0234
[ "MIT" ]
null
null
null
#include <iostream> #include <windows.h> #include "Entity.h" #include "Player.h" #include "CGameItem.h" #include "GroundItem.h" #include "Container.h" #include "Map.h" using namespace std; void drawDefaultDisplay(); void printInvItem(string itemToPrint, int itemNo); void outputMessage(string messageToOutput); void gotoXY(int, int); bool getNumber(int & number); void printRemovedItem(int itemNo); void printMap(Map m, const int SCREEN_HEIGHT, const int SCREEN_WIDTH); int main(){ const int SCREEN_WIDTH = 56; const int SCREEN_HEIGHT = 20; const int MAX_ITEMS = 8; //the max amount of inventory items we want to hold const char PLAYER_CHAR = '@'; container<Entity*> ItemsOnMap; //holds all the items that are on the map container<CGameItem*> invItems; //This is the inventory system Map m = Map(); //Spawn Potion at 10,10 ItemsOnMap.push(new GroundItem(10,10,'P')); //Spawn a Spell at 15,4 ItemsOnMap.push(new GroundItem(15,4,'S')); int startx = 3, starty = 3, lastx = 1, lasty = 1; Player P1(startx,starty,PLAYER_CHAR, 100); ItemsOnMap.push(&P1); bool quit = false; //Screen output junk to make windows.h work HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); DWORD NumInputs = 0; DWORD InputsRead = 0; bool running = true; INPUT_RECORD irInput; GetNumberOfConsoleInputEvents(hInput, &NumInputs); //End of windows.h junk /*FIRST WE DRAW THE INTERFACE*/ drawDefaultDisplay(); /**DRAW ACTUAL MAP HERE**/ //In this case we only draw map once because it is not yet destructable //if it were to be destructable we would either redraw it each time or simply draw over the tile(s) that were destroyed //sidenote: when a tile is destroyed remember to replace it in map[][] with ' ' //If I were we would redraw the map once each time the user entered a new room (or perhaps moves out of screen bounds //in which case we would have that check in the movement section) printMap(m, SCREEN_HEIGHT, SCREEN_WIDTH); //Main Game Loop while(!quit){ ReadConsoleInput(hInput, &irInput, 1, &InputsRead); //There is no collision detection for anyhting yet... actually this is really just //practice for drawing stuff to the screen... //Buffering variables lastx = P1.getX(); lasty = P1.getY(); /* MOVEMENT HANDLING */ //TODO: Add key input for using items if(irInput.Event.KeyEvent.bKeyDown){ switch(irInput.Event.KeyEvent.wVirtualKeyCode){ case VK_ESCAPE: quit = true; break; case VK_UP: //if map[x][y-1] != some walkable character dont walk there if(P1.getY() > 1 && m.isWalkableAt(P1.getX()-1, P1.getY()-2)) P1.moveY(-1); break; case VK_DOWN: if(P1.getY() < SCREEN_HEIGHT && m.isWalkableAt(P1.getX()-1, P1.getY())) P1.moveY(1); break; case VK_LEFT: if(P1.getX() > 1 && m.isWalkableAt(P1.getX()-2, P1.getY()-1)) P1.moveX(-1); break; case VK_RIGHT: if(P1.getX() < SCREEN_WIDTH && m.isWalkableAt(P1.getX(), P1.getY()-1)) P1.moveX(1); break; case 'U': int input; outputMessage("Enter index of item to use: "); if (getNumber(input) == false) { outputMessage("Invalid input"); break; // get out of switch statement } if (input >= 0 && input < invItems.size()) { invItems[input]->use(); } else { outputMessage("index out of range or no items yet"); } break; } } /*Here we would check if the character went off screen and update the map to refresh accordingly That is, if I was using a real map that went beyond the limit of what i had room to draw*/ //as a side note if we update the map to move over by 5 spaces we must also load the coordinates of //everything we draw with a map modifier (so like gotoXY(x-Xmodifier, y-Ymodifier)) so that everything //draws in the correct location /*OVERWRITE WHERE THE PLAYER WAS*/ gotoXY(lastx, lasty); cout << " "; /**For now we will load the inventory screen every time the map updates**/ for(int i=0; i<invItems.size(); i++){ printInvItem((*invItems[i]).description(),i); } printRemovedItem(invItems.size()); /*NEXT WE LOAD ENTITIES THAT ARE ON THE MAP*/ for(int i=0; i < ItemsOnMap.size(); i++){ //check collision with player if((*ItemsOnMap[i]).getChar() != '@'){ if(P1.detectCollision(*ItemsOnMap[i])){ //if we have room to add an item to our inventory if(invItems.size() < MAX_ITEMS){ //Handle Collision outputMessage("Item added to inventory"); switch((*ItemsOnMap[i]).getChar()){ case 'P': //Remove Item from map ItemsOnMap.remove(i); //Add Potion to inventory invItems.push(new CPotion()); break; case 'S': //Remove item from map ItemsOnMap.remove(i); //Add Spell to inventory invItems.push(new CSpell()); break; default: outputMessage("You picked up an invalid item"); break; } } } } /*Possible good idea*/ //handle collision Both objects need to be able to //Trigger each other's destroyed state so if one //Object is destroyed we dont have to detect collisions //with or draw the other item unless it is a player //Draw all entities To screen gotoXY(ItemsOnMap[i]->getX(), ItemsOnMap[i]->getY()); cout << ItemsOnMap[i]->getChar(); } } system("Pause"); return 0; } /*This is my version of gotoXY that uses windows libraries instead of the dos conio.h*/ void gotoXY(int x,int y){ COORD coord; coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle( STD_OUTPUT_HANDLE ),coord); } void outputMessage(string messageToOutput){ //Clear line gotoXY(1,22); cout << " \n"; cout << " \n"; cout << " "; //Write line gotoXY(1,22); cout << messageToOutput; } void drawDefaultDisplay(){ gotoXY(0,0); cout << "*********************************************************** **************\n"; for(int i=0;i<20;i++) cout << "* * * *\n"; cout << "*********************************************************** **************"; } void printInvItem(string itemToPrint, int itemNo){ //Clear Line gotoXY(67,1+itemNo); cout << endl; //write line gotoXY(66,1+itemNo); cout << itemNo << " " << itemToPrint; } //In the event we remove an item from the inventory we need to be able to stop printing it on the inv screen void printRemovedItem(int itemNo){ gotoXY(66,1+itemNo); cout << endl; } bool getNumber(int & number) { // no code to add here string input; getline(cin, input); // check that input is numeric for (unsigned int i = 0; i < input.length(); i++) { if (input[i] < '0' || input[i] > '9') { return false; } } number = atoi(input.c_str()); return true; } void printMap(Map m, const int SCREEN_HEIGHT, const int SCREEN_WIDTH){ for(int y = 0; y < SCREEN_HEIGHT; y++){ for(int x = 0; x < SCREEN_WIDTH; x++){ gotoXY(x+1, y+1); cout << m.getTileAt(x,y); } } }
25.322807
120
0.615907
[ "object" ]
ef021f631e11b79fbc2b0f19f6bc67745246d5bf
10,082
hpp
C++
include/nodamushi/svd/normalized/node_container.hpp
nodamushi/nsvd-reader
cf3a840aaac78d5791df1cf045596ec20dc03257
[ "CC0-1.0" ]
null
null
null
include/nodamushi/svd/normalized/node_container.hpp
nodamushi/nsvd-reader
cf3a840aaac78d5791df1cf045596ec20dc03257
[ "CC0-1.0" ]
null
null
null
include/nodamushi/svd/normalized/node_container.hpp
nodamushi/nsvd-reader
cf3a840aaac78d5791df1cf045596ec20dc03257
[ "CC0-1.0" ]
null
null
null
/*! @brief container class decralation @file nodamushi/svd/normalized/node_container.hpp */ /* * These codes are licensed under CC0. * http://creativecommons.org/publicdomain/zero/1.0/ */ #ifndef NODAMUSHI_SVD_NORMALIZED_NODE_CONTAINER_HPP #define NODAMUSHI_SVD_NORMALIZED_NODE_CONTAINER_HPP # include <vector> # include <memory> # include <string> # include "nodamushi/svd/normalized/nullable.hpp" # include "nodamushi/svd/normalized/dim_info.hpp" # include "nodamushi/svd/normalized/dim_helper.hpp" # include "nodamushi/svd/Access.hpp" # include "nodamushi/svd/ReadAction.hpp" # include "nodamushi/svd/Protection.hpp" # include "nodamushi/svd/DataType.hpp" # include "nodamushi/svd/ModifiedWriteValues.hpp" # include "nodamushi/boxvec.hpp" # include "nodamushi/svd/normalized/normalized_visitor.hpp" namespace nodamushi{ namespace svd{ namespace normalized{ // ---------------------------------------------------------------------- // * interface // get_address() : return absolute address // get_offset() : return relative address in the peripheral // get_protection(): return protection // get_access() : return get access // get_resetValue(): return reset value // get_resetMask() : return reset mask.default value is ~0 // get_parent() : return parent node pointer. // if it has no parent , return void*. // get_parent2() : return cluster parent. // if it has no cluster parent, return void*. // ---------------------------------------------------------------------- template<typename STRREF> struct Device; template<typename STRREF> struct Peripheral; template<typename STRREF> struct Cluster; template<typename STRREF> struct Register; template<typename STRREF> struct Field; template<typename STRREF> struct Enumeration; template<typename STRREF> struct Cpu; template<typename STRREF> struct SAURegionsConfig; template<typename T> using node_ptr = std::shared_ptr<T>; template<typename Parent> using parent_ptr= std::weak_ptr<Parent>; template<typename Child> using list = ::nodamushi::boxvec<Child,node_ptr<Child>>; template<typename T,typename... ARGS> node_ptr<T> make_node_ptr(ARGS&&... args) { return std::make_shared<T>(std::forward<ARGS>(args)...); } template<typename PTR> struct parent_method_call { template<typename T> static uint32_t get_size(T p){return p->get_size();} template<typename T> static Protection get_protection(T p){return p->get_protection();} template<typename T> static Access get_access(T p){return p->get_access();} template<typename T> static uint64_t get_resetValue(T p){return p->get_resetValue();} template<typename T> static uint64_t get_resetMask(T p){return p->get_resetMask();} template<typename T> static ModifiedWriteValues get_modifiedWriteValues(T p){return p->get_modifiedWriteValues();} template<typename T> static ReadAction get_readAction(T p){return p->get_readAction();} }; //----------------------- helper methods ------------------------------ template<typename T,typename You> void update_parent_of_children(list<T>& l,node_ptr<You>& you) { parent_ptr<You> _you(you); auto itr = l.ptr_begin(); auto end = l.ptr_end(); while(itr != end){ auto& ptr = *itr; ptr->update_parent(_you,ptr); ++itr; } } template<typename O,typename S> void path_helper(const O& o,::nodamushi::svd::path<S>& path) { if(auto p = o.get_parent()){ path_helper(*p,path); }else if(auto p=o.get_parent2()){ path_helper(*p,path); } path.add_name(o.name); } template<typename O,typename S> void path_helper(const Peripheral<O>& o,::nodamushi::svd::path<S>& path) { path.add_name(o.name); } template<typename STRREF,template<class>class O> node_ptr<Peripheral<STRREF>> find_parent_peripheral(O<STRREF>& o){ if(auto p = o.get_parent()){ return find_parent_peripheral(p); }else if(auto p=o.get_parent2()){ return find_parent_peripheral(p); } return {}; } template<typename STRREF,template<class>class O> node_ptr<const Peripheral<STRREF>> find_parent_peripheral(const O<STRREF>& o){ if(auto p = o.get_parent()){ return find_parent_peripheral(p); }else if(auto p=o.get_parent2()){ return find_parent_peripheral(p); } return {}; } template<typename STRREF,template<class>class O> node_ptr<Peripheral<STRREF>> find_parent_peripheral(node_ptr<O<STRREF>>& o){ if(auto p = o->get_parent()){ return find_parent_peripheral(p); }else if(auto p=o->get_parent2()){ return find_parent_peripheral(p); } return {}; } template<typename STRREF,template<class>class O> node_ptr<const Peripheral<STRREF>> find_parent_peripheral(node_ptr<const O<STRREF>>& o){ if(auto p = o->get_parent()){ return find_parent_peripheral(p); }else if(auto p=o->get_parent2()){ return find_parent_peripheral(p); } return {}; } template<typename STRREF> node_ptr<Peripheral<STRREF>> find_parent_peripheral(node_ptr<Peripheral<STRREF>>& o){return o;} template<typename STRREF> node_ptr<Peripheral<STRREF>> find_parent_peripheral(void* o){return {};} template<typename STRREF> node_ptr<const Peripheral<STRREF>> find_parent_peripheral(node_ptr<const Peripheral<STRREF>>& o){return o;} template<typename STRREF> node_ptr<const Peripheral<STRREF>> find_parent_peripheral(const void* o){return {};} //--------------- Address ------------------------------------------- template<typename O> uint64_t calc_address(const O& o,uint64_t offset = 0) { offset += o.addressOffset; if(auto ptr = o.get_parent()) return calc_address(*ptr,offset); else if(auto ptr = o.get_parent2()) return calc_address(*ptr,offset); return offset; } template<typename X> uint64_t constexpr calc_address(const Device<X>& d,uint64_t offset=0){return offset;} template<typename X> uint64_t constexpr calc_address(const Peripheral<X>& p,uint64_t offset=0){return p.baseAddress+offset;} template<typename O> uint64_t calc_offset(const O& o,uint64_t offset = 0) { offset += o.addressOffset; if(auto ptr = o.get_parent()) return calc_offset(*ptr,offset); else if(auto ptr = o.get_parent2()) return calc_offset(*ptr,offset); return offset; } template<typename X> uint64_t constexpr calc_offset(const Device<X>& d,uint64_t offset=0){return offset;} template<typename X> uint64_t constexpr calc_offset(const Peripheral<X>& p,uint64_t offset=0){return offset;} //------------------------------------------------------------------ template<typename O>uint32_t get_default_size(const O& o)noexcept { if(auto ptr = o.get_parent()){ return parent_method_call<decltype(ptr)>::get_size(ptr); }else if(auto ptr = o.get_parent2()){ return parent_method_call<decltype(ptr)>::get_size(ptr); } return 32; } template<typename O>Access get_default_access(const O& o)noexcept { if(auto ptr = o.get_parent()){ return parent_method_call<decltype(ptr)>::get_access(ptr); }else if(auto ptr = o.get_parent2()){ return parent_method_call<decltype(ptr)>::get_access(ptr); } return static_cast<Access>(0); } template<typename O>Access get_default_fieldaccess(const O& o)noexcept { if(auto ptr = o.get_parent()){ return parent_method_call<decltype(ptr)>::get_access(ptr); } return static_cast<Access>(0); } template<typename O>Protection get_default_protection(const O& o)noexcept { if(auto ptr = o.get_parent()){ return parent_method_call<decltype(ptr)>::get_protection(ptr); }else if(auto ptr = o.get_parent2()){ return parent_method_call<decltype(ptr)>::get_protection(ptr); } return static_cast<Protection>(0); } template<typename O>uint64_t get_default_resetValue(const O& o)noexcept { if(auto ptr = o.get_parent()){ return parent_method_call<decltype(ptr)>::get_resetValue(ptr); }else if(auto ptr = o.get_parent2()){ return parent_method_call<decltype(ptr)>::get_resetValue(ptr); } return 0; } template<typename O>uint64_t get_default_resetMask(const O& o) { if(auto ptr = o.get_parent()){ return parent_method_call<decltype(ptr)>::get_resetMask(ptr); }else if(auto ptr = o.get_parent2()){ return parent_method_call<decltype(ptr)>::get_resetMask(ptr); } //TODO error? return ~(uint64_t)0; } template<typename O> ModifiedWriteValues get_default_modifiedWriteValues(const O& o){ if(auto ptr = o.get_parent()){ return parent_method_call<decltype(ptr)>::get_modifiedWriteValues(ptr); } return static_cast<ModifiedWriteValues>(0); } template<typename O> ReadAction get_default_readAction(const O& o){ if(auto ptr = o.get_parent()){ return parent_method_call<decltype(ptr)>::get_readAction(ptr); } return static_cast<ReadAction>(0); } template<typename O> DataType get_default_dataType(const O& r)noexcept { auto s = r.get_size(); if(s <= 8)return DataType::UINT8; //0 - 8 else if(s <= 16)return DataType::UINT16;//9 -16 else if(s <= 32)return DataType::UINT32;//17 - 32 else if(s <= 64)return DataType::UINT64;//33 - 64 return DataType::UNDEFINED; } template<typename R> node_ptr<R> __find_helper(list<R>& v,string_ref n) { if(v.size()!=0){ auto i= v.ptr_begin(),e =v.ptr_end(); while(i!=e){ auto c = *i; if(c->name == n) return c; ++i; } } return {}; } // for void* template<>struct parent_method_call<void*> { static constexpr uint64_t get_address(const void*){return 0;} static constexpr uint32_t get_size(const void*){return 0;} static constexpr Protection get_protection(const void*){return static_cast<Protection>(0);} static constexpr Access get_access(const void*){return static_cast<Access>(0);} static constexpr uint64_t get_resetValue(const void*){return 0;} static constexpr uint64_t get_resetMask(const void*){return ~0;} static constexpr ModifiedWriteValues get_modifiedWriteValues(const void*){return static_cast<ModifiedWriteValues>(0);} static constexpr ReadAction get_readAction(const void*){return static_cast<ReadAction>(0);} }; template<typename STRREF,typename STR,typename V> struct normalizer; }}} #endif // NODAMUSHI_SVD_NORMALIZED_NODE_CONTAINER_HPP
31.50625
120
0.706507
[ "vector" ]
ef0a552247c307fce315b09cc6b3d31200fce665
16,961
cc
C++
src/Utilities/SpheralTimers.cc
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
1
2020-10-21T01:56:55.000Z
2020-10-21T01:56:55.000Z
src/Utilities/SpheralTimers.cc
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
src/Utilities/SpheralTimers.cc
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
null
null
null
//---------------------------------Spheral++----------------------------------// // SpheralTimers -- Declare the Timers for use in profiling Spheral // // Created by J. Michael Owen, Sat Dec 1 15:03:19 PST 2001 //----------------------------------------------------------------------------// #include "Timer.hh" #include <list> // Must initialize the static list defined in Timer.hh #ifdef TIMER std::list<Timer*> Timer::TimerList(0); #endif //------------------------------------------------------------------------------ // Root Timers //------------------------------------------------------------------------------ Timer TIME_Spheral ("Root Timer "); // Timer TimeNestedGridNeighbor ("Root NestedGridNeighbor "); Timer TIME_Physics ("All physics derivatives ", TIME_Spheral); // Timer TimeSphNodeList ("Root Sph NodeList "); // Timer TimeMashNodeList ("Root MASH NodeList "); // Timer TimeDataBase ("Root DataBase "); // Timer TimeDistributedBound ("Root DistributedBoundary "); // Timer TimeNestedDistributedBound("Root NestedDistribBound "); //------------------------------------------------------------------------------ // Voronoi //------------------------------------------------------------------------------ Timer TIME_computeVoronoiVolume("computeVoronoiVolume", TIME_Spheral); //------------------------------------------------------------------------------ // Polyhedron timers //------------------------------------------------------------------------------ Timer TIME_Polyhedron_construct1 ("Polyhedron::Polyhedron(points)", TIME_Spheral); Timer TIME_Polyhedron_construct2 ("Polyhedron::Polyhedron(points, facets)", TIME_Spheral); Timer TIME_Polyhedron_BB ("Polyhedron::setBoundingBox", TIME_Spheral); Timer TIME_Polyhedron_BB_ancillary ("Polyhedron::setBoundingBox - computeAncillaryGeometry", TIME_Polyhedron_BB); Timer TIME_Polyhedron_BB_centroid ("Polyhedron::setBoundingBox - centroid", TIME_Polyhedron_BB); Timer TIME_Polyhedron_BB_R2 ("Polyhedron::setBoundingBox - Rinterior2", TIME_Polyhedron_BB); Timer TIME_Polyhedron_convex ("Polyhedron::convex", TIME_Spheral); //------------------------------------------------------------------------------ // PolyClipper2d timers //------------------------------------------------------------------------------ Timer TIME_PC2d_convertto ("Spheral::Polygon -> PolyClipper::Polygon", TIME_Spheral); Timer TIME_PC2d_convertfrom ("PolyClipper::Polygon -> Spheral::Polygon", TIME_Spheral); Timer TIME_PC2d_copy ("Copy PolyClipper::Polygon", TIME_Spheral); Timer TIME_PC2d_moments ("Compute polygon moments", TIME_Spheral); Timer TIME_PC2d_clip ("clipPolygon", TIME_Spheral); Timer TIME_PC2d_planes ("Apply clip planes (clipPolygon)", TIME_PC2d_clip); Timer TIME_PC2d_checkverts ("Clip vertices", TIME_PC2d_planes); Timer TIME_PC2d_insertverts ("Insert new vertices", TIME_PC2d_planes); Timer TIME_PC2d_hanging ("Link hanging vertices", TIME_PC2d_planes); Timer TIME_PC2d_compress ("Compress to active vertices", TIME_PC2d_planes); Timer TIME_PC2d_collapseDegenerates ("Remove degenerate edges/vertices", TIME_Spheral); //------------------------------------------------------------------------------ // PolyClipper3d timers //------------------------------------------------------------------------------ Timer TIME_PC3d_convertto("Spheral::Polyhedron -> PolyClipper::Polyhedron", TIME_Spheral); Timer TIME_PC3d_convertfrom("PolyClipper::Polyhedron -> Spheral::Polyhedron", TIME_Spheral); Timer TIME_PC3d_copy("Copy PolyClipper::Polyhedron", TIME_Spheral); Timer TIME_PC3d_moments("Compute polyhedron moments", TIME_Spheral); Timer TIME_PC3d_clip("clipPolyhedron", TIME_Spheral); Timer TIME_PC3d_planes("Apply clip planes (clipPolyhedron)", TIME_PC3d_clip); Timer TIME_PC3d_checkverts("Clip vertices", TIME_PC3d_planes); Timer TIME_PC3d_insertverts("Insert new vertices", TIME_PC3d_planes); Timer TIME_PC3d_planeverts("Relink in-plane vertices", TIME_PC3d_planes); Timer TIME_PC3d_linknew("Link hanging vertices", TIME_PC3d_planes); Timer TIME_PC3d_compress("Compress to active vertices", TIME_PC3d_planes); Timer TIME_PC3d_collapseDegenerates ("Remove degenerate edges/vertices", TIME_Spheral); //------------------------------------------------------------------------------ // ConnectivityMap //------------------------------------------------------------------------------ Timer TIME_ConnectivityMap_patch("ConnectivityMap::patchConnectivity", TIME_Spheral); Timer TIME_ConnectivityMap_cutConnectivity("ConnectivityMap::cutConnectivity", TIME_Spheral); Timer TIME_ConnectivityMap_valid("ConnectivityMap::valid", TIME_Spheral); Timer TIME_ConnectivityMap_computeConnectivity("ConnectivityMap::computeConnectivity", TIME_Spheral); Timer TIME_ConnectivityMap_computeOverlapConnectivity("ConnectivityMap::computeOverlapConnectivity", TIME_ConnectivityMap_computeConnectivity); //------------------------------------------------------------------------------ // CRKSPH //------------------------------------------------------------------------------ Timer TIME_CRKSPH_editMultimaterialSurfaceTopology("CRKSPH editMultimaterialSurfaceTopology", TIME_Spheral); Timer TIME_interpolateCRKSPH("RK interpolation standalone function", TIME_Spheral); // //------------------------------------------------------------------------------ // // Second order predictor corrector integrator // //------------------------------------------------------------------------------ // Timer TimePC2 ("Root Pred-Correct 2nd or", TIME_Spheral); // Timer TimePC2Boundaries1 ("Set boundaries 1 ", TimePC2); // Timer TimePC2Dt ("Set dt ", TimePC2); // Timer TimePC2StepInitialize1("Pre-step initialize 1 ", TimePC2); // Timer TimePC2ReadDB ("Read DataBase FieldLists", TimePC2); // Timer TimePC2CopyFields ("Copy initial Derivs ", TimePC2); // Timer TimePC2PredStep ("Predictor step ", TimePC2); // Timer TimePC2Weights1 ("Update Weights 1 ", TimePC2); // Timer TimePC2StepInitialize2("Pre-step initialize 2 ", TimePC2); // Timer TimePC2Boundaries2 ("Set boundaries 2 ", TimePC2); // Timer TimePC2Zero1 ("Zero derivs 1 ", TimePC2); // Timer TimePC2CopyDvDx1 ("Copy DvDx to temp ", TimePC2); // Timer TimePC2EvalDerivs1 ("Eval derivs mid step ", TimePC2); // Timer TimePC2CorStep ("Corrector step ", TimePC2); // Timer TimePC2CopyDvDx2 ("Copy DvDx to DB ", TimePC2); // Timer TimePC2Weights2 ("Update Weights 2 ", TimePC2); // Timer TimePC2Boundaries3 ("Set boundaries 3 ", TimePC2); // Timer TimePC2StepInitialize3("Pre-step initialize 3 ", TimePC2); // Timer TimePC2Zero2 ("Zero derivs 2 ", TimePC2); // Timer TimePC2EvalDerivs2 ("Eval derivs end step ", TimePC2); // Timer TimePC2CopyDvDx3 ("Copy DvDx to DB again ", TimePC2); // Timer TimePC2SumDensity ("Sum end mass density ", TimePC2); // Timer TimePC2Weights3 ("Update Weights 3 ", TimePC2); // //------------------------------------------------------------------------------ // // RK2 Synchronous integrator // //------------------------------------------------------------------------------ // Timer TimeSyncRK2 ("Root Sync RK2Integrator ", TIME_Spheral); // Timer TimeSyncRK2Boundaries1 ("Set boundaries 1 ", TimeSyncRK2); // Timer TimeSyncRK2Dt ("Set dt ", TimeSyncRK2); // Timer TimeSyncRK2StepInitialize1("Pre-step initialize 1 ", TimeSyncRK2); // Timer TimeSyncRK2ReadDB ("Read DataBase FieldLists", TimeSyncRK2); // Timer TimeSyncRK2CopyFields ("Copy initial Derivs ", TimeSyncRK2); // Timer TimeSyncRK2MidStep ("Advance to mid-step ", TimeSyncRK2); // Timer TimeSyncRK2Weights1 ("Update Weights 1 ", TimeSyncRK2); // Timer TimeSyncRK2StepInitialize2("Pre-step initialize 2 ", TimeSyncRK2); // Timer TimeSyncRK2Boundaries2 ("Set boundaries 2 ", TimeSyncRK2); // Timer TimeSyncRK2Zero1 ("Zero derivs 1 ", TimeSyncRK2); // Timer TimeSyncRK2CopyDvDx1 ("Copy DvDx to temp ", TimeSyncRK2); // Timer TimeSyncRK2EvalDerivs1 ("Eval derivs mid step ", TimeSyncRK2); // Timer TimeSyncRK2EndStep ("Advance to end of step ", TimeSyncRK2); // Timer TimeSyncRK2CopyDvDx2 ("Copy DvDx to DB ", TimeSyncRK2); // Timer TimeSyncRK2Weights2 ("Update Weights 2 ", TimeSyncRK2); // Timer TimeSyncRK2Boundaries3 ("Set boundaries 3 ", TimeSyncRK2); // Timer TimeSyncRK2StepInitialize3("Pre-step initialize 3 ", TimeSyncRK2); // Timer TimeSyncRK2Zero2 ("Zero derivs 2 ", TimeSyncRK2); // Timer TimeSyncRK2EvalDerivs2 ("Eval derivs end step ", TimeSyncRK2); // Timer TimeSyncRK2CopyDvDx3 ("Copy DvDx to DB again ", TimeSyncRK2); // Timer TimeSyncRK2SumDensity ("Sum end mass density ", TimeSyncRK2); // Timer TimeSyncRK2Weights3 ("Update Weights 3 ", TimeSyncRK2); //------------------------------------------------------------------------------ // Cheap RK2 Synchronous integrator //------------------------------------------------------------------------------ Timer TIME_CheapRK2 ("Root Cheap RK2Integrator", TIME_Spheral); Timer TIME_CheapRK2PreInit ("preStepIntialize ", TIME_CheapRK2); Timer TIME_CheapRK2Dt ("Set dt ", TIME_CheapRK2); Timer TIME_CheapRK2CopyState ("Copy initial state ", TIME_CheapRK2); Timer TIME_CheapRK2MidStep ("Advance to mid-step ", TIME_CheapRK2); Timer TIME_CheapRK2EvalDerivs ("Eval derivs mid step ", TIME_CheapRK2); Timer TIME_CheapRK2EndStep ("Advance to end of step ", TIME_CheapRK2); Timer TIME_CheapRK2Finalize ("postStepFinalize ", TIME_CheapRK2); Timer TIME_CheapRK2EnforceBound ("Enforce boundaries ", TIME_CheapRK2); // //------------------------------------------------------------------------------ // // NestedGridNeighbor // //------------------------------------------------------------------------------ // Timer TimeNestedMaster ("Set the master list (node)", TimeNestedGridNeighbor); // Timer TimeNestedRefine ("Set the refine list (node)", TimeNestedGridNeighbor); // Timer TimeNestedMasterPlane ("Set the master list(plane)", TimeNestedGridNeighbor); // Timer TimeNestedUpdateNodes ("Update the node info ", TimeNestedGridNeighbor); // Timer TimeNestedUpdateNodes1 ("Update the given node info", TimeNestedGridNeighbor); // Timer TimeNestedPrecull ("Precull nodes ", TimeNestedRefine); // //------------------------------------------------------------------------------ // // Hydro // //------------------------------------------------------------------------------ // Timer TimeHydro ("Root Hydro ", TimePhysics); // Timer TimeHydroFlagNodes ("Initialize flag nodes ", TimeHydro); // Timer TimeHydroReadState ("Read the initial state ", TimeHydro); // Timer TimeHydroSetMaster ("Set master nodes ", TimeHydro); // Timer TimeHydroSetRefine ("Set the refine nodes ", TimeHydro); // Timer TimeHydroEvalDerivs ("Set derivs for node ", TimeHydro); //------------------------------------------------------------------------------ // SPH //------------------------------------------------------------------------------ Timer TIME_SPH ("SPH base timer ", TIME_Physics); Timer TIME_SPHinitializeStartup ("SPH initializeProblemStartup ", TIME_SPH); Timer TIME_SPHregister ("SPH register ", TIME_SPH); Timer TIME_SPHregisterDerivs ("SPH registerDerivatives ", TIME_SPH); Timer TIME_SPHinitialize ("SPH initialize (evalderivs) ", TIME_SPH); Timer TIME_SPHfinalizeDerivs ("SPH finalizeDerivatives ", TIME_SPH); Timer TIME_SPHfinalize ("SPH finalize (step) ", TIME_SPH); Timer TIME_SPHghostBounds ("SPH ghost boundaries ", TIME_SPH); Timer TIME_SPHupdateVol ("SPH updateVolume ", TIME_SPH); Timer TIME_SPHenforceBounds ("SPH enforceBoundaries ", TIME_SPH); Timer TIME_SPHevalDerivs ("SPH evaluateDerivates ", TIME_SPH); Timer TIME_SPHevalDerivs_initial ("SPH evaluateDerivates (initial)", TIME_SPHevalDerivs); Timer TIME_SPHevalDerivs_pairs ("SPH evaluateDerivates (pairs) ", TIME_SPHevalDerivs); Timer TIME_SPHevalDerivs_final ("SPH evaluateDerivates (final) ", TIME_SPHevalDerivs); // //------------------------------------------------------------------------------ // // MASH NodeList // //------------------------------------------------------------------------------ // Timer TimeMashDerivs ("Base Mash Derivs ", TimeMashNodeList); // Timer TimeMashNodeIState ("Get state for node i ", TimeMashDerivs); // Timer TimeMashNodeJState ("Get state for node j ", TimeMashDerivs); // Timer TimeMashRij ("Calc rij, etaij, ... ", TimeMashDerivs); // Timer TimeMashKernel ("Evaluate Wij ", TimeMashDerivs); // Timer TimeMashQ ("Evaluate Qij ", TimeMashDerivs); // Timer TimeMashIncDerivs ("Increment the derivs ", TimeMashDerivs); // Timer TimeMashHDeriv ("Evaluate the H deriv ", TimeMashDerivs); // Timer TimeMashHSmooth ("Smoothing contrib to H ", TimeMashDerivs); // //------------------------------------------------------------------------------ // // DataBase // //------------------------------------------------------------------------------ // Timer TimeDataBaseRho ("Sum fluid density ", TimeDataBase); // Timer TimeDataBaseGetState ("Read state FieldLists ", TimeDataBaseRho); // Timer TimeDataBaseInitFlags ("Init node done flags ", TimeDataBaseRho); // Timer TimeDataBaseSetMaster ("Set master nodes ", TimeDataBaseRho); // Timer TimeDataBaseSetRefine ("Set refine nodes ", TimeDataBaseRho); // Timer TimeDataBaseSumNode ("Sum rho for single node ", TimeDataBaseRho); // Timer TimeDataBasePostConditions("Verify post conditions ", TimeDataBaseRho); // //------------------------------------------------------------------------------ // // DistributedBoundary // //------------------------------------------------------------------------------ // Timer TimeDBExchange ("Generic Field exchange ", TimeDistributedBound); // //------------------------------------------------------------------------------ // // NestedGridDistributedBoundary // //------------------------------------------------------------------------------ // Timer TimeNDSetGhost ("Set ghost nodes ", TimeNestedDistributedBound); // Timer TimeNDReset ("Clear existing info ", TimeNDSetGhost); // Timer TimeNDFlatten ("Flatten occupied gridcells", TimeNDSetGhost); // Timer TimeNDReduceGridCells ("Reduce occupied gridcells ", TimeNDSetGhost); // Timer TimeNDBuildCommMaps ("Build comm maps on master ", TimeNDSetGhost); // Timer TimeNDDistributeCommMaps ("Distribute comm maps ", TimeNDSetGhost); // Timer TimeNDBuildGhost ("Build ghost nodes ", TimeNDSetGhost); // Timer TimeNDExchangeMinimal ("Exchange r, H ", TimeNDSetGhost); // //------------------------------------------------------------------------------ // // Golden rule grad div vector field. // //------------------------------------------------------------------------------ // Timer TimeGoldenSecond ("Golden rule grad div "); // Timer TimeGoldenSecondReserve ("Reserve return Fields ", TimeGoldenSecond); // Timer TimeGoldenSecondMaster ("Select master nodes ", TimeGoldenSecond); // Timer TimeGoldenSecondRefine ("Select refine nodes ", TimeGoldenSecond); // Timer TimeGoldenSecondNodeI ("State for node I ", TimeGoldenSecond); // Timer TimeGoldenSecondNodeJ ("State for node J ", TimeGoldenSecond); // Timer TimeGoldenSecondRefineLoop("Main loop over refine nei ", TimeGoldenSecond); // Timer TimeGoldenSecondW ("Calculate W, gradW, grad2W", TimeGoldenSecond); // Timer TimeGoldenSecondAccumulate("Accumulate components ", TimeGoldenSecond); // Timer TimeGoldenSecondFinalize ("Determine final answer ", TimeGoldenSecond); // Timer TimeGoldenSecondCheck ("Completeness check ", TimeGoldenSecond);
68.116466
143
0.560698
[ "vector" ]
ef164cd39e20d18c9a67417d6a4e1de41877f230
9,894
cpp
C++
helios/scattering/dielectric_bxdf.cpp
filipecn/helios
5c64c36485c403858279f66870f5d31f8722edb9
[ "MIT" ]
null
null
null
helios/scattering/dielectric_bxdf.cpp
filipecn/helios
5c64c36485c403858279f66870f5d31f8722edb9
[ "MIT" ]
null
null
null
helios/scattering/dielectric_bxdf.cpp
filipecn/helios
5c64c36485c403858279f66870f5d31f8722edb9
[ "MIT" ]
null
null
null
/// Copyright (c) 2021, FilipeCN. /// /// The MIT License (MIT) /// /// 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. /// ///\file dielectric_bxdf.cpp ///\author FilipeCN (filipedecn@gmail.com) ///\date 2021-10-14 /// ///\brief #include <helios/scattering/dielectric_bxdf.h> #include <helios/scattering/scattering.h> namespace helios { HERMES_DEVICE_CALLABLE DielectricBxDF::DielectricBxDF() {} HERMES_DEVICE_CALLABLE DielectricBxDF::DielectricBxDF(real_t eta, const TrowbridgeReitzDistribution &mf_distribution) : eta_(eta), mf_distribution_(mf_distribution) {} HERMES_DEVICE_CALLABLE DielectricBxDF::~DielectricBxDF() {} HERMES_DEVICE_CALLABLE SampledSpectrum DielectricBxDF::f(const hermes::vec3 &wo, const hermes::vec3 &wi, TransportMode mode) const { if (eta_ == 1 || mf_distribution_.effectivelySmooth()) return SampledSpectrum(0.f); // Evaluate rough dielectric BSDF // Compute generalized half vector _wm_ real_t cosTheta_o = ShadingCoordinateSystem::cosTheta(wo), cosTheta_i = ShadingCoordinateSystem::cosTheta(wi); bool reflect = cosTheta_i * cosTheta_o > 0; float etap = 1; if (!reflect) etap = cosTheta_o > 0 ? eta_ : (1 / eta_); hermes::vec3 wm = wi * etap + wo; // TODO check wm.length2() == 0 if (cosTheta_i == 0 || cosTheta_o == 0 || wm.length2() == 0) return {}; wm = hermes::faceForward(hermes::normalize(wm), hermes::normal3(0, 0, 1)); // Discard back-facing microfacets if (hermes::dot(wm, wi) * cosTheta_i < 0 || hermes::dot(wm, wo) * cosTheta_o < 0) return {}; real_t F = Scattering::frDielectric(hermes::dot(wo, wm), eta_); if (reflect) { // Compute reflection at rough dielectric interface return SampledSpectrum(mf_distribution_.D(wm) * mf_distribution_.G(wo, wi) * F / fabsf(4 * cosTheta_i * cosTheta_o)); } // Compute transmission at rough dielectric interface real_t denom = hermes::Numbers::sqr(hermes::dot(wi, wm) + hermes::dot(wo, wm) / etap); real_t ft = (1 - F) * mf_distribution_.D(wm) * mf_distribution_.G(wo, wi) * fabsf(hermes::dot(wi, wm) * hermes::dot(wo, wm) / (cosTheta_i * cosTheta_o * denom)); // Account for non-symmetry with transmission to different medium if (mode == TransportMode::RADIANCE) ft /= hermes::Numbers::sqr(etap); return SampledSpectrum(ft); } HERMES_DEVICE_CALLABLE BSDFSampleReturn DielectricBxDF::sample_f(const hermes::vec3 &wo, real_t uc, const hermes::point2 &u, TransportMode mode, bxdf_refl_trans_flags sample_flags) const { if (eta_ == 1 || mf_distribution_.effectivelySmooth()) { // Sample perfectly specular dielectric BSDF real_t R = Scattering::frDielectric(ShadingCoordinateSystem::cosTheta(wo), eta_), T = 1 - R; // Compute probabilities _pr_ and _pt_ for sampling reflection and transmission real_t pr = R, pt = T; if (!((u32) sample_flags & (u32) bxdf_refl_trans_flags::REFLECTION)) pr = 0; if (!((u32) sample_flags & (u32) bxdf_refl_trans_flags::TRANSMISSION)) pt = 0; if (pr == 0 && pt == 0) return {}; if (uc < pr / (pr + pt)) { // Sample perfect specular dielectric BRDF hermes::vec3 wi(-wo.x, -wo.y, wo.z); SampledSpectrum fr(R / ShadingCoordinateSystem::absCosTheta(wi)); return BSDFSample(fr, wi, pr / (pr + pt), bxdf_flags::SPECULAR_REFLECTION); } else { // Sample perfect specular dielectric BTDF // Compute ray direction for specular transmission hermes::vec3 wi; real_t eta_p; bool valid = Scattering::refract(wo, hermes::normal3(0, 0, 1), eta_, &eta_p, &wi); // TODO CHECK VALID if (!valid) return {}; SampledSpectrum ft(T / ShadingCoordinateSystem::absCosTheta(wi)); // Account for non-symmetry with transmission to different medium if (mode == TransportMode::RADIANCE) ft /= hermes::Numbers::sqr(eta_p); return BSDFSample(ft, wi, pt / (pr + pt), bxdf_flags::SPECULAR_TRANSMISSION, eta_p); } } else { // Sample rough dielectric BSDF hermes::vec3 wm = mf_distribution_.sample_wm(wo, u); real_t R = Scattering::frDielectric(hermes::dot(wo, wm), eta_); real_t T = 1 - R; // Compute probabilities _pr_ and _pt_ for sampling reflection and transmission real_t pr = R, pt = T; if (!((u32) sample_flags & (u32) bxdf_refl_trans_flags::REFLECTION)) pr = 0; if (!((u32) sample_flags & (u32) bxdf_refl_trans_flags::TRANSMISSION)) pt = 0; if (pr == 0 && pt == 0) return {}; real_t pdf; if (uc < pr / (pr + pt)) { // Sample reflection at rough dielectric interface hermes::vec3 wi = Scattering::reflect(wo, wm); if (!Scattering::sameHemisphere(wo, wi)) return {}; // Compute PDF of rough dielectric reflection pdf = mf_distribution_.PDF(wo, wm) / (4 * abs(hermes::dot(wo, wm))) * pr / (pr + pt); HERMES_CHECK_EXP(!hermes::Check::is_nan(pdf)) SampledSpectrum f(mf_distribution_.D(wm) * mf_distribution_.G(wo, wi) * R / (4 * ShadingCoordinateSystem::cosTheta(wi) * ShadingCoordinateSystem::cosTheta(wo))); return BSDFSample(f, wi, pdf, bxdf_flags::GLOSSY_REFLECTION); } else { // Sample transmission at rough dielectric interface real_t eta_p; hermes::vec3 wi; bool tir = !Scattering::refract(wo, (hermes::normal3) wm, eta_, &eta_p, &wi); // TODO CHECK_RARE(1e-5f, tir); if (Scattering::sameHemisphere(wo, wi) || wi.z == 0 || tir) return {}; // Compute PDF of rough dielectric transmission real_t denom = hermes::Numbers::sqr(hermes::dot(wi, wm) + hermes::dot(wo, wm) / eta_p); real_t dwm_dwi = abs(hermes::dot(wi, wm)) / denom; pdf = mf_distribution_.PDF(wo, wm) * dwm_dwi * pt / (pr + pt); HERMES_CHECK_EXP(!hermes::Check::is_nan(pdf)); // Evaluate BRDF and return _BSDFSample_ for rough transmission SampledSpectrum ft(T * mf_distribution_.D(wm) * mf_distribution_.G(wo, wi) * std::abs(hermes::dot(wi, wm) * hermes::dot(wo, wm) / (ShadingCoordinateSystem::cosTheta(wi) * ShadingCoordinateSystem::cosTheta(wo) * denom))); // Account for non-symmetry with transmission to different medium if (mode == TransportMode::RADIANCE) ft /= hermes::Numbers::sqr(eta_p); return BSDFSample(ft, wi, pdf, bxdf_flags::GLOSSY_TRANSMISSION, eta_p); } } return helios::BSDFSampleReturn(); } HERMES_DEVICE_CALLABLE real_t DielectricBxDF::PDF(const hermes::vec3 &wo, const hermes::vec3 &wi, TransportMode mode, bxdf_refl_trans_flags sampleFlags) const { if (eta_ == 1 || mf_distribution_.effectivelySmooth()) return 0.f; // Evaluate sampling PDF of rough dielectric BSDF // Compute generalized half vector _wm_ real_t cosTheta_o = ShadingCoordinateSystem::cosTheta(wo), cosTheta_i = ShadingCoordinateSystem::cosTheta(wi); bool reflect = cosTheta_i * cosTheta_o > 0; float etap = 1; if (!reflect) etap = cosTheta_o > 0 ? eta_ : (1 / eta_); hermes::vec3 wm = wi * etap + wo; // TODO CHECK_RARE(1e-5f, LengthSquared(wm) == 0); if (cosTheta_i == 0 || cosTheta_o == 0 || wm.length2() == 0) return {}; wm = hermes::faceForward(hermes::normalize(wm), hermes::normal3(0, 0, 1)); // Discard back-facing microfacets if (hermes::dot(wm, wi) * cosTheta_i < 0 || hermes::dot(wm, wo) * cosTheta_o < 0) return {}; // Determine Fresnel reflectance of rough dielectric boundary real_t R = Scattering::frDielectric(hermes::dot(wo, wm), eta_); real_t T = 1.f - R; // Compute probabilities _pr_ and _pt_ for sampling reflection and transmission real_t pr = R, pt = T; if (!((u32) sampleFlags & (u32) bxdf_refl_trans_flags::REFLECTION)) pr = 0; if (!((u32) sampleFlags & (u32) bxdf_refl_trans_flags::TRANSMISSION)) pt = 0; if (pr == 0 && pt == 0) return {}; real_t pdf; if (reflect) { // Compute PDF of rough dielectric reflection pdf = mf_distribution_.PDF(wo, wm) / (4 * abs(hermes::dot(wo, wm))) * pr / (pr + pt); } else { // Compute PDF of rough dielectric transmission real_t denom = hermes::Numbers::sqr(hermes::dot(wi, wm) + hermes::dot(wo, wm) / etap); real_t dwm_dwi = abs(hermes::dot(wi, wm)) / denom; pdf = mf_distribution_.PDF(wo, wm) * dwm_dwi * pt / (pr + pt); } return pdf; } }
42.831169
117
0.634728
[ "vector" ]
fa9ca690612d248fed2f095e3b0fbdac7492bcc5
1,587
cpp
C++
Engine/ArrayGeometry.cpp
larso0/Engine
6078646fd92ea86c737f6769d50be9bd18c6dac8
[ "MIT" ]
null
null
null
Engine/ArrayGeometry.cpp
larso0/Engine
6078646fd92ea86c737f6769d50be9bd18c6dac8
[ "MIT" ]
1
2017-04-04T23:58:04.000Z
2017-04-04T23:58:04.000Z
Engine/ArrayGeometry.cpp
larso0/Engine
6078646fd92ea86c737f6769d50be9bd18c6dac8
[ "MIT" ]
null
null
null
/* * File: ArrayGeometry.cpp * Author: larso * * Created on 28. desember 2015, 19:34 */ #include "ArrayGeometry.h" #include <stdexcept> namespace Engine { ArrayGeometry::ArrayGeometry() : Geometry(), dataIsSent(false), vertexBuffer(0) { } ArrayGeometry::~ArrayGeometry() { if(dataIsSent) { glDeleteBuffers(1, &vertexBuffer); } } void ArrayGeometry::sendData() { if(!dataIsSent) { glGenBuffers(1, &vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), vertices.data(), GL_STATIC_DRAW); dataIsSent = true; } } GLuint ArrayGeometry::createVertexArrayObject(GLint positionLocation, GLint normalLocation, GLint uvLocation) { if(!dataIsSent) { throw std::runtime_error("Data must be sent to GPU with sendData() before creating a vertex array object."); } GLuint vertexArrayObject; glGenVertexArrays(1, &vertexArrayObject); glBindVertexArray(vertexArrayObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glEnableVertexAttribArray(positionLocation); glVertexAttribPointer(positionLocation, 3, GL_FLOAT, false, Vertex::stride, Vertex::positionOffset); glEnableVertexAttribArray(normalLocation); glVertexAttribPointer(normalLocation, 3, GL_FLOAT, false, Vertex::stride, Vertex::normalOffset); glEnableVertexAttribArray(uvLocation); glVertexAttribPointer(uvLocation, 2, GL_FLOAT, false, Vertex::stride, Vertex::uvOffset); return vertexArrayObject; } void ArrayGeometry::draw() { glDrawArrays(drawMode, 0, vertices.size()); } }
23.338235
111
0.742911
[ "geometry", "object" ]
fa9f537ef8c9fedb2d805ca698e74df1b93f0eb6
2,088
cpp
C++
problemsets/Codejam/2008/ROUND 1C 2008/PB/PB.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codejam/2008/ROUND 1C 2008/PB/PB.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/Codejam/2008/ROUND 1C 2008/PB/PB.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cassert> using namespace std; #define FOR(i,a,b) for (int i = a; i < b; i++) #define SI(V) (int)V.size() #define PB push_back typedef long long i64; typedef vector<int> VI; const double EPS = 1E-14; const int MAXV = 45; const int MOD = 2*3*5*7; char S[50]; i64 DP[50][MOD]; int main() { // freopen("B.in","r",stdin); // freopen("B-small-practice.in","r",stdin);freopen("B-small-practice.out","w",stdout); freopen("B-large-practice.in","r",stdin);freopen("B-large-practice.out","w",stdout); // freopen("B-small-attempt0.in","r",stdin);freopen("B-small-attempt0.out","w",stdout); // freopen("B-small-attempt1.in","r",stdin);freopen("B-small-attempt1.out","w",stdout); // freopen("B-small-attempt2.in","r",stdin);freopen("B-small-attempt2.out","w",stdout); // freopen("B-large.in","r",stdin);freopen("B-large.ans","w",stdout); int TC; scanf("%d", &TC); for (int tc = 1; tc <= TC; tc++) { scanf("%s", S); memset(DP, 0, sizeof(DP)); DP[0][0] = 1; int i; for (i = 0; S[i]; i++) for (int s = (i) ? -1 : 1; s <= 1; s+=2) { int c = 0; for (int j = i; S[j]; j++) { c = (c*10 + S[j]-'0') % MOD; for (int x = 0; x < MOD; x++) DP[j+1][(x + s*c + MOD)%MOD] += DP[i][x]; } } i64 ret = 0; for (int x = 0; x <= MOD; x++) if (x%2==0 || x%3==0 || x%5==0 || x%7==0) ret += DP[i][x]; printf("Case #%d: %lld\n", tc, ret); } return 0; }
24
87
0.547893
[ "vector" ]
faa1be1b1c32484218112ba9d888d5f22f140e7f
26,363
cpp
C++
bookviewer/Classes/BookView.cpp
JaagaLabs/GLEXP-Team-KitkitSchool
f94ea3e53bd05fdeb2a9edcc574bc054e575ecc0
[ "Apache-2.0" ]
45
2019-05-16T20:49:31.000Z
2021-11-05T21:40:54.000Z
bookviewer/Classes/BookView.cpp
rdsmarketing/GLEXP-Team-KitkitSchool
6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e
[ "Apache-2.0" ]
10
2019-05-17T13:38:22.000Z
2021-07-31T19:38:27.000Z
bookviewer/Classes/BookView.cpp
rdsmarketing/GLEXP-Team-KitkitSchool
6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e
[ "Apache-2.0" ]
29
2019-05-16T17:49:26.000Z
2021-12-30T16:36:24.000Z
// // BookView.cpp // booktest // // Created by Gunho Lee on 6/29/16. // // #include "BookView.hpp" #include "Utils/TodoUtil.h" #include "Common/Controls/CompletePopup.hpp" #include "Common/Controls/ProgressIndicator.hpp" #include "Managers/GameSoundManager.h" #include "CCAppController.hpp" #include "Managers/LogManager.hpp" using namespace ui; namespace BookViewSpace { const Size defaultSize = Size(2560, 1800); const int upperZ = 100; const int lowerZ = 50; const float turnDuration = 0.25; } using namespace BookViewSpace; bool BookView::_isReadAll = false; bool BookView::_libraryMode = false; static std::string _currentBook; std::string BookView::_languageCode = "en"; BookView* BookView::create(const cocos2d::Size &size, std::string &bookPath) { return BookView::create(size, bookPath, true); } BookView* BookView::create(const cocos2d::Size &size, std::string &bookPath, bool checkCompleteCondition) { BookView *pRet = new(std::nothrow) BookView(); if (pRet && pRet->init(size, bookPath, checkCompleteCondition)) { pRet->autorelease(); return pRet; } else { delete pRet; pRet= nullptr; return nullptr; } } bool BookView::init(const Size &size, std::string &bookPath, bool checkCompleteCondition) { if (!Node::init()) return false; GameSoundManager::getInstance()->stopAllEffects(); GameSoundManager::getInstance()->unloadAllEffect(); _checkCompleteCondition = checkCompleteCondition; _buttonEnabled = false; _soundSetting = true; // for memory release Director::getInstance()->getTextureCache()->removeUnusedTextures(); TodoBook *book = new TodoBook; if (!book->readFile(bookPath)) return false; setBook(book); setColor(Color3B::WHITE); setContentSize(size); _isReadAll = false; _finishReading = false; _bgView = Sprite::create("Books/book_vertical_bg.jpg"); auto bgSize = _bgView->getContentSize(); auto bgScale = MAX(size.width/bgSize.width, size.height/bgSize.height); _bgView->setScale(bgScale); _bgView->setPosition(size/2); addChild(_bgView); /* moved to below: apply to all book layout if (_libraryMode && _book->bookType == TDBookType::WithAudio && (_bookLayout == TDBookLayout::Portrait || _bookLayout == TDBookLayout::Portrait_Traditional)) { _soundBtn = ui::Button::create("Common/Controls/library_book_button_sound-on.png"); _soundBtn->setAnchorPoint(Vec2::ANCHOR_TOP_RIGHT); _soundBtn->setPosition(Vec2(size.width-25, size.height-25)); addChild(_soundBtn); _soundBtn->addClickEventListener([this](Ref*) { this->setSoundSetting(!_soundSetting); }); _soundSetting = getSoundSetting(); setSoundSetting(_soundSetting); _soundView = Sprite::create("Common/Controls/book_readaloud_base.png"); Size soundSize = _soundView->getContentSize(); bool isEnglish = _languageCode == "en"; std::string textAloud = (isEnglish) ? "Read Aloud?" : "Sauti"; auto labelAloud = Label::createWithTTF(textAloud, "fonts/TodoSchoolV2.ttf", 90); labelAloud->setTextColor(Color4B(255, 248, 219, 255)); labelAloud->setPosition(soundSize.width / 2, soundSize.height / 2 + 255); _soundView->addChild(labelAloud); _soundOnButton = ImageView::create("Common/Controls/book_readaloud_button_normal.png"); _soundOnButton->setTouchEnabled(true); _soundOnButton->addTouchEventListener([this, isEnglish](Ref*, Widget::TouchEventType type) { if (type == Widget::TouchEventType::BEGAN) { if (!_soundSetting) { if (isEnglish) { GameSoundManager::getInstance()->playEffectSound("Common/Sounds/Effect/soundon.m4a"); } else { GameSoundManager::getInstance()->playEffectSound("Common/Sounds/Effect/washasauti.m4a"); } } setSoundButton(true, _soundOnButton, _soundOnLabel); setSoundButton(false, _soundOffButton, _soundOffLabel); _soundSetting = true; BookView::setSoundSetting(_soundSetting); } }); std::string textOn = (isEnglish) ? "on" : "Washa"; float textSizeOnOff = (isEnglish) ? 120 : 95; _soundOnLabel = Label::createWithTTF(textOn, "fonts/TodoSchoolV2.ttf", textSizeOnOff); _soundOnLabel->setTextColor(Color4B(255, 255, 255, 255)); _soundOnLabel->setPosition(Vec2(_soundOnButton->getContentSize().width / 2, 156)); _soundOnButton->addChild(_soundOnLabel); _soundOnButton->setAnchorPoint(Vec2(0.5f, 0.0f)); _soundOnButton->setPosition(Vec2(soundSize.width / 2, soundSize.height / 2 - 90)); _soundView->addChild(_soundOnButton); _soundOffButton = ImageView::create("Common/Controls/book_readaloud_button_normal.png"); _soundOffButton->setTouchEnabled(true); _soundOffButton->addTouchEventListener([this, isEnglish](Ref*, Widget::TouchEventType type) { if (type == Widget::TouchEventType::BEGAN) { bool beforeSoundSetting = _soundSetting; setSoundButton(false, _soundOnButton, _soundOnLabel); setSoundButton(true, _soundOffButton, _soundOffLabel); _soundSetting = false; BookView::setSoundSetting(_soundSetting); if (_currentPageView != nullptr) { _currentPageView->stopReading(); } if (beforeSoundSetting) { if (isEnglish) { GameSoundManager::getInstance()->playEffectSound("Common/Sounds/Effect/soundoff.m4a"); } else { GameSoundManager::getInstance()->playEffectSound("Common/Sounds/Effect/zimasauti.m4a"); } } } }); std::string textOff = (isEnglish) ? "off" : "Zima"; _soundOffLabel = Label::createWithTTF(textOff, "fonts/TodoSchoolV2.ttf", textSizeOnOff); _soundOffLabel->setTextColor(Color4B(255, 255, 255, 255)); _soundOffLabel->setPosition(Vec2(_soundOffButton->getContentSize().width / 2, 156)); _soundOffButton->addChild(_soundOffLabel); _soundOffButton->setAnchorPoint(Vec2(0.5f, 0.0f)); _soundOffButton->setPosition(Vec2(soundSize.width / 2, soundSize.height / 2 - 340)); _soundView->addChild(_soundOffButton); _soundView->setPosition(Vec2(size.width / 4, size.height / 2)); addChild(_soundView); _soundSetting = BookView::getSoundSetting(); setSoundButton(_soundSetting, _soundOnButton, _soundOnLabel); setSoundButton(!_soundSetting, _soundOffButton, _soundOffLabel); } */ _contentsView = Node::create(); _contentsView->setContentSize(size); addChild(_contentsView); _pageScale = MIN(size.width/defaultSize.width, size.height/defaultSize.height); //auto imageScale = MIN(size.width/2560, size.height/1800.0); //auto imageScale = 1.f; //Size imageSize = Size(imageScale*2280, imageScale*1410); //Size textSize = Size(imageScale*2280, imageScale*200); //float topMargin = (size.height-imageSize.height)/2-100*imageScale; //auto backButton = TodoSchoolBackButton::create(); //backButton->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); //backButton->setPosition(Vec2(25, size.height-25)); //addChild(backButton); { auto backBtn = ui::Button::create(); backBtn->loadTextures("Common/Controls/back_arrow_inactive.png", "Common/Controls/back_arrow_active.png"); auto keyListener = EventListenerKeyboard::create(); keyListener->onKeyReleased = [this](EventKeyboard::KeyCode keyCode, Event *event) { if (keyCode == EventKeyboard::KeyCode::KEY_ESCAPE) { LogManager::getInstance()->logEvent(_book->bookTitle, "esc_pressed", "", _currentPage); this->popBookScene(); } }; backBtn->getEventDispatcher()->addEventListenerWithSceneGraphPriority(keyListener, backBtn); backBtn->addClickEventListener([this](Ref*){ LogManager::getInstance()->logEvent(_book->bookTitle, "back_pressed", "", _currentPage); GameSoundManager::getInstance()->playEffectSound("Common/Sounds/Effect/SFX_GUIBack.m4a"); this->popBookScene(); }); backBtn->setAnchorPoint(Vec2::ANCHOR_TOP_LEFT); backBtn->setPosition(Vec2(25, size.height-25)); addChild(backBtn); } { if (_libraryMode && _book->bookType == TDBookType::WithAudio) { // change - audio button for all book layout _soundBtn = ui::Button::create("Common/Controls/library_book_button_sound-on.png"); _soundBtn->setAnchorPoint(Vec2::ANCHOR_TOP_RIGHT); _soundBtn->setPosition(Vec2(size.width-25, size.height-25)); addChild(_soundBtn); _soundBtn->addClickEventListener([this](Ref*) { this->setSoundSetting(!_soundSetting); if (_soundSetting) { _currentPageView->startReading(); } else { _currentPageView->stopReading(); } }); _soundSetting = getSoundSetting(); setSoundSetting(_soundSetting); } } _progressBar = ProgressIndicator::create(); _progressBar->setPosition(Vec2(size.width/2, size.height - _progressBar->getContentSize().height)); addChild(_progressBar); _progressBar->setMax(_book->pages.size()); if (true) { _prevButton = Button::create("Books/book_arrow_left_normal.png", "Books/book_arrow_left_active.png"); _nextButton = Button::create("Books/book_arrow_right_normal.png", "Books/book_arrow_right_active.png"); Director::getInstance()->getTextureCache()->addImage("Books/book_vertical_pagespread_texture.png"); } else { _prevButton = Button::create("Books/page_left.png"); _nextButton = Button::create("Books/page_right.png"); } _prevButtonPos = Vec2(_prevButton->getContentSize().width*0.5, size.height/2); _prevButton->setPosition(_prevButtonPos); _prevButton->addClickEventListener([this](Ref*){ previousPage(); }); addChild(_prevButton); _nextButtonPos = Vec2(size.width-_nextButton->getContentSize().width*0.5, size.height/2); _nextButton->setPosition(_nextButtonPos); _nextButton->addClickEventListener([this](Ref*){ nextPage(); }); addChild(_nextButton); Director::getInstance()->getTextureCache()->addImage("Common/Controls/CompletePopup/game_effect_glow.png"); Director::getInstance()->getTextureCache()->addImage("Common/Controls/CompletePopup/game_effect_rotatingleft.png"); Director::getInstance()->getTextureCache()->addImage("Common/Controls/CompletePopup/game_effect_rotatingright.png"); Director::getInstance()->getTextureCache()->addImage("Common/Controls/CompletePopup/game_effect_sparkle_1.png"); Director::getInstance()->getTextureCache()->addImage("Common/Controls/CompletePopup/game_effect_starmedal.png"); Director::getInstance()->getTextureCache()->addImage("Common/Controls/CompletePopup/game_effect_done_touch.png"); Director::getInstance()->getTextureCache()->addImage("Common/Controls/CompletePopup/game_effect_done_normal.png"); _currentPage = -1; _currentPageView = nullptr; showPageButton(); return true; } void BookView::onEnter() { Node::onEnter(); LogManager::getInstance()->tagScreen(_book->bookTitle); } void BookView::onExit() { Node::onExit(); GameSoundManager::getInstance()->stopAllEffects(); GameSoundManager::getInstance()->unloadAllEffect(); } void BookView::setBook(TodoBook *book) { _book = book; _bookLayout = book->bookLayout; //_isPortrait = (_bookLayout==TDBookLayout::Portrait || _bookLayout==TDBookLayout::Portrait_Traditional); } void BookView::viewTitle(float delay) { _currentPage = -1; unscheduleUpdate(); _progressBar->setVisible(false); if (_currentPageView) { _currentPageView->removeFromParent(); _currentPageView = nullptr; } _currentPageView = BookPage::create(); //_currentPageView->setTitle(_book->bookTitle, _book->imagePrefix+_book->titleImageFilename, _soundSetting ? _book->imagePrefix+_book->titleAudioFilename : "", _bookLayout, delay); _currentPageView->setTitle(_book->bookTitle, _book->imagePrefix+_book->titleImageFilename, _book->imagePrefix+_book->titleAudioFilename, _bookLayout, delay); _currentPageView->setScale(_pageScale); _currentPageView->setAnchorPoint(Vec2::ANCHOR_MIDDLE); _currentPageView->setPosition(getContentSize()/2); _contentsView->addChild(_currentPageView); //showSoundButton(); } void BookView::viewPage(int page) { if (page<0) return; if (page>=_book->pages.size()) return; if (page==_currentPage) return; if (page == _book->pages.size()-1) { _finishReading = true; } _currentPage = page; _progressBar->setVisible(true); _progressBar->setCurrent(page+1); if (_currentPageView) { _currentPageView->removeFromParent(); _currentPageView = nullptr; } _currentPageView = BookPage::create(); //_currentPageView->setPage(_book, &(_book->pages[_currentPage]), _bookLayout, _book->bookType == TDBookType::WithAudio && _soundSetting); _currentPageView->setPage(_book, &(_book->pages[_currentPage]), _bookLayout, _book->bookType == TDBookType::WithAudio); _currentPageView->setScale(_pageScale); _currentPageView->setAnchorPoint(Vec2::ANCHOR_MIDDLE); _currentPageView->setPosition(getContentSize()/2); _contentsView->addChild(_currentPageView); } void BookView::nextPage() { if (!_buttonEnabled) return; hidePageButton(); if (true) { auto oldPage = _currentPageView; oldPage->stopReading(); _currentPageView = nullptr; viewPage(_currentPage+1); _contentsView->reorderChild(oldPage, upperZ); _contentsView->reorderChild(_currentPageView, lowerZ); _currentPageView->hideLeftHalf(false); float nextDuration = (_currentPage + 1 >= _book->pages.size()) ? turnDuration * 2 : turnDuration; oldPage->runAction(Sequence::create(CallFunc::create([oldPage](){ oldPage->hideRightHalf(true); }), DelayTime::create(turnDuration), CallFunc::create([this, oldPage](){ _contentsView->reorderChild(oldPage, lowerZ); _contentsView->reorderChild(_currentPageView, upperZ); _currentPageView->showLeftHalf(true); }), DelayTime::create(nextDuration), CallFunc::create([this](){ if (_currentPage + 1 >= _book->pages.size()) { LogManager::getInstance()->logEvent( _book->bookTitle, "finish_read", "", _currentPage); CompletePopup::create()->show(0.0, [this]() { _isReadAll = true; if (_checkCompleteCondition) { CCAppController::sharedAppController()->handleGameComplete(1); } else { CCAppController::sharedAppController()->handleGameQuit(); } //TodoSchoolBackButton::popGameScene(); }); } else { showPageButton(); if (getSoundSetting()) _currentPageView->startReading(); } //hideSoundButton(); }), DelayTime::create(turnDuration), CallFunc::create([oldPage](){ oldPage->removeFromParent(); }), nullptr)); } else { float w = getContentSize().width; _contentsView->runAction(Sequence::create( MoveBy::create(0.15, Vec2(-w, 0)), CallFunc::create([this, w](){ _contentsView->setPositionX(w); viewPage(_currentPage+1); showPageButton(); if (getSoundSetting()) _currentPageView->startReading(); }), MoveBy::create(0.15, Vec2(-w, 0)), nullptr)); } } void BookView::previousPage() { if (!_buttonEnabled) return; hidePageButton(); if (true) { auto oldPage = _currentPageView; oldPage->stopReading(); _currentPageView = nullptr; if (_currentPage==0) { viewTitle(turnDuration*2); } else if (_currentPage>0) { viewPage(_currentPage-1); } _contentsView->reorderChild(oldPage, upperZ); _contentsView->reorderChild(_currentPageView, lowerZ); _currentPageView->hideRightHalf(false); oldPage->runAction(Sequence::create(CallFunc::create([oldPage](){ oldPage->hideLeftHalf(true); }), DelayTime::create(turnDuration), CallFunc::create([this, oldPage](){ _contentsView->reorderChild(oldPage, lowerZ); _contentsView->reorderChild(_currentPageView, upperZ); _currentPageView->showRightHalf(true); }), DelayTime::create(turnDuration), CallFunc::create([this](){ showPageButton(); if (getSoundSetting()) _currentPageView->startReading(); }), DelayTime::create(turnDuration), CallFunc::create([oldPage](){ oldPage->removeFromParent(); }), nullptr)); } else { float w = getContentSize().width; _contentsView->runAction(Sequence::create( MoveBy::create(0.15, Vec2(w, 0)), CallFunc::create([this, w](){ _contentsView->setPositionX(-w); if (_currentPage==0) { viewTitle(); } else if (_currentPage>0) { viewPage(_currentPage-1); } showPageButton(); if (getSoundSetting()) _currentPageView->startReading(); }), MoveBy::create(0.15, Vec2(w, 0)), nullptr)); } } void BookView::showPageButton() { _buttonEnabled = true; _prevButton->setVisible(_currentPage>=0); _prevButton->setPositionX(-_prevButton->getContentSize().width/2); _prevButton->runAction(Sequence::create(DelayTime::create(1.0), EaseBounceOut::create(MoveTo::create(0.2, _prevButtonPos)), nullptr)); _nextButton->setVisible(true); _nextButton->setPositionX(getContentSize().width+_nextButton->getContentSize().width/2); _nextButton->runAction(Sequence::create(DelayTime::create(1.0), EaseBounceOut::create(MoveTo::create(0.2, _nextButtonPos)), nullptr)); } void BookView::hidePageButton() { _buttonEnabled = false; _prevButton->setPosition(_prevButtonPos); _prevButton->runAction(MoveBy::create(0.1, Vec2(-_prevButton->getContentSize().width, 0))); _nextButton->setPosition(_nextButtonPos); _nextButton->runAction(MoveBy::create(0.1, Vec2(_nextButton->getContentSize().width, 0))); } void BookView::popBookScene() { if (_libraryMode) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) if (_finishReading) { LogManager::getInstance()->logEvent(_book->bookTitle, "finish_read", "", _currentPage); CCAppController::sharedAppController()->handleGameComplete(1); } else { JniMethodInfo t; bool result = JniHelper::getStaticMethodInfo(t, "org/cocos2dx/cpp/AppActivity", "sendToBack", "()V"); if (result) { t.env->CallStaticVoidMethod(t.classID, t.methodID); t.env->DeleteLocalRef(t.classID); } } #elif (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) { auto uri = ref new Windows::Foundation::Uri("kitkitlibrary:"); concurrency::create_task(Windows::System::Launcher::LaunchUriAsync(uri)).then([](bool launchResult) { }); } #else Director::getInstance()->end(); #endif } else { if (_finishReading) { LogManager::getInstance()->logEvent(_book->bookTitle, "finish_read", "", _currentPage); CCAppController::sharedAppController()->handleGameComplete(1); } else { //(Director::getInstance())->popScene(); CCAppController::sharedAppController()->handleGameQuit(); } } } //void BookView::setSoundButton(bool isSelect, ui::ImageView *imageButton, Label *textLabel) { // Size size = imageButton->getContentSize(); // // if (isSelect) { // imageButton->loadTexture("Common/Controls/book_readaloud_button_active.png"); // textLabel->setTextColor(Color4B(255, 255, 255, 255)); // textLabel->setPosition(size.width / 2, 156 - 15); // // } else { // imageButton->loadTexture("Common/Controls/book_readaloud_button_normal.png"); // textLabel->setTextColor(Color4B(87, 44, 0, 255)); // textLabel->setPosition(size.width / 2, 156); // // } //} //void BookView::showSoundButton() { // if (_soundView != nullptr) { // _soundView->setVisible(true); // } //} // //void BookView::hideSoundButton() { // if (_soundView != nullptr) { // _soundView->setVisible(false); // } //} string BookView::getCurrentBook() { return _currentBook; } void BookView::setCurrentBook(string book) { _currentBook = book; } bool BookView::getSoundSetting() { bool result = UserDefault::getInstance()->getBoolForKey("SOUND_ENABLE_BOOK_GLOBAL", true); return result; /* bool result = true; string soundOffBook = UserDefault::getInstance()->getStringForKey("SOUND_OFF_BOOK", ""); vector<std::string> splitSoundOffBook = TodoUtil::split(soundOffBook, ','); if (splitSoundOffBook.size() == 0) { return true; } for (string soundOffBook : splitSoundOffBook) { if (soundOffBook == getCurrentBook()) { return false; } } return result; */ } void BookView::setSoundSetting(bool enable) { _soundSetting = enable; if (enable) { _soundBtn->loadTextureNormal("Common/Controls/library_book_button_sound-on.png"); } else { _soundBtn->loadTextureNormal("Common/Controls/library_book_button_sound-off.png"); } UserDefault::getInstance()->setBoolForKey("SOUND_ENABLE_BOOK_GLOBAL", enable); /* string soundOffBook = UserDefault::getInstance()->getStringForKey("SOUND_OFF_BOOK", ""); vector<std::string> splitSoundOffBook = TodoUtil::split(soundOffBook, ','); splitSoundOffBook.erase(std::remove(splitSoundOffBook.begin(), splitSoundOffBook.end(), getCurrentBook()), splitSoundOffBook.end()); if (enable == false) { splitSoundOffBook.push_back(getCurrentBook()); } string strSave = ""; for (int i = 0; i < splitSoundOffBook.size(); ++i) { strSave += splitSoundOffBook[i]; if (i < splitSoundOffBook.size() - 1) { strSave += ","; } } UserDefault::getInstance()->setStringForKey("SOUND_OFF_BOOK", strSave); */ }
35.386577
184
0.564617
[ "vector" ]
faa1e8c5c701bfc8f694775b8f81330d520a3388
11,760
cpp
C++
TP3/ex1.cpp
biromiro/feup-cal
d0fe01603e13729a5b91ca2758d8db5aafd2a13c
[ "MIT" ]
null
null
null
TP3/ex1.cpp
biromiro/feup-cal
d0fe01603e13729a5b91ca2758d8db5aafd2a13c
[ "MIT" ]
null
null
null
TP3/ex1.cpp
biromiro/feup-cal
d0fe01603e13729a5b91ca2758d8db5aafd2a13c
[ "MIT" ]
2
2021-04-11T17:31:16.000Z
2021-04-27T14:04:44.000Z
#include "exercises.h" #include <limits> #include <thread> #include <algorithm> #include <cmath> const double MAX_DOUBLE = std::numeric_limits<double>::max(); Point::Point(double x, double y) { this->x = x; this->y = y; } Point::Point(int x, int y) { this->x = x; this->y = y; } double Point::distance(Point &p) const { return sqrt((x-p.x) * (x-p.x) + (y-p.y) * (y-p.y)); } double Point::distSquare(Point &p) const { return (x-p.x) * (x-p.x) + (y-p.y) * (y-p.y); } bool Point::operator==(const Point &p) const { return (x == p.x && y == p.y); } std::ostream& operator<<(std::ostream& os, Point &p) { os << "(" << p.x << "," << p.y << ")"; return os; } Result::Result(double dmin, Point p1, Point p2): dmin(dmin), p1(p1), p2(p2) { } Result::Result(): Result(MAX_DOUBLE, Point(0,0), Point(0,0)) { } /** * Defines the number of threads to be used. */ static int numThreads = 1; void setNumThreads(int num) { numThreads = num; } // Auxiliary functions to sort vector of points by X or Y axis. static void sortByX(std::vector<Point> &v, int left, int right) { std::sort(v.begin( ) + left, v.begin() + right + 1, [](Point p, Point q){ return p.x < q.x || (p.x == q.x && p.y < q.y); }); } static void sortByY(std::vector<Point> &v, int left, int right) { std::sort(v.begin( ) + left, v.begin() + right + 1, [](Point p, Point q){ return p.y < q.y || (p.y == q.y && p.x < q.x); }); } Result nearestPoints_BF(std::vector<Point> &vp) { Result res; res.dmin = -1; double distance; for(size_t i = 0; i < vp.size() - 1; i++){ for(size_t j = i + 1; j < vp.size(); j++){ if(res.dmin == -1 || (distance = vp[i].distSquare(vp[j])) < res.dmin) res = Result(sqrt(distance), vp[i], vp[j]); } } return res; //loop invariant -> res contains the minimally distanced pair starting at one of vp[0:i]'s points (by Balta) //loop variant ->n = vp.size(), (n - i) -> strictly decreasing and when it reaches 1, i=n-1 and vp[0:n-1] // contains the minimum distance of all points in vp } Result nearestPoints_BF_SortByX(std::vector<Point> &vp) { Result res; sortByX(vp, 0, vp.size()-1); return nearestPoints_BF(vp); } Result minDist(const Result& d1, const Result& d2){ if(d1.dmin < d2.dmin) return d1; else return d2; } Result nearestPoints_DC_R(std::vector<Point> &vp){ if(vp.empty() || vp.size() == 1) return {}; if(vp.size() == 2) return {vp[0].distance(vp[1]), vp[0], vp[1]}; std::vector<Point> left = std::vector<Point>(vp.begin(),vp.begin() + vp.size()/2); std::vector<Point> right = std::vector<Point>(vp.begin() + vp.size()/2,vp.end()); Result dL = nearestPoints_DC_R(left), dR = nearestPoints_DC_R(right), delta = minDist(dL, dR); double divisionLineX = (left.back().x + right.front().x) / 2; std::vector<Point> inStrip; for(auto i = left.rbegin(); i != left.rend(); i++) if(divisionLineX - i->x < delta.dmin) inStrip.push_back(*i); for(auto & i : right) if(i.x - divisionLineX < delta.dmin) inStrip.push_back(i); sortByY(inStrip, 0, inStrip.size() - 1); sortByY(inStrip, 0, inStrip.size() - 1); double distance; for(size_t i = 0; i < inStrip.size(); ++i){ for(size_t j = i + 1; j < inStrip.size(); ++j){ if(std::abs(inStrip[i].y - inStrip[j].y) >= delta.dmin) break; else{ if((distance = inStrip[i].distance(inStrip[j])) < delta.dmin) delta = Result(distance, inStrip[i], inStrip[j]); } } } return delta; } Result nearestPoints_DC_MT_R(std::vector<Point> &vp, int threads){ if(vp.empty() || vp.size() == 1) return {}; if(vp.size() == 2) return {vp[0].distance(vp[1]), vp[0], vp[1]}; std::vector<Point> left = std::vector<Point>(vp.begin(),vp.begin() + vp.size()/2); std::vector<Point> right = std::vector<Point>(vp.begin() + vp.size()/2,vp.end()); Result dL, dR; if(threads > 1){ std::thread t([&](){dL = nearestPoints_DC_MT_R(left, threads/2);}); dR = nearestPoints_DC_MT_R(right, threads/2); t.join(); }else{ dL = nearestPoints_DC_R(left), dR = nearestPoints_DC_R(right); } Result delta = minDist(dL, dR); double divisionLineX = (left.back().x + right.front().x) / 2; std::vector<Point> inStrip; for(auto i = left.rbegin(); i != left.rend(); i++) if(divisionLineX - i->x < delta.dmin) inStrip.push_back(*i); for(auto & i : right) if(i.x - divisionLineX < delta.dmin) inStrip.push_back(i); sortByY(inStrip, 0, inStrip.size() - 1); sortByY(inStrip, 0, inStrip.size() - 1); double distance; for(size_t i = 0; i < inStrip.size(); ++i){ for(size_t j = i + 1; j < inStrip.size(); ++j){ if(std::abs(inStrip[i].y - inStrip[j].y) >= delta.dmin) break; else{ if((distance = inStrip[i].distance(inStrip[j])) < delta.dmin) delta = Result(distance, inStrip[i], inStrip[j]); } } } return delta; } Result nearestPoints_DC(std::vector<Point> &vp) { sortByX(vp, 0, vp.size()-1); return nearestPoints_DC_R(vp); //to sort -> O(nlogn), each division is O(logn) => O(nlogn)*O(logn) = O(nlog^2(n)) } Result nearestPoints_DC_MT(std::vector<Point> &vp) { Result res; sortByX(vp, 0, vp.size()-1); return nearestPoints_DC_MT_R(vp,numThreads); } /// TESTS /// #include <gtest/gtest.h> #include <fstream> #include <time.h> #include <sys/timeb.h> #include <random> #include <stdlib.h> #define REL_PATH "../TP3/" // relative path to the tests /** * Auxiliary function to read points from file to vector. */ void readPoints(std::string in, std::vector<Point> &vp) { std::ifstream is(REL_PATH + in); vp.clear(); if (!is) { std::cerr << "Failed to read file " << in << "." << std::endl; return; } while (!is.eof()) { double x, y; is >> x >> y; Point p(x,y); vp.push_back(p); } } /** * Auxiliary functions to generate random sets of points. */ void shuffle(std::vector<Point> &vp, int left, int right) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dis(0, right - left +1); for (int i = left; i < right; i++){ int k = i + dis(gen) % (right - i + 1); Point tmp = vp[i]; vp[i] = vp[k]; vp[k] = tmp; } } void shuffleY(std::vector<Point> &vp, int left, int right) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dis(0, right - left +1); for (int i = left; i < right; i++){ int k = i + dis(gen) % (right - i + 1); double tmp = vp[i].y; vp[i].y = vp[k].y; vp[k].y = tmp; } } // Generates a vector of n distinct points with minimum distance 1. void generateRandom(int n, std::vector<Point> &vp) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dis(0, n-1); vp.clear(); // reference value for reference points (r, r), (r, r+1) int r = dis(gen); vp.push_back(Point(r,r)); vp.push_back(Point(r,r+1)); for (int i = 2; i < n; i++) if (i < r) vp.push_back(Point(i, i)); else vp.push_back(Point(i+1, i+2)); shuffleY(vp, 2, n-1); shuffle(vp, 0, n-1); } // Similar, but with constant X. void generateRandomConstX(int n, std::vector<Point> &vp) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dis(0, n-1); vp.clear(); // reference value for min dist int r = dis(gen); int y = 0; for (int i = 0; i < n; i++) { vp.push_back(Point(0, y)); if (i == r) y++; else y += 1 + dis(gen) % 100; } shuffleY(vp, 0, n-1); } /** * Auxiliary functions to obtain current time and time elapsed * in milliseconds. * Something like GetTickCount but portable. * It rolls over every ~ 12.1 days (0x100000/24/60/60) * Use GetMilliSpan to correct for rollover */ int GetMilliCount() { timeb tb; ftime( &tb ); int nCount = tb.millitm + (tb.time & 0xfffff) * 1000; return nCount; } int GetMilliSpan(int nTimeStart) { int nSpan = GetMilliCount() - nTimeStart; if (nSpan < 0) nSpan += 0x100000 * 1000; return nSpan; } int testNP(std::string name, std::vector<Point> &points, double dmin, NP_FUNC func, std::string alg) { int nTimeStart = GetMilliCount(); Result res = (func)(points); int nTimeElapsed = GetMilliSpan(nTimeStart); std::cout << alg << "; " << name << "; " << nTimeElapsed << "; "; std::cout.precision(17); std::cout << res.dmin << "; " << res.p1 << "; " << res.p2 << std::endl; EXPECT_NEAR(dmin, res.dmin, 0.01); return nTimeElapsed; } /** * Runs the given algorithm (func) for an input file (in) * and checks the expected result (res). * Prints result and performance information. */ int testNPFile(std::string in, double dmin, NP_FUNC func, std::string alg) { std::vector<Point> pontos; readPoints(in, pontos); return testNP(in, pontos, dmin, func, alg); } int testNPRand(int size, std::string name, double dmin, NP_FUNC func, std::string alg) { std::vector<Point> pontos; generateRandom(size, pontos); return testNP(name, pontos, dmin, func, alg); } int testNPRandConstX(int size, std::string name, double dmin, NP_FUNC func, std::string alg) { std::vector<Point> pontos; generateRandomConstX(size, pontos); return testNP(name, pontos, dmin, func, alg); } /** * Runs the given algorithm for the existent data files. */ void testNearestPoints(NP_FUNC func, std::string alg) { std::cout << "algorithm; data set; time elapsed (ms); distance; point1; point2" << std::endl; int maxTime = 10000; if ( testNPFile("Pontos8", 11841.3, func, alg) > maxTime) return; if ( testNPFile("Pontos64", 556.066, func, alg) > maxTime) return; if (testNPFile("Pontos1k", 100.603, func, alg) > maxTime) return; if (testNPFile("Pontos16k", 13.0384, func, alg) > maxTime) return; // Uncomment to use more tests if (testNPFile("Pontos32k", 1.0, func, alg) > maxTime) return; if (testNPFile("Pontos64k", 1.0, func, alg) > maxTime) return; if (testNPFile("Pontos128k", 0.0, func, alg) > maxTime) return; if (testNPRand(0x40000, "Pontos256k", 1.0, func, alg) > maxTime) return; if (testNPRand(0x80000, "Pontos512k", 1.0, func, alg) > maxTime) return; if ( testNPRand(0x100000, "Pontos1M", 1.0, func, alg) > maxTime) return; if ( testNPRand(0x200000, "Pontos2M", 1.0, func, alg) > maxTime) return; } TEST(TP3_Ex1, testNP_BF) { testNearestPoints(nearestPoints_BF, "Brute force"); } TEST(TP3_Ex1, testNP_BF_SortedX) { testNearestPoints(nearestPoints_BF_SortByX, "Brute force, sorted by x"); } TEST(TP3_Ex1, testNP_DC) { testNearestPoints(nearestPoints_DC, "Divide and conquer"); } TEST(TP3_Ex1, testNP_DC_2Threads) { setNumThreads(2); testNearestPoints(nearestPoints_DC_MT, "Divide and conquer with 2 threads"); } TEST(TP3_Ex1, testNP_DC_4Threads) { setNumThreads(4); testNearestPoints(nearestPoints_DC_MT, "Divide and conquer with 4 threads"); } TEST(TP3_Ex1, testNP_DC_8Threads) { setNumThreads(8); testNearestPoints(nearestPoints_DC_MT, "Divide and conquer with 8 threads"); } TEST(TP3_Ex1, testNP_DC_Max) { unsigned int numThreads = std::thread::hardware_concurrency(); std::cout << numThreads << std::endl; setNumThreads(numThreads); testNearestPoints(nearestPoints_DC_MT, "Divide and conquer with max threads"); }
30.947368
127
0.599405
[ "vector" ]
faa8d6be9116a3a6ef06ba28e1155688be62c6c9
11,205
cpp
C++
tools/layout-tool/sources/reader.cpp
jjYBdx4IL/string-machine
0bb2ac9092d31402c8ecfd5f681a3a4f2d575024
[ "BSL-1.0" ]
34
2019-07-08T15:02:10.000Z
2022-02-20T01:44:02.000Z
tools/layout-tool/sources/reader.cpp
jjYBdx4IL/string-machine
0bb2ac9092d31402c8ecfd5f681a3a4f2d575024
[ "BSL-1.0" ]
27
2019-07-08T21:46:19.000Z
2022-03-24T16:01:02.000Z
tools/layout-tool/sources/reader.cpp
jjYBdx4IL/string-machine
0bb2ac9092d31402c8ecfd5f681a3a4f2d575024
[ "BSL-1.0" ]
3
2019-08-03T22:35:08.000Z
2022-02-20T01:19:52.000Z
#include "reader.h" #include <boost/tokenizer.hpp> #include <iostream> #include <fstream> typedef std::vector<std::string> TokenList; static bool read_file_tokens(const char *filename, TokenList &tokens); static Layout read_tokens_layout(TokenList::iterator &tok_it, TokenList::iterator tok_end); Layout read_file_layout(const char *filename) { std::vector<std::string> tokens; if (!read_file_tokens(filename, tokens)) throw std::runtime_error("Cannot read fluid design file."); TokenList::iterator tok_it = tokens.begin(); TokenList::iterator tok_end = tokens.end(); return read_tokens_layout(tok_it, tok_end); } static std::string consume_next_token(TokenList::iterator &tok_it, TokenList::iterator tok_end) { if (tok_it == tok_end) throw file_format_error("Premature end of tokens"); return *tok_it++; } static bool try_consume_next_token(const char *text, TokenList::iterator &tok_it, TokenList::iterator tok_end) { if (tok_it == tok_end) return false; if (*tok_it != text) return false; ++tok_it; return true; } static void ensure_next_token(const char *text, TokenList::iterator &tok_it, TokenList::iterator tok_end) { std::string tok = consume_next_token(tok_it, tok_end); if (tok != text) throw file_format_error("Unexpected token: " + tok); } static std::string consume_enclosed_string(TokenList::iterator &tok_it, TokenList::iterator tok_end) { ensure_next_token("{", tok_it, tok_end); unsigned depth = 1; std::string text; for (;;) { std::string part = consume_next_token(tok_it, tok_end); if (part == "}") { if (--depth == 0) return text; } else if (part == "{") ++depth; if (!text.empty()) text.push_back(' '); text.append(part); } return text; } static std::string consume_any_string(TokenList::iterator &tok_it, TokenList::iterator tok_end) { if (tok_it != tok_end && *tok_it == "{") return consume_enclosed_string(tok_it, tok_end); else return consume_next_token(tok_it, tok_end); } static int consume_int_token(TokenList::iterator &tok_it, TokenList::iterator tok_end) { std::string text = consume_next_token(tok_it, tok_end); return std::stoi(text); } static int consume_real_token(TokenList::iterator &tok_it, TokenList::iterator tok_end) { std::string text = consume_next_token(tok_it, tok_end); return std::stod(text); } static void consume_image_properties(LayoutImage &image, TokenList::iterator &tok_it, TokenList::iterator tok_end) { for (bool have = true; have;) { if (try_consume_next_token("xywh", tok_it, tok_end)) { ensure_next_token("{", tok_it, tok_end); image.x = consume_int_token(tok_it, tok_end); image.y = consume_int_token(tok_it, tok_end); image.w = consume_int_token(tok_it, tok_end); image.h = consume_int_token(tok_it, tok_end); ensure_next_token("}", tok_it, tok_end); } else have = false; } } // static void consume_layout_item_properties(LayoutItem &item, TokenList::iterator &tok_it, TokenList::iterator tok_end) // { // ensure_next_token("{", tok_it, tok_end); // for (std::string text; (text = consume_next_token(tok_it, tok_end)) != "}";) { // if (text == "open" || text == "selected") // ; // skip // else if (text == "label") // item.label = consume_any_string(tok_it, tok_end); // else if (text == "xywh") { // ensure_next_token("{", tok_it, tok_end); // item.x = consume_int_token(tok_it, tok_end); // item.y = consume_int_token(tok_it, tok_end); // item.w = consume_int_token(tok_it, tok_end); // item.h = consume_int_token(tok_it, tok_end); // ensure_next_token("}", tok_it, tok_end); // } // else if (text == "box") // item.box = consume_next_token(tok_it, tok_end); // else if (text == "labelfont") // item.labelfont = consume_int_token(tok_it, tok_end); // else if (text == "labelsize") // item.labelsize = consume_int_token(tok_it, tok_end); // else if (text == "labeltype") // item.labeltype = consume_any_string(tok_it, tok_end); // else if (text == "align") // item.align = consume_int_token(tok_it, tok_end); // else if (text == "type") // item.type = consume_any_string(tok_it, tok_end); // else if (text == "callback") // item.callback = consume_any_string(tok_it, tok_end); // else if (text == "class") // item.classname = consume_any_string(tok_it, tok_end); // else if (text == "minimum") // item.minimum = consume_real_token(tok_it, tok_end); // else if (text == "maximum") // item.maximum = consume_real_token(tok_it, tok_end); // else if (text == "step") // item.step = consume_real_token(tok_it, tok_end); // else if (text == "image") { // item.image.filepath = consume_any_string(tok_it, tok_end); // consume_image_properties(item.image, tok_it, tok_end); // } // } // } static void consume_layout_item_properties(LayoutItem &item, TokenList::iterator &tok_it, TokenList::iterator tok_end) { ensure_next_token("{", tok_it, tok_end); for (bool have = true; have;) { if (try_consume_next_token("open", tok_it, tok_end)) ; // skip else if (try_consume_next_token("selected", tok_it, tok_end)) ; // skip else if (try_consume_next_token("label", tok_it, tok_end)) item.label = consume_any_string(tok_it, tok_end); else if (try_consume_next_token("xywh", tok_it, tok_end)) { ensure_next_token("{", tok_it, tok_end); item.x = consume_int_token(tok_it, tok_end); item.y = consume_int_token(tok_it, tok_end); item.w = consume_int_token(tok_it, tok_end); item.h = consume_int_token(tok_it, tok_end); ensure_next_token("}", tok_it, tok_end); } else if (try_consume_next_token("box", tok_it, tok_end)) item.box = consume_next_token(tok_it, tok_end); else if (try_consume_next_token("down_box", tok_it, tok_end)) item.down_box = consume_next_token(tok_it, tok_end); else if (try_consume_next_token("labelfont", tok_it, tok_end)) item.labelfont = consume_int_token(tok_it, tok_end); else if (try_consume_next_token("labelsize", tok_it, tok_end)) item.labelsize = consume_int_token(tok_it, tok_end); else if (try_consume_next_token("labeltype", tok_it, tok_end)) item.labeltype = consume_any_string(tok_it, tok_end); else if (try_consume_next_token("align", tok_it, tok_end)) item.align = consume_int_token(tok_it, tok_end); else if (try_consume_next_token("type", tok_it, tok_end)) item.type = consume_any_string(tok_it, tok_end); else if (try_consume_next_token("callback", tok_it, tok_end)) item.callback = consume_any_string(tok_it, tok_end); else if (try_consume_next_token("class", tok_it, tok_end)) item.classname = consume_any_string(tok_it, tok_end); else if (try_consume_next_token("minimum", tok_it, tok_end)) item.minimum = consume_real_token(tok_it, tok_end); else if (try_consume_next_token("maximum", tok_it, tok_end)) item.maximum = consume_real_token(tok_it, tok_end); else if (try_consume_next_token("step", tok_it, tok_end)) item.step = consume_real_token(tok_it, tok_end); else if (try_consume_next_token("image", tok_it, tok_end)) { item.image.filepath = consume_any_string(tok_it, tok_end); consume_image_properties(item.image, tok_it, tok_end); } else if (try_consume_next_token("visible", tok_it, tok_end)) /* skip */; else have = false; } ensure_next_token("}", tok_it, tok_end); } static LayoutItem consume_layout_item(const std::string &classname, TokenList::iterator &tok_it, TokenList::iterator tok_end, bool anonymous = false) { LayoutItem item; item.classname = classname; if (!anonymous) item.id = consume_any_string(tok_it, tok_end); consume_layout_item_properties(item, tok_it, tok_end); if (tok_it != tok_end && *tok_it == "{") { consume_next_token(tok_it, tok_end); for (std::string text; (text = consume_next_token(tok_it, tok_end)) != "}";) { if (text == "decl") { consume_any_string(tok_it, tok_end); consume_any_string(tok_it, tok_end); } else if (text == "Function") { consume_any_string(tok_it, tok_end); consume_any_string(tok_it, tok_end); consume_any_string(tok_it, tok_end); } else item.items.push_back(consume_layout_item(text, tok_it, tok_end)); } } return item; } static Layout read_tokens_layout(TokenList::iterator &tok_it, TokenList::iterator tok_end) { Layout layout; std::string version_name; std::string header_name; std::string code_name; while (tok_it != tok_end) { std::string key = consume_next_token(tok_it, tok_end); if (key == "version") version_name = consume_next_token(tok_it, tok_end); else if (key == "header_name") { ensure_next_token("{", tok_it, tok_end); header_name = consume_next_token(tok_it, tok_end); ensure_next_token("}", tok_it, tok_end); } else if (key == "code_name") { ensure_next_token("{", tok_it, tok_end); code_name = consume_next_token(tok_it, tok_end); ensure_next_token("}", tok_it, tok_end); } else if (key == "decl") { consume_any_string(tok_it, tok_end); consume_any_string(tok_it, tok_end); } else if (key == "widget_class") { key = consume_next_token(tok_it, tok_end); layout.items.push_back(consume_layout_item(key, tok_it, tok_end, true)); } else layout.items.push_back(consume_layout_item(key, tok_it, tok_end)); } return layout; } static bool read_file_tokens(const char *filename, TokenList &tokens) { std::ifstream stream(filename); std::string line; std::string text; while (std::getline(stream, line)) { if (!line.empty() && line[0] != '#') { text.append(line); text.push_back('\n'); } } if (stream.bad()) return false; typedef boost::tokenizer<boost::char_separator<char>> tokenizer; tokenizer tok(text, boost::char_separator<char>(" \t\r\n", "{}")); for (tokenizer::iterator tok_iter = tok.begin(); tok_iter != tok.end(); ++tok_iter) tokens.push_back(*tok_iter); return !stream.bad(); }
38.505155
149
0.619099
[ "vector" ]
faaa3f43f258b85f31bd18ca4e3a1152e25db8d3
21,741
hpp
C++
stapl_release/stapl/containers/vector/distribution.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/containers/vector/distribution.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
stapl_release/stapl/containers/vector/distribution.hpp
parasol-ppl/PPL_utils
92728bb89692fda1705a0dee436592d97922a6cb
[ "BSD-3-Clause" ]
null
null
null
/* // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a // component of the Texas A&M University System. // All rights reserved. // The information and source code contained herein is the exclusive // property of TEES and may not be disclosed, examined or reproduced // in whole or in part without explicit written authorization from TEES. */ #ifndef STAPL_CONTAINERS_VECTOR_DISTRIBUTION_HPP #define STAPL_CONTAINERS_VECTOR_DISTRIBUTION_HPP #include <stapl/runtime.hpp> #include <stapl/containers/iterators/container_accessor.hpp> #include <stapl/containers/iterators/container_iterator.hpp> #include <stapl/domains/indexed.hpp> #include <stapl/containers/distribution/static_metadata.hpp> #include <stapl/containers/distribution/distribution.hpp> #include <stapl/containers/distribution/container_manager/ordering/base_container_ranking.hpp> #include <stapl/containers/distribution/operations/base.hpp> #include <stapl/views/proxy.h> #include <stapl/algorithms/numeric.hpp> #include <stapl/containers/array/static_array.hpp> #include <stapl/views/vector_view.hpp> #include <stapl/views/array_view.hpp> namespace stapl { template<typename Container> class vector_distribution; ////////////////////////////////////////////////////////////////////// /// @brief Specialization for @ref distribution_traits over /// @ref vector_distribution. ////////////////////////////////////////////////////////////////////// template<typename C> struct distribution_traits<vector_distribution<C> > { typedef C container_type; typedef typename container_traits<C>::directory_type directory_type; typedef typename container_traits< C>::container_manager_type container_manager_type; typedef typename container_manager_type:: base_container_type base_container_type; typedef typename container_traits<C>::gid_type gid_type; typedef gid_type index_type; typedef typename container_traits<C>::value_type value_type; typedef container_accessor<C> accessor_type; typedef proxy<value_type, accessor_type> reference; }; ////////////////////////////////////////////////////////////////////// /// @brief Defines the vector distribution. /// /// Provides the functionality required to manage the data /// distributions of the @ref vector. /// @tparam Container Type of the container that is managing this /// distribution. ////////////////////////////////////////////////////////////////////// template<typename Container> class vector_distribution : public distribution<Container>, public operations::base<vector_distribution<Container> >, public operations::iterable<vector_distribution<Container> >, public operations::random_access<vector_distribution<Container> > { private: typedef distribution<Container> base_type; typedef operations::iterable<vector_distribution<Container> > it_base_t; public: STAPL_IMPORT_TYPE(typename base_type, directory_type) STAPL_IMPORT_TYPE(typename base_type, container_manager_type) STAPL_IMPORT_TYPE(typename base_type, partition_type) STAPL_IMPORT_TYPE(typename base_type, mapper_type) STAPL_IMPORT_TYPE(typename container_manager_type, base_container_type) STAPL_IMPORT_TYPE(typename container_manager_type, gid_type) STAPL_IMPORT_TYPE(typename container_manager_type, value_type) STAPL_IMPORT_TYPE(typename base_container_type, cid_type) typedef gid_type index_type; typedef Container container_type; /// Distribution metadata type used for coarsening /// @todo Change to associative_metadata or move it into set or map /// distribution. typedef metadata::static_container_extractor< vector_distribution > loc_dist_metadata; typedef indexed_domain<gid_type> domain_type; STAPL_IMPORT_TYPE(typename it_base_t, iterator); protected: enum action_type {INSERT, DELETE}; typedef std::queue<std::pair<gid_type,value_type> > insert_queue_type; typedef std::queue<gid_type> erase_queue_type; insert_queue_type m_insert_queue; erase_queue_type m_erase_queue; domain_type m_domain; private: void register_local_keys() { typedef typename container_manager_type::iterator bc_iterator; typedef typename container_manager_type::base_container_type ::domain_type::gid_type gid_type; bc_iterator bc_it = this->m_container_manager.begin(); bc_iterator bc_end = this->m_container_manager.end(); for (; bc_it != bc_end; ++bc_it) { std::pair<gid_type, gid_type> range = std::make_pair((*bc_it).domain().first(), (*bc_it).domain().last()); this->directory().register_keys(range); } } public: ////////////////////////////////////////////////////////////////////// /// @brief Copy construction of this distribution. /// /// @param other Another distribution to copy from. ////////////////////////////////////////////////////////////////////// vector_distribution(vector_distribution const& other) : base_type(other), m_domain(other.m_domain) { } ////////////////////////////////////////////////////////////////////// /// @brief Creates a distribution with default constructed elements. /// /// @param partition Partition used by the container. /// @param mapper Mapper used by the container. ////////////////////////////////////////////////////////////////////// vector_distribution(partition_type const& partition, mapper_type const& mapper) : base_type(partition, mapper), m_domain(partition.global_domain()) { register_local_keys(); } ////////////////////////////////////////////////////////////////////// /// @brief Creates a distribution with an initial value for elements. /// /// @param partition Partition used by the container. /// @param mapper Mapper used by the container. /// @param default_value The value that the elements in this /// distribution will be initialized with. ////////////////////////////////////////////////////////////////////// vector_distribution(partition_type const& partition, mapper_type const& mapper, value_type const& default_value) : base_type(partition, mapper, default_value), m_domain(partition.global_domain()) { register_local_keys(); } ////////////////////////////////////////////////////////////////////// /// @brief Creates a distribution with with the given @p directory /// and base container manager @p bcmangr. /// /// @param directory Directory used by the container. /// @param bcmangr Base container manager used by the container. ////////////////////////////////////////////////////////////////////// vector_distribution(directory_type const& directory, container_manager_type const& bcmangr) : base_type(directory, bcmangr) { register_local_keys(); } void set_domain(domain_type const& domain) { m_domain = domain; } protected: ////////////////////////////////////////////////////////////////////// /// @brief Helper method to update the domain by increasing or /// reducing the number of elements in the domain based on /// the given @p action. /// /// If a non-null view pointer is provided, the domain of the view /// will be updated as well. ////////////////////////////////////////////////////////////////////// template<typename View> void update_metadata(action_type action, location_type origin, View* view) { if (origin != this->get_location_id()) { // Inserting a new element if (action==INSERT) { if (m_domain.empty()) this->m_domain = domain_type(0, 0, true); else this->m_domain = domain_type(m_domain.first(), m_domain.last()+1, true); } // Removing an element else { this->m_domain = domain_type(m_domain.first(), m_domain.last()-1, true); } // Update the view domain if called through a view interface if (view) view->update_domain(); } } ////////////////////////////////////////////////////////////////////// /// @brief Helper method to insert the given @p value at the given /// @p gid position, updating the domain. ////////////////////////////////////////////////////////////////////// void insert_bcast(gid_type gid, value_type const& value, cid_type dest, promise<void> p) { // Update container_manager domains to base containers and insert the value // into the predetermined base container this->m_container_manager.insert(gid, value, dest); // Update registry this->directory().insert(gid, m_domain.last(), std::move(p)); // Update global directory if (m_domain.empty()) this->m_domain = domain_type(0, 0, true); else this->m_domain = domain_type(m_domain.first(), m_domain.last() + 1, true); } ////////////////////////////////////////////////////////////////////// /// @brief Helper method to determine into which base container the // given @p gid and @p value pair should be inserted ////////////////////////////////////////////////////////////////////// void try_insert(gid_type gid, value_type const& value, promise<void> p) { cid_type insert_cid; // We arrived at this location by following (gid - 1), so check for the // location of gid to see where we should insert if (gid == 0) insert_cid = 0; else if (this->m_container_manager.contains(gid)) insert_cid = this->m_container_manager.within(gid); else // Element should go into the next numbered base container insert_cid = this->m_container_manager.within(gid - 1) + 1; async_rmi(all_locations, this->get_rmi_handle(), &vector_distribution::insert_bcast, gid, value, insert_cid, std::move(p)); } public: ////////////////////////////////////////////////////////////////////// /// @brief Inserts the given @p value at the given @p gid position. /// /// If a non-null view pointer is provided, initiates an update of the /// view domain at all locations as well. ////////////////////////////////////////////////////////////////////// template<typename View> void insert(gid_type gid, value_type const& value, View* view) { m_insert_queue.push(std::make_pair(gid, value)); if (m_insert_queue.size() > 1) return; while (!m_insert_queue.empty()) { const std::pair<gid_type, value_type> val = m_insert_queue.front(); typedef promise<void> promise_type; promise_type p; auto f = p.get_future(); this->directory().invoke_where( std::bind( [](p_object& d, gid_type gid, value_type const& value, promise_type& p) { down_cast<vector_distribution>(d).try_insert( gid, value, std::move(p)); }, std::placeholders::_1, val.first, val.second, std::move(p)), gid == 0 ? gid : gid - 1); f.get(); m_insert_queue.pop(); } if (view) async_rmi(all_locations, view->get_rmi_handle(), &View::update_domain); } protected: ////////////////////////////////////////////////////////////////////// /// @brief Helper method to remove the element at the given @p gid /// position, updating the domain. ////////////////////////////////////////////////////////////////////// void erase_bcast(gid_type gid, promise<void> p) { // Update registry this->directory().erase(gid, m_domain.last(), std::move(p)); // Update container_manager domains to base containers and erase the value this->m_container_manager.erase(gid); // Update global directory this->m_domain = domain_type(m_domain.first(), m_domain.last() - 1, true); } public: ////////////////////////////////////////////////////////////////////// /// @brief Removes the element at the given @p gid position. /// /// If a non-null view pointer is provided, initiates an update of the /// view domain at all locations as well. ////////////////////////////////////////////////////////////////////// template<typename View> void erase(gid_type gid, View* view) { stapl_assert(!m_domain.empty(), "vector is empty"); m_erase_queue.push(gid); if (m_erase_queue.size() > 1) return; while (!m_erase_queue.empty()) { const gid_type tmp_gid = m_erase_queue.front(); typedef promise<void> promise_type; promise_type p; auto f = p.get_future(); async_rmi(all_locations, this->get_rmi_handle(), &vector_distribution::erase_bcast, tmp_gid, std::move(p)); f.get(); m_erase_queue.pop(); } if (view) async_rmi(all_locations, view->get_rmi_handle(), &View::update_domain); } ////////////////////////////////////////////////////////////////////// /// @copydoc stapl::vector::clear(void) ////////////////////////////////////////////////////////////////////// void clear(void) { this->m_container_manager.clear(); this->directory().reset(); this->m_domain = domain_type(); } protected: ////////////////////////////////////////////////////////////////////// /// @brief Helper method to insert the given @p value locally. /// /// If a non-null view pointer is provided, initiates an update of the /// view domain at all locations as well. ////////////////////////////////////////////////////////////////////// template<typename View> void push_back_local(value_type const& value, location_type origin,View* view) { size_t new_index = this->m_container_manager.push_back(value); this->directory().register_key(new_index); // Update the domains at all locations except for origin async_rmi(all_locations, this->get_rmi_handle(), &vector_distribution::update_metadata<View>, INSERT, origin, view); rmi_flush(); } public: ////////////////////////////////////////////////////////////////////// /// @brief Inserts the given @p value at the end of the container. /// /// If a non-null view pointer is provided, initiates an update of the /// view domain at all locations as well. ////////////////////////////////////////////////////////////////////// template<typename View> void push_back(value_type const& value, View* view) { const location_type this_loc = this->get_location_id(); if (size() == 0) { if (0 == this_loc) { push_back_local(value, 0, view); } else { async_rmi(0, this->get_rmi_handle(), &vector_distribution::push_back_local<View>, value, this_loc, view); } } else this->directory().invoke_where( std::bind( [](p_object& d, value_type const& val, location_type src, View *v) { down_cast<vector_distribution&>(d).template push_back_local<View>( val,src,v); }, std::placeholders::_1, value, this_loc, view ), this->m_domain.last() ); // Update local metadata immediately. // An invalid location id is used to make sure it's different from the // current location id and the domain update isn't skipped. update_metadata(INSERT, invalid_location_id, view); } protected: ////////////////////////////////////////////////////////////////////// /// @brief Helper method to pop_back on current location. /// /// If a non-null view pointer is provided, initiates an update of the /// view domain at all locations as well. ////////////////////////////////////////////////////////////////////// template<typename View> void pop_back_local(location_type origin, View* view) { gid_type gid = this->container_manager().pop_back(); stapl_assert(gid != index_bounds<gid_type>::invalid(), "Attempting to pop_back from an empty vector."); this->directory().unregister_key(gid); // Update the domains at all locations except for origin async_rmi(all_locations, this->get_rmi_handle(), &vector_distribution::update_metadata<View>, DELETE, origin, view); rmi_flush(); } public: ////////////////////////////////////////////////////////////////////// /// @brief Removes the given @p value from the end of the container. /// /// If a non-null view pointer is provided, initiates an update of the /// view domain at all locations as well. /// /// The pop_back is attempted at the location of current last GID. The method /// calls @ref decreasing_invoke_where which first asks the key mapper for /// the location where GID is supposed to be registered and if it still is, /// it will query the registry at that location for the actual location /// where the GID is stored. Then, @ref pop_back_local will be invoked via /// RMI at that location (or directly if the last GID happens to be stored /// on current location). /// /// If the GID is no longer registered at the managing location, a pop_back /// from a different location already removed it (note that all locations /// initially start from the same GID and their domains are updated /// asynchronously). In this case, the whole process will be repeated with /// GID - 1, until a location with the GID in registry is found or all /// positive GIDs have been used. ////////////////////////////////////////////////////////////////////// template<typename View> void pop_back(View* view) { gid_type gid = this->m_domain.last(); this->directory().decreasing_invoke_where( std::bind( [](p_object& d, location_type src, View* v) { down_cast<vector_distribution&>(d).template pop_back_local<View>( src, v); }, std::placeholders::_1, this->get_location_id(), view), gid); // Update local metadata immediately. // An invalid location id is used to make sure it's different from the // current location id and the domain update isn't skipped. update_metadata(DELETE, invalid_location_id, view); } ////////////////////////////////////////////////////////////////////// /// @brief Helper method to insert the given @p value locally. ////////////////////////////////////////////////////////////////////// void local_push_back(value_type const& value) { this->m_container_manager.push_back(value); } ////////////////////////////////////////////////////////////////////// /// @brief Updates the stored domain to represent a domain with /// @p num_elem number of elements. ////////////////////////////////////////////////////////////////////// void update_domain(size_t num_elem) { if (m_domain.empty()) this->m_domain = domain_type(0, num_elem-1, true); else this->m_domain = domain_type(m_domain.first(), m_domain.last()+num_elem, true); } ////////////////////////////////////////////////////////////////////// /// @brief Method used to update the container's metadata /// (directory's registry, domain) based on the information in /// the base containers. /// @bug Generalize this code to handle arbitrary number of base /// containers with arbitrary domains. Right now only works for /// for one base container per location, with gid strictly increasing /// per location. Related todo in /// @ref vector_container_manager::update_domains. See gforge #1240. ////////////////////////////////////////////////////////////////////// void synchronize_metadata(void) { STAPL_IMPORT_TYPE(typename container_manager_type, iterator) iterator it = this->m_container_manager.begin(); const iterator end_it = this->m_container_manager.end(); const size_t num_local_elements = it == end_it ? 0 : it->domain().size(); size_t nelems = num_local_elements; size_t offset = 0; if (this->get_num_locations() > 1) { typedef static_array<size_t> array_t; array_t psum(this->get_num_locations()); psum[this->get_location_id()] = num_local_elements; array_view<array_t> vpsum(psum); typedef plus<size_t> wf_t; nelems = accumulate(vpsum, (size_t) 0, wf_t()); stapl::partial_sum(vpsum, vpsum, wf_t(), true); offset = vpsum.get_element(this->get_location_id()); } this->m_container_manager.update_domains(offset); this->m_domain = domain_type(nelems); this->directory().reset(); // advance the epoch to ensure no key registrations are received on a // location before the directory on the location is reset. this->advance_epoch(); for (it = this->m_container_manager.begin(); it != end_it; ++it) { this->directory().register_keys( std::make_pair(it->domain().first(), it->domain().last()) ); } base_container_ranking(this->container_manager().m_ordering); } domain_type const& domain(void) const { return m_domain; } iterator find(gid_type index) { return make_iterator(index); } size_t local_size() { return this->container_manager().num_elements(); } size_t size(void) const { return domain().size(); } }; // class vector_distribution } // namespace stapl #endif // STAPL_CONTAINERS_VECTOR_DISTRIBUTION_HPP
35.466558
94
0.581114
[ "vector" ]
fab92f38df8eb12672e96811afb8b15532283385
41,547
cc
C++
ui/gtk/gtk_ui.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/gtk/gtk_ui.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/gtk/gtk_ui.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gtk/gtk_ui.h" #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> #include <pango/pango.h> #include <cmath> #include <memory> #include <set> #include <utility> #include "base/command_line.h" #include "base/containers/flat_map.h" #include "base/debug/leak_annotations.h" #include "base/environment.h" #include "base/logging.h" #include "base/nix/mime_util_xdg.h" #include "base/nix/xdg_util.h" #include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/strings/stringprintf.h" #include "chrome/browser/themes/theme_properties.h" #include "printing/buildflags/buildflags.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkShader.h" #include "ui/base/cursor/cursor_theme_manager_linux_observer.h" #include "ui/base/ime/linux/fake_input_method_context.h" #include "ui/base/ime/linux/linux_input_method_context.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/display/display.h" #include "ui/events/keycodes/dom/dom_code.h" #include "ui/events/keycodes/dom/dom_keyboard_layout_manager.h" #include "ui/events/keycodes/dom/keycode_converter.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font_render_params.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia_source.h" #include "ui/gfx/skbitmap_operations.h" #include "ui/gfx/skia_util.h" #include "ui/gtk/gtk_key_bindings_handler.h" #include "ui/gtk/gtk_ui_delegate.h" #include "ui/gtk/gtk_util.h" #include "ui/gtk/input_method_context_impl_gtk.h" #include "ui/gtk/native_theme_gtk.h" #include "ui/gtk/nav_button_provider_gtk.h" #include "ui/gtk/print_dialog_gtk.h" #include "ui/gtk/printing_gtk_util.h" #include "ui/gtk/select_file_dialog_impl.h" #include "ui/gtk/settings_provider_gtk.h" #include "ui/native_theme/native_theme.h" #include "ui/shell_dialogs/select_file_policy.h" #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/label_button_border.h" #include "ui/views/linux_ui/device_scale_factor_observer.h" #include "ui/views/linux_ui/nav_button_provider.h" #include "ui/views/linux_ui/window_button_order_observer.h" #if defined(USE_GIO) #include "ui/gtk/settings_provider_gsettings.h" #endif #if defined(USE_OZONE) #include "ui/base/ime/input_method.h" #include "ui/ozone/public/ozone_platform.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "printing/printing_context_linux.h" #endif namespace gtk { namespace { // Stores the GtkUi singleton instance const GtkUi* g_gtk_ui = nullptr; const double kDefaultDPI = 96; class GtkButtonImageSource : public gfx::ImageSkiaSource { public: GtkButtonImageSource(bool focus, views::Button::ButtonState button_state, gfx::Size size) : focus_(focus), width_(size.width()), height_(size.height()) { switch (button_state) { case views::Button::ButtonState::STATE_NORMAL: state_ = ui::NativeTheme::kNormal; break; case views::Button::ButtonState::STATE_HOVERED: state_ = ui::NativeTheme::kHovered; break; case views::Button::ButtonState::STATE_PRESSED: state_ = ui::NativeTheme::kPressed; break; case views::Button::ButtonState::STATE_DISABLED: state_ = ui::NativeTheme::kDisabled; break; case views::Button::ButtonState::STATE_COUNT: NOTREACHED(); state_ = ui::NativeTheme::kNormal; break; } } ~GtkButtonImageSource() override = default; gfx::ImageSkiaRep GetImageForScale(float scale) override { int width = width_ * scale; int height = height_ * scale; SkBitmap border; border.allocN32Pixels(width, height); border.eraseColor(0); cairo_surface_t* surface = cairo_image_surface_create_for_data( static_cast<unsigned char*>(border.getAddr(0, 0)), CAIRO_FORMAT_ARGB32, width, height, width * 4); cairo_t* cr = cairo_create(surface); ScopedStyleContext context = GetStyleContextFromCss("GtkButton#button"); GtkStateFlags state_flags = StateToStateFlags(state_); if (focus_) { state_flags = static_cast<GtkStateFlags>(state_flags | GTK_STATE_FLAG_FOCUSED); } gtk_style_context_set_state(context, state_flags); gtk_render_background(context, cr, 0, 0, width, height); gtk_render_frame(context, cr, 0, 0, width, height); if (focus_) { gfx::Rect focus_rect(width, height); #if !GTK_CHECK_VERSION(3, 90, 0) if (!GtkCheckVersion(3, 14)) { gint focus_pad; gtk_style_context_get_style(context, "focus-padding", &focus_pad, nullptr); focus_rect.Inset(focus_pad, focus_pad); if (state_ == ui::NativeTheme::kPressed) { gint child_displacement_x, child_displacement_y; gboolean displace_focus; gtk_style_context_get_style( context, "child-displacement-x", &child_displacement_x, "child-displacement-y", &child_displacement_y, "displace-focus", &displace_focus, nullptr); if (displace_focus) focus_rect.Offset(child_displacement_x, child_displacement_y); } } #endif if (!GtkCheckVersion(3, 20)) { GtkBorder border; #if GTK_CHECK_VERSION(3, 90, 0) gtk_style_context_get_border(context, &border); #else gtk_style_context_get_border(context, state_flags, &border); #endif focus_rect.Inset(border.left, border.top, border.right, border.bottom); } gtk_render_focus(context, cr, focus_rect.x(), focus_rect.y(), focus_rect.width(), focus_rect.height()); } cairo_destroy(cr); cairo_surface_destroy(surface); return gfx::ImageSkiaRep(border, scale); } private: bool focus_; ui::NativeTheme::State state_; int width_; int height_; DISALLOW_COPY_AND_ASSIGN(GtkButtonImageSource); }; class GtkButtonPainter : public views::Painter { public: GtkButtonPainter(bool focus, views::Button::ButtonState button_state) : focus_(focus), button_state_(button_state) {} ~GtkButtonPainter() override = default; gfx::Size GetMinimumSize() const override { return gfx::Size(); } void Paint(gfx::Canvas* canvas, const gfx::Size& size) override { gfx::ImageSkia image( std::make_unique<GtkButtonImageSource>(focus_, button_state_, size), 1); canvas->DrawImageInt(image, 0, 0); } private: const bool focus_; const views::Button::ButtonState button_state_; DISALLOW_COPY_AND_ASSIGN(GtkButtonPainter); }; struct GObjectDeleter { void operator()(void* ptr) { g_object_unref(ptr); } }; struct GtkIconInfoDeleter { void operator()(GtkIconInfo* ptr) { #if GTK_CHECK_VERSION(3, 90, 0) g_object_unref(ptr); #else G_GNUC_BEGIN_IGNORE_DEPRECATIONS gtk_icon_info_free(ptr); G_GNUC_END_IGNORE_DEPRECATIONS #endif } }; typedef std::unique_ptr<GIcon, GObjectDeleter> ScopedGIcon; typedef std::unique_ptr<GtkIconInfo, GtkIconInfoDeleter> ScopedGtkIconInfo; typedef std::unique_ptr<GdkPixbuf, GObjectDeleter> ScopedGdkPixbuf; // Number of app indicators used (used as part of app-indicator id). int indicators_count; // The unknown content type. const char kUnknownContentType[] = "application/octet-stream"; std::unique_ptr<SettingsProvider> CreateSettingsProvider(GtkUi* gtk_ui) { if (GtkCheckVersion(3, 14)) return std::make_unique<SettingsProviderGtk>(gtk_ui); #if defined(USE_GIO) return std::make_unique<SettingsProviderGSettings>(gtk_ui); #else return nullptr; #endif } // Returns a gfx::FontRenderParams corresponding to GTK's configuration. gfx::FontRenderParams GetGtkFontRenderParams() { GtkSettings* gtk_settings = gtk_settings_get_default(); CHECK(gtk_settings); gint antialias = 0; gint hinting = 0; gchar* hint_style = nullptr; gchar* rgba = nullptr; g_object_get(gtk_settings, "gtk-xft-antialias", &antialias, "gtk-xft-hinting", &hinting, "gtk-xft-hintstyle", &hint_style, "gtk-xft-rgba", &rgba, nullptr); gfx::FontRenderParams params; params.antialiasing = antialias != 0; if (hinting == 0 || !hint_style || strcmp(hint_style, "hintnone") == 0) { params.hinting = gfx::FontRenderParams::HINTING_NONE; } else if (strcmp(hint_style, "hintslight") == 0) { params.hinting = gfx::FontRenderParams::HINTING_SLIGHT; } else if (strcmp(hint_style, "hintmedium") == 0) { params.hinting = gfx::FontRenderParams::HINTING_MEDIUM; } else if (strcmp(hint_style, "hintfull") == 0) { params.hinting = gfx::FontRenderParams::HINTING_FULL; } else { LOG(WARNING) << "Unexpected gtk-xft-hintstyle \"" << hint_style << "\""; params.hinting = gfx::FontRenderParams::HINTING_NONE; } if (!rgba || strcmp(rgba, "none") == 0) { params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE; } else if (strcmp(rgba, "rgb") == 0) { params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_RGB; } else if (strcmp(rgba, "bgr") == 0) { params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_BGR; } else if (strcmp(rgba, "vrgb") == 0) { params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VRGB; } else if (strcmp(rgba, "vbgr") == 0) { params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_VBGR; } else { LOG(WARNING) << "Unexpected gtk-xft-rgba \"" << rgba << "\""; params.subpixel_rendering = gfx::FontRenderParams::SUBPIXEL_RENDERING_NONE; } g_free(hint_style); g_free(rgba); return params; } views::LinuxUI::WindowFrameAction GetDefaultMiddleClickAction() { if (GtkCheckVersion(3, 14)) return views::LinuxUI::WindowFrameAction::kNone; std::unique_ptr<base::Environment> env(base::Environment::Create()); switch (base::nix::GetDesktopEnvironment(env.get())) { case base::nix::DESKTOP_ENVIRONMENT_KDE4: case base::nix::DESKTOP_ENVIRONMENT_KDE5: // Starting with KDE 4.4, windows' titlebars can be dragged with the // middle mouse button to create tab groups. We don't support that in // Chrome, but at least avoid lowering windows in response to middle // clicks to avoid surprising users who expect the KDE behavior. return views::LinuxUI::WindowFrameAction::kNone; default: return views::LinuxUI::WindowFrameAction::kLower; } } const SkBitmap GdkPixbufToSkBitmap(GdkPixbuf* pixbuf) { // TODO(erg): What do we do in the case where the pixbuf fails these dchecks? // I would prefer to use our gtk based canvas, but that would require // recompiling half of our skia extensions with gtk support, which we can't // do in this build. DCHECK_EQ(GDK_COLORSPACE_RGB, gdk_pixbuf_get_colorspace(pixbuf)); int n_channels = gdk_pixbuf_get_n_channels(pixbuf); int w = gdk_pixbuf_get_width(pixbuf); int h = gdk_pixbuf_get_height(pixbuf); SkBitmap ret; ret.allocN32Pixels(w, h); ret.eraseColor(0); uint32_t* skia_data = static_cast<uint32_t*>(ret.getAddr(0, 0)); if (n_channels == 4) { int total_length = w * h; guchar* gdk_pixels = gdk_pixbuf_get_pixels(pixbuf); // Now here's the trick: we need to convert the gdk data (which is RGBA and // isn't premultiplied) to skia (which can be anything and premultiplied). for (int i = 0; i < total_length; ++i, gdk_pixels += 4) { const unsigned char& red = gdk_pixels[0]; const unsigned char& green = gdk_pixels[1]; const unsigned char& blue = gdk_pixels[2]; const unsigned char& alpha = gdk_pixels[3]; skia_data[i] = SkPreMultiplyARGB(alpha, red, green, blue); } } else if (n_channels == 3) { // Because GDK makes rowstrides word aligned, we need to do something a bit // more complex when a pixel isn't perfectly a word of memory. int rowstride = gdk_pixbuf_get_rowstride(pixbuf); guchar* gdk_pixels = gdk_pixbuf_get_pixels(pixbuf); for (int y = 0; y < h; ++y) { int row = y * rowstride; for (int x = 0; x < w; ++x) { guchar* pixel = gdk_pixels + row + (x * 3); const unsigned char& red = pixel[0]; const unsigned char& green = pixel[1]; const unsigned char& blue = pixel[2]; skia_data[y * w + x] = SkPreMultiplyARGB(255, red, green, blue); } } } else { NOTREACHED(); } return ret; } } // namespace GtkUi::GtkUi(ui::GtkUiDelegate* delegate) : delegate_(delegate) { using Action = views::LinuxUI::WindowFrameAction; using ActionSource = views::LinuxUI::WindowFrameActionSource; DCHECK(delegate_); DCHECK(!g_gtk_ui); g_gtk_ui = this; window_frame_actions_ = { {ActionSource::kDoubleClick, Action::kToggleMaximize}, {ActionSource::kMiddleClick, GetDefaultMiddleClickAction()}, {ActionSource::kRightClick, Action::kMenu}}; // Avoid GTK initializing atk-bridge, and let AuraLinux implementation // do it once it is ready. std::unique_ptr<base::Environment> env(base::Environment::Create()); env->SetVar("NO_AT_BRIDGE", "1"); GtkInitFromCommandLine(*base::CommandLine::ForCurrentProcess()); native_theme_ = NativeThemeGtk::instance(); fake_window_ = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_widget_realize(fake_window_); } GtkUi::~GtkUi() { gtk_widget_destroy(fake_window_); g_gtk_ui = nullptr; } ui::GtkUiDelegate* GtkUi::GetDelegate() { DCHECK(g_gtk_ui) << "GtkUi instance is not set."; return g_gtk_ui->delegate_; } void GtkUi::Initialize() { #if defined(USE_OZONE) // Linux ozone platforms may want to set LinuxInputMethodContextFactory // instance instead of using GtkUi context factory. This step is made upon // CreateInputMethod call. If the factory is not set, use the GtkUi context // factory. if (!ui::OzonePlatform::GetInstance()->CreateInputMethod( nullptr, gfx::kNullAcceleratedWidget)) { DCHECK(!ui::LinuxInputMethodContextFactory::instance()); ui::LinuxInputMethodContextFactory::SetInstance(this); } #endif GtkSettings* settings = gtk_settings_get_default(); g_signal_connect_after(settings, "notify::gtk-theme-name", G_CALLBACK(OnThemeChangedThunk), this); g_signal_connect_after(settings, "notify::gtk-icon-theme-name", G_CALLBACK(OnThemeChangedThunk), this); g_signal_connect_after(settings, "notify::gtk-application-prefer-dark-theme", G_CALLBACK(OnThemeChangedThunk), this); g_signal_connect_after(settings, "notify::gtk-cursor-theme-name", G_CALLBACK(OnCursorThemeNameChangedThunk), this); g_signal_connect_after(settings, "notify::gtk-cursor-theme-size", G_CALLBACK(OnCursorThemeSizeChangedThunk), this); GdkScreen* screen = gdk_screen_get_default(); // Listen for DPI changes. g_signal_connect_after(screen, "notify::resolution", G_CALLBACK(OnDeviceScaleFactorMaybeChangedThunk), this); // Listen for scale factor changes. We would prefer to listen on // |screen|, but there is no scale-factor property, so use an // unmapped window instead. g_signal_connect(fake_window_, "notify::scale-factor", G_CALLBACK(OnDeviceScaleFactorMaybeChangedThunk), this); LoadGtkValues(); #if BUILDFLAG(ENABLE_PRINTING) printing::PrintingContextLinux::SetCreatePrintDialogFunction( &PrintDialogGtk::CreatePrintDialog); printing::PrintingContextLinux::SetPdfPaperSizeFunction( &GetPdfPaperSizeDeviceUnitsGtk); #endif // We must build this after GTK gets initialized. settings_provider_ = CreateSettingsProvider(this); indicators_count = 0; GetDelegate()->OnInitialized(); } bool GtkUi::GetTint(int id, color_utils::HSL* tint) const { switch (id) { // Tints for which the cross-platform default is fine. Before adding new // values here, specifically verify they work well on Linux. case ThemeProperties::TINT_BACKGROUND_TAB: // TODO(estade): Return something useful for TINT_BUTTONS so that chrome:// // page icons are colored appropriately. case ThemeProperties::TINT_BUTTONS: break; default: // Assume any tints not specifically verified on Linux aren't usable. // TODO(pkasting): Try to remove values from |colors_| that could just be // added to the group above instead. NOTREACHED(); } return false; } bool GtkUi::GetColor(int id, SkColor* color, bool use_custom_frame) const { for (const ColorMap& color_map : {colors_, use_custom_frame ? custom_frame_colors_ : native_frame_colors_}) { auto it = color_map.find(id); if (it != color_map.end()) { *color = it->second; return true; } } return false; } bool GtkUi::GetDisplayProperty(int id, int* result) const { if (id == ThemeProperties::SHOULD_FILL_BACKGROUND_TAB_COLOR) { *result = 0; return true; } return false; } SkColor GtkUi::GetFocusRingColor() const { return focus_ring_color_; } SkColor GtkUi::GetActiveSelectionBgColor() const { return active_selection_bg_color_; } SkColor GtkUi::GetActiveSelectionFgColor() const { return active_selection_fg_color_; } SkColor GtkUi::GetInactiveSelectionBgColor() const { return inactive_selection_bg_color_; } SkColor GtkUi::GetInactiveSelectionFgColor() const { return inactive_selection_fg_color_; } base::TimeDelta GtkUi::GetCursorBlinkInterval() const { // From http://library.gnome.org/devel/gtk/unstable/GtkSettings.html, this is // the default value for gtk-cursor-blink-time. static const gint kGtkDefaultCursorBlinkTime = 1200; // Dividing GTK's cursor blink cycle time (in milliseconds) by this value // yields an appropriate value for // blink::mojom::RendererPreferences::caret_blink_interval. static const double kGtkCursorBlinkCycleFactor = 2000.0; gint cursor_blink_time = kGtkDefaultCursorBlinkTime; gboolean cursor_blink = TRUE; g_object_get(gtk_settings_get_default(), "gtk-cursor-blink-time", &cursor_blink_time, "gtk-cursor-blink", &cursor_blink, nullptr); return cursor_blink ? base::TimeDelta::FromSecondsD( cursor_blink_time / kGtkCursorBlinkCycleFactor) : base::TimeDelta(); } ui::NativeTheme* GtkUi::GetNativeTheme(aura::Window* window) const { return (use_system_theme_callback_.is_null() || use_system_theme_callback_.Run(window)) ? native_theme_ : ui::NativeTheme::GetInstanceForNativeUi(); } void GtkUi::SetUseSystemThemeCallback(UseSystemThemeCallback callback) { use_system_theme_callback_ = std::move(callback); } bool GtkUi::GetDefaultUsesSystemTheme() const { std::unique_ptr<base::Environment> env(base::Environment::Create()); switch (base::nix::GetDesktopEnvironment(env.get())) { case base::nix::DESKTOP_ENVIRONMENT_CINNAMON: case base::nix::DESKTOP_ENVIRONMENT_GNOME: case base::nix::DESKTOP_ENVIRONMENT_PANTHEON: case base::nix::DESKTOP_ENVIRONMENT_UNITY: case base::nix::DESKTOP_ENVIRONMENT_XFCE: return true; case base::nix::DESKTOP_ENVIRONMENT_KDE3: case base::nix::DESKTOP_ENVIRONMENT_KDE4: case base::nix::DESKTOP_ENVIRONMENT_KDE5: case base::nix::DESKTOP_ENVIRONMENT_OTHER: return false; } // Unless GetDesktopEnvironment() badly misbehaves, this should never happen. NOTREACHED(); return false; } gfx::Image GtkUi::GetIconForContentType(const std::string& content_type, int size) const { // This call doesn't take a reference. GtkIconTheme* theme = gtk_icon_theme_get_default(); std::string content_types[] = {content_type, kUnknownContentType}; for (size_t i = 0; i < base::size(content_types); ++i) { ScopedGIcon icon(g_content_type_get_icon(content_types[i].c_str())); ScopedGtkIconInfo icon_info(gtk_icon_theme_lookup_by_gicon( theme, icon.get(), size, static_cast<GtkIconLookupFlags>(GTK_ICON_LOOKUP_FORCE_SIZE))); if (!icon_info) continue; ScopedGdkPixbuf pixbuf(gtk_icon_info_load_icon(icon_info.get(), nullptr)); if (!pixbuf) continue; SkBitmap bitmap = GdkPixbufToSkBitmap(pixbuf.get()); DCHECK_EQ(size, bitmap.width()); DCHECK_EQ(size, bitmap.height()); gfx::ImageSkia image_skia = gfx::ImageSkia::CreateFrom1xBitmap(bitmap); image_skia.MakeThreadSafe(); return gfx::Image(image_skia); } return gfx::Image(); } std::unique_ptr<views::Border> GtkUi::CreateNativeBorder( views::LabelButton* owning_button, std::unique_ptr<views::LabelButtonBorder> border) { if (owning_button->GetNativeTheme() != native_theme_) return std::move(border); auto gtk_border = std::make_unique<views::LabelButtonAssetBorder>(); gtk_border->set_insets(border->GetInsets()); constexpr bool kFocus = true; static struct { bool focus; views::Button::ButtonState state; } const paintstate[] = { {!kFocus, views::Button::STATE_NORMAL}, {!kFocus, views::Button::STATE_HOVERED}, {!kFocus, views::Button::STATE_PRESSED}, {!kFocus, views::Button::STATE_DISABLED}, {kFocus, views::Button::STATE_NORMAL}, {kFocus, views::Button::STATE_HOVERED}, {kFocus, views::Button::STATE_PRESSED}, {kFocus, views::Button::STATE_DISABLED}, }; for (unsigned i = 0; i < base::size(paintstate); i++) { gtk_border->SetPainter( paintstate[i].focus, paintstate[i].state, border->PaintsButtonState(paintstate[i].focus, paintstate[i].state) ? std::make_unique<GtkButtonPainter>(paintstate[i].focus, paintstate[i].state) : nullptr); } return std::move(gtk_border); } void GtkUi::AddWindowButtonOrderObserver( views::WindowButtonOrderObserver* observer) { if (nav_buttons_set_) observer->OnWindowButtonOrderingChange(leading_buttons_, trailing_buttons_); window_button_order_observer_list_.AddObserver(observer); } void GtkUi::RemoveWindowButtonOrderObserver( views::WindowButtonOrderObserver* observer) { window_button_order_observer_list_.RemoveObserver(observer); } void GtkUi::SetWindowButtonOrdering( const std::vector<views::FrameButton>& leading_buttons, const std::vector<views::FrameButton>& trailing_buttons) { leading_buttons_ = leading_buttons; trailing_buttons_ = trailing_buttons; nav_buttons_set_ = true; for (views::WindowButtonOrderObserver& observer : window_button_order_observer_list_) { observer.OnWindowButtonOrderingChange(leading_buttons_, trailing_buttons_); } } void GtkUi::SetWindowFrameAction(WindowFrameActionSource source, WindowFrameAction action) { window_frame_actions_[source] = action; } std::unique_ptr<ui::LinuxInputMethodContext> GtkUi::CreateInputMethodContext( ui::LinuxInputMethodContextDelegate* delegate, bool is_simple) const { return std::make_unique<InputMethodContextImplGtk>(delegate, is_simple); } gfx::FontRenderParams GtkUi::GetDefaultFontRenderParams() const { static gfx::FontRenderParams params = GetGtkFontRenderParams(); return params; } void GtkUi::GetDefaultFontDescription(std::string* family_out, int* size_pixels_out, int* style_out, gfx::Font::Weight* weight_out, gfx::FontRenderParams* params_out) const { *family_out = default_font_family_; *size_pixels_out = default_font_size_pixels_; *style_out = default_font_style_; *weight_out = default_font_weight_; *params_out = default_font_render_params_; } ui::SelectFileDialog* GtkUi::CreateSelectFileDialog( ui::SelectFileDialog::Listener* listener, std::unique_ptr<ui::SelectFilePolicy> policy) const { return SelectFileDialogImpl::Create(listener, std::move(policy)); } views::LinuxUI::WindowFrameAction GtkUi::GetWindowFrameAction( WindowFrameActionSource source) { return window_frame_actions_[source]; } void GtkUi::NotifyWindowManagerStartupComplete() { // TODO(port) Implement this using _NET_STARTUP_INFO_BEGIN/_NET_STARTUP_INFO // from http://standards.freedesktop.org/startup-notification-spec/ instead. gdk_notify_startup_complete(); } void GtkUi::AddDeviceScaleFactorObserver( views::DeviceScaleFactorObserver* observer) { device_scale_factor_observer_list_.AddObserver(observer); } void GtkUi::RemoveDeviceScaleFactorObserver( views::DeviceScaleFactorObserver* observer) { device_scale_factor_observer_list_.RemoveObserver(observer); } bool GtkUi::PreferDarkTheme() const { gboolean dark = false; g_object_get(gtk_settings_get_default(), "gtk-application-prefer-dark-theme", &dark, nullptr); return dark; } bool GtkUi::AnimationsEnabled() const { gboolean animations_enabled = false; g_object_get(gtk_settings_get_default(), "gtk-enable-animations", &animations_enabled, nullptr); return animations_enabled; } std::unique_ptr<views::NavButtonProvider> GtkUi::CreateNavButtonProvider() { if (GtkCheckVersion(3, 14)) return std::make_unique<gtk::NavButtonProviderGtk>(); return nullptr; } // Mapping from GDK dead keys to corresponding printable character. static struct { guint gdk_key; guint16 unicode; } kDeadKeyMapping[] = { {GDK_KEY_dead_grave, 0x0060}, {GDK_KEY_dead_acute, 0x0027}, {GDK_KEY_dead_circumflex, 0x005e}, {GDK_KEY_dead_tilde, 0x007e}, {GDK_KEY_dead_diaeresis, 0x00a8}, }; base::flat_map<std::string, std::string> GtkUi::GetKeyboardLayoutMap() { GdkDisplay* display = gdk_display_get_default(); GdkKeymap* keymap = gdk_keymap_get_for_display(display); if (!keymap) return {}; ui::DomKeyboardLayoutManager* layouts = new ui::DomKeyboardLayoutManager(); auto map = base::flat_map<std::string, std::string>(); for (unsigned int i_domcode = 0; i_domcode < ui::kWritingSystemKeyDomCodeEntries; ++i_domcode) { ui::DomCode domcode = ui::writing_system_key_domcodes[i_domcode]; guint16 keycode = ui::KeycodeConverter::DomCodeToNativeKeycode(domcode); GdkKeymapKey* keys = nullptr; guint* keyvals = nullptr; gint n_entries = 0; // The order of the layouts is based on the system default ordering in // Keyboard Settings. The currently active layout does not affect this // order. if (gdk_keymap_get_entries_for_keycode(keymap, keycode, &keys, &keyvals, &n_entries)) { for (gint i = 0; i < n_entries; ++i) { // There are 4 entries per layout group, one each for shift level 0..3. // We only care about the unshifted values (level = 0). if (keys[i].level == 0) { uint16_t unicode = gdk_keyval_to_unicode(keyvals[i]); if (unicode == 0) { for (unsigned int i_dead = 0; i_dead < base::size(kDeadKeyMapping); ++i_dead) { if (keyvals[i] == kDeadKeyMapping[i_dead].gdk_key) unicode = kDeadKeyMapping[i_dead].unicode; } } if (unicode != 0) layouts->GetLayout(keys[i].group)->AddKeyMapping(domcode, unicode); } } } g_free(keys); keys = nullptr; g_free(keyvals); keyvals = nullptr; } return layouts->GetFirstAsciiCapableLayout()->GetMap(); } std::string GtkUi::GetCursorThemeName() { gchar* theme = nullptr; g_object_get(gtk_settings_get_default(), "gtk-cursor-theme-name", &theme, nullptr); std::string theme_string; if (theme) { theme_string = theme; g_free(theme); } return theme_string; } int GtkUi::GetCursorThemeSize() { gint size = 0; g_object_get(gtk_settings_get_default(), "gtk-cursor-theme-size", &size, nullptr); return size; } bool GtkUi::MatchEvent(const ui::Event& event, std::vector<ui::TextEditCommandAuraLinux>* commands) { // TODO(crbug.com/963419): Use delegate's |GetGdkKeymap| here to // determine if GtkUi's key binding handling implementation is used or not. // Ozone/Wayland was unintentionally using GtkUi for keybinding handling, so // early out here, for now, until a proper solution for ozone is implemented. if (!GetDelegate()->GetGdkKeymap()) return false; // Ensure that we have a keyboard handler. if (!key_bindings_handler_) key_bindings_handler_ = std::make_unique<GtkKeyBindingsHandler>(); return key_bindings_handler_->MatchEvent(event, commands); } void GtkUi::OnThemeChanged(GtkSettings* settings, GtkParamSpec* param) { colors_.clear(); custom_frame_colors_.clear(); native_frame_colors_.clear(); native_theme_->OnThemeChanged(settings, param); LoadGtkValues(); native_theme_->NotifyObservers(); } void GtkUi::OnCursorThemeNameChanged(GtkSettings* settings, GtkParamSpec* param) { std::string cursor_theme_name = GetCursorThemeName(); if (cursor_theme_name.empty()) return; for (auto& observer : cursor_theme_observers()) observer.OnCursorThemeNameChanged(cursor_theme_name); } void GtkUi::OnCursorThemeSizeChanged(GtkSettings* settings, GtkParamSpec* param) { int cursor_theme_size = GetCursorThemeSize(); if (!cursor_theme_size) return; for (auto& observer : cursor_theme_observers()) observer.OnCursorThemeSizeChanged(cursor_theme_size); } void GtkUi::OnDeviceScaleFactorMaybeChanged(void*, GParamSpec*) { UpdateDeviceScaleFactor(); } void GtkUi::LoadGtkValues() { // TODO(thomasanderson): GtkThemeService had a comment here about having to // muck with the raw Prefs object to remove prefs::kCurrentThemeImages or else // we'd regress startup time. Figure out how to do that when we can't access // the prefs system from here. UpdateDeviceScaleFactor(); UpdateColors(); } void GtkUi::UpdateColors() { SkColor location_bar_border = GetBorderColor("GtkEntry#entry"); if (SkColorGetA(location_bar_border)) colors_[ThemeProperties::COLOR_LOCATION_BAR_BORDER] = location_bar_border; inactive_selection_bg_color_ = GetSelectionBgColor( GtkCheckVersion(3, 20) ? "GtkTextView#textview.view:backdrop " "#text:backdrop #selection:backdrop" : "GtkTextView.view:selected:backdrop"); inactive_selection_fg_color_ = GetFgColor(GtkCheckVersion(3, 20) ? "GtkTextView#textview.view:backdrop " "#text:backdrop #selection:backdrop" : "GtkTextView.view:selected:backdrop"); SkColor tab_border = GetBorderColor("GtkButton#button"); // Separates the toolbar from the bookmark bar or butter bars. colors_[ThemeProperties::COLOR_TOOLBAR_CONTENT_AREA_SEPARATOR] = tab_border; // Separates entries in the downloads bar. colors_[ThemeProperties::COLOR_TOOLBAR_VERTICAL_SEPARATOR] = tab_border; colors_[ThemeProperties::COLOR_NTP_BACKGROUND] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldDefaultBackground); colors_[ThemeProperties::COLOR_NTP_TEXT] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldDefaultColor); colors_[ThemeProperties::COLOR_NTP_HEADER] = GetBorderColor("GtkButton#button"); SkColor tab_text_color = GetFgColor("GtkLabel"); colors_[ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON] = tab_text_color; colors_[ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON_HOVERED] = tab_text_color; colors_[ThemeProperties::COLOR_TOOLBAR_BUTTON_ICON_PRESSED] = tab_text_color; colors_[ThemeProperties::COLOR_TAB_FOREGROUND_ACTIVE_FRAME_ACTIVE] = tab_text_color; colors_[ThemeProperties::COLOR_TAB_FOREGROUND_ACTIVE_FRAME_INACTIVE] = tab_text_color; colors_[ThemeProperties::COLOR_BOOKMARK_TEXT] = tab_text_color; colors_[ThemeProperties::COLOR_NTP_LINK] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused); // Generate the colors that we pass to Blink. focus_ring_color_ = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_FocusedBorderColor); // Some GTK themes only define the text selection colors on the GtkEntry // class, so we need to use that for getting selection colors. active_selection_bg_color_ = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused); active_selection_fg_color_ = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldSelectionColor); colors_[ThemeProperties::COLOR_TAB_THROBBER_SPINNING] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_ThrobberSpinningColor); colors_[ThemeProperties::COLOR_TAB_THROBBER_WAITING] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_ThrobberWaitingColor); // Generate colors that depend on whether or not a custom window frame is // used. These colors belong in |color_map| below, not |colors_|. for (bool custom_frame : {false, true}) { ColorMap& color_map = custom_frame ? custom_frame_colors_ : native_frame_colors_; const std::string header_selector = custom_frame ? "#headerbar.header-bar.titlebar" : "GtkMenuBar#menubar"; const std::string header_selector_inactive = header_selector + ":backdrop"; const SkColor frame_color = SkColorSetA(GetBgColor(header_selector), SK_AlphaOPAQUE); const SkColor frame_color_incognito = color_utils::HSLShift(frame_color, kDefaultTintFrameIncognito); const SkColor frame_color_inactive = SkColorSetA(GetBgColor(header_selector_inactive), SK_AlphaOPAQUE); const SkColor frame_color_incognito_inactive = color_utils::HSLShift(frame_color_inactive, kDefaultTintFrameIncognito); color_map[ThemeProperties::COLOR_FRAME_ACTIVE] = frame_color; color_map[ThemeProperties::COLOR_FRAME_INACTIVE] = frame_color_inactive; color_map[ThemeProperties::COLOR_FRAME_ACTIVE_INCOGNITO] = frame_color_incognito; color_map[ThemeProperties::COLOR_FRAME_INACTIVE_INCOGNITO] = frame_color_incognito_inactive; // Compose the window color on the frame color to ensure the resulting tab // color is opaque. SkColor tab_color = color_utils::GetResultingPaintColor(GetBgColor(""), frame_color); color_map[ThemeProperties::COLOR_TOOLBAR] = tab_color; color_map[ThemeProperties::COLOR_DOWNLOAD_SHELF] = tab_color; color_map[ThemeProperties::COLOR_INFOBAR] = tab_color; color_map[ThemeProperties::COLOR_STATUS_BUBBLE] = tab_color; color_map[ThemeProperties::COLOR_TAB_BACKGROUND_ACTIVE_FRAME_ACTIVE] = tab_color; color_map[ThemeProperties::COLOR_TAB_BACKGROUND_ACTIVE_FRAME_INACTIVE] = tab_color; const SkColor background_tab_text_color = GetFgColor(header_selector + " GtkLabel.title"); const SkColor background_tab_text_color_inactive = GetFgColor(header_selector_inactive + " GtkLabel.title"); color_map[ThemeProperties::COLOR_TAB_FOREGROUND_INACTIVE_FRAME_ACTIVE] = background_tab_text_color; color_map[ThemeProperties:: COLOR_TAB_FOREGROUND_INACTIVE_FRAME_ACTIVE_INCOGNITO] = color_utils::BlendForMinContrast( color_utils::HSLShift(background_tab_text_color, kDefaultTintFrameIncognito), frame_color_incognito) .color; color_map[ThemeProperties::COLOR_TAB_FOREGROUND_INACTIVE_FRAME_INACTIVE] = background_tab_text_color_inactive; color_map[ThemeProperties:: COLOR_TAB_FOREGROUND_INACTIVE_FRAME_INACTIVE_INCOGNITO] = color_utils::BlendForMinContrast( color_utils::HSLShift(background_tab_text_color_inactive, kDefaultTintFrameIncognito), frame_color_incognito_inactive) .color; color_map[ThemeProperties::COLOR_OMNIBOX_TEXT] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldDefaultColor); color_map[ThemeProperties::COLOR_OMNIBOX_BACKGROUND] = native_theme_->GetSystemColor( ui::NativeTheme::kColorId_TextfieldDefaultBackground); // These colors represent the border drawn around tabs and between // the tabstrip and toolbar. SkColor toolbar_top_separator = GetBorderColor( header_selector + " GtkSeparator#separator.vertical.titlebutton"); SkColor toolbar_top_separator_inactive = GetBorderColor(header_selector + ":backdrop GtkSeparator#separator.vertical.titlebutton"); auto toolbar_top_separator_has_good_contrast = [&]() { // This constant is copied from chrome/browser/themes/theme_service.cc. const float kMinContrastRatio = 2.f; SkColor active = color_utils::GetResultingPaintColor( toolbar_top_separator, frame_color); SkColor inactive = color_utils::GetResultingPaintColor( toolbar_top_separator_inactive, frame_color_inactive); return color_utils::GetContrastRatio(frame_color, active) >= kMinContrastRatio && color_utils::GetContrastRatio(frame_color_inactive, inactive) >= kMinContrastRatio; }; if (!toolbar_top_separator_has_good_contrast()) { toolbar_top_separator = GetBorderColor(header_selector + " GtkButton#button"); toolbar_top_separator_inactive = GetBorderColor(header_selector + ":backdrop GtkButton#button"); } // If we can't get a contrasting stroke from the theme, have ThemeService // provide a stroke color for us. if (toolbar_top_separator_has_good_contrast()) { color_map[ThemeProperties::COLOR_TOOLBAR_TOP_SEPARATOR] = toolbar_top_separator; color_map[ThemeProperties::COLOR_TOOLBAR_TOP_SEPARATOR_INACTIVE] = toolbar_top_separator_inactive; } } } void GtkUi::UpdateDefaultFont() { gfx::SetFontRenderParamsDeviceScaleFactor(device_scale_factor_); GtkWidget* fake_label = gtk_label_new(nullptr); g_object_ref_sink(fake_label); // Remove the floating reference. PangoContext* pc = gtk_widget_get_pango_context(fake_label); const PangoFontDescription* desc = pango_context_get_font_description(pc); // Use gfx::FontRenderParams to select a family and determine the rendering // settings. gfx::FontRenderParamsQuery query; query.families = base::SplitString(pango_font_description_get_family(desc), ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); if (pango_font_description_get_size_is_absolute(desc)) { // If the size is absolute, it's specified in Pango units. There are // PANGO_SCALE Pango units in a device unit (pixel). const int size_pixels = pango_font_description_get_size(desc) / PANGO_SCALE; default_font_size_pixels_ = size_pixels; query.pixel_size = size_pixels; } else { // Non-absolute sizes are in points (again scaled by PANGO_SIZE). // Round the value when converting to pixels to match GTK's logic. const double size_points = pango_font_description_get_size(desc) / static_cast<double>(PANGO_SCALE); default_font_size_pixels_ = static_cast<int>(kDefaultDPI / 72.0 * size_points + 0.5); query.point_size = static_cast<int>(size_points); } query.style = gfx::Font::NORMAL; query.weight = static_cast<gfx::Font::Weight>(pango_font_description_get_weight(desc)); // TODO(davemoore): What about PANGO_STYLE_OBLIQUE? if (pango_font_description_get_style(desc) == PANGO_STYLE_ITALIC) query.style |= gfx::Font::ITALIC; default_font_render_params_ = gfx::GetFontRenderParams(query, &default_font_family_); default_font_style_ = query.style; gtk_widget_destroy(fake_label); g_object_unref(fake_label); } float GtkUi::GetRawDeviceScaleFactor() { if (display::Display::HasForceDeviceScaleFactor()) return display::Display::GetForcedDeviceScaleFactor(); GdkScreen* screen = gdk_screen_get_default(); float scale = gtk_widget_get_scale_factor(fake_window_); DCHECK_GT(scale, 0.0); gdouble resolution = gdk_screen_get_resolution(screen); // TODO(https://crbug.com/1033552): Remove this hack once the Trusty bots are // fixed to have a resolution of 96, or when the Trusty bots are removed // altogether. if (std::abs(resolution - 95.8486) < 0.001) resolution = 96; if (resolution > 0) scale *= resolution / kDefaultDPI; return scale; } void GtkUi::UpdateDeviceScaleFactor() { float old_device_scale_factor = device_scale_factor_; device_scale_factor_ = GetRawDeviceScaleFactor(); if (device_scale_factor_ != old_device_scale_factor) { for (views::DeviceScaleFactorObserver& observer : device_scale_factor_observer_list_) { observer.OnDeviceScaleFactorChanged(); } } UpdateDefaultFont(); } float GtkUi::GetDeviceScaleFactor() const { return device_scale_factor_; } } // namespace gtk views::LinuxUI* BuildGtkUi(ui::GtkUiDelegate* delegate) { return new gtk::GtkUi(delegate); }
37.128686
80
0.714636
[ "geometry", "object", "vector" ]
fab96c5a478b50057a659b5085f56e8059fc555e
14,260
cpp
C++
innative/tools.cpp
elliott-wen/innative
4fb456876d75fea2d3bf2b69dc1372efc710477e
[ "Apache-2.0" ]
null
null
null
innative/tools.cpp
elliott-wen/innative
4fb456876d75fea2d3bf2b69dc1372efc710477e
[ "Apache-2.0" ]
null
null
null
innative/tools.cpp
elliott-wen/innative
4fb456876d75fea2d3bf2b69dc1372efc710477e
[ "Apache-2.0" ]
null
null
null
// Copyright (c)2019 Black Sphere Studios // For conditions of distribution and use, see copyright notice in innative.h #include "parse.h" #include "validate.h" #include "compile.h" #include "link.h" #include "tools.h" #include "wast.h" #include "serialize.h" #include <atomic> #include <thread> #include <fstream> #include <stdio.h> #include <sstream> using namespace innative; using namespace utility; Environment* innative::CreateEnvironment(unsigned int modules, unsigned int maxthreads, const char* arg0) { Environment* env = (Environment*)calloc(1, sizeof(Environment)); if(env) { env->modulemap = kh_init_modules(); env->whitelist = kh_init_modulepair(); env->cimports = kh_init_cimport(); env->modules = trealloc<Module>(0, modules); env->alloc = new IN_WASM_ALLOCATOR(); if(!env->modules) { free(env); return nullptr; } env->capacity = modules; env->flags = ENV_SANDBOX; env->optimize = ENV_OPTIMIZE_O3; env->features = ENV_FEATURE_ALL; env->maxthreads = maxthreads; env->linker = 0; env->log = stdout; env->loglevel = LOG_WARNING; env->rootpath = utility::AllocString(*env, GetProgramPath(arg0).parent_path().u8string()); env->libpath = env->rootpath; if(!env->libpath) // Out of memory { free(env); return nullptr; } env->objpath = 0; env->system = ""; env->wasthook = 0; } return env; } void innative::ClearEnvironmentCache(Environment* env, Module* m) { assert(env != nullptr); if(m) DeleteCache(*env, *m); else DeleteContext(*env, false); // We can't actually shutdown LLVM here because that permanently shuts it down and // there is no way to restore it. } void innative::DestroyEnvironment(Environment* env) { if(!env) return; ClearEnvironmentCache(env, 0); for(varuint32 i = 0; i < env->n_modules; ++i) { kh_destroy_exports(env->modules[i].exports); assert(!env->modules[i].cache); } delete env->alloc; kh_destroy_modulepair(env->whitelist); kh_destroy_modules(env->modulemap); kh_destroy_cimport(env->cimports); free(env->modules); free(env); } void innative::LoadModule(Environment* env, size_t index, const void* data, uint64_t size, const char* name, const char* file, int* err) { Stream s = { (uint8_t*)data, (size_t)size, 0 }; std::string fallback; if(!name) { fallback = "m" + std::to_string(index); name = fallback.data(); } if((env->flags & ENV_ENABLE_WAT) && size > 0 && s.data[0] != 0) { env->modules[index] = { 0 }; *err = innative::ParseWatModule(*env, env->modules[index], s.data, (size_t)size, StringRef{ name, strlen(name) }); } else *err = ParseModule(s, *env, env->modules[index], ByteArray((uint8_t*)name, (varuint32)strlen(name)), env->errors); env->modules[index].path = utility::AllocString(*env, file); ((std::atomic<size_t>&)env->n_modules).fetch_add(1, std::memory_order_release); } void innative::AddModule(Environment* env, const void* data, uint64_t size, const char* name, int* err) { if(!env || !err) { *err = ERR_FATAL_NULL_POINTER; return; } const char* file = nullptr; std::unique_ptr<uint8_t[]> data_module; if(!size) { long sz = 0; file = (const char*)data; data_module = utility::LoadFile(file, sz); if(data_module.get() == nullptr) { *err = ERR_FATAL_FILE_ERROR; return; } size = sz; data = data_module.get(); } if((env->flags & ENV_MULTITHREADED) != 0 && env->maxthreads > 0) { while(((std::atomic<size_t>&)env->size).load(std::memory_order_relaxed) - ((std::atomic<size_t>&)env->n_modules).load(std::memory_order_relaxed) >= env->maxthreads) std::this_thread::sleep_for(std::chrono::milliseconds( 2)); // If we're using maxthreads, block until one finishes (we must block up here or we risk a deadlock) } size_t index = ((std::atomic<size_t>&)env->size).fetch_add(1, std::memory_order_acq_rel); if(index >= ((std::atomic<size_t>&)env->capacity).load(std::memory_order_acquire)) { while(((std::atomic<size_t>&)env->n_modules).load(std::memory_order_relaxed) != index) std::this_thread::sleep_for( std::chrono::milliseconds(5)); // If we've exceeded our capacity, block until all other threads have finished env->modules = trealloc<Module>(env->modules, index * 2); if(!env->modules) { *err = ERR_FATAL_OUT_OF_MEMORY; return; } ((std::atomic<size_t>&)env->capacity).store(index * 2, std::memory_order_release); } if(env->flags & ENV_MULTITHREADED) std::thread(LoadModule, env, index, data, size, name, file, err).detach(); else LoadModule(env, index, data, size, name, file, err); } IN_ERROR innative::AddWhitelist(Environment* env, const char* module_name, const char* export_name) { if(!export_name) return ERR_PARSE_INVALID_NAME; char* whitelist = tmalloc<char>(*env, CanonWhitelist(module_name, export_name, env->system, nullptr)); if(!whitelist) return ERR_FATAL_OUT_OF_MEMORY; CanonWhitelist(module_name, export_name, env->system, whitelist); int r; auto iter = kh_put_modulepair(env->whitelist, whitelist, &r); // kh_val(env->whitelist, iter) = !ftype ? FunctionType{ TE_NONE, 0, 0, 0, 0 } : *ftype; return ERR_SUCCESS; } IN_ERROR innative::AddEmbedding(Environment* env, int tag, const void* data, uint64_t size) { if(!env) return ERR_FATAL_NULL_POINTER; Embedding* embed = tmalloc<Embedding>(*env, 1); if(!embed) return ERR_FATAL_OUT_OF_MEMORY; embed->tag = tag; embed->data = data; embed->size = size; embed->next = env->embeddings; env->embeddings = embed; return ERR_SUCCESS; } IN_ERROR innative::FinalizeEnvironment(Environment* env) { if(env->cimports) { for(Embedding* embed = env->embeddings; embed != nullptr; embed = embed->next) { std::vector<std::string> symbols; #ifdef IN_PLATFORM_WIN32 LLD_FORMAT format = LLD_FORMAT::COFF; #else LLD_FORMAT format = LLD_FORMAT::ELF; #endif if(embed->size) symbols = GetSymbols((const char*)embed->data, (size_t)embed->size, env->log, format); else { auto testpath = [](FILE* f, const path& file, path& out) -> FILE* { if(!f) { out = file; FOPEN(f, out.c_str(), "rb"); } return f; }; path envpath(utility::GetPath(env->libpath)); path rootpath(utility::GetPath(env->rootpath)); path src(utility::GetPath((const char*)embed->data)); path out; FILE* f = 0; f = testpath(f, envpath / src, out); f = testpath(f, src, out); f = testpath(f, rootpath / src, out); #ifdef IN_PLATFORM_POSIX if(CURRENT_ARCH_BITS == 64) f = testpath(f, rootpath.parent_path() / "lib64" / src, out); f = testpath(f, rootpath.parent_path() / "lib" / src, out); if(CURRENT_ARCH_BITS == 64) f = testpath(f, path("/usr/lib64/") / src, out); f = testpath(f, path("/usr/lib/") / src, out); #endif if(!f) { fprintf(env->log, "Error loading file: %s\n", src.u8string().c_str()); return ERR_FATAL_FILE_ERROR; } fclose(f); std::string buf = out.u8string(); char* tmp = tmalloc<char>(*env, buf.size() + 1); if(!tmp) return ERR_FATAL_OUT_OF_MEMORY; tmemcpy<char>(tmp, buf.size() + 1, buf.c_str(), buf.size() + 1); embed->data = tmp; symbols = GetSymbols(out.u8string().c_str(), 0, env->log, format); } int r; for(auto symbol : symbols) { Identifier id; id.resize((varuint32)symbol.size(), true, *env); if(!id.get() || symbol.size() > std::numeric_limits<varuint32>::max()) return ERR_FATAL_OUT_OF_MEMORY; memcpy(id.get(), symbol.data(), symbol.size()); kh_put_cimport(env->cimports, id, &r); // On windows, because .lib files map to DLLs, they can have duplicate symbols from the dependent DLLs // that the DLL itself depends on. As a result, we cannot enforce this check until the linker resolves the symbols. #ifndef IN_PLATFORM_WIN32 if(!r) return ERR_INVALID_EMBEDDING; #endif } } } while(((std::atomic<size_t>&)env->size).load(std::memory_order_relaxed) > ((std::atomic<size_t>&)env->n_modules).load(std::memory_order_relaxed)) std::this_thread::sleep_for(std::chrono::milliseconds(5)); // Spin until all modules have loaded return ERR_SUCCESS; } IN_ERROR innative::Validate(Environment* env) { if(!env) return ERR_FATAL_NULL_POINTER; // Before validating, add all modules to the modulemap. We must do this outside of LoadModule for multithreading reasons. // kh_clear_modules(env->modulemap); for(size_t i = 0; i < env->n_modules; ++i) { int r; khiter_t iter = kh_put_modules(env->modulemap, env->modules[i].name, &r); if(!r) return ERR_FATAL_DUPLICATE_MODULE_NAME; kh_val(env->modulemap, iter) = i; } ValidateEnvironment(*env); if(env->errors) { internal::ReverseErrorList(env->errors); // Reverse error list so it appears in chronological order return ERR_VALIDATION_ERROR; } return ERR_SUCCESS; } IN_ERROR innative::Compile(Environment* env, const char* file) { if(!env) return ERR_FATAL_NULL_POINTER; IN_ERROR err = Validate(env); if(err != ERR_SUCCESS) return err; return CompileEnvironment(env, file); } IN_Entrypoint innative::LoadFunction(void* assembly, const char* module_name, const char* function) { auto canonical = utility::CanonicalName(StringRef::From(module_name), StringRef::From(function)); return (IN_Entrypoint)LoadDLLFunction(assembly, !function ? IN_INIT_FUNCTION : canonical.c_str()); } struct IN_TABLE { IN_Entrypoint func; varuint32 type; }; IN_Entrypoint innative::LoadTable(void* assembly, const char* module_name, const char* table, varuint32 index) { IN_TABLE* ref = (IN_TABLE*)LoadDLLFunction(assembly, utility::CanonicalName(StringRef::From(module_name), StringRef::From(table)).c_str()); return !ref ? nullptr : ref[index].func; } IRGlobal* innative::LoadGlobal(void* assembly, const char* module_name, const char* export_name) { return (IRGlobal*)LoadDLLFunction( assembly, utility::CanonicalName(StringRef::From(module_name), StringRef::From(export_name)).c_str()); } void* innative::LoadAssembly(const char* file) { if(!file) return 0; path envpath = GetPath(file); return envpath.is_absolute() ? LoadDLL(envpath) : LoadDLL(GetWorkingDir() / envpath); } void innative::FreeAssembly(void* assembly) { FreeDLL(assembly); } const char* innative::GetTypeEncodingString(int type_encoding) { return utility::EnumToString(utility::TYPE_ENCODING_MAP, type_encoding, 0, 0); } const char* innative::GetErrorString(int error_code) { return utility::EnumToString(utility::ERR_ENUM_MAP, error_code, 0, 0); } int innative::CompileScript(const uint8_t* data, size_t sz, Environment* env, bool always_compile, const char* output) { int err = ERR_SUCCESS; char buf[40]; snprintf(buf, 40, "memory%p", data); const char* target = buf; std::string dumpfile; // Load the module std::unique_ptr<uint8_t[]> data_module; if(!sz) { long len; target = reinterpret_cast<const char*>(data); data_module = utility::LoadFile(utility::GetPath(target), len); if(data_module.get() == nullptr) return ERR_FATAL_FILE_ERROR; data = data_module.get(); sz = len; } else if(env->flags & ENV_DEBUG) { path out = u8path(output) / buf; if(!DumpFile(out, data, sz)) return ERR_FATAL_FILE_ERROR; dumpfile = out.u8string(); target = dumpfile.c_str(); } if(!env) { fputs("Environment cannot be null.\n", stderr); return ERR_FATAL_NULL_POINTER; } if(err < 0) { char buf[10]; if(env->loglevel >= LOG_FATAL) FPRINTF(env->log, "Error loading environment: %s\n", utility::EnumToString(utility::ERR_ENUM_MAP, err, buf, 10)); return err; } err = ParseWast(*env, data, sz, utility::GetPath(target), always_compile, output); if(env->loglevel >= LOG_ERROR && err < 0) { char buf[10]; FPRINTF(env->log, "Error loading modules: %s\n", utility::EnumToString(utility::ERR_ENUM_MAP, err, buf, 10)); } if(env->loglevel >= LOG_NOTICE && target) FPRINTF(env->log, "Finished Script: %s\n", target); return err; } int innative::SerializeModule(Environment* env, size_t m, const char* out, size_t* len) { if(!env) return ERR_FATAL_NULL_POINTER; if(m >= env->n_modules) return ERR_FATAL_INVALID_MODULE; Queue<WatToken> tokens; wat::TokenizeModule(*env, tokens, env->modules[m]); int err = CheckWatTokens(*env, env->errors, tokens, ""); if(err < 0) return err; std::string name = env->modules[m].name.str(); if(!len) { if(out != nullptr) name = out; else name += ".wat"; } else { std::ostringstream ss; wat::WriteTokens(tokens, ss); if(ss.tellp() < 0) return ERR_FATAL_FILE_ERROR; size_t pos = (size_t)ss.tellp(); if(*len < pos) { *len = pos; return ERR_INSUFFICIENT_BUFFER; } tmemcpy<char>(const_cast<char*>(out), *len, ss.str().data(), pos); *len = pos; return ERR_SUCCESS; } std::ofstream f(name, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc); if(f.bad()) return ERR_FATAL_FILE_ERROR; wat::WriteTokens(tokens, f); return ERR_SUCCESS; }
29.52381
124
0.62195
[ "vector" ]
fac11c9752a7ded3e6a4d84a99fc2ffaf4cd5a0a
2,376
cpp
C++
src/PR_methods/gmmreg-master/C++/extract_correspondence.cpp
wangfudong/ZAC_GM
b5dddbb36f25d7210de4e14c2a9e189474353c61
[ "MIT" ]
12
2020-06-13T09:07:17.000Z
2022-03-27T08:56:39.000Z
src/PR_methods/gmmreg-master/C++/extract_correspondence.cpp
wangfudong/ZAC_GM
b5dddbb36f25d7210de4e14c2a9e189474353c61
[ "MIT" ]
6
2020-06-22T08:06:02.000Z
2022-01-22T11:26:19.000Z
src/PR_methods/gmmreg-master/C++/extract_correspondence.cpp
wangfudong/ZAC_GM
b5dddbb36f25d7210de4e14c2a9e189474353c61
[ "MIT" ]
4
2021-06-22T15:20:26.000Z
2022-03-23T07:10:51.000Z
/*========================================================================= $Author: bing.jian $ $Date: 2011-01-27 14:35:23 -0500 (Thu, 27 Jan 2011) $ $Revision: 134 $ =========================================================================*/ #include <iostream> #include <fstream> #include <vector> #include <cstdlib> #include <vnl/algo/vnl_determinant.h> #include <vnl/vnl_matrix.h> #include <vnl/vnl_vector.h> #include "gmmreg_utils.h" #include "utils/match_utils.h" namespace gmmreg { template <typename T> void ExtractMatchingPairs( const vnl_matrix<T>& model, const vnl_matrix<T>& scene, const T& threshold, vnl_matrix<T>& extracted_model, vnl_matrix<T>& extracted_scene) { vnl_matrix<T> dist; vnl_matrix<int> pairs; ComputeSquaredDistanceMatrix<T>(model, scene, dist); PickIndices<T>(dist, pairs, threshold*threshold); std::cout << "distance threshold : " << threshold << std::endl; int n = pairs.cols(); int d = model.cols(); extracted_model.set_size(n, d); extracted_scene.set_size(n, d); std::cout << "# of matched point pairs : " << n << std::endl; for (int j = 0; j < n; ++j) { extracted_model.set_row(j,model.get_row(pairs(0, j))); } for (int j = 0; j < n; ++j) { extracted_scene.set_row(j,scene.get_row(pairs(1, j))); } } template <typename T> void ExtractMatchingPairs( const char* model_file, const char* scene_file, const T& threshold, const char* extracted_model_file, const char* extracted_scene_file) { std::ifstream infile1(model_file); vnl_matrix<T> model; model.read_ascii(infile1); std::ifstream infile2(scene_file); vnl_matrix<T> scene; scene.read_ascii(infile2); vnl_matrix<T> extracted_model, extracted_scene; ExtractMatchingPairs<T>( model, scene, threshold, extracted_model, extracted_scene); std::ofstream outfile1(extracted_model_file, std::ios_base::out); extracted_model.print(outfile1); std::ofstream outfile2(extracted_scene_file, std::ios_base::out); extracted_scene.print(outfile2); } } // namespace gmmreg int main(int argc, char* argv[]) { if (argc < 6) { std::cerr << "Usage: " << argv[0] << " modelFile sceneFile threshold extracted_model extracted_scene" << std::endl; return -1; } gmmreg::ExtractMatchingPairs<float>( argv[1], argv[2], atof(argv[3]), argv[4], argv[5]); }
27.952941
77
0.638047
[ "vector", "model" ]
fac1611142df28c3d94e32d99b5a488185a1786c
5,960
cc
C++
tensorrt-laboratory/tensorrt/src/model.cc
ryanleary/tensorrt-laboratory
1bb2151bfdffbb2e72b1a096e41b67602789c445
[ "BSD-3-Clause" ]
4
2020-01-16T13:50:28.000Z
2021-12-08T09:35:13.000Z
tensorrt-laboratory/tensorrt/src/model.cc
ryanleary/tensorrt-laboratory
1bb2151bfdffbb2e72b1a096e41b67602789c445
[ "BSD-3-Clause" ]
5
2020-03-24T17:57:33.000Z
2022-03-12T00:07:08.000Z
tensorrt-laboratory/tensorrt/src/model.cc
ryanleary/tensorrt-laboratory
1bb2151bfdffbb2e72b1a096e41b67602789c445
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2018-2019, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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. */ #include "tensorrt/laboratory/model.h" #include <cuda.h> #include <cuda_runtime.h> #include <glog/logging.h> #include "tensorrt/laboratory/bindings.h" #include "tensorrt/laboratory/execution_context.h" #include "tensorrt/laboratory/utils.h" using ::nvinfer1::ICudaEngine; using ::nvinfer1::IExecutionContext; namespace trtlab { namespace TensorRT { void BaseModel::AddBinding(TensorBindingInfo&& binding) { const std::string name = binding.name; m_Bindings.push_back(std::move(binding)); auto id = m_Bindings.size() - 1; m_BindingIdByName[name] = id; if(binding.isInput) { m_InputBindings.push_back(id); } else { m_OutputBindings.push_back(id); } } Model::Model(std::shared_ptr<ICudaEngine> engine) : BaseModel(), m_Engine(engine) { CHECK(m_Engine) << "Model required an initialzed ICudaEngine*"; DLOG(INFO) << "Initializing Bindings from Engine"; for(int i = 0; i < m_Engine->getNbBindings(); i++) { AddBinding(ConfigureBinding(i)); } CHECK_EQ(GetBindingsCount(), m_Engine->getNbBindings()); } Model::~Model() { DLOG(INFO) << "Destroying Model: " << Name(); } Model::TensorBindingInfo Model::ConfigureBinding(uint32_t i) { TensorBindingInfo binding; auto dims = m_Engine->getBindingDimensions(i); size_t elements = 1; for(int j = 0; j < dims.nbDims; j++) { binding.dims.push_back(dims.d[j]); elements *= dims.d[j]; } binding.name = m_Engine->getBindingName(i); binding.dtype = m_Engine->getBindingDataType(i); binding.dtypeSize = SizeofDataType(binding.dtype); binding.elementsPerBatchItem = elements; binding.bytesPerBatchItem = elements * binding.dtypeSize; binding.isInput = m_Engine->bindingIsInput(i); LOG(INFO) << "Binding: " << binding.name << "; isInput: " << (binding.isInput ? "true" : "false") << "; dtype size: " << binding.dtypeSize << "; bytes per batch item: " << binding.bytesPerBatchItem; return binding; } auto BaseModel::BindingId(const std::string& name) const -> uint32_t { auto search = m_BindingIdByName.find(name); CHECK(search != m_BindingIdByName.end()); return search->second; } auto BaseModel::GetBinding(uint32_t id) const -> const TensorBindingInfo& { CHECK_LT(id, m_Bindings.size()) << "Invalid BindingId; given: " << id << "; max: " << m_Bindings.size(); return m_Bindings[id]; } BaseModel::BindingType BaseModel::GetBindingType(const std::string& name) const { auto search = m_BindingIdByName.find(name); if(search == m_BindingIdByName.end()) { return BindingType::Invalid; } const auto& binding = m_Bindings[search->second]; if(binding.isInput) { return BindingType::Input; } else { return BindingType::Output; } return BindingType::Invalid; } auto BaseModel::GetBinding(const std::string& name) const -> const TensorBindingInfo& { auto search = m_BindingIdByName.find(name); CHECK(search != m_BindingIdByName.end()); return m_Bindings[search->second]; } auto Model::CreateExecutionContext() const -> std::shared_ptr<IExecutionContext> { return nv_shared<IExecutionContext>(m_Engine->createExecutionContextWithoutDeviceMemory(), [engine = m_Engine, name = Name()]() mutable { DLOG(INFO) << "Destroying IExecutionContext for Model: " << name; }); } void Model::AddWeights(void* ptr, size_t size) { m_Weights.push_back(Weights{ptr, size}); } void Model::PrefetchWeights(cudaStream_t stream) const { for(auto weights : m_Weights) { CHECK_EQ(cudaMemPrefetchAsync(weights.addr, weights.size, 0, stream), CUDA_SUCCESS) << "Failed to Prefetch Weights"; } } auto Model::GetWeightsMemorySize() const -> const size_t { size_t total = 0; for(auto weights : m_Weights) { total += weights.size; } return total; } auto BaseModel::GetBindingMemorySize() const -> const size_t { size_t bytes = 0; for(auto const& binding : m_Bindings) { bytes += binding.bytesPerBatchItem; } bytes *= GetMaxBatchSize(); return bytes; } } // namespace TensorRT } // namespace trtlab
33.111111
100
0.67349
[ "model" ]
fac38644450a28f842dcae5b5fc7bdfa193a94d1
3,653
cpp
C++
moses/moses/PCNTools.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
3
2018-01-25T00:51:56.000Z
2022-01-07T15:09:38.000Z
moses/moses/PCNTools.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
1
2020-06-23T08:29:09.000Z
2020-06-24T12:11:47.000Z
moses/moses/PCNTools.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
3
2018-06-08T08:36:27.000Z
2021-12-26T20:36:16.000Z
#include "PCNTools.h" #include <iostream> #include <cstdlib> namespace PCN { const std::string chars = "'\\"; const char& quote = chars[0]; const char& slash = chars[1]; // safe get inline char get(const std::string& in, int c) { if (c < 0 || c >= (int)in.size()) return 0; else return in[(size_t)c]; } // consume whitespace inline void eatws(const std::string& in, int& c) { while (get(in,c) == ' ') { c++; } } // from 'foo' return foo std::string getEscapedString(const std::string& in, int &c) { eatws(in,c); if (get(in,c++) != quote) return "ERROR"; std::string res; char cur = 0; do { cur = get(in,c++); if (cur == slash) { res += get(in,c++); } else if (cur != quote) { res += cur; } } while (get(in,c) != quote && (c < (int)in.size())); c++; eatws(in,c); return res; } // basically atof float getFloat(const std::string& in, int &c) { std::string tmp; eatws(in,c); while (c < (int)in.size() && get(in,c) != ' ' && get(in,c) != ')' && get(in,c) != ',') { tmp += get(in,c++); } eatws(in,c); return atof(tmp.c_str()); } // basically atof int getInt(const std::string& in, int &c) { std::string tmp; eatws(in,c); while (c < (int)in.size() && get(in,c) != ' ' && get(in,c) != ')' && get(in,c) != ',') { tmp += get(in,c++); } eatws(in,c); return atoi(tmp.c_str()); } // parse ('foo', 0.23) CNAlt getCNAlt(const std::string& in, int &c) { if (get(in,c++) != '(') { std::cerr << "PCN/PLF parse error: expected ( at start of cn alt block\n"; // throw "expected ("; return CNAlt(); } std::string word = getEscapedString(in,c); if (get(in,c++) != ',') { std::cerr << "PCN/PLF parse error: expected , after string\n"; // throw "expected , after string"; return CNAlt(); } size_t cnNext = 1; std::vector<float> probs; probs.push_back(getFloat(in,c)); while (get(in,c) == ',') { c++; float val = getFloat(in,c); probs.push_back(val); } //if we read more than one prob, this was a lattice, last item was column increment if (probs.size()>1) { cnNext = static_cast<size_t>(probs.back()); probs.pop_back(); if (cnNext < 1) { ; //throw "bad link length" std::cerr << "PCN/PLF parse error: bad link length at last element of cn alt block\n"; return CNAlt(); } } if (get(in,c++) != ')') { std::cerr << "PCN/PLF parse error: expected ) at end of cn alt block\n"; // throw "expected )"; return CNAlt(); } eatws(in,c); return CNAlt(std::pair<std::string, std::vector<float> >(word,probs), cnNext); } // parse (('foo', 0.23), ('bar', 0.77)) CNCol getCNCol(const std::string& in, int &c) { CNCol res; if (get(in,c++) != '(') return res; // error eatws(in,c); while (1) { if (c > (int)in.size()) { break; } if (get(in,c) == ')') { c++; eatws(in,c); break; } if (get(in,c) == ',' && get(in,c+1) == ')') { c+=2; eatws(in,c); break; } if (get(in,c) == ',') { c++; eatws(in,c); } res.push_back(getCNAlt(in, c)); } return res; } // parse ((('foo', 0.23), ('bar', 0.77)), (('a', 0.3), ('c', 0.7))) CN parsePCN(const std::string& in) { CN res; int c = 0; if (in[c++] != '(') return res; // error while (1) { if (c > (int)in.size()) { break; } if (get(in,c) == ')') { c++; eatws(in,c); break; } if (get(in,c) == ',' && get(in,c+1) == ')') { c+=2; eatws(in,c); break; } if (get(in,c) == ',') { c++; eatws(in,c); } res.push_back(getCNCol(in, c)); } return res; } }
21.362573
103
0.509444
[ "vector" ]
fad3bccfd4a50896d868b93a6abc1766b8f807a7
4,862
cpp
C++
External/FEXCore/Source/Interface/Core/ObjectCache/JobHandling.cpp
Seas0/FEX
4f4263263b560b0a25e0d48555d5b99ca12c938f
[ "MIT" ]
null
null
null
External/FEXCore/Source/Interface/Core/ObjectCache/JobHandling.cpp
Seas0/FEX
4f4263263b560b0a25e0d48555d5b99ca12c938f
[ "MIT" ]
null
null
null
External/FEXCore/Source/Interface/Core/ObjectCache/JobHandling.cpp
Seas0/FEX
4f4263263b560b0a25e0d48555d5b99ca12c938f
[ "MIT" ]
null
null
null
#include "Interface/Context/Context.h" #include "Interface/Core/ObjectCache/ObjectCacheService.h" #include <FEXCore/Config/Config.h> #include <fcntl.h> #include <filesystem> #include <memory> #include <string> #include <sys/uio.h> #include <sys/mman.h> #include <xxhash.h> namespace FEXCore::CodeSerialize { void AsyncJobHandler::AsyncAddNamedRegionJob(uintptr_t Base, uintptr_t Size, uintptr_t Offset, const std::string &filename) { // This function adds a named region *JOB* to our named region handler // This needs to be as fast as possible to keep out of the way of the JIT auto BaseFilename = std::filesystem::path(filename).filename().string(); if (!BaseFilename.empty()) { // Create a new entry that once set up will be put in to our section object map auto Entry = std::make_unique<CodeRegionEntry>( Base, Size, Offset, filename, NamedRegionHandler->DefaultCodeHeader(Base, Offset) ); // Lock the job ref counter so we can block anything attempting to use the entry before it is loaded Entry->NamedJobRefCountMutex.lock(); CodeRegionMapType::iterator EntryIterator; { std::unique_lock lk {CodeObjectCacheService->GetEntryMapMutex()}; auto &EntryMap = CodeObjectCacheService->GetEntryMap(); auto it = EntryMap.emplace(Base, std::move(Entry)); if (!it.second) { // This happens when an application overwrites a previous region without unmapping what was there // Lock this entry's Named job reference counter. // Once this passes then we know that this section has been loaded. it.first->second->NamedJobRefCountMutex.lock(); // Finalize anything the region needs to do first. CodeObjectCacheService->DoCodeRegionClosure(it.first->second->Base, it.first->second.get()); // munmap the file that was mapped FEXCore::Allocator::munmap(it.first->second->CodeData, it.first->second->FileSize); // Remove this entry from the unrelocated map as well { std::unique_lock lk2 {CodeObjectCacheService->GetUnrelocatedEntryMapMutex()}; CodeObjectCacheService->GetUnrelocatedEntryMap().erase(it.first->second->EntryHeader.OriginalBase); } // Now overwrite the entry in the map it = EntryMap.insert_or_assign(Base, std::move(Entry)); EntryIterator = it.first; } else { // No overwrite, just insert EntryIterator = it.first; } } // Now that this entry has been added to the map, we can insert a load job using the entry iterator. // This allows us to quickly unblock the JIT thread when it is loading multiple regions and have the async thread // do the loading for us. // // Create the async work queue job now so it can load NamedRegionHandler->AsyncAddNamedRegionWorkItem(BaseFilename, filename, true, EntryIterator); // Tell the async thread that it has work to do CodeObjectCacheService->NotifyWork(); } } void AsyncJobHandler::AsyncRemoveNamedRegionJob(uintptr_t Base, uintptr_t Size) { // Removing a named region through the job system // We need to find the entry that we are deleting first std::unique_ptr<CodeRegionEntry> EntryPointer; { std::unique_lock lk {CodeObjectCacheService->GetEntryMapMutex()}; auto &EntryMap = CodeObjectCacheService->GetEntryMap(); auto it = EntryMap.find(Base); if (it != EntryMap.end()) { // Lock the job ref counter since we are erasing it // Once this passes it will have been loaded it->second->NamedJobRefCountMutex.lock(); // Take the pointer from the map EntryPointer = std::move(it->second); // We can now unmap the file data FEXCore::Allocator::munmap(EntryPointer->CodeData, EntryPointer->FileSize); // Remove this from the entry map EntryMap.erase(it); // Remove this entry from the unrelocated map as well { std::unique_lock lk2 {CodeObjectCacheService->GetUnrelocatedEntryMapMutex()}; CodeObjectCacheService->GetUnrelocatedEntryMap().erase(EntryPointer->EntryHeader.OriginalBase); } } else { // Tried to remove something that wasn't in our code object tracking return; } // Create the async work queue job now so it can finalize what it needs to do NamedRegionHandler->AsyncRemoveNamedRegionWorkItem(Base, Size, std::move(EntryPointer)); // Tell the async thread that it has work to do CodeObjectCacheService->NotifyWork(); } } void AsyncJobHandler::AsyncAddSerializationJob(std::unique_ptr<SerializationJobData> Data) { // XXX: Actually add serialization job } }
37.984375
127
0.672563
[ "object" ]
fad536d29a178103b6cd8086a68076d4254c8de7
551
hpp
C++
include/opt-methods/math/DiagonalMatrix.hpp
kp2pml30/optimization-methods-labs
654d982fafea4dcaaea80aa78d89128bc443398b
[ "Apache-2.0" ]
3
2021-05-13T14:05:21.000Z
2021-05-13T14:05:39.000Z
include/opt-methods/math/DiagonalMatrix.hpp
kp2pml30/optimization-methods-labs
654d982fafea4dcaaea80aa78d89128bc443398b
[ "Apache-2.0" ]
null
null
null
include/opt-methods/math/DiagonalMatrix.hpp
kp2pml30/optimization-methods-labs
654d982fafea4dcaaea80aa78d89128bc443398b
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cassert> #include <valarray> #include <cmath> #include <ranges> #include <algorithm> #include <numeric> #include "./Vector.hpp" template<typename T> class DiagonalMatrix { public: const std::valarray<T> diag; DiagonalMatrix(std::valarray<T> diag) : diag(std::move(diag)) {} size_t Dims() const { return diag.size(); } DiagonalMatrix Transpose() const { return *this; } }; template<typename T> Vector<T> operator*(DiagonalMatrix<T> const& l, Vector<T> const& r) { assert(l.Dims() == r.size()); return l.diag * r; }
17.21875
67
0.68784
[ "vector" ]
fade8b68711cd79491594d0751e4489238beaf31
761
cpp
C++
C++/STL/Vector Sort/Vector Sort/main.cpp
huyht1205/coding
6f046587faba107e99b007466fd6140c0de59574
[ "MIT" ]
null
null
null
C++/STL/Vector Sort/Vector Sort/main.cpp
huyht1205/coding
6f046587faba107e99b007466fd6140c0de59574
[ "MIT" ]
null
null
null
C++/STL/Vector Sort/Vector Sort/main.cpp
huyht1205/coding
6f046587faba107e99b007466fd6140c0de59574
[ "MIT" ]
null
null
null
// // main.cpp // Vector Sort // // Created by Hoàng Trung Huy on 7/15/16. // Copyright © 2016 Hoàng Trung Huy. All rights reserved. // #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int N = 0; cin >> N; vector<int> answer; for (int i = 0; i < N; i++) { int input; cin >> input; answer.push_back(input); } sort(answer.begin(), answer.end()); for (int i = 0; i < answer.size(); i++) { cout << answer.at(i) << " "; } cout << endl; return 0; }
19.025
81
0.498029
[ "vector" ]
fae183cda89677e34f0ef551b3df7d1a9977c6e5
2,069
cpp
C++
HighOrderCRF/LabelSequence.cpp
hiroshi-manabe/CRFSegmenter
c8b0544933701f91ff9cfac9301c51b181a4f846
[ "BSL-1.0" ]
16
2016-07-01T01:40:56.000Z
2020-05-06T03:29:42.000Z
HighOrderCRF/LabelSequence.cpp
hiroshi-manabe/CRFSegmenter
c8b0544933701f91ff9cfac9301c51b181a4f846
[ "BSL-1.0" ]
9
2016-07-04T06:44:42.000Z
2020-05-14T21:23:46.000Z
HighOrderCRF/LabelSequence.cpp
hiroshi-manabe/CRFSegmenter
c8b0544933701f91ff9cfac9301c51b181a4f846
[ "BSL-1.0" ]
2
2016-07-05T14:50:32.000Z
2019-10-03T02:35:53.000Z
#include <algorithm> #include <vector> #include "LabelSequence.h" namespace HighOrderCRF { using std::min; using std::vector; LabelSequence::LabelSequence(vector<label_t> labels) { this->labels = labels; } size_t LabelSequence::getLength() const { return labels.size(); } label_t LabelSequence::getLabelAt(size_t pos) const { if (pos >= labels.size()) { return INVALID_LABEL; } return labels.at(pos); } const label_t *LabelSequence::getLabelData() const { return labels.data(); } label_t LabelSequence::getLastLabel() const { return getLabelAt(0); } LabelSequence LabelSequence::createPrefix() const { vector<label_t> seq(labels.begin() + 1, labels.end()); return LabelSequence(seq); } size_t LabelSequence::getDifferencePosition(const LabelSequence &that) const { size_t minLength = min(getLength(), that.getLength()); for (size_t i = 0; i < minLength; ++i) { if (getLabelAt(i) != that.getLabelAt(i)) { return i; } } return minLength; } bool LabelSequence::operator<(const LabelSequence &that) const { size_t thisLength = getLength(); size_t thatLength = that.getLength(); size_t minLength = min(thisLength, thatLength); for (size_t i = 0; i < minLength; ++i) { if (getLabelAt(i) != that.getLabelAt(i)) { return getLabelAt(i) < that.getLabelAt(i); } } return thisLength < thatLength; } bool LabelSequence::operator==(const LabelSequence &that) const { if (this->getLength() != that.getLength()) { return false; } for (size_t i = 0; i < this->getLength(); ++i) { if (getLabelAt(i) != that.getLabelAt(i)) { return false; } } return true; } size_t LabelSequence::hash() const { size_t ret = 0; for (size_t i = 0; i < getLength(); ++i) { ret ^= std::hash<label_t>()(labels.at(i)); } return ret; }; LabelSequence LabelSequence::createEmptyLabelSequence() { return LabelSequence(vector<label_t>()); } } // namespace HighOrderCRF
22.48913
78
0.633156
[ "vector" ]
fae1ece39728793d7490c0fa7f24eb8b7438e66f
1,369
cpp
C++
aws-cpp-sdk-kinesisvideo/source/model/GetSignalingChannelEndpointResult.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-kinesisvideo/source/model/GetSignalingChannelEndpointResult.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-kinesisvideo/source/model/GetSignalingChannelEndpointResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/kinesisvideo/model/GetSignalingChannelEndpointResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::KinesisVideo::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; GetSignalingChannelEndpointResult::GetSignalingChannelEndpointResult() { } GetSignalingChannelEndpointResult::GetSignalingChannelEndpointResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } GetSignalingChannelEndpointResult& GetSignalingChannelEndpointResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("ResourceEndpointList")) { Array<JsonView> resourceEndpointListJsonList = jsonValue.GetArray("ResourceEndpointList"); for(unsigned resourceEndpointListIndex = 0; resourceEndpointListIndex < resourceEndpointListJsonList.GetLength(); ++resourceEndpointListIndex) { m_resourceEndpointList.push_back(resourceEndpointListJsonList[resourceEndpointListIndex].AsObject()); } } return *this; }
31.113636
146
0.794741
[ "model" ]
fae688180bab7b8dc3ee3fae148d28a66104e7f3
11,124
cpp
C++
Source/SystemQOR/SanOS/SanCmpSupQORVC/src/Exceptions/EH_GuardDescriptor.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/SystemQOR/SanOS/SanCmpSupQORVC/src/Exceptions/EH_GuardDescriptor.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/SystemQOR/SanOS/SanCmpSupQORVC/src/Exceptions/EH_GuardDescriptor.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//EH_GuardDescriptor.cpp // Copyright Querysoft Limited 2013 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "WinQL/WinQL.h" #include "SystemQOR.h" #include "WinQL/CodeServices/CriticalSection.h" #include "../SystemQOR/MSWindows/WinCmpSupQORVC/include/Exceptions/EH_Context.h" #include "../SystemQOR/MSWindows/WinCmpSupQORVC/include/Exceptions/EH_GuardDescriptor.h" #include "CodeQOR/Modules/ProcessBase.h" #include "../SystemQOR/MSWindows/WinCmpSupQORVC/include/Exceptions/SEH/excpt.h" #include "CodeQOR/Threading/ThreadContext.h" //-------------------------------------------------------------------------------- namespace nsCompiler { void CallMemberFunction( void* pObject, void* pfn, ... ); void JumpToFunction( void* target, void* targetStack, void* targetEBP ); void* __stdcall CallOnFrame0( void* addr, void* new_frame, void* temp1 = 0, void* temp2 = 0 ); void* __stdcall CallOnFrame2( void* addr, void* new_frame, void* arg1, void* arg2, void* temp1 = 0, void* temp2 = 0 ); namespace EH { //-------------------------------------------------------------------------------- nsWin32::EXCEPTION_DISPOSITION CxxFrameHandler( ExceptionContext& context, GuardDescriptor& guard, BasicRegistrationNode* pMarkerRN, bool recursive ); //-------------------------------------------------------------------------------- GuardDescriptor::FrameInfo::FrameInfo( const ThrownObject& object ): m_pThrownObject( &object ) { FrameInfo*& pChain = reinterpret_cast< FrameInfo*& >( nsCodeQOR::CProcessBase::ThisProcess()->ThreadContext()->ExceptionContext()->FrameInfoChain() ); m_pNext = pChain; pChain = this; } //-------------------------------------------------------------------------------- GuardDescriptor::FrameInfo::~FrameInfo() { FrameInfo*& pChain = reinterpret_cast< FrameInfo*& >( nsCodeQOR::CProcessBase::ThisProcess()->ThreadContext()->ExceptionContext()->FrameInfoChain() ); if ( pChain == this ) { pChain = m_pNext; return; } FrameInfo* pInfo = 0; for( pInfo = pChain; pInfo->m_pNext != this; pInfo = pInfo->m_pNext ) { if ( pInfo->m_pNext == 0 ) { inconsistency(); } } pInfo->m_pNext = m_pNext; } //-------------------------------------------------------------------------------- const TryBlockMapEntry* GuardDescriptor::GetRangeOfTrysToCheck( unsigned int* pStart, unsigned int* pEnd ) const { if( m_pFuncInfo->pTryBlockMap == 0 ) { return 0; } const int curState = m_pRN->state; int CatchDepth = m_CatchDepth; unsigned start = m_pFuncInfo->nTryBlocks; unsigned temp = start; unsigned end = start; while ( CatchDepth >= 0 ) { if ( start-- == -1 ) { inconsistency(); } const TryBlockMapEntry* const pEntry = m_pFuncInfo->pTryBlockMap + start; if ( ( pEntry->tryHigh >= curState || curState > pEntry->catchHigh ) && start != -1 )//Modified { end = temp; temp = start; --CatchDepth; } } *pStart = /*++*/start; *pEnd = end; if ( end > m_pFuncInfo->nTryBlocks || start > end )//Modified { inconsistency(); } return m_pFuncInfo->pTryBlockMap + start; } //-------------------------------------------------------------------------------- int GuardDescriptor::FrameUnwindFilter( nsWin32::EXCEPTION_POINTERS* pExPtrs ) { if ( pExPtrs->ExceptionRecord->ExceptionCode == CPP_EXCEPTION ) { nsCodeQOR::CThreadContextBase::GetCurrent()->ExceptionContext()->ProcessingThrow() = 0; std::terminate(); } return nsWin32::Exception_Continue_Search; } //-------------------------------------------------------------------------------- void GuardDescriptor::FrameUnwindToState( int targetState ) { int curState = m_pRN->state; int& ProcessingThrow = nsCodeQOR::CProcessBase::ThisProcess()->ThreadContext()->ExceptionContext()->ProcessingThrow(); ++ProcessingThrow; __try { while ( curState != targetState ) { if ( curState <= -1 || curState >= m_pFuncInfo->maxState ) { inconsistency(); } int nxtState = m_pFuncInfo->pUnwindMap[curState].toState; __try { if ( m_pFuncInfo->pUnwindMap[curState].action != 0 ) { m_pRN->state = nxtState; CallOnFrame0( reinterpret_cast< void* >( m_pFuncInfo->pUnwindMap[curState].action ), m_pRN->GetStackFrame() ); } } __except( FrameUnwindFilter( (nsWin32::EXCEPTION_POINTERS*)_exception_info() ) ) { } curState = nxtState; } } __finally { if ( ProcessingThrow > 0 ) { --ProcessingThrow; } } if ( curState != targetState ) { inconsistency(); } m_pRN->state = curState; } //-------------------------------------------------------------------------------- nsWin32::EXCEPTION_DISPOSITION GuardDescriptor::CatchGuardHandler( ExceptionRecord* pExcept, CatchGuardRN* pRN, nsWin32::CONTEXT* pContext, void* /*pDC*/ ) { ExceptionContext context( pExcept, pContext, 0 ); return CxxFrameHandler( context, pRN->StoredValue(), pRN, false ); } //-------------------------------------------------------------------------------- void* GuardDescriptor::CallCatchBlock2( void* handlerAddress ) { CatchGuardRN CGRN( m_pRN, m_pFuncInfo, reinterpret_cast< void* >( CatchGuardHandler ), m_CatchDepth + 1 ); CGRN.SetCurrent(); void* continuationAddress = CallOnFrame0( handlerAddress, m_pRN->GetStackFrame() ); CGRN.Remove(); return continuationAddress; } //-------------------------------------------------------------------------------- int GuardDescriptor::ExFilterRethrow( nsWin32::EXCEPTION_POINTERS* pExPtrs ) { const ExceptionRecord* pExcept = ( const ExceptionRecord* )( pExPtrs->ExceptionRecord ); if ( !pExcept->IsCpp() || pExcept->Object().IsValid() != 0 ) { return nsWin32::Exception_Continue_Search; } return nsWin32::Exception_Execute_Handler; } //-------------------------------------------------------------------------------- void* GuardDescriptor::CallCatchBlock( ExceptionContext& context, void* handlerAddress ) { //nsCodeQOR::IThread* const pThreadData = nsCodeQOR::IThread::GetCurrent(); nsCodeQOR::CThreadContextBase* pThreadContext = nsCodeQOR::CProcessBase::ThisProcess()->ThreadContext(); void* continuationAddress = handlerAddress; bool ExceptionObjectDestroyed = false; void* const saveESP = m_pRN->GetStack(); const ExceptionContext SavedContext = pThreadContext->ExceptionContext()->CurrentException(); pThreadContext->ExceptionContext()->CurrentException() = reinterpret_cast< ExceptData& >( context ); __try { __try { continuationAddress = CallCatchBlock2(handlerAddress); } __except( ExFilterRethrow( ( nsWin32::EXCEPTION_POINTERS* )_exception_info() ) ) { const UnwindMapEntry* pUnwindMap = m_pFuncInfo->pUnwindMap; int cState = m_pRN->state; const TryBlockMapEntry* pTryBlockMap = m_pFuncInfo->pTryBlockMap; for( unsigned i = 0; i < m_pFuncInfo->nTryBlocks; ++i ) { if ( cState <= pTryBlockMap[i].tryHigh || cState > pTryBlockMap[i].catchHigh ) { continue; } cState = pTryBlockMap[i].tryHigh + 1; cState = pUnwindMap[cState].toState; } FrameUnwindToState(cState); continuationAddress = 0; } } __finally { m_pRN->SetStack( saveESP ); pThreadContext->ExceptionContext()->CurrentException() = *( reinterpret_cast< const ExceptData* >( &SavedContext ) ); if ( context.IsCppException() && !ExceptionObjectDestroyed && continuationAddress != 0 && IsToBeDestroyed( context.ExceptionObject() ) ) { context.ExceptionObject().Destruct( _abnormal_termination() != 0 ); } } return continuationAddress; } //-------------------------------------------------------------------------------- void GuardDescriptor::Catch( ExceptionContext& context, const HandlerType* pCatch, const CatchableType* pConv, const TryBlockMapEntry* pEntry, BasicRegistrationNode* pMarkerRN ) { if ( pConv != 0 ) { context.CopyExceptionObject( m_pRN, pCatch, pConv ); } context.UnwindNestedFrames( pMarkerRN != 0 ? pMarkerRN : m_pRN ); FrameUnwindToState( pEntry->tryLow ); m_pRN->state = pEntry->tryHigh + 1; void* continuationAddress = 0; { FrameInfo aFrameInfo( context.ExceptionObject() ); continuationAddress = CallCatchBlock( context, pCatch->addressOfHandler ); } if ( continuationAddress ) { JumpToContinuation( continuationAddress ); } } //-------------------------------------------------------------------------------- void __stdcall GuardDescriptor::JumpToContinuation( void* target ) { ( reinterpret_cast< CExceptionFrame* >( RegistrationNode::GetCurrent() ) )->Remove(); void* const targetEBP = m_pRN->GetStackFrame(); void* const targetStack = m_pRN->GetStack(); JumpToFunction( target, targetStack, targetEBP ); } //-------------------------------------------------------------------------------- bool GuardDescriptor::IsToBeDestroyed( const ThrownObject& object ) const { for( const FrameInfo* pInfo = reinterpret_cast< const FrameInfo* >( nsCodeQOR::CThreadContextBase::GetCurrent()->ExceptionContext()->FrameInfoChain() ); pInfo != 0; pInfo = pInfo->Next() ) { if( pInfo->Object() == object ) { return false; } } return true; } }//EH }//nsCompiler
36.592105
191
0.597267
[ "object" ]
faed4da3316f21a4cb0c07f34fdbf01057c16cbe
7,208
hh
C++
src/lsp-protocol/lsp-connection.hh
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
src/lsp-protocol/lsp-connection.hh
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
src/lsp-protocol/lsp-connection.hh
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
#pragma once #ifndef HGUARD_d_LSP_PROTOCOL_d_LSP_CONNECTION_HH_ #define HGUARD_d_LSP_PROTOCOL_d_LSP_CONNECTION_HH_ /****************************************************************************************/ #include "Common.hh" #include "client.hh" #include "rapid.hh" #include <nlohmann/json.hpp> namespace emlsp::rpc::lsp { namespace detail {} /** * TODO: Documentation */ template <typename ConnectionType> class base_connection : public emlsp::rpc::base_connection<ConnectionType> { #ifdef __INTELLISENSE__ static constexpr ssize_t discard_buffer_size = SSIZE_C(16383); #else static constexpr ssize_t discard_buffer_size = SSIZE_C(65536); #endif using base = emlsp::rpc::base_connection<ConnectionType>; public: using base::connection; using base::pid; using base::raw_read; using base::raw_write; using base::spawn_connection; private: size_t get_content_length() { /* Exactly 64 bytes assuming an 8 byte pointer size. Three cheers for * pointless "optimizations". */ char buf[47]; char *ptr = buf; size_t len; uint8_t ch; raw_read(buf, 16); // Discard raw_read(&ch, 1); while (::isdigit(ch)) { *ptr++ = static_cast<char>(ch); raw_read(&ch, 1); } *ptr = '\0'; len = ::strtoull(buf, &ptr, 10); raw_read(buf, 3); // Discard if (ptr == buf || len == 0) [[unlikely]] { throw std::runtime_error( fmt::format(FMT_COMPILE("Invalid JSON-RPC: no non-zero number " "found in header at \"{}\"."), buf)); } return len; } void write_jsonrpc_header(size_t const len) { /* It's safe to go with sprintf because we know for certain that a single * 64 bit integer will fit in this buffer along with the format. */ char buf[60]; int buflen = ::sprintf(buf, "Content-Length: %zu\r\n\r\n", len); raw_write(buf, buflen); } /*------------------------------------------------------------------------------------*/ public: base_connection() = default; ~base_connection() override = default; template <typename ...Types> explicit base_connection(Types &&...args) { spawn_connection(args...); } std::string read_message_string() override { auto len = get_content_length(); auto msg = std::string(len + 1, '\0'); raw_read(msg.data(), len); return msg; } /** * \brief Read an rpc message into a buffer contained in an std::vector. */ std::vector<char> read_message() override { auto len = get_content_length(); auto msg = std::vector<char>(); util::resize_vector_hack(msg, len + 1); raw_read(msg.data(), len); msg[len] = '\0'; return msg; } /** * \brief Read an RPC message into an allocated buffer, and assign it to the * supplied double pointer. * \param buf Nonnull pointer to a valid (char *) variable. * \return Number of bytes read. */ __attribute__((nonnull)) size_t read_message(_Notnull_ char **buf) override { auto len = get_content_length(); *buf = new char[len + 1]; raw_read(*buf, len); (*buf)[len] = '\0'; return len; } /** * \brief Simple wrapper for the (char **) overload for those too lazy to cast. */ __attribute__((nonnull)) size_t read_message(_Notnull_ void **buf) override { return read_message(reinterpret_cast<char **>(buf)); } /** * \brief Read an RPC message into an allocated buffer, and assign it to the * supplied pointer. * \param buf Reference to a valid (char *) variable. * \return Number of bytes read. */ size_t read_message(char *&buf) override { char *msg; auto const len = read_message(&msg); buf = msg; return len; } /** * \brief Read an RPC message into an allocated buffer, and assign it to the * supplied unique_ptr, which should not be initialized. * \param buf Reference to an uninitialized unique_ptr<char[]>. * \return Number of bytes read. */ size_t read_message(std::unique_ptr<char[]> &buf) override { char *msg; auto const len = read_message(&msg); buf = std::unique_ptr<char[]>(msg); return len; } /** * \brief Read and ignore an entire RPC message. * \return Number of bytes read. */ size_t discard_message() override { ssize_t const len = get_content_length(); char msg[discard_buffer_size]; for (auto n = len; n > 0; n -= discard_buffer_size) raw_read(msg, std::min(n, discard_buffer_size)); return len; } __attribute__((nonnull)) void write_message(_Notnull_ char const *msg) override { write_message(msg, strlen(msg)); } __attribute__((nonnull)) void write_message(_Notnull_ void const *msg, size_t const len) override { write_jsonrpc_header(len); raw_write(msg, len); } void write_message(std::string const &msg) override { write_jsonrpc_header(msg.size()); raw_write(msg.data(), msg.size()); } void write_message(std::vector<char> const &msg) override { write_jsonrpc_header(msg.size() - SIZE_C(1)); raw_write(msg.data(), msg.size() - SIZE_C(1)); } void write_message(rapidjson::Document &doc) { doc.AddMember("jsonrpc", "2.0", doc.GetAllocator()); rapidjson::MemoryBuffer ss; rapidjson::Writer writer(ss); doc.Accept(writer); write_message(ss.GetBuffer(), ss.GetSize()); } void write_message(nlohmann::json &doc) { doc ["jsonrpc"] = "2.0"; std::stringstream buf; buf << doc; auto const msg = buf.str(); write_message(msg.data(), msg.size()); } DELETE_COPY_CTORS(base_connection); DEFAULT_MOVE_CTORS(base_connection); }; using unix_socket_connection = base_connection<emlsp::rpc::detail::unix_socket_connection_impl>; using pipe_connection = base_connection<emlsp::rpc::detail::pipe_connection_impl>; #ifdef _WIN32 using named_pipe_connection = base_connection<emlsp::rpc::detail::win32_named_pipe_impl>; #endif } // namespace emlsp::rpc::lsp /****************************************************************************************/ #endif // lsp-connection.hh
30.542373
96
0.530383
[ "vector" ]
faee567b70e372128759200857881aca15f275e4
7,928
cpp
C++
BoidsApp/BoidsApp.cpp
FelipeEd/Jellyfish3D
448ca5462fdab2a28677c7f4d05d2e733267da6f
[ "Apache-2.0" ]
null
null
null
BoidsApp/BoidsApp.cpp
FelipeEd/Jellyfish3D
448ca5462fdab2a28677c7f4d05d2e733267da6f
[ "Apache-2.0" ]
null
null
null
BoidsApp/BoidsApp.cpp
FelipeEd/Jellyfish3D
448ca5462fdab2a28677c7f4d05d2e733267da6f
[ "Apache-2.0" ]
null
null
null
#include <jellyfish\Jellyfish3D.hpp> #include "classes\Debug.h" #include "classes\Boids.h" // Global // Window size unsigned int WIDTH = 1980; //1280; unsigned int HEIGHT = 1080; //720; bool pbr = true; #define NUM_BOIDS 500 // ----------------------------------------------------------------------------------- int main() { INIT_TIMER("Boids") App app; // When using opengl GLFWwindow *window = app.display.getWindow(); Timer pauseCooldown(5); Timer addsubBoidsCooldown(5); GUI gui; gui.init(window); Renderer renderer; Scene scene; bool pause = false; { TIME_IT("Load Assets") // light model app.assets.loadMesh("resources/simplesphere.obj"); app.assets.loadMesh("resources/uvsphere.obj"); app.assets.loadMesh("resources/plane.obj"); app.assets.loadMesh("resources/newship.obj"); app.assets.loadMesh("resources/tower.obj"); app.assets.loadMesh("resources/leadership.obj"); app.assets.loadMaterial("resources/textures/Silver_Worn", "_2k"); //assets->loadMaterial("resources/textures/denmin_fabric_02", "_1k"); app.assets.loadMaterial("resources/textures/blue_painted_planks", "_1k"); //assets->loadMaterial("resources/textures/concrete_floor_02", "_1k"); app.assets.loadMaterial("resources/textures/Gold_Worn", "_2k"); app.assets.loadMaterial("resources/textures/floor_tiles_06", "_1k"); app.assets.loadMaterial("resources/textures/Plastic_Glossy_red", "_2k"); } { TIME_IT("Setup scene") // Box size float BoxSize = 50; float halfBox = BoxSize / 2.0; float halfBoxH = BoxSize / 4.0; scene.addLight("light1", glm::vec3(5000), {0, halfBoxH, 0}); scene.addLight("light2", {1000, 1000, 100}, {10, -5, 10}); scene.addLight("light3", {1000, 1000, 100}, {-10, -5, 10}); scene.addLight("light4", {1000, 1000, 1000}, {0, -5, -10}); scene.addObject("ground", 3, 4); scene.setPosition("ground", {0.0, -halfBoxH, 0.0}); scene.setScale("ground", halfBox); scene.addObject("tower", 5, 3); scene.setScale("tower", halfBoxH / 1.8); scene.addObject("tower2", 5, 3); scene.setScale("tower2", halfBoxH / 1.8); scene.setPosition("tower2", glm::vec3(BoxSize / 3.0, 0.0, 0.0)); scene.addObject("tower3", 5, 3); scene.setScale("tower3", halfBoxH / 1.8); scene.setPosition("tower3", glm::vec3(-BoxSize / 3.0, 0.0, 0.0)); for (int i = 0; i < 8; i++) { float x = 1; float y = 1; float z = 1; scene.addObject("sphere" + std::to_string(i), 1, 0); x = pow(-1, i % 2); y = pow(-1, (i / 2) % 2); z = pow(-1, (i / 4) % 2); scene.setPosition("sphere" + std::to_string(i), {x * halfBox, y * halfBoxH, z * halfBox}); } } int leaderBoidIndex = scene.m_object.size(); Boids boids = Boids(scene.m_object.size(), NUM_BOIDS, scene); while (!glfwWindowShouldClose(window)) { TIME_IT("Whole loop") { TIME_IT("Clear Buffers") // Define a cor de fundo da janela glClearColor(0.05f, 0.05f, 0.09f, 1.0f); // Limpa algum buffer específico glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } { TIME_IT("Clock tick") gui.startFrame("Boid Parameters"); if (app.clock.tick()) { // Inputs--------------------------------------------------------------------------------------------------- app.inputs.observeInputs(window); //app.inputs.printInputs(); scene.reactToInput(window, app.inputs); pauseCooldown.tick(); if (app.inputs.keys["pause"] && pauseCooldown.isUp()) { pause = !pause; pauseCooldown.reset(); } // Camera management // Camera 0 glm::vec3 avgVeldirection = glm::normalize(boids.getAvgVelocity() + glm::vec3(0.000001f, 0.000001f, 0.000001f)); // Camera 1 scene.m_cams[1].transform.position = glm::vec3(0.0, 0.0, 0.0); scene.m_cams[1].pointTo(boids.getAvgPos()); // Camaera 2 scene.m_cams[2].transform.position = boids.getAvgPos() - 20.0f * avgVeldirection; scene.m_cams[2].pointTo(boids.getAvgPos()); // Camaera 2 scene.m_cams[3].transform.position = boids.getAvgPos() + 20.0f * glm::vec3(-avgVeldirection.z, 0.0f, avgVeldirection.x); scene.m_cams[3].pointTo(boids.getAvgPos()); // Boid control addsubBoidsCooldown.tick(); if (app.inputs.keys["addboid"] && addsubBoidsCooldown.isUp()) { boids.addBoid(); addsubBoidsCooldown.reset(); } if (app.inputs.keys["removeboid"] && addsubBoidsCooldown.isUp()) { boids.removeBoid(); addsubBoidsCooldown.reset(); } //---------------------------------------------------------------------------------------------------------- // User interface gui.text("Limits : "); gui.sliderFloat("View Radius", boids.m_viewRad, 0.5, 25.0); gui.sliderFloat("View FOV", boids.m_boidsFOV, 10.0f, 359.0); gui.sliderFloat("Max Speed", boids.m_maxSpeed, 0.001, 2.0); gui.sliderFloat("Max Accel", boids.m_maxAccel, 0.0001, 0.2); gui.text("Forces : "); gui.sliderFloat("Speed Multiplier", boids.m_speedMultiplier, 0.01, 3.0); gui.sliderFloat("Accel Multiplier", boids.m_accelMultiplier, 0.01, 3.0); gui.sliderFloat("Align factor", boids.A_fac, 0.001, 2.0); gui.sliderFloat("Cohesion factor", boids.C_fac, 0.001, 2.0); gui.sliderFloat("Separation factor", boids.S_fac, 0.001, 10.0); gui.sliderFloat("Follow factor", boids.F_fac, 0.000, 10.0); if (gui.button("Reset")) { boids.reset(); scene.m_object[leaderBoidIndex].transform.position = glm::vec3(0.0f); } if (gui.button("Wireframe")) { renderer.switchWireframeMode(); } if (gui.button("Skybox")) renderer.switchSkybox(); float radius = 10.0f; float freq = 0.05f; if (!pause) { { //TIME_IT("Find Target") //scene.setPosition("Target", {radius * glm::cos(glfwGetTime() * freq), 0.0f, radius * glm::sin(glfwGetTime() * freq)}); scene.m_object[leaderBoidIndex].reactToInput(window, app.inputs); { TIME_IT("Update Boids") boids.updateAll(); } } } } } { TIME_IT("Draw calls"); renderer.draw(scene, app); } { TIME_IT("Swap Buffers"); app.inputs.resetState(); gui.endFrame(); // Faz a troca do framebuffer antigo para o novo (double buffer) glfwSwapBuffers(window); glFlush(); } // Captura eventos de IO (movimento de mouse, teclas pressionadas, etc) glfwPollEvents(); } END_TIMER return 0; }
35.235556
144
0.494324
[ "model", "transform" ]
faeff3fc5cc5013d262fb7a4caa31e14907c79f2
3,062
hpp
C++
include/xleaflet/xbasemaps.hpp
martinRenou/xleaflet
2e445fca772e82760f77340f020c83cb8d1e1cbe
[ "BSD-3-Clause" ]
36
2018-04-14T15:15:43.000Z
2019-12-22T22:16:11.000Z
include/xleaflet/xbasemaps.hpp
martinRenou/xleaflet
2e445fca772e82760f77340f020c83cb8d1e1cbe
[ "BSD-3-Clause" ]
9
2018-04-20T08:50:08.000Z
2020-01-18T01:12:45.000Z
include/xleaflet/xbasemaps.hpp
martinRenou/xleaflet
2e445fca772e82760f77340f020c83cb8d1e1cbe
[ "BSD-3-Clause" ]
8
2018-04-20T18:06:04.000Z
2019-10-06T11:49:10.000Z
/****************************************************************************** * Copyright (c) 2018, Sylvain Corlay and Johan Mabille, Wolf Vollprecht and * * Martin Renou * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * *******************************************************************************/ #ifndef XLEAFLET_BASEMAPS_HPP #define XLEAFLET_BASEMAPS_HPP #include <fstream> #include <iostream> #include <stdexcept> #include <vector> #include "nlohmann/json.hpp" #include "xget_basemaps_path.hpp" #include "xtile_layer.hpp" namespace nl = nlohmann; namespace detail { inline nl::json load_basemaps() { std::ifstream maps_json(xlf::get_basemaps_path()); nl::json maps; maps_json >> maps; return maps; } } namespace xlf { inline const nl::json& basemaps() { static nl::json maps = detail::load_basemaps(); return maps; } inline tile_layer basemap(const std::vector<std::string>& path, const std::string& day = "2018-01-01") { const nl::json& maps = basemaps(); const nl::json* node = &maps; try { for (const auto& level : path) { node = &((*node)[level]); } } catch (const std::exception&) { std::cerr << "Invalid map spec" << std::endl; return tile_layer(); } const nl::json& mapspec = *node; if (mapspec.find("url") == mapspec.end()) { std::cerr << "Invalid map spec" << std::endl; return tile_layer(); } std::string url = mapspec["url"].get<std::string>(); std::string attribution = ""; std::string name = ""; int max_zoom = 19; int min_zoom = 1; std::size_t date = url.find("%s"); if (date != std::string::npos) { url.replace(date, 2, day); } if (mapspec.find("attribution") != mapspec.end()) { attribution = mapspec["attribution"].get<std::string>(); } if (mapspec.find("name") != mapspec.end()) { name = mapspec["name"].get<std::string>(); } if (mapspec.find("max_zoom") != mapspec.end()) { max_zoom = mapspec["max_zoom"].get<int>(); } if (mapspec.find("min_zoom") != mapspec.end()) { min_zoom = mapspec["min_zoom"].get<int>(); } return tile_layer::initialize() .url(url) .attribution(attribution) .name(name) .max_zoom(max_zoom) .min_zoom(min_zoom) .finalize(); } } #endif
26.396552
80
0.453952
[ "vector" ]
faf12f6cee67fcac7957dc373bf16ffddab6dc00
10,779
cc
C++
chrome/browser/background_page_tracker.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome/browser/background_page_tracker.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/background_page_tracker.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2010 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 "chrome/browser/background_page_tracker.h" #include <string> #include "base/command_line.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/background_application_list_model.h" #include "chrome/browser/background_contents_service.h" #include "chrome/browser/background_mode_manager.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/common/pref_names.h" /////////////////////////////////////////////////////////////////////////////// // BackgroundPageTracker keeps a single DictionaryValue (stored at // prefs::kKnownBackgroundPages). We keep only two pieces of information for // each background page: the parent application/extension ID, and a boolean // flag that is true if the user has acknowledged this page. // // kKnownBackgroundPages: // DictionaryValue { // <appid_1>: false, // <appid_2>: true, // ... etc ... // } // static void BackgroundPageTracker::RegisterPrefs(PrefService* prefs) { prefs->RegisterDictionaryPref(prefs::kKnownBackgroundPages); } // static BackgroundPageTracker* BackgroundPageTracker::GetInstance() { return Singleton<BackgroundPageTracker>::get(); } int BackgroundPageTracker::GetBackgroundPageCount() { if (!IsEnabled()) return 0; PrefService* prefs = GetPrefService(); const DictionaryValue* contents = prefs->GetDictionary(prefs::kKnownBackgroundPages); return contents ? contents->size() : 0; } int BackgroundPageTracker::GetUnacknowledgedBackgroundPageCount() { if (!IsEnabled()) return 0; PrefService* prefs = GetPrefService(); const DictionaryValue* contents = prefs->GetDictionary(prefs::kKnownBackgroundPages); if (!contents) return 0; int count = 0; for (DictionaryValue::key_iterator it = contents->begin_keys(); it != contents->end_keys(); ++it) { Value* value; bool found = contents->GetWithoutPathExpansion(*it, &value); DCHECK(found); bool acknowledged = true; bool valid = value->GetAsBoolean(&acknowledged); DCHECK(valid); if (!acknowledged) count++; } return count; } void BackgroundPageTracker::AcknowledgeBackgroundPages() { if (!IsEnabled()) return; PrefService* prefs = GetPrefService(); DictionaryValue* contents = prefs->GetMutableDictionary(prefs::kKnownBackgroundPages); if (!contents) return; bool prefs_modified = false; for (DictionaryValue::key_iterator it = contents->begin_keys(); it != contents->end_keys(); ++it) { contents->SetWithoutPathExpansion(*it, Value::CreateBooleanValue(true)); prefs_modified = true; } if (prefs_modified) { prefs->ScheduleSavePersistentPrefs(); SendChangeNotification(); } } BackgroundPageTracker::BackgroundPageTracker() { // If background mode is disabled, just exit - don't load information from // prefs or listen for any notifications so we will act as if there are no // background pages, effectively disabling any associated badging. if (!IsEnabled()) return; // Check to make sure all of the extensions are loaded - once they are loaded // we can update the list. Profile* profile = g_browser_process->profile_manager()->GetDefaultProfile(); if (profile->GetExtensionService() && profile->GetExtensionService()->is_ready()) { UpdateExtensionList(); // We do not send any change notifications here, because the object was // just created (it doesn't seem appropriate to send a change notification // at initialization time). Also, since this is a singleton object, sending // a notification in the constructor can lead to deadlock if one of the // observers tries to get the singleton. } else { // Extensions aren't loaded yet - register to be notified when they are // ready. registrar_.Add(this, NotificationType::EXTENSIONS_READY, NotificationService::AllSources()); } } BackgroundPageTracker::~BackgroundPageTracker() { } PrefService* BackgroundPageTracker::GetPrefService() { PrefService* service = g_browser_process->local_state(); DCHECK(service); return service; } bool BackgroundPageTracker::IsEnabled() { // Disable the background page tracker for unittests. if (!g_browser_process->local_state()) return false; // BackgroundPageTracker is enabled if background mode is enabled. CommandLine* command_line = CommandLine::ForCurrentProcess(); return BackgroundModeManager::IsBackgroundModeEnabled(command_line); } void BackgroundPageTracker::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { switch (type.value) { case NotificationType::EXTENSIONS_READY: if (UpdateExtensionList()) SendChangeNotification(); break; case NotificationType::BACKGROUND_CONTENTS_OPENED: { std::string id = UTF16ToUTF8( Details<BackgroundContentsOpenedDetails>(details)->application_id); OnBackgroundPageLoaded(id); break; } case NotificationType::EXTENSION_LOADED: { const Extension* extension = Details<const Extension>(details).ptr(); if (extension->background_url().is_valid()) OnBackgroundPageLoaded(extension->id()); break; } case NotificationType::EXTENSION_UNLOADED: { std::string id = Details<const Extension>(details)->id(); OnExtensionUnloaded(id); break; } default: NOTREACHED(); } } bool BackgroundPageTracker::UpdateExtensionList() { // Extensions are loaded - update our list. Profile* profile = g_browser_process->profile_manager()->GetDefaultProfile(); ExtensionService* extensions_service = profile->GetExtensionService(); DCHECK(extensions_service); // We will make two passes to update the list: // 1) Walk our list, and make sure that there's a corresponding extension for // each item in the list. If not, delete it (extension was uninstalled). // 2) Walk the set of currently loaded extensions and background contents, and // make sure there's an entry in our list for each one. If not, create one. PrefService* prefs = GetPrefService(); std::set<std::string> keys_to_delete; bool pref_modified = false; DictionaryValue* contents = prefs->GetMutableDictionary(prefs::kKnownBackgroundPages); for (DictionaryValue::key_iterator it = contents->begin_keys(); it != contents->end_keys(); ++it) { // Check to make sure that the parent extension is still enabled. const Extension* extension = extensions_service->GetExtensionById( *it, false); // If the extension is not loaded, add the id to our list of keys to delete // later (can't delete now since we're still iterating). if (!extension) { keys_to_delete.insert(*it); pref_modified = true; } } for (std::set<std::string>::const_iterator iter = keys_to_delete.begin(); iter != keys_to_delete.end(); ++iter) { contents->RemoveWithoutPathExpansion(*iter, NULL); } // Look for new extensions/background contents. const ExtensionList* list = extensions_service->extensions(); for (ExtensionList::const_iterator iter = list->begin(); iter != list->begin(); ++iter) { // Any extension with a background page should be in our list. if ((*iter)->background_url().is_valid()) { // If we have not seen this extension ID before, add it to our list. if (!contents->HasKey((*iter)->id())) { contents->SetWithoutPathExpansion( (*iter)->id(), Value::CreateBooleanValue(false)); pref_modified = true; } } } // Add all apps with background contents also. BackgroundContentsService* background_contents_service = profile->GetBackgroundContentsService(); std::vector<BackgroundContents*> background_contents = background_contents_service->GetBackgroundContents(); for (std::vector<BackgroundContents*>::const_iterator iter = background_contents.begin(); iter != background_contents.end(); ++iter) { std::string application_id = UTF16ToUTF8( background_contents_service->GetParentApplicationId(*iter)); if (!contents->HasKey(application_id)) { contents->SetWithoutPathExpansion( application_id, Value::CreateBooleanValue(false)); pref_modified = true; } } // Register for when new pages are loaded/unloaded so we can update our list. registrar_.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::EXTENSION_UNLOADED, NotificationService::AllSources()); registrar_.Add(this, NotificationType::BACKGROUND_CONTENTS_OPENED, NotificationService::AllSources()); // If we modified the list, save it to prefs and let our caller know. if (pref_modified) prefs->ScheduleSavePersistentPrefs(); return pref_modified; } void BackgroundPageTracker::OnBackgroundPageLoaded(const std::string& id) { DCHECK(IsEnabled()); PrefService* prefs = GetPrefService(); DictionaryValue* contents = prefs->GetMutableDictionary(prefs::kKnownBackgroundPages); // No need to update our list if this extension was already known. if (!contents || contents->HasKey(id)) return; // Update our list with this new as-yet-unacknowledged page. contents->SetWithoutPathExpansion(id, Value::CreateBooleanValue(false)); prefs->ScheduleSavePersistentPrefs(); SendChangeNotification(); } void BackgroundPageTracker::OnExtensionUnloaded(const std::string& id) { DCHECK(IsEnabled()); PrefService* prefs = GetPrefService(); DictionaryValue* contents = prefs->GetMutableDictionary(prefs::kKnownBackgroundPages); if (!contents || !contents->HasKey(id)) return; contents->RemoveWithoutPathExpansion(id, NULL); prefs->ScheduleSavePersistentPrefs(); SendChangeNotification(); } void BackgroundPageTracker::SendChangeNotification() { NotificationService::current()->Notify( NotificationType::BACKGROUND_PAGE_TRACKER_CHANGED, Source<BackgroundPageTracker>(this), NotificationService::NoDetails()); }
36.415541
80
0.708229
[ "object", "vector" ]
faf1821ab333020c79da9119214fc733d3e7c14d
2,863
cpp
C++
src/log/object.cpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
src/log/object.cpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
src/log/object.cpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // 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/log/context.hpp> #include <fcppt/log/enabled_level_array.hpp> #include <fcppt/log/level.hpp> #include <fcppt/log/level_stream.hpp> #include <fcppt/log/level_stream_array.hpp> #include <fcppt/log/location_fwd.hpp> #include <fcppt/log/object.hpp> #include <fcppt/log/parameters.hpp> #include <fcppt/log/setting.hpp> #include <fcppt/log/detail/context_tree.hpp> #include <fcppt/log/detail/temporary_output_fwd.hpp> #include <fcppt/log/format/chain.hpp> #include <fcppt/log/format/optional_function.hpp> #include <fcppt/log/impl/tree_formatter.hpp> fcppt::log::object::object( fcppt::log::context &_context, fcppt::log::parameters const &_parameters ) : object( _context.root(), _parameters ) { } fcppt::log::object::object( fcppt::log::object &_parent, fcppt::log::parameters const &_parameters ) : object( _parent.auto_context_.node(), _parameters ) { } fcppt::log::object::object( fcppt::log::context &_context, fcppt::log::location const &_location, fcppt::log::parameters const &_parameters ) : object( _context.find_location( _location ), _parameters ) { } fcppt::log::object::~object() { } void fcppt::log::object::log( fcppt::log::level const _level, fcppt::log::detail::temporary_output const &_helper ) { if( !this->enabled( _level ) ) return; this->level_sink( _level ).log( _helper, formatter_ ); } fcppt::log::level_stream & fcppt::log::object::level_sink( fcppt::log::level const _level ) { return level_streams_[ _level ]; } fcppt::log::level_stream const & fcppt::log::object::level_sink( fcppt::log::level const _level ) const { return level_streams_[ _level ]; } bool fcppt::log::object::enabled( fcppt::log::level const _level ) const { return this->enabled_levels()[ _level ]; } fcppt::log::format::optional_function const & fcppt::log::object::formatter() const { return formatter_; } fcppt::log::level_stream_array const & fcppt::log::object::level_streams() const { return level_streams_; } fcppt::log::enabled_level_array const & fcppt::log::object::enabled_levels() const { return this->setting().enabled_levels(); } fcppt::log::setting const & fcppt::log::object::setting() const { return auto_context_.node().value().setting(); } fcppt::log::object::object( fcppt::log::detail::context_tree &_node, fcppt::log::parameters const &_parameters ) : auto_context_{ _node, _parameters.name() }, formatter_( fcppt::log::format::chain( _parameters.formatter(), fcppt::log::impl::tree_formatter( auto_context_.node() ) ) ), level_streams_( _parameters.level_streams() ) { }
16.841176
61
0.70241
[ "object" ]
4f071b1d590dd402bee11d77d22e268491c17115
1,523
cc
C++
src/test/network_perf_ps.cc
xcgoner/parameter_server
ce317bc2c657909270fc740f7dcdf9a5f45c3d1a
[ "Apache-2.0" ]
435
2015-03-17T19:32:35.000Z
2022-02-20T13:18:01.000Z
src/test/network_perf_ps.cc
xcgoner/parameter_server
ce317bc2c657909270fc740f7dcdf9a5f45c3d1a
[ "Apache-2.0" ]
19
2015-03-18T01:22:36.000Z
2021-03-16T21:34:55.000Z
src/test/network_perf_ps.cc
xcgoner/parameter_server
ce317bc2c657909270fc740f7dcdf9a5f45c3d1a
[ "Apache-2.0" ]
182
2015-03-17T17:49:09.000Z
2021-12-09T20:09:33.000Z
#include "ps.h" #include "util/resource_usage.h" DEFINE_int32(n, 1000, "repeat n times"); DEFINE_int32(data_size, 1000, "data in KB sent from a worker to a server"); DEFINE_bool(server_aggregation, false, "servers will aggregate the data from servs if true"); namespace PS { class Server : public App { public: virtual void Run() { // if (FLAGS_server_aggregation) { // WaitWorkersReady(); // auto data = split(FLAGS_data_size, ',',true); // for (int i = 0; i < data.size() * FLAGS_n; ++i) { // } // } } }; class Worker : public App { public: virtual void Slice(const Message& request, const std::vector<Range<Key>>& krs, std::vector<Message*>* msgs) { for (auto m : *msgs) *m = request; } virtual void Run() { int n = FLAGS_n; int m = FLAGS_data_size; auto tv = tic(); for (int j = 0; j < n; ++j) { SArray<int> val(m*1000/sizeof(int), 1); Message msg; msg.add_value(val); msg.recver = kServerGroup; int ts = Submit(&msg); Wait(ts); } double thr = (double)m / 1000.0 * n * sys_.manager().num_servers() / toc(tv); printf("%s: packet size: %d KB, throughput %.3lf MB/sec\n", MyNodeID().c_str(), m, thr); } }; App* App::Create(const std::string& conf) { if (IsWorker()) return new Worker(); if (IsServer()) return new Server(); return new App(); } } // namespace PS int main(int argc, char *argv[]) { return PS::RunSystem(argc, argv); }
25.383333
81
0.581747
[ "vector" ]
4f0a3e02dae50ab10cb361608ab44ea4dc37b6e4
2,338
cpp
C++
view/musicplaylisttracksview.cpp
5in4/yonder
56bd5b0b8e822b0338752b41debf2e7514f2a25b
[ "Linux-OpenIB" ]
null
null
null
view/musicplaylisttracksview.cpp
5in4/yonder
56bd5b0b8e822b0338752b41debf2e7514f2a25b
[ "Linux-OpenIB" ]
null
null
null
view/musicplaylisttracksview.cpp
5in4/yonder
56bd5b0b8e822b0338752b41debf2e7514f2a25b
[ "Linux-OpenIB" ]
null
null
null
#include "musicplaylisttracksview.h" MusicPlaylistTracksView::MusicPlaylistTracksView(QWidget *parent): QTableView(parent) { library_mime_type = "application/sg-music-library-reference"; } QModelIndexList MusicPlaylistTracksView::getSelectedIndexes() { return this->selectedIndexes(); } void MusicPlaylistTracksView::startDrag(QMouseEvent *event) { QModelIndexList indices = this->selectedIndexes(); QByteArray tracks; for(int i=0;i<indices.length(); i++) { int row = 0; tracks.append(this->model()->data(indices.at(i)).toByteArray()); tracks.append(" "); } tracks.remove(tracks.length() - 1, 1); QMimeData *mimedata = new QMimeData(); mimedata->setData("application/sg-music-library-reference-drag", tracks); QDrag *drag = new QDrag(this); drag->setMimeData(mimedata); QPixmap pixmap(this->style()->standardPixmap(QStyle::SP_FileIcon)); drag->setPixmap(pixmap); Qt::DropAction dropAction = drag->exec(Qt::CopyAction); } void MusicPlaylistTracksView::mouseMoveEvent(QMouseEvent *event) { this->startDrag(event); } void MusicPlaylistTracksView::dragEnterEvent(QDragEnterEvent *event) { if(custom_model->oid == 0) { event->ignore(); return; } if(event->mimeData()->hasFormat(library_mime_type)) { event->acceptProposedAction(); } else { event->ignore(); } } void MusicPlaylistTracksView::dragMoveEvent(QDragMoveEvent *event) { if(event->mimeData()->hasFormat(library_mime_type)) { event->acceptProposedAction(); } else { event->ignore(); } } void MusicPlaylistTracksView::dropEvent(QDropEvent *event) { if(event->mimeData()->hasFormat(library_mime_type)) { QByteArray data(event->mimeData()->data(library_mime_type)); QString data_parse(data); QStringList tracks = data_parse.split(" "); custom_model->database().transaction(); for(int i=0; i<tracks.length(); i++) { custom_model->insertTrackIntoObject(tracks.at(i).toInt()); this->resizeColumnsToContents(); this->resizeRowsToContents(); } custom_model->database().commit(); custom_model->select(); event->acceptProposedAction(); } else { event->ignore(); } event->ignore(); }
29.974359
85
0.657827
[ "model" ]
4f0f2f8a03e06a1642a47791757aa66caaf9a71d
3,833
cpp
C++
mooc50-bobo-DS/cppHoupengfei88/14-Hash-Table/05-Hash-Table-Implementation/main.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
2
2019-03-20T17:05:59.000Z
2019-10-15T07:56:45.000Z
mooc50-bobo-DS/cppHoupengfei88/14-Hash-Table/05-Hash-Table-Implementation/main.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
6
2019-12-04T06:08:32.000Z
2021-05-10T20:22:47.000Z
mooc50-bobo-DS/cppHoupengfei88/14-Hash-Table/05-Hash-Table-Implementation/main.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "FileOperation.h" #include "BST.h" #include "RBTree.h" #include "AVLTree.h" #include "HashTable.h" template<typename T> double testMap(T *map, string filename) { clock_t startTime = clock(); srand(66); vector<string> words; if (FileOps::readFile(filename, words)) { std::cout << "Total words: " << words.size() << std::endl; for (string word : words) { if (map->contains(word)) { map->set(word, *(map->get(word)) + 1); } else { map->add(word, 1); } } for (string word : words) { map->contains(word); } std::cout << "Total different words: " << map->getSize() << std::endl; std::cout << "Frequency of PRIDE: " << *(map->get("pride")) << std::endl; std::cout << "Frequency of PREJUDICE: " << *(map->get("prejudice")) << std::endl; } clock_t endTime = clock(); return double(endTime - startTime) / CLOCKS_PER_SEC; } template<typename T> double testData(T *map, vector<int> &dataes) { clock_t startTime = clock(); for (int data : dataes) { if (map->contains(data)) { map->set(data, *(map->get(data)) + 1); } else { map->add(data, 1); } } for (int data : dataes) { map->contains(data); } clock_t endTime = clock(); return double(endTime - startTime) / CLOCKS_PER_SEC; } int main() { std::cout << "pride-and-prejudice.txt" << std::endl; string filename = ".././pride-and-prejudice.txt"; int n = 20000; vector<int> testDataes, testDataes1; for (int i = 0; i < n; ++i) { testDataes.push_back(rand() % INT64_MAX); testDataes1.push_back(i); } BSTMap<string, int> *bstMap = new BSTMap<string, int>(); float time1 = testMap(bstMap, filename); std::cout << "BSTMap time : " << time1 << " s " << std::endl; RBTree<string, int> *rbTree = new RBTree<string, int>(); float time2 = testMap(rbTree, filename); std::cout << "RBTree time : " << time2 << " s " << std::endl; AVLTree<string, int> *avlTree = new AVLTree<string, int>(); float time3 = testMap(avlTree, filename); std::cout << "AVLTree time : " << time3 << " s " << std::endl; HashTable<string, int> *hashTable = new HashTable<string, int> (); float time4 = testMap(hashTable, filename); std::cout << "HashTable time : " << time4 << " s " << std::endl; std::cout << "Test Dataes:" << std::endl; BSTMap<int, int> *bstMap1 = new BSTMap<int, int>(); float time5 = testData(bstMap1, testDataes); std::cout << "BSTMap time : " << time5 << " s " << std::endl; RBTree<int, int> *rbTree1 = new RBTree<int, int>(); float time6 = testData(rbTree1, testDataes); std::cout << "RBTree time : " << time6 << " s " << std::endl; AVLTree<int, int> *avlTree1 = new AVLTree<int, int>(); float time7 = testData(avlTree1, testDataes); std::cout << "AVLTree time : " << time7 << " s " << std::endl; HashTable<int, int> *hashTable1 = new HashTable<int, int> (); float time8 = testData(hashTable1, testDataes); std::cout << "HashTable time : " << time8 << " s " << std::endl; std::cout << "Test Dataes1" << std::endl; RBTree<int, int> *rbTree2 = new RBTree<int, int>(); float time9 = testData(rbTree2, testDataes1); std::cout << "RBTree time : " << time9 << " s " << std::endl; AVLTree<int, int> *avlTree2 = new AVLTree<int, int>(); float time10 = testData(avlTree2, testDataes1); std::cout << "AVLTree time : " << time10 << " s " << std::endl; HashTable<int, int> *hashTable2 = new HashTable<int, int> (); float time11 = testData(hashTable2, testDataes1); std::cout << "HashTable time : " << time11 << " s " << std::endl; return 0; }
36.504762
89
0.566919
[ "vector" ]
4f0f364275516ab58d72d372b3dfeca7e1bf80bc
3,136
cpp
C++
src/java/pmod/jni/JniUtility.cpp
Bhaskers-Blu-Org2/pmod
92e3c0ecff25763dcfabab0c1fb86d58e60cbb1a
[ "MIT" ]
19
2019-06-16T02:29:24.000Z
2022-03-01T23:20:25.000Z
src/java/pmod/jni/JniUtility.cpp
microsoft/pmod
92e3c0ecff25763dcfabab0c1fb86d58e60cbb1a
[ "MIT" ]
null
null
null
src/java/pmod/jni/JniUtility.cpp
microsoft/pmod
92e3c0ecff25763dcfabab0c1fb86d58e60cbb1a
[ "MIT" ]
5
2019-11-03T11:40:25.000Z
2020-08-05T14:56:13.000Z
/*** * Copyright (C) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. * * File:JniUtility.cpp ****/ #include "JniUtility.h" #include "JVMEnv.h" #include "JClass.h" #include "JString.h" using namespace Java; //+--------------------------------------------------------------------- // Routine Description: // Create JNI global reference. // // Arguments: // env: The JNIEnv pointer. // jobj: The java object which will be globally referenced. // // Return value: // The global reference. //---------------------------------------------------------------------- jobject JniUtility::newGlobalRef(JNIEnv* env, jobject jobj) { if (env == NULL) { return NULL; } return env->NewGlobalRef(jobj); } //+--------------------------------------------------------------------- // Routine Description: // Create JNI global reference. // // Arguments: // jobj: The java object which will be globally referenced. // // Return value: // The global reference. //---------------------------------------------------------------------- jobject JniUtility::newGlobalRef(jobject jobj) { if (jobj != NULL) { JNIEnv* env; if (JVMEnv::attachCurrentJNIEnv(&env) == 0) { return JniUtility::newGlobalRef(env, jobj); } } return NULL; } //+--------------------------------------------------------------------- // Routine Description: // Delete JNI global reference. // // Arguments: // jobj: The java global reference which will be deleted. //---------------------------------------------------------------------- void JniUtility::deleteGlobalRef(jobject jobj) { if (jobj != NULL) { JNIEnv* env; if (JVMEnv::attachCurrentJNIEnv(&env) == 0) { env->DeleteGlobalRef(jobj); } } } JString JniUtility::getClassName(JNIEnv* env, jobject jobj) { JClass objClass(jobj); JClass clazz("java/lang/Class"); static jmethodID methodID = env->GetMethodID((jclass)clazz, "getName", "()Ljava/lang/String;"); return JString((jstring)env->CallObjectMethod(objClass, methodID), true); } JString JniUtility::getClassName(jobject jobj) { JNIEnv* env = NULL; JVMEnv::attachCurrentJNIEnv(&env); return getClassName(env, jobj); } void JniUtility::clearJavaException(JNIEnv* env) { env->ExceptionClear(); } bool JniUtility::retrieveJavaException(JNIEnv* env, bool clearException, JObject& exception) { jobject objException = env->ExceptionOccurred(); if (objException != NULL) { env->ExceptionClear(); // have to clear exception before call JObject // Workaround: throw exception back after JObject is called. exception = JObject(objException, true); if (!clearException && objException != NULL) { env->Throw((jthrowable)objException); } } return (objException != NULL); }
27.034483
105
0.529018
[ "object" ]
4f0f8c522d73d9cfeefe5829acaafb01fcc1a651
2,185
cpp
C++
primer/Associative_Containers_11/transformation_map.cpp
misslzyan/CPlusPlus
92c05955cf0221c63c687cdb71ee758a3e978ac2
[ "Apache-2.0" ]
null
null
null
primer/Associative_Containers_11/transformation_map.cpp
misslzyan/CPlusPlus
92c05955cf0221c63c687cdb71ee758a3e978ac2
[ "Apache-2.0" ]
null
null
null
primer/Associative_Containers_11/transformation_map.cpp
misslzyan/CPlusPlus
92c05955cf0221c63c687cdb71ee758a3e978ac2
[ "Apache-2.0" ]
null
null
null
#include <fstream> #include <sstream> #include <iostream> #include <map> #include <string> std::map<std::string, std::string> build_map(std::ifstream &in) { std::map<std::string, std::string> map; std::string line; std::string word; std::istringstream in_str; while(getline(in, line)){ // std::cout << "line:" << line << "\n"; in_str.str(line); in_str.clear(); bool first = true; std::ostringstream out_str; std::string k; bool vfirst = true; while(in_str >> word) { // std::cout << "word:" << word << "\n"; if(first){ first = false; k = word; }else { if(vfirst){ out_str << word; vfirst = false; }else{ out_str << " " << word; } } } //std::cout << "K:" << k << "\n"; // std::cout << "v:" << out_str.str() << "\n"; map[k] = out_str.str(); } return map; } void print(std::map<std::string, std::string> map) { for(auto &w : map) { std::cout << w.first << " -> " << w.second << "\n"; } } std::string transfor_line(std::map<std::string, std::string> &map, std::string &line) { std::string res; std::istringstream input(line); std::string word; auto end = map.end(); bool first = true; while(input >> word) { auto begin = map.find(word); if (begin == end) { if(first){ res.append(word); first = false; }else{ res.append(" "); res.append(word); } }else{ if(first){ res.append(begin->second); first = false; }else{ res.append(" "); res.append(begin->second); } } } return res; } void transform(std::ifstream &map_in, std::ifstream &i_in){ auto map = build_map(map_in); // print(map); std::string line; // getline(i_in, line); while(getline(i_in, line)) { std::cout << transfor_line(map, line) << "\n"; } // auto r = transfor_line(map, line); // std::cout << r << "\n"; } int main () { std::string map_file = "map_file.data"; std::string in_file = "in_file.data"; std::ifstream map_in(map_file); std::ifstream i_in(in_file); transform(map_in, i_in); return 0; }
22.295918
87
0.535011
[ "transform" ]
4f15396d6b8374b15c75d62b92e654c393134ace
18,486
cpp
C++
test/TileQueueTests.cpp
klada/online
3c1185aca331222fefcc7a55c8d30064e2ef0a58
[ "BSD-2-Clause" ]
null
null
null
test/TileQueueTests.cpp
klada/online
3c1185aca331222fefcc7a55c8d30064e2ef0a58
[ "BSD-2-Clause" ]
1
2022-02-24T13:46:43.000Z
2022-02-24T13:46:43.000Z
test/TileQueueTests.cpp
klada/online
3c1185aca331222fefcc7a55c8d30064e2ef0a58
[ "BSD-2-Clause" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */ /* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <config.h> #include <test/lokassert.hpp> #include <Common.hpp> #include <Protocol.hpp> #include <Message.hpp> #include <MessageQueue.hpp> #include <SenderQueue.hpp> #include <Util.hpp> /// TileQueue unit-tests. class TileQueueTests : public CPPUNIT_NS::TestFixture { CPPUNIT_TEST_SUITE(TileQueueTests); CPPUNIT_TEST(testTileQueuePriority); CPPUNIT_TEST(testTileCombinedRendering); CPPUNIT_TEST(testTileRecombining); CPPUNIT_TEST(testViewOrder); CPPUNIT_TEST(testPreviewsDeprioritization); CPPUNIT_TEST(testSenderQueue); CPPUNIT_TEST(testSenderQueueTileDeduplication); CPPUNIT_TEST(testInvalidateViewCursorDeduplication); CPPUNIT_TEST(testCallbackModifiedStatusIsSkipped); CPPUNIT_TEST(testCallbackInvalidation); CPPUNIT_TEST(testCallbackIndicatorValue); CPPUNIT_TEST(testCallbackPageSize); CPPUNIT_TEST_SUITE_END(); void testTileQueuePriority(); void testTileCombinedRendering(); void testTileRecombining(); void testViewOrder(); void testPreviewsDeprioritization(); void testSenderQueue(); void testSenderQueueTileDeduplication(); void testInvalidateViewCursorDeduplication(); void testCallbackModifiedStatusIsSkipped(); void testCallbackInvalidation(); void testCallbackIndicatorValue(); void testCallbackPageSize(); }; void TileQueueTests::testTileQueuePriority() { constexpr auto testname = __func__; const std::string reqHigh = "tile nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=0 tilewidth=3840 tileheight=3840 oldwid=0 wid=0"; const std::string resHigh = "tile nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=0 tilewidth=3840 tileheight=3840 oldwid=0 wid=0 ver=-1"; const TileQueue::Payload payloadHigh(resHigh.data(), resHigh.data() + resHigh.size()); const std::string reqLow = "tile nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=253440 tilewidth=3840 tileheight=3840 oldwid=0 wid=0"; const std::string resLow = "tile nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=253440 tilewidth=3840 tileheight=3840 oldwid=0 wid=0 ver=-1"; const TileQueue::Payload payloadLow(resLow.data(), resLow.data() + resLow.size()); TileQueue queue; // Request the tiles. queue.put(reqLow); queue.put(reqHigh); // Original order. LOK_ASSERT_EQUAL_STR(payloadLow, queue.get()); LOK_ASSERT_EQUAL_STR(payloadHigh, queue.get()); // Request the tiles. queue.put(reqLow); queue.put(reqHigh); queue.put(reqHigh); queue.put(reqLow); // Set cursor above reqHigh. queue.updateCursorPosition(0, 0, 0, 0, 10, 100); // Prioritized order. LOK_ASSERT_EQUAL_STR(payloadHigh, queue.get()); LOK_ASSERT_EQUAL_STR(payloadLow, queue.get()); // Repeat with cursor position set. queue.put(reqLow); queue.put(reqHigh); LOK_ASSERT_EQUAL_STR(payloadHigh, queue.get()); LOK_ASSERT_EQUAL_STR(payloadLow, queue.get()); // Repeat by changing cursor position. queue.put(reqLow); queue.put(reqHigh); queue.updateCursorPosition(0, 0, 0, 253450, 10, 100); LOK_ASSERT_EQUAL_STR(payloadLow, queue.get()); LOK_ASSERT_EQUAL_STR(payloadHigh, queue.get()); } void TileQueueTests::testTileCombinedRendering() { constexpr auto testname = __func__; const std::string req1 = "tile nviewid=0 nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=0 tilewidth=3840 tileheight=3840"; const std::string req2 = "tile nviewid=0 part=0 width=256 height=256 tileposx=3840 tileposy=0 tilewidth=3840 tileheight=3840"; const std::string req3 = "tile nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=3840 tilewidth=3840 tileheight=3840"; const std::string resHor = "tilecombine nviewid=0 part=0 width=256 height=256 tileposx=0,3840 tileposy=0,0 imgsize=0,0 tilewidth=3840 tileheight=3840 ver=-1,-1 oldwid=0,0 wid=0,0"; const TileQueue::Payload payloadHor(resHor.data(), resHor.data() + resHor.size()); const std::string resVer = "tilecombine nviewid=0 part=0 width=256 height=256 tileposx=0,0 tileposy=0,3840 imgsize=0,0 tilewidth=3840 tileheight=3840 ver=-1,-1 oldwid=0,0 wid=0,0"; const TileQueue::Payload payloadVer(resVer.data(), resVer.data() + resVer.size()); const std::string resFull = "tilecombine nviewid=0 part=0 width=256 height=256 tileposx=0,3840,0 tileposy=0,0,3840 imgsize=0,0,0 tilewidth=3840 tileheight=3840 ver=-1,-1,-1 oldwid=0,0,0 wid=0,0,0"; const TileQueue::Payload payloadFull(resFull.data(), resFull.data() + resFull.size()); TileQueue queue; // Horizontal. queue.put(req1); queue.put(req2); LOK_ASSERT_EQUAL_STR(payloadHor, queue.get()); // Vertical. queue.put(req1); queue.put(req3); LOK_ASSERT_EQUAL_STR(payloadVer, queue.get()); // Vertical. queue.put(req1); queue.put(req2); queue.put(req3); LOK_ASSERT_EQUAL_STR(payloadFull, queue.get()); } void TileQueueTests::testTileRecombining() { constexpr auto testname = __func__; TileQueue queue; queue.put("tilecombine nviewid=0 part=0 width=256 height=256 tileposx=0,3840,7680 tileposy=0,0,0 tilewidth=3840 tileheight=3840"); queue.put("tilecombine nviewid=0 part=0 width=256 height=256 tileposx=0,3840 tileposy=0,0 tilewidth=3840 tileheight=3840"); // the tilecombine's get merged, resulting in 3 "tile" messages LOK_ASSERT_EQUAL(3, static_cast<int>(queue.getQueue().size())); // but when we later extract that, it is just one "tilecombine" message LOK_ASSERT_EQUAL_STR( "tilecombine nviewid=0 part=0 width=256 height=256 tileposx=7680,0,3840 tileposy=0,0,0 " "imgsize=0,0,0 tilewidth=3840 tileheight=3840 ver=-1,-1,-1 oldwid=0,0,0 wid=0,0,0", queue.get()); // and nothing remains in the queue LOK_ASSERT_EQUAL(0, static_cast<int>(queue.getQueue().size())); } void TileQueueTests::testViewOrder() { constexpr auto testname = __func__; TileQueue queue; // should result in the 3, 2, 1, 0 order of the views queue.updateCursorPosition(0, 0, 0, 0, 10, 100); queue.updateCursorPosition(2, 0, 0, 0, 10, 100); queue.updateCursorPosition(1, 0, 0, 7680, 10, 100); queue.updateCursorPosition(3, 0, 0, 0, 10, 100); queue.updateCursorPosition(2, 0, 0, 15360, 10, 100); queue.updateCursorPosition(3, 0, 0, 23040, 10, 100); const std::vector<std::string> tiles = { "tile nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=0 tilewidth=3840 tileheight=3840 oldwid=0 wid=0 ver=-1", "tile nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=7680 tilewidth=3840 tileheight=3840 oldwid=0 wid=0 ver=-1", "tile nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=15360 tilewidth=3840 tileheight=3840 oldwid=0 wid=0 ver=-1", "tile nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=23040 tilewidth=3840 tileheight=3840 oldwid=0 wid=0 ver=-1" }; for (auto &tile : tiles) queue.put(tile); LOK_ASSERT_EQUAL(4, static_cast<int>(queue.getQueue().size())); // should result in the 3, 2, 1, 0 order of the tiles thanks to the cursor // positions for (size_t i = 0; i < tiles.size(); ++i) { LOK_ASSERT_EQUAL_STR(tiles[3 - i], queue.get()); } } void TileQueueTests::testPreviewsDeprioritization() { constexpr auto testname = __func__; TileQueue queue; // simple case - put previews to the queue and get everything back again const std::vector<std::string> previews = { "tile nviewid=0 part=0 width=180 height=135 tileposx=0 tileposy=0 tilewidth=15875 tileheight=11906 ver=-1 id=0", "tile nviewid=0 part=1 width=180 height=135 tileposx=0 tileposy=0 tilewidth=15875 tileheight=11906 ver=-1 id=1", "tile nviewid=0 part=2 width=180 height=135 tileposx=0 tileposy=0 tilewidth=15875 tileheight=11906 ver=-1 id=2", "tile nviewid=0 part=3 width=180 height=135 tileposx=0 tileposy=0 tilewidth=15875 tileheight=11906 ver=-1 id=3" }; for (auto &preview : previews) queue.put(preview); for (size_t i = 0; i < previews.size(); ++i) { LOK_ASSERT_EQUAL_STR(previews[i], queue.get()); } // stays empty after all is done LOK_ASSERT_EQUAL(0, static_cast<int>(queue.getQueue().size())); // re-ordering case - put previews and normal tiles to the queue and get // everything back again but this time the tiles have to interleave with // the previews const std::vector<std::string> tiles = { "tile nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=0 tilewidth=3840 tileheight=3840 oldwid=0 wid=0 ver=-1", "tile nviewid=0 part=0 width=256 height=256 tileposx=0 tileposy=7680 tilewidth=3840 tileheight=3840 oldwid=0 wid=0 ver=-1" }; for (auto &preview : previews) queue.put(preview); queue.put(tiles[0]); LOK_ASSERT_EQUAL_STR(previews[0], queue.get()); LOK_ASSERT_EQUAL_STR(tiles[0], queue.get()); LOK_ASSERT_EQUAL_STR(previews[1], queue.get()); queue.put(tiles[1]); LOK_ASSERT_EQUAL_STR(previews[2], queue.get()); LOK_ASSERT_EQUAL_STR(tiles[1], queue.get()); LOK_ASSERT_EQUAL_STR(previews[3], queue.get()); // stays empty after all is done LOK_ASSERT_EQUAL(0, static_cast<int>(queue.getQueue().size())); // cursor positioning case - the cursor position should not prioritize the // previews queue.updateCursorPosition(0, 0, 0, 0, 10, 100); queue.put(tiles[1]); queue.put(previews[0]); LOK_ASSERT_EQUAL_STR(tiles[1], queue.get()); LOK_ASSERT_EQUAL_STR(previews[0], queue.get()); // stays empty after all is done LOK_ASSERT_EQUAL(0, static_cast<int>(queue.getQueue().size())); } void TileQueueTests::testSenderQueue() { constexpr auto testname = __func__; SenderQueue<std::shared_ptr<Message>> queue; std::shared_ptr<Message> item; // Empty queue LOK_ASSERT_EQUAL_STR(false, queue.dequeue(item)); LOK_ASSERT_EQUAL(static_cast<size_t>(0), queue.size()); const std::vector<std::string> messages = { "message 1", "message 2", "message 3" }; for (const auto& msg : messages) { queue.enqueue(std::make_shared<Message>(msg, Message::Dir::Out)); } LOK_ASSERT_EQUAL(static_cast<size_t>(3), queue.size()); LOK_ASSERT_EQUAL_STR(true, queue.dequeue(item)); LOK_ASSERT_EQUAL(static_cast<size_t>(2), queue.size()); LOK_ASSERT_EQUAL(messages[0], std::string(item->data().data(), item->data().size())); LOK_ASSERT_EQUAL_STR(true, queue.dequeue(item)); LOK_ASSERT_EQUAL(static_cast<size_t>(1), queue.size()); LOK_ASSERT_EQUAL(messages[1], std::string(item->data().data(), item->data().size())); LOK_ASSERT_EQUAL_STR(true, queue.dequeue(item)); LOK_ASSERT_EQUAL(static_cast<size_t>(0), queue.size()); LOK_ASSERT_EQUAL(messages[2], std::string(item->data().data(), item->data().size())); LOK_ASSERT_EQUAL(static_cast<size_t>(0), queue.size()); } void TileQueueTests::testSenderQueueTileDeduplication() { constexpr auto testname = __func__; SenderQueue<std::shared_ptr<Message>> queue; std::shared_ptr<Message> item; // Empty queue LOK_ASSERT_EQUAL_STR(false, queue.dequeue(item)); LOK_ASSERT_EQUAL(static_cast<size_t>(0), queue.size()); const std::vector<std::string> part_messages = { "tile: nviewid=0 part=0 width=180 height=135 tileposx=0 tileposy=0 tilewidth=15875 tileheight=11906 ver=0", "tile: nviewid=0 part=1 width=180 height=135 tileposx=0 tileposy=0 tilewidth=15875 tileheight=11906 ver=1", "tile: nviewid=0 part=2 width=180 height=135 tileposx=0 tileposy=0 tilewidth=15875 tileheight=11906 ver=-1" }; for (const auto& msg : part_messages) { queue.enqueue(std::make_shared<Message>(msg, Message::Dir::Out)); } LOK_ASSERT_EQUAL(static_cast<size_t>(3), queue.size()); LOK_ASSERT_EQUAL_STR(true, queue.dequeue(item)); LOK_ASSERT_EQUAL_STR(true, queue.dequeue(item)); LOK_ASSERT_EQUAL_STR(true, queue.dequeue(item)); LOK_ASSERT_EQUAL(static_cast<size_t>(0), queue.size()); const std::vector<std::string> dup_messages = { "tile: nviewid=0 part=0 width=180 height=135 tileposx=0 tileposy=0 tilewidth=15875 tileheight=11906 ver=-1", "tile: nviewid=0 part=0 width=180 height=135 tileposx=0 tileposy=0 tilewidth=15875 tileheight=11906 ver=1", "tile: nviewid=0 part=0 width=180 height=135 tileposx=0 tileposy=0 tilewidth=15875 tileheight=11906 ver=1" }; for (const auto& msg : dup_messages) { queue.enqueue(std::make_shared<Message>(msg, Message::Dir::Out)); } LOK_ASSERT_EQUAL(static_cast<size_t>(1), queue.size()); LOK_ASSERT_EQUAL_STR(true, queue.dequeue(item)); // The last one should persist. LOK_ASSERT_EQUAL(dup_messages[2], std::string(item->data().data(), item->data().size())); LOK_ASSERT_EQUAL(static_cast<size_t>(0), queue.size()); } void TileQueueTests::testInvalidateViewCursorDeduplication() { constexpr auto testname = __func__; SenderQueue<std::shared_ptr<Message>> queue; std::shared_ptr<Message> item; // Empty queue LOK_ASSERT_EQUAL_STR(false, queue.dequeue(item)); LOK_ASSERT_EQUAL(static_cast<size_t>(0), queue.size()); const std::vector<std::string> view_messages = { "invalidateviewcursor: { \"viewId\": \"1\", \"rectangle\": \"3999, 1418, 0, 298\", \"part\": \"0\" }", "invalidateviewcursor: { \"viewId\": \"2\", \"rectangle\": \"3999, 1418, 0, 298\", \"part\": \"0\" }", "invalidateviewcursor: { \"viewId\": \"3\", \"rectangle\": \"3999, 1418, 0, 298\", \"part\": \"0\" }", }; for (const auto& msg : view_messages) { queue.enqueue(std::make_shared<Message>(msg, Message::Dir::Out)); } LOK_ASSERT_EQUAL(static_cast<size_t>(3), queue.size()); LOK_ASSERT_EQUAL_STR(true, queue.dequeue(item)); LOK_ASSERT_EQUAL(static_cast<size_t>(2), queue.size()); LOK_ASSERT_EQUAL(view_messages[0], std::string(item->data().data(), item->data().size())); LOK_ASSERT_EQUAL_STR(true, queue.dequeue(item)); LOK_ASSERT_EQUAL(static_cast<size_t>(1), queue.size()); LOK_ASSERT_EQUAL(view_messages[1], std::string(item->data().data(), item->data().size())); LOK_ASSERT_EQUAL_STR(true, queue.dequeue(item)); LOK_ASSERT_EQUAL(static_cast<size_t>(0), queue.size()); LOK_ASSERT_EQUAL(view_messages[2], std::string(item->data().data(), item->data().size())); LOK_ASSERT_EQUAL(static_cast<size_t>(0), queue.size()); const std::vector<std::string> dup_messages = { "invalidateviewcursor: { \"viewId\": \"1\", \"rectangle\": \"3999, 1418, 0, 298\", \"part\": \"0\" }", "invalidateviewcursor: { \"viewId\": \"1\", \"rectangle\": \"1000, 1418, 0, 298\", \"part\": \"0\" }", "invalidateviewcursor: { \"viewId\": \"1\", \"rectangle\": \"2000, 1418, 0, 298\", \"part\": \"0\" }", }; for (const auto& msg : dup_messages) { queue.enqueue(std::make_shared<Message>(msg, Message::Dir::Out)); } LOK_ASSERT_EQUAL(static_cast<size_t>(1), queue.size()); LOK_ASSERT_EQUAL_STR(true, queue.dequeue(item)); // The last one should persist. LOK_ASSERT_EQUAL(dup_messages[2], std::string(item->data().data(), item->data().size())); LOK_ASSERT_EQUAL(static_cast<size_t>(0), queue.size()); } void TileQueueTests::testCallbackInvalidation() { constexpr auto testname = __func__; TileQueue queue; // join tiles queue.put("callback all 0 284, 1418, 11105, 275, 0"); queue.put("callback all 0 4299, 1418, 7090, 275, 0"); LOK_ASSERT_EQUAL(1, static_cast<int>(queue.getQueue().size())); LOK_ASSERT_EQUAL_STR("callback all 0 284, 1418, 11105, 275, 0", queue.get()); // invalidate everything with EMPTY, but keep the different part intact queue.put("callback all 0 284, 1418, 11105, 275, 0"); queue.put("callback all 0 4299, 1418, 7090, 275, 1"); queue.put("callback all 0 4299, 10418, 7090, 275, 0"); queue.put("callback all 0 4299, 20418, 7090, 275, 0"); LOK_ASSERT_EQUAL(4, static_cast<int>(queue.getQueue().size())); queue.put("callback all 0 EMPTY, 0"); LOK_ASSERT_EQUAL(2, static_cast<int>(queue.getQueue().size())); LOK_ASSERT_EQUAL_STR("callback all 0 4299, 1418, 7090, 275, 1", queue.get()); LOK_ASSERT_EQUAL_STR("callback all 0 EMPTY, 0", queue.get()); } void TileQueueTests::testCallbackIndicatorValue() { constexpr auto testname = __func__; TileQueue queue; // join tiles queue.put("callback all 10 25"); queue.put("callback all 10 50"); LOK_ASSERT_EQUAL(1, static_cast<int>(queue.getQueue().size())); LOK_ASSERT_EQUAL_STR("callback all 10 50", queue.get()); } void TileQueueTests::testCallbackPageSize() { constexpr auto testname = __func__; TileQueue queue; // join tiles queue.put("callback all 13 12474, 188626"); queue.put("callback all 13 12474, 205748"); LOK_ASSERT_EQUAL(1, static_cast<int>(queue.getQueue().size())); LOK_ASSERT_EQUAL_STR("callback all 13 12474, 205748", queue.get()); } void TileQueueTests::testCallbackModifiedStatusIsSkipped() { constexpr auto testname = __func__; TileQueue queue; std::stringstream ss; ss << "callback all " << LOK_CALLBACK_STATE_CHANGED; const std::vector<std::string> messages = { ss.str() + " .uno:ModifiedStatus=false", ss.str() + " .uno:ModifiedStatus=true", ss.str() + " .uno:ModifiedStatus=true", ss.str() + " .uno:ModifiedStatus=false" }; for (const auto& msg : messages) { queue.put(msg); } LOK_ASSERT_EQUAL(static_cast<size_t>(4), queue.getQueue().size()); LOK_ASSERT_EQUAL_STR(messages[0], queue.get()); LOK_ASSERT_EQUAL_STR(messages[1], queue.get()); LOK_ASSERT_EQUAL_STR(messages[2], queue.get()); LOK_ASSERT_EQUAL_STR(messages[3], queue.get()); } CPPUNIT_TEST_SUITE_REGISTRATION(TileQueueTests); /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
36.824701
201
0.682408
[ "vector" ]
b7c225ad7efc3581b41f8689242dfb40eb1244ef
11,345
cpp
C++
src/wnd_manager.cpp
mikejzx/compasshub
f58bfd3c7e631464b61c3e333c7bcf34d47d28b1
[ "WTFPL" ]
null
null
null
src/wnd_manager.cpp
mikejzx/compasshub
f58bfd3c7e631464b61c3e333c7bcf34d47d28b1
[ "WTFPL" ]
null
null
null
src/wnd_manager.cpp
mikejzx/compasshub
f58bfd3c7e631464b61c3e333c7bcf34d47d28b1
[ "WTFPL" ]
null
null
null
/* * wnd_manager.cpp * The window manager. */ #include "pch.h" #include "anchor.h" #include "application.h" #include "datetime.h" #include "datetime_dmy.h" #include "net_client.h" #include "tt_day.h" #include "tt_period.h" #include "vec2.h" #include "window.h" #include "window_main.h" #include "window_second.h" #include "wnd_manager.h" // Constructor. wnd_manager::wnd_manager() { // Initialise ncurses TUI. ncurses_init(); // Refresh standard screen. wclear(stdscr); wrefresh(stdscr); // Create our windows. // Header window* whead = new window({ 1, COH_WND_STRETCH }, { 0, 0 }, anchor::TOP); whead->colour_bg_set(COH_COL_HEADER); whead->add_str(COH_WND_HEADER_TEXT, { 0, 0 }, ANCH_TL); whead->add_str(COH_PROGRAM_CREDIT, { 0, 0 }, ANCH_TR); // Main window_main* wmain = new window_main({ COH_WND_STRETCH, 100 }, { 2, 0 }, anchor::LEFT, { 1, 0, 2, 0 }); wmain_str_load = wmain->add_str("", { 4, 0 }, ANCH_CTR_T); // Events window* wevnt = new window_second({ COH_WND_STRETCH, 70 }, { 0, 2 }, anchor::RIGHT, { 1, 0, 2, 0 }); wevnt->add_str("Events:", { 2, 0 }, ANCH_CTR_T); wevnt_str_status = wevnt->add_str(COH_SZ_NOEVENTS, { 4, 0 }, ANCH_CTR_T); // Footer window* wfoot = new window({ 1, COH_WND_STRETCH }, { 1, 0 }, anchor::BOTTOM); wfoot->colour_bg_set(COH_COL_FOOTER); wfoot_str_status = wfoot->add_str(COH_SZ_STATUS_LOGGEDOFF, { 0, 2 }, ANCH_BR); wfoot_str_retrv = wfoot->add_str(COH_SZ_RETR_PROMPT, { 0, 2 }, ANCH_BL, A_BOLD); // Status line. Most of this is handled manually. window* wstat = new window({ 1, COH_WND_STRETCH }, { 0, 0 }, anchor::BOTTOM); wstat_str_status = wstat->add_str("", { 0, 0 }, anchor::LEFT); // Add to the windows vector. wnds.resize(5); wnds[COH_WND_IDX_FOOTER] = wfoot; wnds[COH_WND_IDX_MAIN] = wmain; wnds[COH_WND_IDX_HEADER] = whead; wnds[COH_WND_IDX_EVENTS] = wevnt; wnds[COH_WND_IDX_STATUS] = wstat; // Handle window resizes. struct sigaction sigact_resize = { [](int param) { (void)param; // Call these to reinitialise terminal. endwin(); wrefresh(stdscr); wclear(stdscr); wrefresh(stdscr); // Redraw everything if we aren't too small. if (wnd_manager::can_draw()) { wnd_manager::get().on_resize(); } } }; sigaction(SIGWINCH, &sigact_resize, NULL); } // Destructor. wnd_manager::~wnd_manager() { // De-initialise ncurses TUI. ncurses_deinit(); // Delete windows. for (unsigned i = 0; i < wnds.size(); ++i) { delete wnds[i]; } } // Called when we have everything already initialised. void wnd_manager::redraw_initial(void) { // Refresh all our stuff from cache. refresh_from_cache(); // Make sure we have reasonable size. if (wnd_manager::can_draw()) { return; } // Mark everything as dirty. for (unsigned i = 0; i < wnds.size(); ++i) { wnds[i]->invalidate(); } // Redraw. redraw(); } // Inform all windows that there was a resize. // We also do a redraw. void wnd_manager::on_resize(void) { use_default_colors(); // Redraw all windows. for (unsigned i = 0; i < wnds.size(); ++i) { wnds[i]->on_resize(); wnds[i]->redraw(); } } // Force draw all windows. void wnd_manager::redraw(void) { use_default_colors(); // Redraw invalidated windows. for (unsigned i = 0; i < wnds.size(); ++i) { wnds[i]->redraw(); } } // Update loop, called constantly. // Return false when the program terminates. bool wnd_manager::update(void) { // Handle inputs. int ch; switch(ch = wgetch(get_wnd_main()->get_wndptr())) { // 'q' to quit. case ('q'): case ('Q'): { // Exit program. return false; } // 'r' to refresh. case ('r'): case ('R'): { refresh_from_server(); } break; // 'h' to navigate left. case ('h'): case ('H'): { // Tell the app to decrement date app->cur_date_decr(); // Refresh from cache. refresh_from_cache(); } break; // 'l' to navigate right. case ('l'): case ('L'): { // Tell the app to increment date app->cur_date_incr(); // Refresh from cache. refresh_from_cache(); } break; } return true; } // Initialises ncurses. void wnd_manager::ncurses_init(void) { initscr(); // Initialise screen. cbreak(); // Input one char at a time. noecho(); // Don't echo our inputs. setlocale(LC_ALL, ""); // Hide the cursor. curs_set(COH_WND_CURSOR_HIDDEN); // Initialise our colour pairs. start_color(); // Colour ID Foregr. Backgr. init_pair(COH_COL_HEADER, COLOR_BLACK, COLOR_YELLOW); init_pair(COH_COL_MAIN, COLOR_WHITE, COLOR_BLACK); init_pair(COH_COL_FOOTER, COLOR_WHITE, COH_COL_BG_STATUS); init_pair(COH_COL_STATUS_LI, COLOR_GREEN, COH_COL_BG_STATUS); init_pair(COH_COL_STATUS_LD, COLOR_YELLOW, COH_COL_BG_STATUS); init_pair(COH_COL_STATUS_LO, COLOR_RED, COH_COL_BG_STATUS); init_pair(COH_COL_STATUS_LO, COLOR_RED, COH_COL_BG_STATUS); init_pair(COH_COL_PERIOD_NORMAL, COLOR_WHITE, COLOR_BLUE); init_pair(COH_COL_PERIOD_NORMAL_B, COLOR_BLACK, COLOR_BLUE); init_pair(COH_COL_PERIOD_RCHANG, COLOR_WHITE, COLOR_RED); init_pair(COH_COL_PERIOD_RCHANG_B, COLOR_BLACK, COLOR_RED); init_pair(COH_COL_PERIOD_SUBST, COLOR_WHITE, COLOR_RED); init_pair(COH_COL_PERIOD_SUBST_B, COLOR_BLACK, COLOR_RED); init_pair(COH_COL_PERIOD_CANCEL, COLOR_WHITE, COLOR_BLACK); init_pair(COH_COL_PERIOD_CANCEL_B, COLOR_BLACK, COLOR_BLACK); LOG_INFO("ncurses initialised."); } // De-initialises ncurses. void wnd_manager::ncurses_deinit(void) { // Show cursor. curs_set(COH_WND_CURSOR_VISIBLE); // Deinitialise screen. endwin(); LOG_INFO("ncurses de-initialised."); } // Show the setup prompt void wnd_manager::show_setup_prompt(void) { // Create the window. window swnd = window({ COH_WND_STRETCH, COH_WND_STRETCH }, { 0, 0 }); swnd.add_str("Not set up yet. Please create the compasshub.prefs file.", { 0, 0 }, ANCH_CTR); swnd.add_str("Press any key to exit...", { 1, 0 }, ANCH_CTR); swnd.invalidate(); // Wait for a keypress. wgetch(swnd.get_wndptr()); } // Called whenever the login status changed. void wnd_manager::cb_login_status_changed(int status) { LOG_INFO("Login status changed to %d", status); // Get window text and attribute. std::string s; int a; switch (status) { // Logged off. case (COH_STATUS_LOGGEDOFF): { s = COH_SZ_STATUS_LOGGEDOFF; a = COLOR_PAIR(COH_COL_STATUS_LO); } break; // Read from disk case (COH_STATUS_READDISK): { s = COH_SZ_STATUS_READDISK; a = COLOR_PAIR(COH_COL_STATUS_LD); } break; // Logged in case (COH_STATUS_LOGGEDIN): { s = COH_SZ_STATUS_LOGGEDIN; a = COLOR_PAIR(COH_COL_STATUS_LI); } break; } // Apply to window. wnd_manager& wm = wnd_manager::get(); wm.get_wnd(COH_WND_IDX_FOOTER)->chg_str(wm.get_wfoot_str_status(), s, a); } // Called whenever the date is set. // We don't instantly update it though. Just change title. // Main timetable view update is done from view_date. void wnd_manager::cb_date_set(const datetime_dmy& d) { LOG_INFO("Date set to %02d.%02d.%02d", d.day, d.month, d.year); // Set the date string of main window. wnd_manager& wm = wnd_manager::get(); wm.get_wnd_main()->set_date(d); } // View the date. void wnd_manager::view_date(const tt_day& t) { // Change status bar retrieve string. get_wnd(COH_WND_IDX_FOOTER)->chg_str(get_wfoot_str_retrv(), std::string(COH_SZ_RETR_LAST).append(t.retrieved.get_pretty_string())); // Tell the main window to show our date. get_wnd_main()->set_date_info(t); } // Refresh the date from cache. void wnd_manager::refresh_from_cache(void) { // Get if we already cached data. tt_day o; if (app->get_tt_for_day_if_cached(o, app->get_cur_date())) { view_date(o); } else { // Set the text to refresh. get_wnd(COH_WND_IDX_FOOTER)->chg_str(get_wfoot_str_retrv(), COH_SZ_RETR_PROMPT); } } // Refresh from the data on server. void wnd_manager::refresh_from_server(void) { // Set loading string. get_wnd_main()->chg_str(get_wmain_str_load(), COH_SZ_LOADING); // Tell the app to get the data. // Then we view it here. auto l_get_tt = [&]() { tt_day o; if (app->get_tt_for_day_update(o, app->get_cur_date())) { // Hide the loading string. get_wnd_main()->chg_str(get_wmain_str_load(), ""); // View the timetable. view_date(o); // Done. return true; } return false; }; // If we get it, just return. if (l_get_tt()) { return; } // Hide loading string. get_wnd_main()->chg_str(get_wmain_str_load(), ""); // Ask for user's credentials. char cred_user[11]; char cred_pass[65]; if (!get_credentials(cred_user, cred_pass)) { return; } // Update string. window* const w = get_wnd(COH_WND_IDX_STATUS); w->chg_str(wstat_str_status, "Logging in..."); // Try login with what we got. app->client_get()->login(cred_user, cred_pass); // Try get schedule. std::string strlogin_status; int strcolour; if (l_get_tt()) { strlogin_status = "Successful login."; strcolour = COH_COL_STATUS_LI; } else { strlogin_status = "Failed to log in."; strcolour = COH_COL_STATUS_LO; } w->chg_str(wstat_str_status, strlogin_status, COLOR_PAIR(strcolour)); // Wait for input to hide string. wgetch(w->get_wndptr()); w->chg_str(wstat_str_status, ""); } // Ask for user's credentials. bool wnd_manager::get_credentials(char* user, char* pass) { // Get window where data is entered. static window& cwnd = *get_wnd(COH_WND_IDX_STATUS); static WINDOW* cwptr = cwnd.get_wndptr(); cwnd.invalidate(); // Enable cursor and echoing. curs_set(COH_WND_CURSOR_VISIBLE); // Used for getting string input. auto l_get_str = [&](char* buf, bool is_pass, size_t maxlen, size_t startpos) { // Position of cursor. size_t pos = 0; while (true) { bool bksp = false; chtype ch; switch(ch = wgetch(cwptr)) { // Handle return key. case (KEY_ENTER): case (0x0A): case (0x0D): { return; } // Handle backspaces. case (KEY_BACKSPACE): case (0x7F): case ('\b'): { // Only backspace if we are after first char. if (pos > 0) { // Clear the old char. mvwaddch(cwptr, 0, startpos + pos - 2, ' ' | A_INVIS); buf[pos] = '\0'; // Move cursor. --pos; wmove(cwptr, 0, startpos + pos - 1); wrefresh(cwptr); } else { buf[0] = '\0'; } bksp = true; } } // Check to make sure we aren't out of bounds. if (pos < maxlen && !bksp) { // Echo the char. wechochar(cwptr, is_pass ? '*' : ch); // Change buffer. buf[pos] = (char)ch; buf[pos + 1] = '\0'; // Move cursor. ++pos; } } }; // Write the username string, and get user input. wmove(cwptr, 0, 0); wrefresh(cwptr); waddstr(cwptr, "Username: "); l_get_str(user, false, 9, sizeof("Username: ")); // If length is zero, just abort. if (strlen(user) == 0) { goto cred_end; } // Write password, string, then get user input. wmove(cwptr, 0, 0); wclear(cwptr); wrefresh(cwptr); waddstr(cwptr, "Password: "); l_get_str(pass, true, 63, sizeof("Password: ")); // If length is zero, just abort. if (strlen(pass) == 0) { goto cred_end; } cred_end: // Clear the window. wclear(cwptr); wrefresh(cwptr); curs_set(COH_WND_CURSOR_HIDDEN); return true; }
22.554672
132
0.661877
[ "vector" ]
b7c4e07c0a9d88119e2b56321afb12a83bec7e05
3,409
hpp
C++
include/Engine3D.hpp
JeromeOrtali/PureBasic-Engine3D
bc584c6469a15cee4c2c7c1deb5dadfe91595eff
[ "BSD-2-Clause", "Apache-2.0" ]
1
2020-07-26T01:30:45.000Z
2020-07-26T01:30:45.000Z
include/Engine3D.hpp
JeromeOrtali/PureBasic-Engine3D
bc584c6469a15cee4c2c7c1deb5dadfe91595eff
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
include/Engine3D.hpp
JeromeOrtali/PureBasic-Engine3D
bc584c6469a15cee4c2c7c1deb5dadfe91595eff
[ "BSD-2-Clause", "Apache-2.0" ]
null
null
null
/* PureBasic Engine3D licence * -------------------------- * * MIT License * * Copyright (c) 2017 Jerome Ortali * * 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. */ #ifndef ENGINE3D_HPP #define ENGINE3D_HPP #include <Urho3D/Engine/Application.h> #include <Urho3D/Engine/Engine.h> #include <Urho3D/Input/InputEvents.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/Graphics/Renderer.h> #include <Urho3D/IO/IOEvents.h> #include <Urho3D/AngelScript/Script.h> #include <Urho3D/AngelScript/ScriptInstance.h> #include "Event.hpp" #include <Urho3D/IO/Log.h> #include "Node.hpp" #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Graphics/Geometry.h> #include <Urho3D/Graphics/DebugRenderer.h> #include <Urho3D/Scene/Node.h> #include <Urho3D/Graphics/Model.h> #include <Urho3D/Graphics/StaticModel.h> #include <Urho3D/Graphics/Drawable.h> #include <Urho3D/Engine/EngineDefs.h> #include <iostream> Urho3D::SharedPtr<Urho3D::Engine> PB_ENGINE; Urho3D::Context* PB_ENGINE_CONTEXT; // do not forget to delete RAW pointer at exit function !!! Urho3D::VariantMap* PB_ENGINE_PARAMETERS; Urho3D::ResourceCache* PB_RESOURCECACHE; PB_EventHandler* PB_URHOEVENT; std::queue<Event>* PB_EVENT; #ifndef PB_FUNCTION #define PB_FUNCTION(T) __declspec(dllexport) T #endif void register_script(); extern "C" { PB_FUNCTION(void) uh3_InitEngine3D(int argc, char **argv); PB_FUNCTION(void) uh3_OpenScreen3D(int width, int height, int fullscreen, const unsigned short* title, int resizable); PB_FUNCTION(void) uh3_EmbedScreen(void *window); PB_FUNCTION(int) uh3_EngineRun(); PB_FUNCTION(void) uh3_EngineExit(); PB_FUNCTION(void) uh3_EngineRenderFrame(); PB_FUNCTION(void) uh3_SetDrawShadow(int enable); PB_FUNCTION(int) uh3_GetDrawShadow(); PB_FUNCTION(void) uh3_SetHDRRendering(int enable); PB_FUNCTION(int) uh3_GetHDRRendering(); PB_FUNCTION(void) uh3_SetSpecularLighting(int enable); PB_FUNCTION(int) uh3_GetSpecularLighting(); PB_FUNCTION(void) uh3_SetShadowMapSize(int size); PB_FUNCTION(int) uh3_GetShadowMapSize(); PB_FUNCTION(void) uh3_SetShadowMapQuality(int quality); PB_FUNCTION(int) uh3_GetShadowMapQuality(); PB_FUNCTION(void) uh3_DrawDebugGeometry(NodeComponent component, Urho3D::Node* node, Urho3D::DebugRenderer* debug, int depthTest); } #endif
35.884211
132
0.751833
[ "geometry", "model" ]
b7cce7611a5210629ca83ef9f769d5ec01411114
612
cpp
C++
ch9/9.38.cpp
FWangTrading/Cpp-Primer-5th-Exercises
bce33ed38306485d503ff5117900ada9623bfbf4
[ "Apache-2.0" ]
545
2016-08-24T00:55:03.000Z
2022-03-29T22:59:24.000Z
ch9/9.38.cpp
FWangTrading/Cpp-Primer-5th-Exercises
bce33ed38306485d503ff5117900ada9623bfbf4
[ "Apache-2.0" ]
25
2017-06-05T18:45:56.000Z
2022-02-18T14:19:05.000Z
ch9/9.38.cpp
FWangTrading/Cpp-Primer-5th-Exercises
bce33ed38306485d503ff5117900ada9623bfbf4
[ "Apache-2.0" ]
260
2016-02-23T01:17:41.000Z
2022-03-26T08:35:54.000Z
#include <vector> #include <iostream> int main() { std::vector<int> vi; std::cout << "Size: " << vi.size() << "\tCapacity : " << vi.capacity() << std::endl; vi.push_back(1); std::cout << "Size: " << vi.size() << "\tCapacity : " << vi.capacity() << std::endl; for (std::vector<int>::size_type ix = 0; ix != 100; ++ix) vi.push_back(ix); std::cout << "Size: " << vi.size() << "\tCapacity : " << vi.capacity() << std::endl; vi.shrink_to_fit(); std::cout << "Size: " << vi.size() << "\tCapacity : " << vi.capacity() << std::endl; return 0; }
25.5
61
0.493464
[ "vector" ]
b7d0bb852836f32b5d2ebbc8af507b58108b6220
1,399
cpp
C++
aws-cpp-sdk-ssm/source/model/DescribePatchBaselinesResult.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-ssm/source/model/DescribePatchBaselinesResult.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-ssm/source/model/DescribePatchBaselinesResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ssm/model/DescribePatchBaselinesResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::SSM::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DescribePatchBaselinesResult::DescribePatchBaselinesResult() { } DescribePatchBaselinesResult::DescribePatchBaselinesResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } DescribePatchBaselinesResult& DescribePatchBaselinesResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("BaselineIdentities")) { Array<JsonView> baselineIdentitiesJsonList = jsonValue.GetArray("BaselineIdentities"); for(unsigned baselineIdentitiesIndex = 0; baselineIdentitiesIndex < baselineIdentitiesJsonList.GetLength(); ++baselineIdentitiesIndex) { m_baselineIdentities.push_back(baselineIdentitiesJsonList[baselineIdentitiesIndex].AsObject()); } } if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } return *this; }
27.98
138
0.774839
[ "model" ]
b7d8531260c022b046f425123fddcfae22565f68
19,129
cpp
C++
prj/tests/main.cpp
KPO-2020-2021/zad3-kgliwinski
d306f659f535f60ad54faed961990dca2c06f1ff
[ "Unlicense" ]
null
null
null
prj/tests/main.cpp
KPO-2020-2021/zad3-kgliwinski
d306f659f535f60ad54faed961990dca2c06f1ff
[ "Unlicense" ]
null
null
null
prj/tests/main.cpp
KPO-2020-2021/zad3-kgliwinski
d306f659f535f60ad54faed961990dca2c06f1ff
[ "Unlicense" ]
null
null
null
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include"../tests/doctest/doctest.h" #include"../include/menu.hh" /*********************************************************/ /* FILE CONTAINS ALL TESTS FOR ALL CLASSES AND METHODS */ /*********************************************************/ /* Tests for vector class */ TEST_CASE("V 1.01: Vector konstruktor bezparametryczny oraz przeciazenie strumienia wyjsciowego<<"){ Vector a; std::ostringstream out; out << a; // CHECK("[ 0.0000000000 ]\n[ 0.0000000000 ]\n" == out.str()); } TEST_CASE("V 1.02: Vector konstruktor parametryczny oraz przeciazenie strumienia #include <cmath>wyjsciowego << i wejsciowego >>"){ Vector a; std::istringstream in("1.0 5.0"); in >> a; std::ostringstream out; out << a; // CHECK("[ 1.0000000000 ]\n[ 5.0000000000 ]\n" == out.str()); } TEST_CASE("V 1.03: Vector konstruktor parametryczny dla malych wartosci oraz przeciazenie strumienia wyjsciowego << i wejsciowego >>"){ Vector a; std::istringstream in("0.0000000001 0.0000000005"); in >> a; std::ostringstream out; out << a; // CHECK("[ 0.0000000001 ]\n[ 0.0000000005 ]\n" == out.str()); } TEST_CASE("V 1.04: Vector konstruktor parametryczny dla duzych wartosci oraz przeciazenie strumienia wyjsciowego << i wejsciowego >>"){ Vector a; std::istringstream in("12345678 12345678"); in >> a; std::ostringstream out; out << a; // CHECK("[ 12345678.0000000000 ]\n[ 12345678.0000000000 ]\n" == out.str()); } TEST_CASE("V 2.01: Vector dodawanie wektorow"){ double tab[3][2] = {{4,2},{2,7}, {6,9}}; Vector a(tab[0]); Vector b(tab[1]); Vector res(tab[2]); Vector sum = a+b; CHECK(res == sum); } TEST_CASE("V 2.02: Vector dodawanie wektorow dla malych wartosci"){ double tab[3][2] = {{0.0000000004,0.0000000002},{0.0000000002,0.0000000007}, {0.0000000006,0.0000000009}}; Vector a(tab[0]); Vector b(tab[1]); Vector res(tab[2]); Vector sum = a+b; CHECK(res == sum); } TEST_CASE("V 2.03: Vector dodawanie wektorow dla malych wartosci (dokladnosc ponizej E-10)"){ double tab[3][2] = {{0.00000000004,0.00000000002},{0.00000000002,0.00000000007}, {0.00000000006,0.00000000009}}; Vector a(tab[0]); Vector b(tab[1]); Vector res(tab[2]); Vector sum = a+b; CHECK(res == sum); } TEST_CASE("V 2.04: Vector dodawanie wektorow dla duzych wartosci, granicze wartosci"){ double tab[3][2] = {{99999,99999},{1,1},{100000,100000}}; Vector a(tab[0]); Vector b(tab[1]); Vector res(tab[2]); Vector sum = a+b; CHECK(res == sum); } TEST_CASE("V 3.01: Vector odejmowanie wektorow"){ double tab[3][2] = {{4,2},{2,7}, {2,-5}}; Vector a(tab[0]); Vector b(tab[1]); Vector res(tab[2]); Vector sum = a-b; CHECK(res == sum); } TEST_CASE("V 3.02: Vector odejmowanie wektorow dla malych wartosci"){ double tab[3][2] = {{0.0000000004,0.0000000002},{0.0000000002,0.0000000007}, {0.0000000002,-0.0000000005}}; Vector a(tab[0]); Vector b(tab[1]); Vector res(tab[2]); Vector sum = a-b; CHECK(res == sum); } TEST_CASE("V 3.03: Vector odejmowanie wektorow dla malych wartosci (dokladnosc ponizej E-10)"){ double tab[3][2] = {{0.00000000004,0.00000000002},{0.00000000002,0.00000000007}, {0.00000000004,-0.00000000005}}; Vector a(tab[0]); Vector b(tab[1]); Vector res(tab[2]); Vector sum = a+b; CHECK(res == sum); } TEST_CASE("V 3.04: Vector odejmowanie wektorow dla duzych wartosci, granicze wartosci"){ double tab[3][2] = {{99999,99999},{1,1},{100000,100000}}; Vector a(tab[2]); Vector b(tab[0]); Vector res(tab[1]); Vector sum = a-b; CHECK(res == sum); } TEST_CASE("V 4.01: Vector mnozenie wektorow przez skalar"){ double tab[2][2] = {{4,2},{136,68}}; double tmp; Vector a(tab[0]); tmp =34; Vector b = a*tmp; Vector res(tab[1]); CHECK(res == b); } TEST_CASE("V 4.02: Vector mnozenie wektorow przez maly skalar"){ double tab[2][2] = {{4,2},{0.000000004,0.0000000002}}; double tmp; Vector a(tab[0]); tmp =0.000000001; Vector b = a*tmp; Vector res(tab[1]); CHECK(res == b); } TEST_CASE("V 4.03: Vector mnozenie wektorow przez 0"){ double tab[2][2] = {{4,2},{0,0}}; double tmp; Vector a(tab[0]); tmp =0; Vector b = a*tmp; Vector res(tab[1]); CHECK(res == b); } TEST_CASE("V 4.04: Vector mnozenie wektora zerowego przez skalar"){ double tab[2][2] = {{0,0},{0,0}}; double tmp; Vector a(tab[0]); tmp =1231234; Vector b = a*tmp; Vector res(tab[1]); CHECK(res == b); } TEST_CASE("V 5.01: Vector dzielenie wektorow przez skalar"){ double tab[2][2] = {{4,2},{2,1}}; double tmp; Vector a(tab[0]); tmp =2; Vector b = a/tmp; Vector res(tab[1]); CHECK(res == b); } TEST_CASE("V 5.02: Vector dzielenie wektorow przez maly skalar"){ double tab[2][2] = {{4,2},{40000000000,20000000000}}; double tmp; Vector a(tab[0]); tmp =0.000000001; Vector b = a/tmp; Vector res(tab[1]); CHECK(!(a == b)); } TEST_CASE("V 5.03: Vector dzielenie wektorow przez 0"){ double tab[2][2] = {{4,2},{4,2}}; double tmp; Vector a(tab[0]); tmp =0; Vector b = a/tmp; Vector res(tab[1]); CHECK(res == b); //nothing happened } TEST_CASE("V 5.04: Vector dzielenie wektora zerowego przez skalar"){ double tab[2][2] = {{0,0},{0,0}}; double tmp; Vector a(tab[0]); tmp =1231234; Vector b = a*tmp; Vector res(tab[1]); CHECK(res == b); } TEST_CASE("V 6.01: Vector::rotate"){ double tab[2][2] = {{3,4},{-4,3}}; double ang; Vector a(tab[0]); ang =90; Vector b = a.rotate(ang); Vector res(tab[1]); CHECK((res == b)); } TEST_CASE("V 6.02: Vector::rotate by 0"){ double tab[2][2] = {{3,4},{3,4}}; double ang; Vector a(tab[0]); ang =0; Vector b = a.rotate(ang); Vector res(tab[1]); CHECK((res == b)); } TEST_CASE("V 6.03: Vector::rotate by 360 deg"){ double tab[2][2] = {{3,4},{3,4}}; double ang; Vector a(tab[0]); ang =360; Vector b = a.rotate(ang); Vector res(tab[1]); CHECK((res == b)); } TEST_CASE("V 6.04: Vector::rotate by 36000000 deg"){ double tab[2][2] = {{3,4},{3,4}}; double ang; Vector a(tab[0]); ang =36000000; Vector b = a.rotate(ang); Vector res(tab[1]); CHECK((res == b)); } TEST_CASE("V 6.05: Vector::rotate by 180 deg"){ double tab[2][2] = {{3,4},{-3,-4}}; double ang; Vector a(tab[0]); ang =180; Vector b = a.rotate(ang); Vector res(tab[1]); CHECK((res == b)); } TEST_CASE("V 7.01: Vector::modulus2"){ double tab[2][2] = {{3,4}}; double res; Vector a(tab[0]); res = 25; CHECK((res == a.modulus2())); } TEST_CASE("V 7.02: Vector::modulus2 small"){ double tab[2][2] = {{0.003,0.004}}; double res; Vector a(tab[0]); res = 0.000025; CHECK((abs(res - a.modulus2())<=0.0001)); } TEST_CASE("V 7.03: Vector::modulus2 zero"){ double tab[2][2] = {{0,0}}; double res; Vector a(tab[0]); res = 0; CHECK((res == a.modulus2())); } TEST_CASE("V 7.04: Vector::modulus2 neg"){ double tab[2][2] = {{-3,-4}}; double res; Vector a(tab[0]); res = 25; CHECK((res == a.modulus2())); } TEST_CASE("V 8.01: Vector::get_len "){ double tab[2][2] = {{3,4}}; double res; Vector a(tab[0]); res = 5; CHECK((res == a.get_len())); } TEST_CASE("V 8.02: Vector::get_len small"){ double tab[2][2] = {{0.003,0.004}}; double res; Vector a(tab[0]); res = 0.005; CHECK((res == a.get_len())); } TEST_CASE("V 8.03: Vector::get_len zero"){ double tab[2][2] = {{0,0}}; double res; Vector a(tab[0]); res = 0; CHECK((res == a.get_len())); } TEST_CASE("V 8.04: Vector::get_len neg"){ double tab[2][2] = {{-5,-12}}; double res; Vector a(tab[0]); res = 13; CHECK((res == a.get_len())); } TEST_CASE("V 9.01: Vector::get_slope_angle "){ double tab[2][2] = {{1,1}}; double res; Vector a(tab[0]); res = 45.0; CHECK (abs(res - a.get_slope_angle())<= 0.000001); } TEST_CASE("V 9.02: Vector::get_slope_angle 0"){ double tab[2][2] = {{0,0}}; double res; Vector a(tab[0]); res = 0; CHECK (abs(res - a.get_slope_angle())<= 0.000001); } TEST_CASE("V 9.03: Vector::get_slope_angle 90 deg"){ double tab[2][2] = {{0,1}}; double res; Vector a(tab[0]); res = 90; CHECK (abs(res - a.get_slope_angle())<= 0.000001); } TEST_CASE("V 10.01: operator []"){ double tab[2][2] = {{3,1}}; double res; Vector a(tab[0]); res = 3; CHECK (abs(res - a[0])<= 0.000001); } TEST_CASE("V 10.02: operator []"){ double tab[2][2] = {{3,1}}; double res; Vector a(tab[0]); res = 1; CHECK (abs(res - a[1])<= 0.000001); } TEST_CASE("V 10.03: operator const []"){ double tab[2][2] = {{3,1}}; double res; Vector a(tab[0]); res = 1; double b = a[1]; CHECK (abs(res - b)<= 0.000001); } TEST_CASE("M 1.01: konstruktor bezparametryczny i przeciazenie operatorow << >>"){ //double tab[2][2] = {{3,1}}; Matrix a; std::ostringstream out; out << a; // CHECK (out.str() == "| 1.0000000000 * | 0.0000000000 * | 0.0000000000 * | 1.0000000000 * "); } TEST_CASE("M 1.02: konstruktor parametryczny i przeciazenie operatorow << >>"){ double tab[2][2] = {{3,1},{3,1}}; Matrix a(tab); std::ostringstream out; out << a; // CHECK (out.str() == "| 3.0000000000 * | 1.0000000000 * | 3.0000000000 * | 1.0000000000 * "); } TEST_CASE("M 1.03: konstruktor parametryczny i przeciazenie operatorow << >>"){ double tab[2][2] = {{0.0003,0.0001},{0.0003,0.0001}}; Matrix a(tab); std::ostringstream out; out << a; // CHECK (out.str() == "| 0.0003000000 * | 0.0001000000 * | 0.0003000000 * | 0.0001000000 * "); } TEST_CASE("M 1.04: konstruktor parametryczny i przeciazenie operatorow << >>"){ double tab[2][2] = {{-0.0003,0.0001},{0.0003,-0.0001}}; Matrix a(tab); std::ostringstream out; out << a; // CHECK (out.str() == "| -0.0003000000 * | 0.0001000000 * | 0.0003000000 * | -0.0001000000 * "); } TEST_CASE("M 1.05: konstruktor parametryczny i przeciazenie operatorow << >>"){ double tab[2][2] = {{0,0},{0,0}}; Matrix a(tab); std::ostringstream out; out << a; // CHECK (out.str() == "| 0.0000000000 * | 0.0000000000 * | 0.0000000000 * | 0.0000000000 * "); } TEST_CASE("M 1.06: przeciazenie operatorow << >>"){ double tab[2][2] = {{0,0},{0,0}}; Matrix a(tab); std::istringstream in("1 2 3 4"); in >> a; std::ostringstream out; out << a; // CHECK (out.str() == "| 1.0000000000 * | 2.0000000000 * | 3.0000000000 * | 4.0000000000 * "); } TEST_CASE("M 2.01: operator * (vector)"){ double tab[2][2] = {{1,0},{0,1}}; double vec[2] = {1,2}; Matrix a(tab); Vector b(vec); Vector c(vec); CHECK (c==(a*b)); } TEST_CASE("M 2.02: operator * (vector) zero"){ double tab[2][2] = {{0,0},{0,0}}; double vec[2] = {0,0}; Matrix a(tab); Vector b(vec); Vector c(vec); CHECK (c==(a*b)); } TEST_CASE("M 2.03: operator * (vector) neg"){ double tab[2][2] = {{1,2},{3,4}}; double vec[2] = {1,-1}; double res[2] = {-1,-1}; Matrix a(tab); Vector b(vec); Vector c(res); CHECK (c==(a*b)); } TEST_CASE("M 3.01: operator +"){ double tab[2][2] = {{1,2},{3,4}}; double tab2[2][2] = {{4,3},{2,1}}; double res[2][2] = {{5,5},{5,5}}; Matrix a(tab); Matrix b(tab2); Matrix c(res); CHECK (c==(a+b)); } TEST_CASE("M 3.02: operator + 0"){ double tab[2][2] = {{1,2},{3,4}}; double tab2[2][2] = {{0,0},{0,0}}; double res[2][2] = {{1,2},{3,4}}; Matrix a(tab); Matrix b(tab2); Matrix c(res); CHECK (c==(a+b)); } TEST_CASE("M 3.03: operator + small"){ double tab[2][2] = {{1,2},{3,4}}; double tab2[2][2] = {{0.0000000001,0.0000000001},{0.0000000001,0.0000000001}}; double res[2][2] = {{1.0000000001,2.0000000001},{3.0000000001,4.0000000001}}; Matrix a(tab); Matrix b(tab2); Matrix c(res); CHECK (c==(a+b)); } TEST_CASE("M 4.01: operator ()"){ double tab[2][2] = {{1,2},{3,4}}; double res = 1; Matrix a(tab); CHECK (res == a(0,0)); } TEST_CASE("M 4.02: operator ()"){ double tab[2][2] = {{1,0.00002},{3,4}}; double res = 0.00002; Matrix a(tab); CHECK (res == a(0,1)); } TEST_CASE("M 4.03: operator ()"){ double tab[2][2] = {{1,2},{-3,4}}; double res = -3; Matrix a(tab); CHECK (res == a(1,0)); } TEST_CASE("M 4.04: operator ()"){ double tab[2][2] = {{1,2},{-3,0}}; double res = 0; Matrix a(tab); CHECK (res == a(1,1)); } TEST_CASE("R 1.01: konstruktor bezparametryczny prostokata i przeciazenie operatorow << >>"){ //double tab[2][2] = {{3,1}}; Rectangle a; Rectangle b; std::ostringstream out; out << a; // std::ostringstream out2; out2 << b; // CHECK (out.str() == out2.str()); } TEST_CASE("R 1.02: konstruktor parametryczny prostokata i przeciazenie operatorow << >>"){ double args[4][2]= {{100.0, 400.0},{100.0, 300.0},{300.0, 300.0},{300.0, 400.0}}; Vector a1[4]; for (int i=0;i<4;i++){ a1[i]=Vector(args[i]); } Rectangle a(a1); Rectangle b(a1); std::ostringstream out; out << a; // std::ostringstream out2; out2 << b; // CHECK (out.str() == out2.str()); } TEST_CASE("R 1.03: konstruktor parametryczny prostokata i przeciazenie operatorow << >>"){ double args[4][2]= {{200.0, 300.0},{300.0, 300.0},{300.0, 300.0},{300.0, 400.0}}; Vector a1[4]; for (int i=0;i<4;i++){ a1[i]=Vector(args[i]); } Rectangle a(a1); Rectangle b(a1); std::ostringstream out; out << a; // std::ostringstream out2; out2 << b; // CHECK (out.str() == out2.str()); } TEST_CASE("R 2.01: Rectangle::translate"){ double args[4][2]= {{100.0, 400.0},{100.0, 300.0},{300.0, 300.0},{300.0, 400.0}}; Vector a1[4]; for (int i=0;i<4;i++){ a1[i]=Vector(args[i]); } Rectangle a(a1); double args2[4][2]= {{200.0, 500.0},{200.0, 400.0},{400.0, 400.0},{400.0, 500.0}}; Vector a2[4]; for (int i=0;i<4;i++){ a2[i]=Vector(args2[i]); } Rectangle b(a2); double tab[2] = {100,100}; Vector trans(tab); CHECK (a.translation(trans) == b); } TEST_CASE("R 2.02: Rectangle::translate neg"){ double args[4][2]= {{100.0, 400.0},{100.0, 300.0},{300.0, 300.0},{300.0, 400.0}}; Vector a1[4]; for (int i=0;i<4;i++){ a1[i]=Vector(args[i]); } Rectangle a(a1); double args2[4][2]= {{0, 300.0},{0, 200.0},{200.0, 200.0},{200.0, 300.0}}; Vector a2[4]; for (int i=0;i<4;i++){ a2[i]=Vector(args2[i]); } Rectangle b(a2); double tab[2] = {-100,-100}; Vector trans(tab); CHECK (a.translation(trans) == b); } TEST_CASE("R 2.03: Rectangle::translate diff"){ double args[4][2]= {{100.0, 400.0},{100.0, 300.0},{300.0, 300.0},{300.0, 400.0}}; Vector a1[4]; for (int i=0;i<4;i++){ a1[i]=Vector(args[i]); } Rectangle a(a1); double args2[4][2]= {{0, 350.0},{0, 250.0},{200.0, 250.0},{200.0, 350.0}}; Vector a2[4]; for (int i=0;i<4;i++){ a2[i]=Vector(args2[i]); } Rectangle b(a2); double tab[2] = {-100,-50}; Vector trans(tab); CHECK (a.translation(trans) == b); } TEST_CASE("R 3.01: Rectangle::rotate"){ double args[4][2]= {{100.0, 400.0},{100.0, 300.0},{300.0, 300.0},{300.0, 400.0}}; Vector a1[4]; for (int i=0;i<4;i++){ a1[i]=Vector(args[i]); } Rectangle a(a1); double args2[4][2]= {{-100.0, -400.0},{-100.0, -300.0},{-300.0, -300.0},{-300.0, -400.0}}; Vector a2[4]; for (int i=0;i<4;i++){ a2[i]=Vector(args2[i]); } Rectangle b(a2); double ang = 180; CHECK (a.rotate(ang) == b); } TEST_CASE("R 3.02: Rectangle::rotate"){ double args[4][2]= {{100.0, 400.0},{100.0, 300.0},{300.0, 300.0},{300.0, 400.0}}; Vector a1[4]; for (int i=0;i<4;i++){ a1[i]=Vector(args[i]); } Rectangle a(a1); double args2[4][2]= {{100.0, 400.0},{100.0, 300.0},{300.0, 300.0},{300.0, 400.0}}; Vector a2[4]; for (int i=0;i<4;i++){ a2[i]=Vector(args2[i]); } Rectangle b(a2); double ang = 360; CHECK (a.rotate(ang) == b); } TEST_CASE("R 4.01: Rectangle::check true"){ double args[4][2]= {{100.0, 400.0},{100.0, 300.0},{300.0, 300.0},{300.0, 400.0}}; Vector a1[4]; for (int i=0;i<4;i++){ a1[i]=Vector(args[i]); } Rectangle a(a1); CHECK (a.check_rec()==1); } TEST_CASE("R 4.02: Rectangle::check false"){ double args[4][2]= {{000.0, 400.0},{100.0, 300.0},{300.0, 300.0},{300.0, 400.0}}; Vector a1[4]; for (int i=0;i<4;i++){ a1[i]=Vector(args[i]); } Rectangle a(a1); CHECK (a.check_rec()==1); } TEST_CASE("Mod 1.01: Matrix::gauss()"){ double tab[2][2] = {{1,2},{3,4}}; double tab2[2][2] = {{1,2},{0,-2}}; Matrix a(tab); Matrix b(tab2); CHECK ((a.gauss()) == b); } TEST_CASE("Mod 1.02: Matrix::gauss() 2"){ double tab[2][2] = {{3,2},{3,4}}; double tab2[2][2] = {{3,2},{0,2}}; Matrix a(tab); Matrix b(tab2); CHECK ((a.gauss()) == b); } TEST_CASE("Mod 1.03: Matrix::determinant() 1"){ double tab[2][2] = {{1,2},{3,4}}; Matrix a(tab); double det; det = -2; CHECK ((a.determinant()) == det); } TEST_CASE("Mod 1.03: Matrix::determinant() 2"){ double tab[2][2] = {{3,2},{3,4}}; Matrix a(tab); double det; det = 6; CHECK ((a.determinant()) == det); } TEST_CASE("Mod 2.01: Matrix::multiply() 1"){ double tab[2][2] = {{3,2},{3,4}}; Matrix a(tab); //macierz jednostkowa Matrix b; double tab_res[2][2] = {{3,2},{3,4}}; Matrix res(tab_res); CHECK (a.multiply(b) == res); } TEST_CASE("Mod 2.02: Matrix::multiply() 2"){ double tab[2][2] = {{1,2},{3,4}}; Matrix a(tab); //macierz jednostkowa Matrix b(tab); double tab_res[2][2] = {{7,10},{15,22}}; Matrix res(tab_res); CHECK (a.multiply(b) == res); } TEST_CASE("Mod 2.03: Matrix::multiply() 3"){ double tab[2][2] = {{-1,0},{12,4}}; double tab2[2][2] = {{12,7},{1,5}}; Matrix a(tab); //macierz jednostkowa Matrix b(tab2); double tab_res[2][2] = {{-12,-7},{148,104}}; Matrix res(tab_res); CHECK (a.multiply(b) == res); } /* std::istringstream in("(1+10i)"); in >> x; std::ostringstream out; out << a; // */
23.941176
135
0.532072
[ "vector" ]
b7d9aadf3b667332f8d1949ccc8f9cb4cf54940a
853
cpp
C++
src/consumer.cpp
personalrobotics/chimera
089e8360da01c04777c904e3106d822aa49e00de
[ "BSD-3-Clause" ]
11
2017-05-05T14:01:21.000Z
2020-07-09T14:05:54.000Z
src/consumer.cpp
personalrobotics/chimera
089e8360da01c04777c904e3106d822aa49e00de
[ "BSD-3-Clause" ]
162
2017-03-11T04:32:32.000Z
2020-12-20T06:45:56.000Z
src/consumer.cpp
personalrobotics/chimera
089e8360da01c04777c904e3106d822aa49e00de
[ "BSD-3-Clause" ]
3
2019-01-13T18:38:21.000Z
2019-12-26T22:08:45.000Z
#include "chimera/consumer.h" #include "chimera/visitor.h" #include <iostream> using namespace clang; chimera::Consumer::Consumer(CompilerInstance *ci, const chimera::Configuration &config) : ci_(ci), config_(config) { // Do nothing. } void chimera::Consumer::HandleTranslationUnit(ASTContext &context) { // Use the current translation unit to resolve the YAML configuration. std::unique_ptr<chimera::CompiledConfiguration> compiled_config = config_.Process(ci_); chimera::Visitor visitor(ci_, *compiled_config); // We can use ASTContext to get the TranslationUnitDecl, which is // a single Decl that collectively represents the entire source file. visitor.TraverseDecl(context.getTranslationUnitDecl()); // Render the top-level mstch template compiled_config->Render(); }
29.413793
74
0.716295
[ "render" ]
b7e77c2b6e392868e49b58916b8b3f3b45dfdf61
1,356
hh
C++
schemelib/scheme/nest/pmap/DiscreteChoiceMap.hh
YaoYinYing/rifdock
cbde6bbeefd29a066273bdf2937cf36b0d2e6335
[ "Apache-2.0" ]
25
2019-07-23T01:03:48.000Z
2022-03-31T04:16:08.000Z
schemelib/scheme/nest/pmap/DiscreteChoiceMap.hh
YaoYinYing/rifdock
cbde6bbeefd29a066273bdf2937cf36b0d2e6335
[ "Apache-2.0" ]
13
2018-01-30T17:45:57.000Z
2022-03-28T11:02:44.000Z
schemelib/scheme/nest/pmap/DiscreteChoiceMap.hh
YaoYinYing/rifdock
cbde6bbeefd29a066273bdf2937cf36b0d2e6335
[ "Apache-2.0" ]
14
2018-02-08T01:42:28.000Z
2022-03-31T12:56:17.000Z
#ifndef INCLUDED_scheme_nest_maps_DiscreteChoiceMap_HH #define INCLUDED_scheme_nest_maps_DiscreteChoiceMap_HH #include "scheme/util/template_loop.hh" #include <boost/bind.hpp> #include <boost/static_assert.hpp> #include <iostream> #include <vector> namespace scheme { namespace nest { namespace pmap { /// @brief Parameter Mapping Policy class which represents a discrete set of choices for 0 dimensional Nests /// @note NEST num_cells MUST agree with choices.size() template< int DIM, class Value, class Index, class Float > struct DiscreteChoiceMap { BOOST_STATIC_ASSERT_MSG(DIM==0,"DiscreteChoiceMap DIM must be == 0"); static int const DIMENSION = DIM; typedef char Params; std::vector<Value> choices; DiscreteChoiceMap(std::vector<Value> const & _choices) : choices(_choices), num_cells_(choices.size()) {} ///@brief sets value based only on cell_index ///@note params has no meaning for zero-dimensional nests, only cell_index ///@return false iff invalid parameters bool params_to_value( Params const & /*params*/, Index cell_index, Index resl, Value & value ) const { if( cell_index >= choices.size() ) return false; value = choices[cell_index]; return true; } Index num_cells() const { return num_cells_; } virtual ~DiscreteChoiceMap(){} private: Index num_cells_; }; } } } #endif
27.673469
109
0.735988
[ "vector" ]
b7e7fea7710cf3c3ff727aa37f77c62df59f7291
5,104
cpp
C++
CLRS/BinaryTree/SerializeandDeserializeBinaryTree.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/BinaryTree/SerializeandDeserializeBinaryTree.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
CLRS/BinaryTree/SerializeandDeserializeBinaryTree.cpp
ComputerProgrammerStorager/DataStructureAlgorithm
508f7e37898c907ea7ea6ec40749621a2349e93f
[ "MIT" ]
null
null
null
/* Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment. Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure. Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself. Example 1: Input: root = [1,2,3,null,null,4,5] Output: [1,2,3,null,null,4,5] Example 2: Input: root = [] Output: [] Example 3: Input: root = [1] Output: [1] Example 4: Input: root = [1,2] Output: [1,2] Constraints: The number of nodes in the tree is in the range [0, 104]. -1000 <= Node.val <= 1000 */ // We can store the pre-order traversal result during serialization, which can uniquely define a tree and thus can deserialize class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { if ( !root ) return "#"; return to_string(root->val) + "," + serialize(root->left) + "," +serialize(root->right); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { vector<TreeNode*> q; for ( int i = 0; i < data.size(); i++ ) { int j = i; while ( j < data.size() && data[j] != ',') { j++; } string val = data.substr(i,j-i); if ( val == "#") { q.push_back(nullptr); } else { q.push_back(new TreeNode(stoi(val))); } i = j; } return dfs(q,0); } TreeNode* dfs(vector<TreeNode*> q, int cur) { if ( !q[cur] ) return nullptr; TreeNode *left = dfs(q,cur+1); int left_sz = GetNumofTreeNodes(left); TreeNode *right = dfs(q,cur+1+left_sz); q[cur]->left = left; q[cur]->right = right; return q[cur]; } int GetNumofTreeNodes(TreeNode *root) { if ( !root ) return 1; return GetNumofTreeNodes(root->left) + GetNumofTreeNodes(root->right) + 1; } }; // We can get rid of calculating the number of nodes by poping out the processed nodes as it proceeds class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { if(!root) return "#"; return to_string(root->val)+","+serialize(root->left)+","+serialize(root->right); } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { queue<string> q; for ( int i = 0; i < data.size(); i++ ) { int j = i; while( j < data.size() && data[j] != ',') { j++; } q.push(data.substr(i,j-i)); i = j; } return dfs(q); } TreeNode *dfs(queue<string>& q) { string cur = q.front(); q.pop(); if ( cur == "#") return nullptr; TreeNode *root = new TreeNode(stoi(cur)); root->left = dfs(q); root->right = dfs(q); return root; } }; // we can store the nodes in level order class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string res; queue<TreeNode*> q; q.push(root); while(!q.empty()) { TreeNode *cur = q.front(); q.pop(); if ( !cur ) res +="#,"; else { res += to_string(cur->val) + ","; q.push(cur->left); q.push(cur->right); } } return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { vector<TreeNode*> q; for ( int i = 0; i < data.size(); i++ ) { int j = i; while( j < data.size() && data[j] != ',') { j++; } string val = data.substr(i,j-i); if ( val == "#" ) q.push_back(nullptr); else q.push_back(new TreeNode(stoi(val))); i = j; } int p = 0, left_child = 1; while ( left_child < q.size() ) // left_child will be always larger than parent { if ( q[p] ) { q[p]->left = q[left_child]; q[p]->right = q[left_child+1]; left_child += 2; } p++; } return q[0]; } };
26.583333
293
0.506074
[ "object", "vector" ]
b7ed1f520aa22e61b26863cea2a25139ccf4a1ba
567
cpp
C++
src/tabstractuser.cpp
KatsutoshiOtogawa/treefrog-framework
369d59d7daa358095f4701bac1a0b7974f51f5e3
[ "BSD-3-Clause" ]
942
2015-01-16T02:02:10.000Z
2022-03-31T02:11:50.000Z
src/tabstractuser.cpp
KatsutoshiOtogawa/treefrog-framework
369d59d7daa358095f4701bac1a0b7974f51f5e3
[ "BSD-3-Clause" ]
250
2015-04-26T23:46:48.000Z
2022-03-30T09:32:05.000Z
src/tabstractuser.cpp
KatsutoshiOtogawa/treefrog-framework
369d59d7daa358095f4701bac1a0b7974f51f5e3
[ "BSD-3-Clause" ]
244
2015-01-16T17:41:06.000Z
2022-02-11T09:34:42.000Z
#include "tabstractuser.h" /*! \class TAbstractUser \brief The TAbstractUser class is the abstract base class of users, providing functionality common to users. */ /*! \fn virtual TAbstractUser::~TAbstractUser() Destroys the user object. */ /*! \fn virtual QString TAbstractUser::identityKey() const = 0 Returns the identity key, such as a user name. This is a pure virtual function. */ /*! \fn virtual QString TAbstractUser::groupKey() const Returns the group key, such as a group name. This is a virtual function. */
18.290323
69
0.689594
[ "object" ]
b7f35d02cea42b6872a0e4f0b52f75d1d9b8d022
1,396
cpp
C++
benchmark/shader.cpp
dixlorenz/pure_simd
fdff69f197d8e26dcefcfc0eba12ee1db847238c
[ "BSD-3-Clause" ]
211
2020-05-11T05:09:18.000Z
2022-02-22T07:18:16.000Z
benchmark/shader.cpp
dixlorenz/pure_simd
fdff69f197d8e26dcefcfc0eba12ee1db847238c
[ "BSD-3-Clause" ]
5
2020-05-11T10:16:52.000Z
2021-10-09T06:22:08.000Z
benchmark/shader.cpp
dixlorenz/pure_simd
fdff69f197d8e26dcefcfc0eba12ee1db847238c
[ "BSD-3-Clause" ]
9
2020-05-11T08:54:21.000Z
2021-11-28T18:27:41.000Z
#include "benchmark/benchmark.h" #include "shader.hpp" void BM_shader_scalar_shader(benchmark::State& state) { std::vector<int> buffer(SCRWIDTH * SCRHEIGHT, 0); for (auto _ : state) { scalar_shader(2, buffer.data()); benchmark::ClobberMemory(); } } BENCHMARK(BM_shader_scalar_shader)->Unit(benchmark::kMillisecond); #define BENCHMARK_FOR(func_name, size) \ void BM_shader_##func_name##_##size(benchmark::State& state) \ { \ std::vector<int> buffer(SCRWIDTH* SCRHEIGHT, 0); \ \ for (auto _ : state) { \ func_name<size>(2, buffer.data()); \ benchmark::ClobberMemory(); \ } \ } \ BENCHMARK(BM_shader_##func_name##_##size)->Unit(benchmark::kMillisecond) BENCHMARK_FOR(pure_simd_shader, 1); BENCHMARK_FOR(pure_simd_shader, 2); BENCHMARK_FOR(pure_simd_shader, 4); BENCHMARK_FOR(pure_simd_shader, 8); BENCHMARK_FOR(pure_simd_shader, 16); BENCHMARK_FOR(pure_simd_shader, 32); BENCHMARK_FOR(pure_simd_shader, 64); BENCHMARK_FOR(pure_simd_shader, 128);
32.465116
76
0.51361
[ "vector" ]
b7f4f457473b945da4ed46de3fa5e4974dc78432
22,993
cpp
C++
src/caffe/test/test_spatial_transformer_layer.cpp
po0ya/caffe-facemagnet
07947ff57ead52a4155c6e04885e06ce23bd23e4
[ "BSD-2-Clause" ]
null
null
null
src/caffe/test/test_spatial_transformer_layer.cpp
po0ya/caffe-facemagnet
07947ff57ead52a4155c6e04885e06ce23bd23e4
[ "BSD-2-Clause" ]
null
null
null
src/caffe/test/test_spatial_transformer_layer.cpp
po0ya/caffe-facemagnet
07947ff57ead52a4155c6e04885e06ce23bd23e4
[ "BSD-2-Clause" ]
null
null
null
#include <cmath> #include <cstring> #include <vector> #include <iostream> #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/custom_layers.hpp" #include "caffe/test/test_caffe_main.hpp" #include "caffe/test/test_gradient_check_util.hpp" namespace caffe { // Reference affine transformer for checking results // compute coordinates and sample feature map explicitly using loops template <typename Dtype> void affine_transform(const Blob<Dtype>* in, const Blob<Dtype>* theta, Blob<Dtype>* out) { int num = in->shape(0); int channels = in->shape(1); int height = in->shape(2); int width = in->shape(3); Dtype* out_data = out->mutable_cpu_data(); caffe_set<Dtype>(out->count(), 0, out_data); const Dtype* theta_data = theta->cpu_data(); for (int n = 0; n < num; ++n) { for (int h = 0; h < height; ++h) { Dtype ty = h / (Dtype) (height - 1) * (Dtype) 2. - (Dtype) 1.; for (int w = 0; w < width; ++w) { Dtype tx = w / (Dtype) (width - 1)*(Dtype) 2. - (Dtype) 1.; Dtype sx = tx * theta_data[n * 6] + ty * theta_data[n * 6 + 1] + theta_data[n * 6 + 2]; Dtype sy = tx * theta_data[n * 6 + 3] + ty * theta_data[n * 6 + 4] + theta_data[n * 6 + 5]; sx = (sx + 1.) / (Dtype) 2. * (width - 1); sy = (sy + 1.) / (Dtype) 2. * (height - 1); for (int c = 0; c < channels; ++c) { for (int hh = 0; hh < height; ++hh) { for (int ww = 0; ww < width; ++ww) { Dtype max_y = 0; if (hh > sy) { max_y = hh - sy; } else { max_y = sy - hh; } if (1 - max_y < 0) { max_y = 0; } else { max_y = 1 - max_y; } Dtype max_x = 0; if (ww > sx) { max_x = ww - sx; } else { max_x = sx - ww; } if (1 - max_x < 0) { max_x = 0; } else { max_x = 1 - max_x; } out_data[out->offset(n, c, h, w)] += in->data_at(n, c, hh, ww) * max_x*max_y; } } } } } } } template void affine_transform(const Blob<float>* in, const Blob<float>* theta, Blob<float>* out); template void affine_transform(const Blob<double>* in, const Blob<double>* theta, Blob<double>* out); template <typename TypeParam> class SpatialTransformerLayerTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: SpatialTransformerLayerTest() : blob_data_(new Blob<Dtype>(vector<int>{2, 3, 5, 9})), blob_theta_(new Blob<Dtype>(vector<int>{2, 6})), blob_top_(new Blob<Dtype>()) { } virtual void SetUp() { FillerParameter filler_param; filler_param.set_min(-1); filler_param.set_max(1); UniformFiller<Dtype> filler(filler_param); filler.Fill(this->blob_data_); blob_bottom_vec_.push_back(blob_data_); blob_bottom_vec_.push_back(blob_theta_); blob_top_vec_.push_back(blob_top_); } virtual ~SpatialTransformerLayerTest() { delete blob_data_; delete blob_theta_; delete blob_top_; } virtual Blob<Dtype>* MakeReferenceTop(Blob<Dtype>* top) { this->ref_blob_top_.reset(new Blob<Dtype>()); this->ref_blob_top_->ReshapeLike(*top); return this->ref_blob_top_.get(); } Blob<Dtype> * const blob_data_; Blob<Dtype> * const blob_theta_; Blob<Dtype> * const blob_top_; shared_ptr<Blob<Dtype> > ref_blob_top_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; TYPED_TEST_CASE(SpatialTransformerLayerTest, TestDtypesAndDevices); // check top blob shape TYPED_TEST(SpatialTransformerLayerTest, TestSetUp) { typedef typename TypeParam::Dtype Dtype; LayerParameter layer_param; shared_ptr<Layer<Dtype> > layer( new SpatialTransformerLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); EXPECT_EQ(this->blob_top_->num(), this->blob_data_->num()); EXPECT_EQ(this->blob_top_->channels(), this->blob_data_->channels()); EXPECT_EQ(this->blob_top_->height(), this->blob_data_->height()); EXPECT_EQ(this->blob_top_->width(), this->blob_data_->width()); } // test forward: to test flip: 1/(h-1) & 1/(w-1) must be 2^{-n} TYPED_TEST(SpatialTransformerLayerTest, TestIdenticalForward) { typedef typename TypeParam::Dtype Dtype; FillerParameter filler_param; ConstantFiller<Dtype> constant_filler(filler_param); constant_filler.Fill(this->blob_theta_); this->blob_theta_->mutable_cpu_data()[0] = 1.; this->blob_theta_->mutable_cpu_data()[1] = 0.; this->blob_theta_->mutable_cpu_data()[2] = 0.; this->blob_theta_->mutable_cpu_data()[3] = 0.; this->blob_theta_->mutable_cpu_data()[4] = 1.; this->blob_theta_->mutable_cpu_data()[5] = 0.; this->blob_theta_->mutable_cpu_data()[0 + 6] = 1.; this->blob_theta_->mutable_cpu_data()[1 + 6] = 0.; this->blob_theta_->mutable_cpu_data()[2 + 6] = 0.; this->blob_theta_->mutable_cpu_data()[3 + 6] = 0.; this->blob_theta_->mutable_cpu_data()[4 + 6] = 1.; this->blob_theta_->mutable_cpu_data()[5 + 6] = 0.; LayerParameter layer_param; shared_ptr<Layer<Dtype> > layer( new SpatialTransformerLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* top_data; const Dtype* ref_top_data; top_data = this->blob_top_->cpu_data(); ref_top_data = this->blob_data_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], 1e-4); } } TYPED_TEST(SpatialTransformerLayerTest, TestFlipXForward) { typedef typename TypeParam::Dtype Dtype; FillerParameter filler_param; ConstantFiller<Dtype> constant_filler(filler_param); constant_filler.Fill(this->blob_theta_); this->blob_theta_->mutable_cpu_data()[0] = -1.; this->blob_theta_->mutable_cpu_data()[1] = 0.; this->blob_theta_->mutable_cpu_data()[2] = 0.; this->blob_theta_->mutable_cpu_data()[3] = 0.; this->blob_theta_->mutable_cpu_data()[4] = 1.; this->blob_theta_->mutable_cpu_data()[5] = 0.; this->blob_theta_->mutable_cpu_data()[0 + 6] = -1.; this->blob_theta_->mutable_cpu_data()[1 + 6] = 0.; this->blob_theta_->mutable_cpu_data()[2 + 6] = 0.; this->blob_theta_->mutable_cpu_data()[3 + 6] = 0.; this->blob_theta_->mutable_cpu_data()[4 + 6] = 1.; this->blob_theta_->mutable_cpu_data()[5 + 6] = 0.; LayerParameter layer_param; shared_ptr<Layer<Dtype> > layer( new SpatialTransformerLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* top_data; const Dtype* ref_top_data; top_data = this->blob_top_->cpu_data(); ref_top_data = this->blob_data_->cpu_data(); int num = this->blob_top_->num(); int channels = this->blob_top_->channels(); int height = this->blob_top_->height(); int width = this->blob_top_->width(); for (int n = 0; n < num; ++n) { for (int c = 0; c < channels; ++c) { for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { EXPECT_NEAR(top_data[this->blob_top_->offset(n, c, h, w)], ref_top_data[this->blob_data_->offset(n, c, h, width - 1 - w)], 1e-4); } } } } } TYPED_TEST(SpatialTransformerLayerTest, TestFlipYForward) { typedef typename TypeParam::Dtype Dtype; FillerParameter filler_param; ConstantFiller<Dtype> constant_filler(filler_param); constant_filler.Fill(this->blob_theta_); this->blob_theta_->mutable_cpu_data()[0] = (Dtype) 1.; this->blob_theta_->mutable_cpu_data()[1] = (Dtype) 0.; this->blob_theta_->mutable_cpu_data()[2] = (Dtype) 0.; this->blob_theta_->mutable_cpu_data()[3] = (Dtype) 0.; this->blob_theta_->mutable_cpu_data()[4] = (Dtype) - 1.; this->blob_theta_->mutable_cpu_data()[5] = (Dtype) 0.; this->blob_theta_->mutable_cpu_data()[0 + 6] = (Dtype) 1.; this->blob_theta_->mutable_cpu_data()[1 + 6] = (Dtype) 0.; this->blob_theta_->mutable_cpu_data()[2 + 6] = (Dtype) 0.; this->blob_theta_->mutable_cpu_data()[3 + 6] = (Dtype) 0.; this->blob_theta_->mutable_cpu_data()[4 + 6] = (Dtype) - 1.; this->blob_theta_->mutable_cpu_data()[5 + 6] = (Dtype) 0.; LayerParameter layer_param; shared_ptr<Layer<Dtype> > layer( new SpatialTransformerLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* top_data; const Dtype* ref_top_data; top_data = this->blob_top_->cpu_data(); ref_top_data = this->blob_data_->cpu_data(); int num = this->blob_top_->num(); int channels = this->blob_top_->channels(); int height = this->blob_top_->height(); int width = this->blob_top_->width(); for (int n = 0; n < num; ++n) { for (int c = 0; c < channels; ++c) { for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { EXPECT_NEAR(top_data[this->blob_top_->offset(n, c, h, w)], ref_top_data[this->blob_data_->offset(n, c, height - 1 - h, w)], 1e-4); } } } } } TYPED_TEST(SpatialTransformerLayerTest, TestFlipXYForward) { typedef typename TypeParam::Dtype Dtype; FillerParameter filler_param; ConstantFiller<Dtype> constant_filler(filler_param); constant_filler.Fill(this->blob_theta_); this->blob_theta_->mutable_cpu_data()[0] = -1.; this->blob_theta_->mutable_cpu_data()[1] = 0.; this->blob_theta_->mutable_cpu_data()[2] = 0.; this->blob_theta_->mutable_cpu_data()[3] = 0.; this->blob_theta_->mutable_cpu_data()[4] = -1.; this->blob_theta_->mutable_cpu_data()[5] = 0.; this->blob_theta_->mutable_cpu_data()[0 + 6] = -1.; this->blob_theta_->mutable_cpu_data()[1 + 6] = 0.; this->blob_theta_->mutable_cpu_data()[2 + 6] = 0.; this->blob_theta_->mutable_cpu_data()[3 + 6] = 0.; this->blob_theta_->mutable_cpu_data()[4 + 6] = -1.; this->blob_theta_->mutable_cpu_data()[5 + 6] = 0.; LayerParameter layer_param; shared_ptr<Layer<Dtype> > layer( new SpatialTransformerLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* top_data; const Dtype* ref_top_data; top_data = this->blob_top_->cpu_data(); ref_top_data = this->blob_data_->cpu_data(); int num = this->blob_top_->num(); int channels = this->blob_top_->channels(); int height = this->blob_top_->height(); int width = this->blob_top_->width(); for (int n = 0; n < num; ++n) { for (int c = 0; c < channels; ++c) { for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { EXPECT_NEAR(top_data[this->blob_top_->offset(n, c, h, w)], ref_top_data[this->blob_data_->offset(n, c, height - 1 - h, width - 1 - w)], 1e-4); } } } } } TYPED_TEST(SpatialTransformerLayerTest, TestScalingForward) { typedef typename TypeParam::Dtype Dtype; FillerParameter filler_param; ConstantFiller<Dtype> constant_filler(filler_param); constant_filler.Fill(this->blob_theta_); this->blob_theta_->mutable_cpu_data()[0] = 2; this->blob_theta_->mutable_cpu_data()[1] = 0.; this->blob_theta_->mutable_cpu_data()[2] = 1.; this->blob_theta_->mutable_cpu_data()[3] = 0.; this->blob_theta_->mutable_cpu_data()[4] = 2; this->blob_theta_->mutable_cpu_data()[5] = 1.; this->blob_theta_->mutable_cpu_data()[0 + 6] = 2; this->blob_theta_->mutable_cpu_data()[1 + 6] = 0.; this->blob_theta_->mutable_cpu_data()[2 + 6] = 1.; this->blob_theta_->mutable_cpu_data()[3 + 6] = 0.; this->blob_theta_->mutable_cpu_data()[4 + 6] = 2; this->blob_theta_->mutable_cpu_data()[5 + 6] = 1.; LayerParameter layer_param; shared_ptr<Layer<Dtype> > layer( new SpatialTransformerLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); const Dtype* top_data; const Dtype* ref_top_data; top_data = this->blob_top_->cpu_data(); ref_top_data = this->blob_data_->cpu_data(); int num = this->blob_top_->num(); int channels = this->blob_top_->channels(); int height = this->blob_top_->height(); int width = this->blob_top_->width(); for (int n = 0; n < num / 2; ++n) { for (int c = 0; c < channels / 2; ++c) { for (int h = 0; h < height / 2; ++h) { for (int w = 0; w < width / 2; ++w) { EXPECT_NEAR(top_data[this->blob_top_->offset(n, c, h, w)], ref_top_data[this->blob_data_->offset(n, c, h * 2, w * 2)], 1e-4); } } } } } TYPED_TEST(SpatialTransformerLayerTest, TestAffineForward) { typedef typename TypeParam::Dtype Dtype; FillerParameter filler_param; filler_param.set_min(-1); filler_param.set_max(1); UniformFiller<Dtype> filler(filler_param); filler.Fill(this->blob_theta_); LayerParameter layer_param; shared_ptr<Layer<Dtype> > layer( new SpatialTransformerLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); affine_transform(this->blob_data_, this->blob_theta_, this->MakeReferenceTop(this->blob_top_)); const Dtype* top_data; const Dtype* ref_top_data; top_data = this->blob_top_->cpu_data(); ref_top_data = this->ref_blob_top_->cpu_data(); for (int i = 0; i < this->blob_top_->count(); ++i) { EXPECT_NEAR(top_data[i], ref_top_data[i], 1e-4); } } // test gradients of data part using standard caffe utility TYPED_TEST(SpatialTransformerLayerTest, TestDataGradient) { typedef typename TypeParam::Dtype Dtype; FillerParameter filler_param; filler_param.set_min(-1); filler_param.set_max(1); UniformFiller<Dtype> filler(filler_param); filler.Fill(this->blob_theta_); LayerParameter layer_param; SpatialTransformerLayer<Dtype> layer(layer_param); GradientChecker<Dtype> checker(1e-2, 1e-3); checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_, 0); } // finite difference with mask trick for max operation: track the winner (refer to http://cs231n.github.io/neural-networks-3/) template <typename Dtype> void theta_gradient(const Blob<Dtype>* in, const Blob<Dtype>* theta, double delta, Blob<Dtype>* gradient) { int num = in->shape(0); int channels = in->shape(1); int height = in->shape(2); int width = in->shape(3); Dtype* gradient_data = gradient->mutable_cpu_diff(); caffe_set<Dtype>(theta->count(), 0, gradient_data); const Dtype* theta_data = theta->cpu_data(); for (int i = 0; i < 6; ++i) { for (int n = 0; n < num; ++n) { for (int h = 0; h < height; ++h) { double ty = h / (double) (height - 1) * (double) 2. - (double) 1.; for (int w = 0; w < width; ++w) { double tx = w / (double) (width - 1)*(double) 2. - (double) 1.; double sx = tx * theta_data[n * 6] + ty * theta_data[n * 6 + 1] + theta_data[n * 6 + 2]; double sy = tx * theta_data[n * 6 + 3] + ty * theta_data[n * 6 + 4] + theta_data[n * 6 + 5]; double sxn = sx; double syn = sy; if (i == 0) { sxn += delta * tx; } else if (i == 1) { sxn += delta * ty; } else if (i == 2) { sxn += delta; } else if (i == 3) { syn += delta * tx; } else if (i == 4) { syn += delta * ty; } else if (i == 5) { syn += delta; } sx = (sx + 1.) / (double) 2. * (width - 1); sy = (sy + 1.) / (double) 2. * (height - 1); sxn = (sxn + 1.) / (double) 2. * (width - 1); syn = (syn + 1.) / (double) 2. * (height - 1); for (int c = 0; c < channels; ++c) { for (int hh = 0; hh < height; ++hh) { for (int ww = 0; ww < width; ++ww) { double max_y = 0; double max_yn = 0; if (hh > sy) { max_y = hh - sy; max_yn = hh - syn; } else { max_y = sy - hh; max_yn = syn - hh; } if (1 - max_y < 0) { max_y = 0; max_yn = 0; } else { max_y = 1 - max_y; max_yn = 1 - max_yn; } double max_x = 0; double max_xn = 0; if (ww > sx) { max_x = ww - sx; max_xn = ww - sxn; } else { max_x = sx - ww; max_xn = sxn - ww; } if (1 - max_x < 0) { max_x = 0; max_xn = 0; } else { max_x = 1 - max_x; max_xn = 1 - max_xn; } gradient_data[i + n * 6] += (Dtype) (in->data_at(n, c, hh, ww) * (max_xn * max_yn - max_x * max_y)); } } } } } } } // to improve numeric precision for(int i = 0; i < theta->count(); ++i) { gradient_data[i] /= delta; } } template void theta_gradient(const Blob<float>* data, const Blob<float>* theta, double delta, Blob<float>* gradient); template void theta_gradient(const Blob<double>* data, const Blob<double>* theta, double delta, Blob<double>* gradient); // test gradients of theta using finite difference method: max operator would fail caffe utility TYPED_TEST(SpatialTransformerLayerTest, TestThetaGradient) { typedef typename TypeParam::Dtype Dtype; FillerParameter filler_param; filler_param.set_min(-1); filler_param.set_max(1); UniformFiller<Dtype> filler(filler_param); filler.Fill(this->blob_theta_); LayerParameter layer_param; SpatialTransformerLayer<Dtype> layer(layer_param); // call backward to generate theta_gradient layer.SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer.Forward(this->blob_bottom_vec_, this->blob_top_vec_); for (int i = 0; i < this->blob_top_->count(); ++i) { this->blob_top_->mutable_cpu_diff()[i] = (Dtype) 1.; } vector<bool> propagate_down(this->blob_bottom_vec_.size(), true); layer.Backward(this->blob_top_vec_, propagate_down, this->blob_bottom_vec_); // compute theta gradient using finite difference shared_ptr<Blob<Dtype> > ref_blob_theta_diff; ref_blob_theta_diff.reset(new Blob<Dtype>()); ref_blob_theta_diff->ReshapeLike(*(this->blob_theta_)); theta_gradient(this->blob_data_, this->blob_theta_, (double) 1e-4, ref_blob_theta_diff.get()); const Dtype* theta_diff = this->blob_theta_->cpu_diff(); const Dtype* ref_theta_diff = ref_blob_theta_diff->cpu_diff(); for (int i = 0; i < this->blob_theta_->count(); ++i) { EXPECT_NEAR(theta_diff[i], ref_theta_diff[i], 1e-4) << "i=" << i; } } }
47.213552
166
0.513852
[ "shape", "vector" ]
4d107659e2066ab5f20729e72181445894e6272a
1,938
hpp
C++
modules/wechat_qrcode/src/zxing/qrcode/detector/pattern_result.hpp
WeChatCV/opencv_contrib
273246d8572cf005c7648e60c6cef78240edfb3e
[ "Apache-2.0" ]
35
2021-01-07T11:58:58.000Z
2022-03-25T11:35:25.000Z
modules/wechat_qrcode/src/zxing/qrcode/detector/pattern_result.hpp
WeChatCV/opencv_contrib
273246d8572cf005c7648e60c6cef78240edfb3e
[ "Apache-2.0" ]
null
null
null
modules/wechat_qrcode/src/zxing/qrcode/detector/pattern_result.hpp
WeChatCV/opencv_contrib
273246d8572cf005c7648e60c6cef78240edfb3e
[ "Apache-2.0" ]
9
2020-12-14T09:13:30.000Z
2021-12-13T07:03:53.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Tencent is pleased to support the open source community by making WeChat QRCode available. // Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. // // Modified from ZXing. Copyright ZXing authors. // Licensed under the Apache License, Version 2.0 (the "License"). #ifndef __ZXING_QRCODE_DETECTOR_PATTERN_RESULT_HPP_ #define __ZXING_QRCODE_DETECTOR_PATTERN_RESULT_HPP_ #include "zxing/common/array.hpp" #include "zxing/common/bitmatrix.hpp" #include "zxing/common/counted.hpp" #include "zxing/common/detector_result.hpp" #include "zxing/qrcode/detector/alignment_pattern.hpp" #include "zxing/qrcode/detector/finder_pattern.hpp" #include "zxing/qrcode/detector/finder_pattern_info.hpp" #include "zxing/resultpoint.hpp" #include <vector> namespace zxing { namespace qrcode { class PatternResult : public Counted { public: Ref<FinderPatternInfo> finderPatternInfo; vector<Ref<AlignmentPattern> > possibleAlignmentPatterns; Ref<AlignmentPattern> confirmedAlignmentPattern; int possibleDimension; // vector<int> possibleDimensions; unsigned int possibleVersion; float possibleFix; float possibleModuleSize; explicit PatternResult(Ref<FinderPatternInfo> info); void setConfirmedAlignmentPattern(int index); int getPossibleAlignmentCount() { return possibleAlignmentPatterns.size(); } // int getPossibleDimensionCount(); public: unsigned int getPossibleVersion() { return possibleVersion; } float getPossibleFix() { return possibleFix; } float getPossibleModuleSize() { return possibleModuleSize; } int getDimension() { return possibleDimension; } }; } // namespace qrcode } // namespace zxing #endif // __ZXING_QRCODE_DETECTOR_PATTERN_RESULT_HPP_
37.269231
93
0.776058
[ "vector" ]
4d12e614146d01263a2f2d4726d22970a7c1822e
19,920
cpp
C++
kgl_genomics/kgl_evidence/kgl_variant_factory_vcf_evidence_data_blk.cpp
kellerberrin/OSM_Gene_Cpp
4ec4d1244f3f1b16213cf05f0056d8e5f85d68c4
[ "MIT" ]
1
2021-04-09T16:24:06.000Z
2021-04-09T16:24:06.000Z
kgl_genomics/kgl_evidence/kgl_variant_factory_vcf_evidence_data_blk.cpp
kellerberrin/KGL_Gene
f8e6c14b8b2009d82d692b28354561b5f0513c5e
[ "MIT" ]
null
null
null
kgl_genomics/kgl_evidence/kgl_variant_factory_vcf_evidence_data_blk.cpp
kellerberrin/KGL_Gene
f8e6c14b8b2009d82d692b28354561b5f0513c5e
[ "MIT" ]
null
null
null
// // Created by kellerberrin on 30/5/20. // #include "kgl_variant_factory_vcf_evidence_data_blk.h" #include "kgl_variant_factory_vcf_evidence.h" #include "kel_utility.h" #include <algorithm> namespace kgl = kellerberrin::genome; kgl::DataMemoryBlock::DataMemoryBlock( std::shared_ptr<const InfoEvidenceHeader> info_evidence_header, const InfoMemoryResource& memory_resource, const VCFInfoParser& info_parser) : info_evidence_header_(std::move(info_evidence_header)) { // booleans and strings are both implemented as type char mem_count_.charCount(memory_resource.boolSize() + memory_resource.charSize()); mem_count_.floatCount(memory_resource.floatSize()); mem_count_.stringCount(memory_resource.viewSize()); mem_count_.integerCount(memory_resource.integerSize()); mem_count_.arrayCount(memory_resource.arraySize()); // Perform actual memory allocation. #ifdef KGL_UNIQUE_PTR char_memory_ = std::make_unique<char[]>(mem_count_.charCount()); integer_memory_ = std::make_unique<InfoIntegerType[]>(mem_count_.integerCount()); float_memory_ = std::make_unique<InfoFloatType[]>(mem_count_.floatCount()) ; array_memory_ = std::make_unique<InfoArrayIndex[]>(mem_count_.arrayCount()); string_memory_ = std::make_unique<std::string_view[]>(mem_count_.stringCount()); #else allocation_strategy_.allocateMemory(mem_count_, MemoryStrategy::SINGLE_MALLOC); char_memory_ = allocation_strategy_.charMemory(); integer_memory_ = allocation_strategy_.integerMemory(); float_memory_ = allocation_strategy_.floatMemory(); array_memory_ = allocation_strategy_.arrayMemory(); string_memory_ = allocation_strategy_.stringMemory(); #endif // Copy the array blocks. // The dynamicAllocation() map ensures that copied array memory blocks will be sorted in ascending identifier order. // We can use a binary search for fast access. size_t index = 0; for (auto const& array_block : memory_resource.arrayResource().dynamicAllocation()) { array_memory_[index] = array_block.second; ++index; } // Resource instance keeps track of string char usage. FixedResourceInstance string_usage("Char Counter"); // allocate the first part of the char array to booleans. string_usage.allocateResource(memory_resource.boolSize()); // Store all the parser data in the memory block. for (auto const& [data_identifier, data_item] : info_evidence_header_->getConstMap()) { // Lookup the matching data token. std::optional<const InfoParserToken> token = info_parser.getToken(data_identifier); switch(data_item.getDataHandle().resourceType()) { case DataResourceType::Boolean: storeBoolean(memory_resource, data_item.getDataHandle(), token); break; case DataResourceType::Integer: storeInteger(data_item.getDataHandle(), token); break; case DataResourceType::Float: storeFloat(data_item.getDataHandle(), token); break; case DataResourceType::String: storeString(data_item.getDataHandle(), token, string_usage); break; } } ++object_count_; } kgl::DataMemoryBlock::~DataMemoryBlock() { --object_count_; } // Binary lookup on the array index. std::optional<const kgl::InfoArrayIndex> kgl::DataMemoryBlock::findArrayIndex(size_t identifier) const { const auto comp = [](const InfoArrayIndex& a, const InfoArrayIndex& b) -> bool { return a.infoVariableIndex() < b.infoVariableIndex(); }; #ifdef KGL_UNIQUE_PTR auto begin_iter = array_memory_.get(); #else auto begin_iter = array_memory_; #endif auto end_iter = begin_iter + mem_count_.arrayCount(); auto result = std::lower_bound(begin_iter, end_iter, InfoArrayIndex(identifier, 0, 0), comp); if (result == end_iter) { return std::nullopt; } else { if (result->infoVariableIndex() == identifier) { return *result; } else { return std::nullopt; } } } void kgl::DataMemoryBlock::storeBoolean(const InfoMemoryResource& memory_resource, const InfoResourceHandle& handle, std::optional<const InfoParserToken> token) { // Check that the bool is fixed with size = 1. if (handle.dynamicType() != DataDynamicType::FixedData or handle.initialDataSize() != 1) { ExecEnv::log().error("DataMemoryBlock::storeBoolean, Boolean type should be Fixed size = 1"); return; } // Check that the offset does not exceed the bounds of the boolean block. if (handle.initialDataOffset() >= memory_resource.boolSize()) { ExecEnv::log().error( "DataMemoryBlock::storeBoolean, Data Offset: {} exceeds maximum calculated boolean offset: {}", handle.initialDataOffset(), memory_resource.boolSize()); return; } char_memory_[handle.initialDataOffset()] = token ? true : false; } void kgl::DataMemoryBlock::storeString(const InfoResourceHandle& handle, std::optional<const InfoParserToken> token, FixedResourceInstance& string_usage) { if (handle.dynamicType() == DataDynamicType::FixedData) { if (handle.initialDataOffset() >= mem_count_.stringCount()) { ExecEnv::log().error("DataMemoryBlock::storeString, Data Offset: {} exceeds maximum calculated string view offset: {}", handle.initialDataOffset(), mem_count_.stringCount()); return; } // No token means a string size of zero (empty string) size_t string_size = token ? token.value().first.size() : 0; size_t string_offset = string_usage.allocateResource(string_size); // increments to the next string. if (string_usage.resourceValue() > mem_count_.charCount()) { ExecEnv::log().error("DataMemoryBlock::storeString, Data Offset: {} exceeds maximum calculated string view offset: {}", string_usage.resourceValue(), mem_count_.charCount()); return; } // Get the destination address char* string_dest_ptr = &char_memory_[string_offset]; // store the string_view string_memory_[handle.initialDataOffset()] = std::string_view(string_dest_ptr, string_size); // If valid token, then copy the string. if (token) { std::memcpy(string_dest_ptr, token.value().first.data(), string_size); } } else if (handle.dynamicType() == DataDynamicType::DynamicData) { std::optional<const InfoArrayIndex> array_index_opt = findArrayIndex(handle.handleId()); if (not array_index_opt) { ExecEnv::log().error("DataMemoryBlock::storeString, Array index for data item handle: {} not found", handle.handleId()); return; } const InfoArrayIndex array_index = array_index_opt.value(); // Ensure we have space in the string view vector for all the strings. if (array_index.infoOffset() + array_index.infoSize() > mem_count_.stringCount()) { ExecEnv::log().error( "DataMemoryBlock::storeString, Identifier: {} Array Offset: {} + Size: {} ({})exceeds maximum calculated string view offset: {}", handle.handleId(), array_index.infoOffset(), array_index.infoSize(), (array_index.infoOffset() + array_index.infoSize()), mem_count_.stringCount()); return; } // Check if we have a valid token. if (token) { // Check the token size and the array size. if (array_index.infoSize() != token.value().second) { ExecEnv::log().error("DataMemoryBlock::storeString, Mismatch between array size {} and token size: {}", array_index.infoSize(), array_index.infoSize()); return; } // Parse out the strings. std::vector<std::string_view> string_vector = Utility::view_tokenizer(token.value().first, VCFInfoParser::INFO_VECTOR_DELIMITER_); // Ensure the array block is the same size as the parsed string count. if (array_index.infoSize() != string_vector.size()) { ExecEnv::log().error("DataMemoryBlock::storeString, Array Size: {} not equal to string array size: {}", array_index.infoSize(), string_vector.size()); return; } // Copy each string. size_t index = array_index.infoOffset(); for (auto const &str_view : string_vector) { size_t string_offset = string_usage.allocateResource(str_view.size()); // increments to the next string. if (string_usage.resourceValue() > mem_count_.charCount()) { ExecEnv::log().error( "DataMemoryBlock::storeString, Data Offset: {} exceeds maximum calculated string view offset: {}", string_usage.resourceValue(), mem_count_.charCount()); return; } // Get the destination address char *string_dest_ptr = &char_memory_[string_offset]; // store the string_view string_memory_[index] = std::string_view(string_dest_ptr, str_view.size()); // copy the string. std::memcpy(string_dest_ptr, str_view.data(), str_view.size()); // next view ++index; } } else { //token not valid so assign zero-sized strings to all array elements. for (size_t index = 0; index < array_index.infoSize(); ++index) { string_memory_[(index + array_index.infoOffset())] = std::string_view(nullptr, 0); } } } else { ExecEnv::log().error( "DataMemoryBlock::storeString, Strings only supported as fixed or dynamic data types"); return; } } void kgl::DataMemoryBlock::storeInteger(const InfoResourceHandle& handle, std::optional<const InfoParserToken> token) { if (handle.dynamicType() == DataDynamicType::FixedData and handle.initialDataSize() == 1) { if (handle.initialDataOffset() >= mem_count_.integerCount()) { ExecEnv::log().error("DataMemoryBlock::storeInteger, Data Offset: {} exceeds maximum calculated integer offset: {}", handle.initialDataOffset(), mem_count_.integerCount()); return; } if (token) { if (token.value().second > 1) { ExecEnv::log().error( "DataMemoryBlock::storeInteger, Expected data size 1, token size: {}, token value: {}", token.value().second, std::string(token.value().first)); return; } integer_memory_[handle.initialDataOffset()] = VCFInfoParser::convertToInteger(std::string(token.value().first)); } else { // Token is not valid. integer_memory_[handle.initialDataOffset()] = VCFInfoParser::MISSING_VALUE_INTEGER_; } } if (handle.dynamicType() == DataDynamicType::FixedDynamic) { if (handle.initialDataOffset() >= mem_count_.integerCount()) { ExecEnv::log().error("DataMemoryBlock::storeInteger, Data Offset: {} exceeds maximum calculated integer offset: {}", handle.initialDataOffset(), mem_count_.integerCount()); return; } if (token) { if (token.value().second > 1) { // Implemented as an array. std::optional<const InfoArrayIndex> array_index_opt = findArrayIndex(handle.handleId()); if (not array_index_opt) { ExecEnv::log().error("DataMemoryBlock::storeString, Array index for data item handle: {} not found", handle.handleId()); return; } const InfoArrayIndex array_index = array_index_opt.value(); if (array_index.infoOffset() + array_index.infoSize() > mem_count_.integerCount()) { ExecEnv::log().error("DataMemoryBlock::storeInteger, Array Offset: {} + Array Size: {} exceeds Integer Array Size: {}", array_index.infoOffset(), array_index.infoSize(), mem_count_.integerCount()); return; } // Parse out the strings. std::vector<std::string_view> string_vector = Utility::view_tokenizer(token.value().first, VCFInfoParser::INFO_VECTOR_DELIMITER_); if (array_index.infoSize() != string_vector.size()) { ExecEnv::log().error("DataMemoryBlock::storeInteger, Mismatch between array size {} and token size: {}", array_index.infoSize(), string_vector.size()); return; } // Invalidate scalar integer_memory_[handle.initialDataOffset()] = VCFInfoParser::MISSING_VALUE_INTEGER_; // Populate array size_t index = array_index.infoOffset(); for (auto const& str_view : string_vector) { integer_memory_[index] = VCFInfoParser::convertToInteger(std::string(str_view)); ++index; } } else { // Implemented as a scalar. integer_memory_[handle.initialDataOffset()] = VCFInfoParser::convertToInteger(std::string(token.value().first)); } } else { // Token not valid. integer_memory_[handle.initialDataOffset()] = VCFInfoParser::MISSING_VALUE_INTEGER_; } } if (handle.dynamicType() == DataDynamicType::DynamicData) { std::optional<const InfoArrayIndex> array_index_opt = findArrayIndex(handle.handleId()); if (not array_index_opt) { ExecEnv::log().error("DataMemoryBlock::storeString, Array index for data item handle: {} not found", handle.handleId()); return; } const InfoArrayIndex array_index = array_index_opt.value(); if (array_index.infoOffset() + array_index.infoSize() > mem_count_.integerCount()) { ExecEnv::log().error( "DataMemoryBlock::storeInteger, Array Offset: {} + Array Size: {} exceeds Integer Array Size: {}", array_index.infoOffset(), array_index.infoSize(), mem_count_.integerCount()); return; } if (token) { // Parse out the strings. std::vector<std::string_view> string_vector = Utility::view_tokenizer(token.value().first, VCFInfoParser::INFO_VECTOR_DELIMITER_); if (array_index.infoSize() != string_vector.size()) { ExecEnv::log().error("DataMemoryBlock::storeInteger, Mismatch between array size {} and token size: {}", array_index.infoSize(), string_vector.size()); return; } // Populate array. size_t index = array_index.infoOffset(); for (auto const &str_view : string_vector) { integer_memory_[index] = VCFInfoParser::convertToInteger(std::string(str_view)); ++index; } } else { // Token not valid. for (size_t index = 0; index < array_index.infoSize(); ++index) { integer_memory_[array_index.infoOffset() + index] = VCFInfoParser::MISSING_VALUE_INTEGER_; } // for loop } // no token } // if dynamic } void kgl::DataMemoryBlock::storeFloat(const InfoResourceHandle& handle, std::optional<const InfoParserToken> token) { if (handle.dynamicType() == DataDynamicType::FixedData and handle.initialDataSize() == 1) { if (handle.initialDataOffset() >= mem_count_.floatCount()) { ExecEnv::log().error("DataMemoryBlock::storeFloat, Data Offset: {} exceeds maximum calculated integer offset: {}", handle.initialDataOffset(), mem_count_.floatCount()); return; } if (token) { if (token.value().second > 1) { ExecEnv::log().error( "DataMemoryBlock::storeFloat, Expected data size 1, token size: {}, token value: {}", token.value().second, std::string(token.value().first)); return; } float_memory_[handle.initialDataOffset()] = VCFInfoParser::convertToFloat(std::string(token.value().first)); } else { // Token is not valid. float_memory_[handle.initialDataOffset()] = VCFInfoParser::MISSING_VALUE_FLOAT_; } } if (handle.dynamicType() == DataDynamicType::FixedDynamic) { if (handle.initialDataOffset() >= mem_count_.floatCount()) { ExecEnv::log().error("DataMemoryBlock::storeFloat, Data Offset: {} exceeds maximum calculated float offset: {}", handle.initialDataOffset(), mem_count_.floatCount()); return; } if (token) { if (token.value().second > 1) { // Implemented as an array. std::optional<const InfoArrayIndex> array_index_opt = findArrayIndex(handle.handleId()); if (not array_index_opt) { ExecEnv::log().error("DataMemoryBlock::storeString, Array index for data item handle: {} not found", handle.handleId()); return; } const InfoArrayIndex array_index = array_index_opt.value(); if (array_index.infoOffset() + array_index.infoSize() > mem_count_.floatCount()) { ExecEnv::log().error("DataMemoryBlock::storeFloat, Array Offset: {} + Array Size: {} exceeds Float Array Size: {}", array_index.infoOffset(), array_index.infoSize(), mem_count_.floatCount()); return; } // Parse out the strings. std::vector<std::string_view> string_vector = Utility::view_tokenizer(token.value().first, VCFInfoParser::INFO_VECTOR_DELIMITER_); if (array_index.infoSize() != string_vector.size()) { ExecEnv::log().error("DataMemoryBlock::storeFloat, Mismatch between array size {} and token size: {}", array_index.infoSize(), string_vector.size()); return; } // Invalidate scalar. float_memory_[handle.initialDataOffset()] = VCFInfoParser::MISSING_VALUE_FLOAT_; // Populate array size_t index = array_index.infoOffset(); for (auto const& str_view : string_vector) { float_memory_[index] = VCFInfoParser::convertToFloat(std::string(str_view)); ++index; } } else { // Implemented as a scalar. float_memory_[handle.initialDataOffset()] = VCFInfoParser::convertToFloat(std::string(token.value().first)); } } else { // Token not valid. float_memory_[handle.initialDataOffset()] = VCFInfoParser::MISSING_VALUE_FLOAT_; } } if (handle.dynamicType() == DataDynamicType::DynamicData) { std::optional<const InfoArrayIndex> array_index_opt = findArrayIndex(handle.handleId()); if (not array_index_opt) { ExecEnv::log().error("DataMemoryBlock::storeString, Array index for data item handle: {} not found", handle.handleId()); return; } const InfoArrayIndex array_index = array_index_opt.value(); if (array_index.infoOffset() + array_index.infoSize() > mem_count_.floatCount()) { ExecEnv::log().error( "DataMemoryBlock::storeFloat, Array Offset: {} + Array Size: {} exceeds Float Array Size: {}", array_index.infoOffset(), array_index.infoSize(), mem_count_.floatCount()); return; } if (token) { // Parse out the strings. std::vector<std::string_view> string_vector = Utility::view_tokenizer(token.value().first, VCFInfoParser::INFO_VECTOR_DELIMITER_); if (array_index.infoSize() != string_vector.size()) { ExecEnv::log().error("DataMemoryBlock::storeFloat, Mismatch between array size {} and token size: {}", array_index.infoSize(), string_vector.size()); return; } // Populate the array. size_t index = array_index.infoOffset(); for (auto const &str_view : string_vector) { float_memory_[index] = VCFInfoParser::convertToFloat(std::string(str_view)); ++index; } } else { // Token not valid. for (size_t index = 0; index < array_index.infoSize(); ++index) { float_memory_[array_index.infoOffset() + index] = VCFInfoParser::MISSING_VALUE_FLOAT_; } // for loop } // no token } // if dynamic }
33.2
162
0.648544
[ "vector" ]
4d194b58ad3160a365e1f81c00d45ff916ec195c
439
cpp
C++
examples/curry/new_adaptors/main.cpp
uselessgoddess/adaptors
400bc40dcd799ed5f52e732eda79643638a702da
[ "MIT" ]
null
null
null
examples/curry/new_adaptors/main.cpp
uselessgoddess/adaptors
400bc40dcd799ed5f52e732eda79643638a702da
[ "MIT" ]
null
null
null
examples/curry/new_adaptors/main.cpp
uselessgoddess/adaptors
400bc40dcd799ed5f52e732eda79643638a702da
[ "MIT" ]
null
null
null
#include <universal_adaptor.h> #include <universal_curry.h> #include <iostream> #include <ranges> #include "../../help_lib.h" int main() { constexpr auto filter = std::views::filter | curry::as_curry(); constexpr auto even = filter([](auto item) { return item % 2 == 0; }) | adaptors::as_adaptor(); auto list = std::vector{1, 2, 3, 4, 5}; for (auto item : list | even()) { std::cout << item << " "; } }
21.95
99
0.587699
[ "vector" ]
4d1d62b2853fdac8eb5ea991f72ced41549355cb
58,857
hpp
C++
include/tribalscript/instructions.hpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
null
null
null
include/tribalscript/instructions.hpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
1
2021-07-24T16:29:11.000Z
2021-07-26T20:00:17.000Z
include/tribalscript/instructions.hpp
Ragora/TribalScript
b7f7cc6b311cee1422f1c7dffd58c85c4f29cc1d
[ "MIT" ]
null
null
null
/** * Copyright 2021 Robert MacGregor * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <vector> #include <cassert> #include <iostream> #include <sstream> #include <tribalscript/function.hpp> #include <tribalscript/interpreter.hpp> #include <tribalscript/executionscope.hpp> #include <tribalscript/storedvalue.hpp> #include <tribalscript/storedvaluestack.hpp> #include <tribalscript/executionstate.hpp> #include <tribalscript/instructionsequence.hpp> namespace TribalScript { namespace Instructions { /** * @brief Base instruction class. All instructions in the interpreter should dervive * from this class and implement all virtual members. */ class Instruction { public: /** * @brief Main execution method of the instruction. This serves as our * switching statement that determines how opcodes will behave. * @param state The current execution state to act upon. */ virtual AddressOffsetType execute(ExecutionState* state) = 0; /** * @brief Helper routine to produce a disassembly for this instruction. */ virtual std::string disassemble() = 0; //! Compiler generated comment, used for generating easier to follow disassembly std::string mComment; }; /** * @brief Push float instruction. This will push a floating point value to the system stack * for later use in execution. */ class PushFloatInstruction : public Instruction { public: PushFloatInstruction(const float value) : mParameter(value) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); stack.emplace_back(mParameter); return 1; }; virtual std::string disassemble() override { std::ostringstream out; out << "PushFloat " << mParameter; return out.str(); } private: //! The value to push. float mParameter; }; /** * @brief Push integer instruction. This will push an integer value to the system stack * for later use in execution. */ class PushIntegerInstruction : public Instruction { public: PushIntegerInstruction(const int value) : mParameter(value) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); stack.emplace_back(mParameter); return 1; }; virtual std::string disassemble() override { std::ostringstream out; out << "PushInteger " << mParameter; return out.str(); } private: //! The value to push. int mParameter; }; /** * @brief Push string instruction. This will push a string value to the system stack for later * use in execution. */ class PushStringInstruction : public Instruction { public: PushStringInstruction(const std::string& value) : mString(value) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); stack.emplace_back(mString.c_str()); return 1; }; virtual std::string disassemble() override { std::ostringstream out; out << "PushString " << mString; return out.str(); } private: //! The string table ID of the parameter to push. std::string mString; }; /** * @brief Push a reference to a named local variable. The parameter provided here * should be excluding the '%' prefix. */ class PushLocalReferenceInstruction : public Instruction { public: PushLocalReferenceInstruction(const StringTableEntry value) : mStringID(value) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); stack.emplace_back(state->mExecutionScope.getVariableOrAllocate(mStringID)); return 1; }; virtual std::string disassemble() override { std::ostringstream out; out << "PushLocalReference " << mStringID; return out.str(); } private: //! The value to push. StringTableEntry mStringID; }; /** * @brief Push a reference to a named global variable. The parameter provided here * should be excluding the '$' prefix. */ class PushGlobalReferenceInstruction : public Instruction { public: PushGlobalReferenceInstruction(const StringTableEntry value) : mStringID(value) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); stack.emplace_back(state->mInterpreter->getGlobalOrAllocate(mStringID)); return 1; }; virtual std::string disassemble() override { std::ostringstream out; out << "PushGlobalReference " << mStringID; return out.str(); } private: //! The value to push. StringTableEntry mStringID; }; /** * @brief Performs an addition of two values on the stack and assigns the result. */ class AddAssignmentInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); // Pull two values off the stack StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); float resultRaw = 0.0f; resultRaw = lhsStored.toFloat(); resultRaw += rhsStored.toFloat(); StoredValue result = StoredValue(resultRaw); if (!lhsStored.setValue(result)) { state->mInterpreter->mConfig.mPlatform->logError("Attempted to perform no-op assignment!"); } stack.erase(stack.end() - 2, stack.end()); // In Torque, the result of the assignment is pushed to stack stack.push_back(result); return 1; }; virtual std::string disassemble() override { return "AddAssignment"; } }; /** * @brief Assign to lhs with whatever is on rhs. */ class AssignmentInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); // Pull two values off the stack StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); if (!lhsStored.setValue(rhsStored)) { state->mInterpreter->mConfig.mPlatform->logError("Attempted to perform no-op assignment!"); } stack.erase(stack.end() - 2, stack.end()); // In Torque, the result of the assignment is pushed to stack stack.push_back(rhsStored); return 1; }; virtual std::string disassemble() override { return "Assignment"; } }; /** * @brief Concatenates two values at the top of the stack and pushes back the * result. */ class ConcatInstruction : public Instruction { public: ConcatInstruction(const std::string& seperator) : mSeperator(seperator) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); // Pull two values off the stack StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); std::string lhs = lhsStored.toString(); std::string rhs = rhsStored.toString(); // Generate a new string ID const std::string requestedString = lhs + mSeperator + rhs; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(requestedString.c_str()); return 1; }; virtual std::string disassemble() override { std::ostringstream result; result << "Concat " << mSeperator; return result.str(); } private: std::string mSeperator; }; /** * @brief Negate a value on the stack. */ class NegateInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 1); // Pull two values off the stack StoredValue& storedTarget = stack.back(); const float result = -storedTarget.toFloat(); stack.pop_back(); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "Negate"; } }; /** * @brief Invert the truthfulness of a value on the stack. */ class NotInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(!stack.empty()); StoredValue& storedTarget = stack.back(); const int result = !storedTarget.toBoolean() ? 1 : 0; stack.pop_back(); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "Not"; } }; /** * @brief Calls a function registered within the current interpreter. */ class CallFunctionInstruction : public Instruction { public: /** * @brief Constructs a new CallFunctionInstruction instance. * @param space The namespace of the function to call. * @param name The name of the function to call. * @param argc The total number of arguments to pull off the stack for use as parameters. */ CallFunctionInstruction(std::string space, std::string name, const std::size_t argc) : mNameSpace(std::move(space)), mName(std::move(name)), mArgc(argc) { } virtual AddressOffsetType execute(ExecutionState* state) override { const std::string namespaceName = toLowerCase(mNameSpace); StoredValueStack& stack = state->mExecutionScope.getStack(); // FIXME: At the moment we're loading parameters like this which is incurring unnecessary copies std::vector<StoredValue> parameters; auto parametersStart = stack.end() - mArgc; for (std::size_t iteration = 0; iteration < mArgc; ++iteration) { auto iterator = parametersStart + iteration; parameters.push_back(*iterator); } stack.erase(parametersStart, stack.end()); // If we're calling a parent function, perform an alternative lookup if (namespaceName == "parent") { Function* currentFunction = state->mExecutionScope.getCurrentFunction(); if (!currentFunction) { state->mInterpreter->mConfig.mPlatform->logError("Attempted to call parent:: function at root!"); stack.push_back(StoredValue(0)); return 1; } // Once we have a valid function pointer, ask the interpreter to find a super function higher up the chain std::shared_ptr<Function> parentFunction = state->mInterpreter->getFunctionParent(currentFunction); if (!parentFunction) { std::ostringstream stream; stream << "Could not find parent function '" << mName << "' for calling! Placing 0 on the stack."; state->mInterpreter->mConfig.mPlatform->logError(stream.str()); stack.push_back(StoredValue(0)); return 1; } // Otherwise, call it parentFunction->execute(nullptr, state, parameters); return 1; } std::shared_ptr<Function> functionLookup = state->mInterpreter->getFunction(mNameSpace, mName); if (functionLookup) { functionLookup->execute(nullptr, state, parameters); } else { std::ostringstream stream; stream << "Could not find function '" << mName << "' for calling! Placing 0 on the stack."; state->mInterpreter->mConfig.mPlatform->logError(stream.str()); stack.push_back(StoredValue(0)); } return 1; }; virtual std::string disassemble() override { std::ostringstream out; if (mNameSpace == "") { out << "CallFunction " << mName << " argc=" << mArgc; } else { out << "CallFunction " << mNameSpace << "::" << mName << " argc=" << mArgc; } return out.str(); } private: //! The namespace of the function to call. std::string mNameSpace; //! The name of the function to call. std::string mName; //! How many arguments are being passed to the function to call. std::size_t mArgc; }; /** * @brief Performs a logical and of two values on the stack and pushes back the result. */ class LogicalAndInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); const bool lhs = lhsStored.toBoolean(); const bool rhs = rhsStored.toBoolean(); const int result = lhs && rhs ? 1 : 0; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "LogicalAnd"; } }; /** * @brief Performs a logical or of two values on the stack and pushes back the result. */ class LogicalOrInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); const bool lhs = lhsStored.toBoolean(); const bool rhs = rhsStored.toBoolean(); const int result = lhs || rhs ? 1 : 0; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "LogicalOr"; } }; /** * @brief Adds together two values on the stack and pushes the sum. */ class AddInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats float lhs = lhsStored.toFloat(); float rhs = rhsStored.toFloat(); const float result = lhs + rhs; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "Add"; } }; /** * @brief Adds together two values on the stack and pushes the sum. */ class MinusInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats float lhs = lhsStored.toFloat(); float rhs = rhsStored.toFloat(); const float result = lhs - rhs; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "Minus"; } }; /** * @brief Adds together two values on the stack and pushes the sum. */ class ModulusInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats int lhs = lhsStored.toInteger(); int rhs = rhsStored.toInteger(); const int result = lhs % rhs; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "Modulus"; } }; /** * @brief Compares two values on the stack using a less than relation. */ class LessThanInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats float lhs = lhsStored.toFloat(); float rhs = rhsStored.toFloat(); const int result = lhs < rhs ? 1 : 0; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "LessThan"; } }; class GreaterThanInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats float lhs = lhsStored.toFloat(); float rhs = rhsStored.toFloat(); const int result = lhs > rhs ? 1 : 0; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "GreaterThan"; } }; class GreaterThanOrEqualInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats float lhs = lhsStored.toFloat(); float rhs = rhsStored.toFloat(); const int result = lhs >= rhs ? 1 : 0; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "GreaterThanOrEqual"; } }; /** * @brief Compares two values on the stack using an equality. */ class EqualsInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats float lhs = lhsStored.toFloat(); float rhs = rhsStored.toFloat(); const int result = lhs == rhs ? 1 : 0; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "Equals"; } }; /** * @brief Compares two values on the stack using an equality. */ class NotEqualsInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats float lhs = lhsStored.toFloat(); float rhs = rhsStored.toFloat(); const int result = lhs != rhs ? 1 : 0; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "NotEquals"; } }; /** * @brief Compares two values on the stack using an equality. */ class StringEqualsInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats std::string lhs = lhsStored.toString(); std::string rhs = rhsStored.toString(); const int result = lhs == rhs ? 1 : 0; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "StringEquals"; } }; class StringNotEqualInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats std::string lhs = lhsStored.toString(); std::string rhs = rhsStored.toString(); const int result = lhs != rhs ? 1 : 0; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "StringNotEqual"; } }; /** * @brief Performs a bitwise AND against two values. */ class BitwiseAndInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats int lhs = lhsStored.toInteger(); int rhs = rhsStored.toInteger(); const int result = lhs & rhs; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "BitwiseAnd"; } }; class BitwiseOrInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats int lhs = lhsStored.toInteger(); int rhs = rhsStored.toInteger(); const int result = lhs | rhs; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "BitwiseOr"; } }; /** * @brief Multiplies together two values on the stack and pushes the result back * to the stack. */ class MultiplyInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats float lhs = lhsStored.toFloat(); float rhs = rhsStored.toFloat(); const float result = lhs * rhs; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "Multiply"; } }; /** * @brief Performs a divide on two values at the top of the stack, pushing * the result back. */ class DivideInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue& rhsStored = *(stack.end() - 1); StoredValue& lhsStored = *(stack.end() - 2); // NOTE: For now we normalize to floats float lhs = lhsStored.toFloat(); float rhs = rhsStored.toFloat(); const float result = lhs / rhs; stack.erase(stack.end() - 2, stack.end()); stack.emplace_back(result); return 1; }; virtual std::string disassemble() override { return "Divide"; } }; /** * @brief Pops a value from the stack, discarding it. */ class PopInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 1); stack.pop_back(); return 1; }; virtual std::string disassemble() override { return "Pop"; } }; /** * @brief Unconditionally jumps to the specified instruction offset. */ class JumpInstruction : public Instruction { public: /** * @brief Constructs a new JumpInstruction instance. * @param offset The instruction offset to unconditionally jump to. */ JumpInstruction(const AddressOffsetType offset) : mOffset(offset) { } virtual AddressOffsetType execute(ExecutionState* state) override { return mOffset; }; virtual std::string disassemble() override { std::ostringstream out; out << "Jump " << mOffset; return out.str(); } private: //! The unconditional jump offset. AddressOffsetType mOffset; }; /** * @brief Jumps to the specified instruction offset if a condition is true. * The condition checked is the value at the top of the stack coerced to a * boolean. If the condition is false, this instruction only pops the stack. */ class JumpTrueInstruction : public Instruction { public: /** * @brief Constructs a new instance of JumpTrueInstruction. * @param offset The instruction offset to jump to if the condition is true. */ JumpTrueInstruction(const AddressOffsetType offset) : mOffset(offset) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 1); StoredValue& booleanStored = stack.back(); if (booleanStored.toBoolean()) { stack.pop_back(); return mOffset; } stack.pop_back(); return 1; }; virtual std::string disassemble() override { std::ostringstream out; out << "JumpTrue " << mOffset; return out.str(); } private: //! The jump offset. AddressOffsetType mOffset; }; /** * @brief Jumps to the specified instruction offset if a condition is false. * The condition checked is the value at the top of the stack coerced to a * boolean. If the condition is true, this instruction only pops the stack. */ class JumpFalseInstruction : public Instruction { public: /** * @brief Constructs a new instance of JumpFalseInstruction. * @param offset The instruction offset to jump to if the condition is false. */ JumpFalseInstruction(const AddressOffsetType offset) : mOffset(offset) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 1); StoredValue& booleanStored = stack.back(); if (!booleanStored.toBoolean()) { stack.pop_back(); return mOffset; } stack.pop_back(); return 1; }; virtual std::string disassemble() override { std::ostringstream out; out << "JumpFalse " << mOffset; return out.str(); } private: //! The jump offset. AddressOffsetType mOffset; }; /** * @brief Instruction that does nothing. It usually is used to pad jumps in order * to provide safe jump targets within the current program space. */ class NOPInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { return 1; }; virtual std::string disassemble() override { return "NOP"; } }; /** * @brief Registers a callable function to the registry in the current interpreter. */ class FunctionDeclarationInstruction : public Instruction { public: /** * @brief Constructs a new instance of FunctionDeclarationInstruction. * @param package The package this function is defined in. * @param space The namespace this function is defined in. * @param name The name of this function. * @param parameterNames The names of all parameters this function is expecting. * @param instructions The instructions that make up the body of this function. */ FunctionDeclarationInstruction(const std::string package, const std::string& space, const std::string& name, const std::vector<std::string> parameterNames, const InstructionSequence& instructions) : mPackageName(package), mNameSpace(space), mName(name), mParameterNames(parameterNames), mInstructions(instructions) { } virtual AddressOffsetType execute(ExecutionState* state) override { // Register the function std::shared_ptr<Function> newFunction = std::shared_ptr<Function>(new Function(mPackageName, mNameSpace, mName, mParameterNames)); newFunction->addInstructions(mInstructions); state->mInterpreter->addFunction(newFunction); return 1; }; virtual std::string disassemble() override { std::ostringstream out; if (mNameSpace == NAMESPACE_EMPTY) { out << "FunctionDeclaration " << mName; } else { out << "FunctionDeclaration " << mNameSpace << "::" << mName; } if (mPackageName != PACKAGE_EMPTY) { out << "[in Package " << mPackageName << "] "; } out << "("; // Generate parameter list for (auto iterator = mParameterNames.begin(); iterator != mParameterNames.end(); ++iterator) { if (iterator != mParameterNames.begin()) { out << ", "; } out << *iterator; } // Output all instructions out << ")" << std::endl; for (auto&& instruction : mInstructions) { out << " " << instruction->disassemble(); if (instruction->mComment != "") { out << " // " << instruction->mComment; } out << std::endl; } return out.str(); } private: std::string mPackageName; std::string mNameSpace; std::string mName; std::vector<std::string> mParameterNames; InstructionSequence mInstructions; }; class SubReferenceInstruction : public Instruction { public: SubReferenceInstruction(const StringTableEntry value, const std::size_t arrayIndices) : mStringID(value), mArrayIndices(arrayIndices) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 1); const std::string arrayName = resolveArrayNameFromStack(stack, state, state->mInterpreter->mStringTable.getString(mStringID), mArrayIndices); StoredValue targetStored = stack.back(); stack.pop_back(); ConsoleObject* referenced = targetStored.toConsoleObject(state); if (referenced) { // Obtain a reference to the console object's field stack.emplace_back(referenced->getTaggedFieldOrAllocate(arrayName)); return 1; } stack.emplace_back(0); return 1; }; virtual std::string disassemble() override { std::ostringstream out; out << "SubReference " << mStringID << " argc=" << mArrayIndices; return out.str(); } private: StringTableEntry mStringID; std::size_t mArrayIndices; }; /** * @brief Ends execution in the current function immediately. It will take one * value from the top of the stack and push it to the parent stack before returning. */ class ReturnInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 1); StoredValue& targetStored = stack.back(); // For if we return a variable reference, we want to pass back a copy StoredValueStack& returnStack = state->mExecutionScope.getReturnStack(); returnStack.push_back(targetStored.getReferencedValueCopy()); stack.pop_back(); return 0; }; virtual std::string disassemble() override { std::ostringstream out; out << "Return"; return out.str(); } }; /** * @brief Breaks out of the current loop, ending all possible loop iterations immediately. */ class BreakInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { // This is a placeholder instruction for the compiler state->mInterpreter->mConfig.mPlatform->logWarning("Break outside of loop, ignoring ..."); return 1; }; virtual std::string disassemble() override { return "Break"; } }; /** * @brief Moves to the next iteration of the current loop. */ class ContinueInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { // This is a placeholder instruction for the compiler state->mInterpreter->mConfig.mPlatform->logWarning("Continue outside of loop, ignoring ..."); return 1; }; virtual std::string disassemble() override { return "Continue"; } }; /** * @brief Accesses an array on a local or global variable. Technically, we just take all * array indices and use them to generate a new variable name to emulate array accesses. */ class AccessArrayInstruction : public Instruction { public: /** * @brief Constructs a new instance of AccessArrayInstruction. * @param name The base name of the array to access. * @param argc The number of array indices to load from the stack. * @param global Whether or not the array access is against a global or not. */ AccessArrayInstruction(const std::string& name, const std::size_t argc, bool global) : mName(name), mArgc(argc), mGlobal(global) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); // When we encounter this instruction, we generate a new variable reference by appending all string representations together // This is what T2 does - it has no concept of arrays despite pretending to const std::string arrayName = resolveArrayNameFromStack(stack, state, mName, mArgc); if (mGlobal) { stack.emplace_back(state->mInterpreter->getGlobalOrAllocate(arrayName)); } else { stack.emplace_back(state->mExecutionScope.getVariableOrAllocate(arrayName)); } return 1; }; virtual std::string disassemble() override { std::ostringstream out; out << "AccessArray " << mName << " argc=" << mArgc << " global=" << mGlobal; return out.str(); } private: std::string mName; std::size_t mArgc; bool mGlobal; }; /** * @brief Calls a function that is bound to an object identified on the stack. */ class CallBoundFunctionInstruction : public Instruction { public: /** * @brief Constructs a new instance of CallBoundFunctionInstruction. * @param name The name of the function to call. * @param argc The number of arguments to pull from the stack when resolving the call. */ CallBoundFunctionInstruction(const std::string& name, const std::size_t argc) : mName(name), mArgc(argc) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 1); // FIXME: At the moment, parameters for bound functions are *after* the target object on the stack std::vector<StoredValue> parameters; auto parametersStart = stack.end() - mArgc; for (std::size_t iteration = 0; iteration < mArgc; ++iteration) { auto iterator = parametersStart + iteration; parameters.push_back(*iterator); } stack.erase(parametersStart, stack.end()); // Next load the target StoredValue targetStored = stack.back(); stack.pop_back(); // Retrieve the referenced ConsoleObject ConsoleObject* targetObject = targetStored.toConsoleObject(state); if (!targetObject) { std::ostringstream output; output << "Cannot find object '" << targetStored.toString() << "' to call function '" << mName << "'!"; state->mInterpreter->mConfig.mPlatform->logWarning(output.str()); stack.push_back(StoredValue(0)); return 1; } // Walk the class hierarchy ConsoleObjectDescriptor* descriptor = state->mInterpreter->lookupDescriptor(targetObject->getVirtualClassName()); assert(descriptor); assert(descriptor->mHierarchy.size() != 0); for (const std::string& className : descriptor->mHierarchy) { // Ask the interpreter to lookup the function std::shared_ptr<Function> calledFunction = state->mInterpreter->getFunction(className, mName); if (calledFunction) { calledFunction->execute(targetObject, state, parameters); return 1; } } std::ostringstream output; output << "Cannot find function '" << mName << "' on object '" << targetStored.toString() << "'!"; state->mInterpreter->mConfig.mPlatform->logWarning(output.str()); stack.emplace_back(0); return 1; }; virtual std::string disassemble() override { std::ostringstream out; out << "CallBoundFunctionInstruction " << mName << " argc=" << mArgc; return out.str(); } private: std::string mName; std::size_t mArgc; }; class PushObjectInstantiationInstruction : public Instruction { public: virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue objectName = stack.back(); stack.pop_back(); StoredValue objectTypeName = stack.back(); stack.pop_back(); state->mExecutionScope.pushObjectInstantiation(objectTypeName.toString(), objectName.toString()); return 1; }; virtual std::string disassemble() override { return "PushObjectInstantiation"; } }; class PushObjectFieldInstruction : public Instruction { public: PushObjectFieldInstruction(const std::size_t fieldComponentCount) : mFieldComponentCount(fieldComponentCount) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); assert(stack.size() >= 2); StoredValue rvalue = stack.back(); stack.pop_back(); // Load array components std::vector<std::string> arrayComponents; for (unsigned int iteration = 0; iteration < mFieldComponentCount; ++iteration) { arrayComponents.push_back(stack.popString(state)); } // Load base name StoredValue fieldBaseName = stack.back(); stack.pop_back(); // FIXME: This should be using the resolveArrayNameFromStack helper function std::ostringstream out; out << fieldBaseName.toString(); for (auto iterator = arrayComponents.rbegin(); iterator != arrayComponents.rend(); ++iterator) { if (iterator != arrayComponents.rend()) { out << "_"; } out << *iterator; } // Final field assignment ObjectInstantiationDescriptor& descriptor = state->mExecutionScope.currentObjectInstantiation(); const std::string chosenFieldName = state->mInterpreter->mConfig.mCaseSensitive ? out.str() : toLowerCase(out.str()); auto search = descriptor.mFieldAssignments.find(chosenFieldName); if (search != descriptor.mFieldAssignments.end()) { search->second = rvalue; } else { descriptor.mFieldAssignments.insert(std::make_pair(chosenFieldName, rvalue)); } return 1; }; virtual std::string disassemble() override { std::ostringstream out; out << "PushObjectField argc=" << mFieldComponentCount; return out.str(); } private: std::size_t mFieldComponentCount; }; class PopObjectInstantiationInstruction : public Instruction { public: PopObjectInstantiationInstruction(std::size_t childrenCount) : mChildrenCount(childrenCount) { } virtual AddressOffsetType execute(ExecutionState* state) override { StoredValueStack& stack = state->mExecutionScope.getStack(); ObjectInstantiationDescriptor descriptor = state->mExecutionScope.popObjectInstantiation(); // Ask the interpreter to initialize the resulting tree ConsoleObject* result = state->mInterpreter->initializeConsoleObjectTree(descriptor); if (result) { // Assign fields -- any construction fields should have been pulled out of the descriptor at this point descriptor.copyFieldsToConsoleObject(result); // Append children for (std::size_t iteration = 0; iteration < mChildrenCount; ++iteration) { StoredValue nextChildID = stack.back(); stack.pop_back(); ConsoleObject* nextChild = state->mInterpreter->mConfig.mConsoleObjectRegistry->getConsoleObject(state->mInterpreter, nextChildID.toInteger()); result->addChild(nextChild); } stack.emplace_back((int)state->mInterpreter->mConfig.mConsoleObjectRegistry->getConsoleObjectID(state->mInterpreter, result)); } else { state->mInterpreter->mConfig.mPlatform->logError("Failed to instantiate object!"); stack.emplace_back(-1); } return 1; }; virtual std::string disassemble() override { return "PopObjectInstantiation"; } private: std::size_t mChildrenCount; }; } }
36.08645
330
0.483426
[ "object", "vector" ]
4d27372567b1df067e80a4dbe3d70fd7cdbb8442
101
cpp
C++
src/main.cpp
patilswapnilv/appjs
003a0d9615e34855460761139554218ba2c2942d
[ "MIT" ]
934
2015-01-02T03:29:12.000Z
2022-02-28T07:10:04.000Z
src/main.cpp
patilswapnilv/appjs
003a0d9615e34855460761139554218ba2c2942d
[ "MIT" ]
3
2016-04-24T17:10:21.000Z
2016-05-26T04:46:47.000Z
src/main.cpp
patilswapnilv/appjs
003a0d9615e34855460761139554218ba2c2942d
[ "MIT" ]
159
2015-01-04T15:20:49.000Z
2021-09-25T22:25:37.000Z
#include "appjs.h" extern "C" void init (v8::Handle<v8::Object> target) { appjs::Init (target); }
16.833333
54
0.643564
[ "object" ]
4d2b3ac22041b44dc81901b0e0a0598bebfc03c6
56,639
cpp
C++
B2G/gecko/js/src/ion/Ion.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/js/src/ion/Ion.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/js/src/ion/Ion.cpp
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * vim: set ts=4 sw=4 et tw=99: * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "Ion.h" #include "IonAnalysis.h" #include "IonBuilder.h" #include "IonLinker.h" #include "IonSpewer.h" #include "LIR.h" #include "AliasAnalysis.h" #include "LICM.h" #include "ValueNumbering.h" #include "EdgeCaseAnalysis.h" #include "RangeAnalysis.h" #include "LinearScan.h" #include "jscompartment.h" #include "jsworkers.h" #include "IonCompartment.h" #include "CodeGenerator.h" #if defined(JS_CPU_X86) # include "x86/Lowering-x86.h" #elif defined(JS_CPU_X64) # include "x64/Lowering-x64.h" #elif defined(JS_CPU_ARM) # include "arm/Lowering-arm.h" #endif #include "gc/Marking.h" #include "jsgcinlines.h" #include "jsinferinlines.h" #include "jsobjinlines.h" #include "vm/Stack-inl.h" #include "ion/IonFrames-inl.h" #include "ion/CompilerRoot.h" #include "methodjit/Retcon.h" #if JS_TRACE_LOGGING #include "TraceLogging.h" #endif using namespace js; using namespace js::ion; // Global variables. IonOptions ion::js_IonOptions; // Assert that IonCode is gc::Cell aligned. JS_STATIC_ASSERT(sizeof(IonCode) % gc::Cell::CellSize == 0); #ifdef JS_THREADSAFE static bool IonTLSInitialized = false; static unsigned IonTLSIndex; static inline IonContext * CurrentIonContext() { return (IonContext *)PR_GetThreadPrivate(IonTLSIndex); } bool ion::SetIonContext(IonContext *ctx) { return PR_SetThreadPrivate(IonTLSIndex, ctx) == PR_SUCCESS; } #else static IonContext *GlobalIonContext; static inline IonContext * CurrentIonContext() { return GlobalIonContext; } bool ion::SetIonContext(IonContext *ctx) { GlobalIonContext = ctx; return true; } #endif IonContext * ion::GetIonContext() { JS_ASSERT(CurrentIonContext()); return CurrentIonContext(); } IonContext::IonContext(JSContext *cx, JSCompartment *compartment, TempAllocator *temp) : cx(cx), compartment(compartment), temp(temp), prev_(CurrentIonContext()), assemblerCount_(0) { SetIonContext(this); } IonContext::~IonContext() { SetIonContext(prev_); } bool ion::InitializeIon() { #ifdef JS_THREADSAFE if (!IonTLSInitialized) { PRStatus status = PR_NewThreadPrivateIndex(&IonTLSIndex, NULL); if (status != PR_SUCCESS) return false; IonTLSInitialized = true; } #endif CheckLogging(); return true; } IonCompartment::IonCompartment() : execAlloc_(NULL), enterJIT_(NULL), bailoutHandler_(NULL), argumentsRectifier_(NULL), invalidator_(NULL), functionWrappers_(NULL), flusher_(NULL) { } bool IonCompartment::initialize(JSContext *cx) { execAlloc_ = cx->runtime->getExecAlloc(cx); if (!execAlloc_) return false; functionWrappers_ = cx->new_<VMWrapperMap>(cx); if (!functionWrappers_ || !functionWrappers_->init()) return false; return true; } void ion::FinishOffThreadBuilder(IonBuilder *builder) { if (builder->script()->isIonCompilingOffThread()) { types::TypeCompartment &types = builder->script()->compartment()->types; builder->recompileInfo.compilerOutput(types)->invalidate(); builder->script()->ion = NULL; } js_delete(builder->temp().lifoAlloc()); } static inline void FinishAllOffThreadCompilations(IonCompartment *ion) { OffThreadCompilationVector &compilations = ion->finishedOffThreadCompilations(); for (size_t i = 0; i < compilations.length(); i++) { IonBuilder *builder = compilations[i]; FinishOffThreadBuilder(builder); } compilations.clear(); } void IonCompartment::mark(JSTracer *trc, JSCompartment *compartment) { // This function marks Ion code objects that must be kept alive if there is // any Ion code currently running. These pointers are marked at the start // of incremental GC. Entering Ion code in the middle of an incremental GC // triggers a read barrier on both these pointers, so they will still be // marked in that case. bool runningIonCode = false; for (IonActivationIterator iter(trc->runtime); iter.more(); ++iter) { IonActivation *activation = iter.activation(); if (activation->compartment() != compartment) continue; runningIonCode = true; break; } // Don't destroy enterJIT if we are running Ion code. Note that enterJIT is // not used for JM -> Ion calls, so it may be NULL in that case. if (runningIonCode && enterJIT_) MarkIonCodeRoot(trc, enterJIT_.unsafeGet(), "enterJIT"); // functionWrappers_ are not marked because this is a WeakCache of VM // function implementations. // Cancel any active or pending off thread compilations. CancelOffThreadIonCompile(compartment, NULL); FinishAllOffThreadCompilations(this); } void IonCompartment::sweep(FreeOp *fop) { if (enterJIT_ && !IsIonCodeMarked(enterJIT_.unsafeGet())) enterJIT_ = NULL; if (bailoutHandler_ && !IsIonCodeMarked(bailoutHandler_.unsafeGet())) bailoutHandler_ = NULL; if (argumentsRectifier_ && !IsIonCodeMarked(argumentsRectifier_.unsafeGet())) argumentsRectifier_ = NULL; if (invalidator_ && !IsIonCodeMarked(invalidator_.unsafeGet())) invalidator_ = NULL; if (valuePreBarrier_ && !IsIonCodeMarked(valuePreBarrier_.unsafeGet())) valuePreBarrier_ = NULL; if (shapePreBarrier_ && !IsIonCodeMarked(shapePreBarrier_.unsafeGet())) shapePreBarrier_ = NULL; for (size_t i = 0; i < bailoutTables_.length(); i++) { if (bailoutTables_[i] && !IsIonCodeMarked(bailoutTables_[i].unsafeGet())) bailoutTables_[i] = NULL; } // Sweep cache of VM function implementations. functionWrappers_->sweep(fop); } IonCode * IonCompartment::getBailoutTable(const FrameSizeClass &frameClass) { JS_ASSERT(frameClass != FrameSizeClass::None()); return bailoutTables_[frameClass.classId()]; } IonCode * IonCompartment::getBailoutTable(JSContext *cx, const FrameSizeClass &frameClass) { uint32 id = frameClass.classId(); if (id >= bailoutTables_.length()) { size_t numToPush = id - bailoutTables_.length() + 1; if (!bailoutTables_.reserve(bailoutTables_.length() + numToPush)) return NULL; for (size_t i = 0; i < numToPush; i++) bailoutTables_.infallibleAppend(NULL); } if (!bailoutTables_[id]) bailoutTables_[id] = generateBailoutTable(cx, id); return bailoutTables_[id]; } IonCompartment::~IonCompartment() { js_delete(functionWrappers_); } IonActivation::IonActivation(JSContext *cx, StackFrame *fp) : cx_(cx), compartment_(cx->compartment), prev_(cx->runtime->ionActivation), entryfp_(fp), bailout_(NULL), prevIonTop_(cx->runtime->ionTop), prevIonJSContext_(cx->runtime->ionJSContext), prevpc_(NULL) { if (fp) fp->setRunningInIon(); cx->runtime->ionJSContext = cx; cx->runtime->ionActivation = this; cx->runtime->ionStackLimit = cx->runtime->nativeStackLimit; } IonActivation::~IonActivation() { JS_ASSERT(cx_->runtime->ionActivation == this); JS_ASSERT(!bailout_); if (entryfp_) entryfp_->clearRunningInIon(); cx_->runtime->ionActivation = prev(); cx_->runtime->ionTop = prevIonTop_; cx_->runtime->ionJSContext = prevIonJSContext_; } IonCode * IonCode::New(JSContext *cx, uint8 *code, uint32 bufferSize, JSC::ExecutablePool *pool) { IonCode *codeObj = gc::NewGCThing<IonCode>(cx, gc::FINALIZE_IONCODE, sizeof(IonCode)); if (!codeObj) { pool->release(); return NULL; } new (codeObj) IonCode(code, bufferSize, pool); return codeObj; } void IonCode::copyFrom(MacroAssembler &masm) { // Store the IonCode pointer right before the code buffer, so we can // recover the gcthing from relocation tables. *(IonCode **)(code_ - sizeof(IonCode *)) = this; insnSize_ = masm.instructionsSize(); masm.executableCopy(code_); dataSize_ = masm.dataSize(); masm.processDeferredData(this, code_ + dataOffset()); jumpRelocTableBytes_ = masm.jumpRelocationTableBytes(); masm.copyJumpRelocationTable(code_ + jumpRelocTableOffset()); dataRelocTableBytes_ = masm.dataRelocationTableBytes(); masm.copyDataRelocationTable(code_ + dataRelocTableOffset()); masm.processCodeLabels(this); } void IonCode::trace(JSTracer *trc) { // Note that we cannot mark invalidated scripts, since we've basically // corrupted the code stream by injecting bailouts. if (invalidated()) { // Note that since we're invalidated, we won't mark the precious // invalidator thunk referenced in the epilogue. We don't move // executable code so the actual reference is okay, we just need to // make sure it says alive before we return. IonCompartment *ion = compartment()->ionCompartment(); MarkIonCodeUnbarriered(trc, ion->getInvalidationThunkAddr(), "invalidator"); return; } if (jumpRelocTableBytes_) { uint8 *start = code_ + jumpRelocTableOffset(); CompactBufferReader reader(start, start + jumpRelocTableBytes_); MacroAssembler::TraceJumpRelocations(trc, this, reader); } if (dataRelocTableBytes_) { uint8 *start = code_ + dataRelocTableOffset(); CompactBufferReader reader(start, start + dataRelocTableBytes_); MacroAssembler::TraceDataRelocations(trc, this, reader); } } void IonCode::finalize(FreeOp *fop) { // Buffer can be freed at any time hereafter. Catch use-after-free bugs. JS_POISON(code_, JS_FREE_PATTERN, bufferSize_); // Code buffers are stored inside JSC pools. // Pools are refcounted. Releasing the pool may free it. if (pool_) pool_->release(); } void IonCode::readBarrier(IonCode *code) { #ifdef JSGC_INCREMENTAL if (!code) return; JSCompartment *comp = code->compartment(); if (comp->needsBarrier()) MarkIonCodeUnbarriered(comp->barrierTracer(), &code, "ioncode read barrier"); #endif } void IonCode::writeBarrierPre(IonCode *code) { #ifdef JSGC_INCREMENTAL if (!code) return; JSCompartment *comp = code->compartment(); if (comp->needsBarrier()) MarkIonCodeUnbarriered(comp->barrierTracer(), &code, "ioncode write barrier"); #endif } void IonCode::writeBarrierPost(IonCode *code, void *addr) { #ifdef JSGC_INCREMENTAL // Nothing to do. #endif } IonScript::IonScript() : method_(NULL), deoptTable_(NULL), osrPc_(NULL), osrEntryOffset_(0), invalidateEpilogueOffset_(0), invalidateEpilogueDataOffset_(0), bailoutExpected_(false), snapshots_(0), snapshotsSize_(0), bailoutTable_(0), bailoutEntries_(0), constantTable_(0), constantEntries_(0), safepointIndexOffset_(0), safepointIndexEntries_(0), frameSlots_(0), frameSize_(0), osiIndexOffset_(0), osiIndexEntries_(0), cacheList_(0), cacheEntries_(0), prebarrierList_(0), prebarrierEntries_(0), safepointsStart_(0), safepointsSize_(0), scriptList_(0), scriptEntries_(0), refcount_(0), recompileInfo_(), slowCallCount(0) { } static const int DataAlignment = 4; IonScript * IonScript::New(JSContext *cx, uint32 frameSlots, uint32 frameSize, size_t snapshotsSize, size_t bailoutEntries, size_t constants, size_t safepointIndices, size_t osiIndices, size_t cacheEntries, size_t prebarrierEntries, size_t safepointsSize, size_t scriptEntries) { if (snapshotsSize >= MAX_BUFFER_SIZE || (bailoutEntries >= MAX_BUFFER_SIZE / sizeof(uint32))) { js_ReportOutOfMemory(cx); return NULL; } // This should not overflow on x86, because the memory is already allocated // *somewhere* and if their total overflowed there would be no memory left // at all. size_t paddedSnapshotsSize = AlignBytes(snapshotsSize, DataAlignment); size_t paddedBailoutSize = AlignBytes(bailoutEntries * sizeof(uint32), DataAlignment); size_t paddedConstantsSize = AlignBytes(constants * sizeof(Value), DataAlignment); size_t paddedSafepointIndicesSize = AlignBytes(safepointIndices * sizeof(SafepointIndex), DataAlignment); size_t paddedOsiIndicesSize = AlignBytes(osiIndices * sizeof(OsiIndex), DataAlignment); size_t paddedCacheEntriesSize = AlignBytes(cacheEntries * sizeof(IonCache), DataAlignment); size_t paddedPrebarrierEntriesSize = AlignBytes(prebarrierEntries * sizeof(CodeOffsetLabel), DataAlignment); size_t paddedSafepointSize = AlignBytes(safepointsSize, DataAlignment); size_t paddedScriptSize = AlignBytes(scriptEntries * sizeof(JSScript *), DataAlignment); size_t bytes = paddedSnapshotsSize + paddedBailoutSize + paddedConstantsSize + paddedSafepointIndicesSize+ paddedOsiIndicesSize + paddedCacheEntriesSize + paddedPrebarrierEntriesSize + paddedSafepointSize + paddedScriptSize; uint8 *buffer = (uint8 *)cx->malloc_(sizeof(IonScript) + bytes); if (!buffer) return NULL; IonScript *script = reinterpret_cast<IonScript *>(buffer); new (script) IonScript(); uint32 offsetCursor = sizeof(IonScript); script->snapshots_ = offsetCursor; script->snapshotsSize_ = snapshotsSize; offsetCursor += paddedSnapshotsSize; script->bailoutTable_ = offsetCursor; script->bailoutEntries_ = bailoutEntries; offsetCursor += paddedBailoutSize; script->constantTable_ = offsetCursor; script->constantEntries_ = constants; offsetCursor += paddedConstantsSize; script->safepointIndexOffset_ = offsetCursor; script->safepointIndexEntries_ = safepointIndices; offsetCursor += paddedSafepointIndicesSize; script->osiIndexOffset_ = offsetCursor; script->osiIndexEntries_ = osiIndices; offsetCursor += paddedOsiIndicesSize; script->cacheList_ = offsetCursor; script->cacheEntries_ = cacheEntries; offsetCursor += paddedCacheEntriesSize; script->prebarrierList_ = offsetCursor; script->prebarrierEntries_ = prebarrierEntries; offsetCursor += paddedPrebarrierEntriesSize; script->safepointsStart_ = offsetCursor; script->safepointsSize_ = safepointsSize; offsetCursor += paddedSafepointSize; script->scriptList_ = offsetCursor; script->scriptEntries_ = scriptEntries; offsetCursor += paddedScriptSize; script->frameSlots_ = frameSlots; script->frameSize_ = frameSize; script->recompileInfo_ = cx->compartment->types.compiledInfo; return script; } void IonScript::trace(JSTracer *trc) { if (method_) MarkIonCode(trc, &method_, "method"); if (deoptTable_) MarkIonCode(trc, &deoptTable_, "deoptimizationTable"); for (size_t i = 0; i < numConstants(); i++) gc::MarkValue(trc, &getConstant(i), "constant"); } void IonScript::copySnapshots(const SnapshotWriter *writer) { JS_ASSERT(writer->size() == snapshotsSize_); memcpy((uint8 *)this + snapshots_, writer->buffer(), snapshotsSize_); } void IonScript::copySafepoints(const SafepointWriter *writer) { JS_ASSERT(writer->size() == safepointsSize_); memcpy((uint8 *)this + safepointsStart_, writer->buffer(), safepointsSize_); } void IonScript::copyBailoutTable(const SnapshotOffset *table) { memcpy(bailoutTable(), table, bailoutEntries_ * sizeof(uint32)); } void IonScript::copyConstants(const HeapValue *vp) { for (size_t i = 0; i < constantEntries_; i++) constants()[i].init(vp[i]); } void IonScript::copyScriptEntries(JSScript **scripts) { for (size_t i = 0; i < scriptEntries_; i++) scriptList()[i] = scripts[i]; } void IonScript::copySafepointIndices(const SafepointIndex *si, MacroAssembler &masm) { /* * Jumps in the caches reflect the offset of those jumps in the compiled * code, not the absolute positions of the jumps. Update according to the * final code address now. */ SafepointIndex *table = safepointIndices(); memcpy(table, si, safepointIndexEntries_ * sizeof(SafepointIndex)); for (size_t i = 0; i < safepointIndexEntries_; i++) table[i].adjustDisplacement(masm.actualOffset(table[i].displacement())); } void IonScript::copyOsiIndices(const OsiIndex *oi, MacroAssembler &masm) { memcpy(osiIndices(), oi, osiIndexEntries_ * sizeof(OsiIndex)); for (unsigned i = 0; i < osiIndexEntries_; i++) osiIndices()[i].fixUpOffset(masm); } void IonScript::copyCacheEntries(const IonCache *caches, MacroAssembler &masm) { memcpy(cacheList(), caches, numCaches() * sizeof(IonCache)); /* * Jumps in the caches reflect the offset of those jumps in the compiled * code, not the absolute positions of the jumps. Update according to the * final code address now. */ for (size_t i = 0; i < numCaches(); i++) getCache(i).updateBaseAddress(method_, masm); } inline CodeOffsetLabel & IonScript::getPrebarrier(size_t index) { JS_ASSERT(index < numPrebarriers()); return prebarrierList()[index]; } void IonScript::copyPrebarrierEntries(const CodeOffsetLabel *barriers, MacroAssembler &masm) { memcpy(prebarrierList(), barriers, numPrebarriers() * sizeof(CodeOffsetLabel)); // On ARM, the saved offset may be wrong due to shuffling code buffers. Correct it. for (size_t i = 0; i < numPrebarriers(); i++) getPrebarrier(i).fixup(&masm); } const SafepointIndex * IonScript::getSafepointIndex(uint32 disp) const { JS_ASSERT(safepointIndexEntries_ > 0); const SafepointIndex *table = safepointIndices(); if (safepointIndexEntries_ == 1) { JS_ASSERT(disp == table[0].displacement()); return &table[0]; } size_t minEntry = 0; size_t maxEntry = safepointIndexEntries_ - 1; uint32 min = table[minEntry].displacement(); uint32 max = table[maxEntry].displacement(); // Raise if the element is not in the list. JS_ASSERT(min <= disp && disp <= max); // Approximate the location of the FrameInfo. size_t guess = (disp - min) * (maxEntry - minEntry) / (max - min) + minEntry; uint32 guessDisp = table[guess].displacement(); if (table[guess].displacement() == disp) return &table[guess]; // Doing a linear scan from the guess should be more efficient in case of // small group which are equally distributed on the code. // // such as: <... ... ... ... . ... ...> if (guessDisp > disp) { while (--guess >= minEntry) { guessDisp = table[guess].displacement(); JS_ASSERT(guessDisp >= disp); if (guessDisp == disp) return &table[guess]; } } else { while (++guess <= maxEntry) { guessDisp = table[guess].displacement(); JS_ASSERT(guessDisp <= disp); if (guessDisp == disp) return &table[guess]; } } JS_NOT_REACHED("displacement not found."); return NULL; } const OsiIndex * IonScript::getOsiIndex(uint32 disp) const { for (const OsiIndex *it = osiIndices(), *end = osiIndices() + osiIndexEntries_; it != end; ++it) { if (it->returnPointDisplacement() == disp) return it; } JS_NOT_REACHED("Failed to find OSI point return address"); return NULL; } const OsiIndex * IonScript::getOsiIndex(uint8 *retAddr) const { IonSpew(IonSpew_Invalidate, "IonScript %p has method %p raw %p", (void *) this, (void *) method(), method()->raw()); JS_ASSERT(containsCodeAddress(retAddr)); uint32 disp = retAddr - method()->raw(); return getOsiIndex(disp); } void IonScript::Trace(JSTracer *trc, IonScript *script) { if (script != ION_DISABLED_SCRIPT) script->trace(trc); } void IonScript::Destroy(FreeOp *fop, IonScript *script) { fop->free_(script); } void IonScript::toggleBarriers(bool enabled) { for (size_t i = 0; i < numPrebarriers(); i++) { CodeLocationLabel loc(method(), getPrebarrier(i)); if (enabled) Assembler::ToggleToCmp(loc); else Assembler::ToggleToJmp(loc); } } void IonScript::purgeCaches(JSCompartment *c) { // Don't reset any ICs if we're invalidated, otherwise, repointing the // inline jump could overwrite an invalidation marker. These ICs can // no longer run, however, the IC slow paths may be active on the stack. // ICs therefore are required to check for invalidation before patching, // to ensure the same invariant. if (invalidated()) return; // This is necessary because AutoFlushCache::updateTop() // looks up the current flusher in the IonContext. Without one // it cannot work. js::ion::IonContext ictx(NULL, c, NULL); AutoFlushCache afc("purgeCaches"); for (size_t i = 0; i < numCaches(); i++) getCache(i).reset(); } void ion::ToggleBarriers(JSCompartment *comp, bool needs) { IonContext ictx(NULL, comp, NULL); AutoFlushCache afc("ToggleBarriers"); for (gc::CellIterUnderGC i(comp, gc::FINALIZE_SCRIPT); !i.done(); i.next()) { JSScript *script = i.get<JSScript>(); if (script->hasIonScript()) script->ion->toggleBarriers(needs); } } namespace js { namespace ion { bool CompileBackEnd(IonBuilder *builder) { IonSpewPass("BuildSSA"); // Note: don't call AssertGraphCoherency before SplitCriticalEdges, // the graph is not in RPO at this point. MIRGraph &graph = builder->graph(); if (!SplitCriticalEdges(builder, graph)) return false; IonSpewPass("Split Critical Edges"); AssertGraphCoherency(graph); if (!RenumberBlocks(graph)) return false; IonSpewPass("Renumber Blocks"); AssertGraphCoherency(graph); if (!BuildDominatorTree(graph)) return false; // No spew: graph not changed. // This must occur before any code elimination. if (!EliminatePhis(graph)) return false; IonSpewPass("Eliminate phis"); AssertGraphCoherency(graph); if (!BuildPhiReverseMapping(graph)) return false; // No spew: graph not changed. // This pass also removes copies. if (!ApplyTypeInformation(graph)) return false; IonSpewPass("Apply types"); AssertGraphCoherency(graph); // Alias analysis is required for LICM and GVN so that we don't move // loads across stores. if (js_IonOptions.licm || js_IonOptions.gvn) { AliasAnalysis analysis(graph); if (!analysis.analyze()) return false; IonSpewPass("Alias analysis"); AssertGraphCoherency(graph); } if (js_IonOptions.edgeCaseAnalysis) { EdgeCaseAnalysis edgeCaseAnalysis(graph); if (!edgeCaseAnalysis.analyzeEarly()) return false; IonSpewPass("Edge Case Analysis (Early)"); AssertGraphCoherency(graph); } if (js_IonOptions.gvn) { ValueNumberer gvn(graph, js_IonOptions.gvnIsOptimistic); if (!gvn.analyze()) return false; IonSpewPass("GVN"); AssertGraphCoherency(graph); } if (js_IonOptions.rangeAnalysis) { RangeAnalysis r(graph); if (!r.addBetaNobes()) return false; IonSpewPass("Beta"); AssertGraphCoherency(graph); if (!r.analyze()) return false; IonSpewPass("Range Analysis"); AssertGraphCoherency(graph); if (!r.removeBetaNobes()) return false; IonSpewPass("De-Beta"); AssertGraphCoherency(graph); } if (!EliminateDeadCode(graph)) return false; IonSpewPass("DCE"); AssertGraphCoherency(graph); if (js_IonOptions.licm) { LICM licm(graph); if (!licm.analyze()) return false; IonSpewPass("LICM"); AssertGraphCoherency(graph); } if (js_IonOptions.edgeCaseAnalysis) { EdgeCaseAnalysis edgeCaseAnalysis(graph); if (!edgeCaseAnalysis.analyzeLate()) return false; IonSpewPass("Edge Case Analysis (Late)"); AssertGraphCoherency(graph); } // Note: bounds check elimination has to run after all other passes that // move instructions. Since bounds check uses are replaced with the actual // index, code motion after this pass could incorrectly move a load or // store before its bounds check. if (!EliminateRedundantBoundsChecks(graph)) return false; IonSpewPass("Bounds Check Elimination"); AssertGraphCoherency(graph); LIRGraph *lir = builder->temp().lifoAlloc()->new_<LIRGraph>(&graph); if (!lir) return false; LIRGenerator lirgen(builder, graph, *lir); if (!lirgen.generate()) return false; IonSpewPass("Generate LIR"); if (js_IonOptions.lsra) { LinearScanAllocator regalloc(&lirgen, *lir); if (!regalloc.go()) return false; IonSpewPass("Allocate Registers", &regalloc); } builder->lir = lir; return true; } class AutoDestroyAllocator { LifoAlloc *alloc; public: AutoDestroyAllocator(LifoAlloc *alloc) : alloc(alloc) {} void cancel() { alloc = NULL; } ~AutoDestroyAllocator() { if (alloc) js_delete(alloc); } }; bool TestCompiler(IonBuilder *builder, MIRGraph *graph, AutoDestroyAllocator &autoDestroy) { JS_ASSERT(!builder->script()->ion); JSContext *cx = GetIonContext()->cx; IonSpewNewFunction(graph, builder->script()); if (!builder->build()) return false; builder->clearForBackEnd(); if (js_IonOptions.parallelCompilation) { builder->script()->ion = ION_COMPILING_SCRIPT; if (!StartOffThreadIonCompile(cx, builder)) return false; // The allocator and associated data will be destroyed after being // processed in the finishedOffThreadCompilations list. autoDestroy.cancel(); return true; } if (!CompileBackEnd(builder)) return false; CodeGenerator codegen(builder, *builder->lir); if (!codegen.generate()) return false; IonSpewEndFunction(); return true; } void AttachFinishedCompilations(JSContext *cx) { IonCompartment *ion = cx->compartment->ionCompartment(); if (!ion) return; AutoLockWorkerThreadState lock(cx->runtime); OffThreadCompilationVector &compilations = ion->finishedOffThreadCompilations(); // Incorporate any off thread compilations which have finished, failed or // have been cancelled, and destroy JM jitcode for any compilations which // succeeded, to allow entering the Ion code from the interpreter. while (!compilations.empty()) { IonBuilder *builder = compilations.popCopy(); if (builder->lir) { JSScript *script = builder->script(); IonContext ictx(cx, cx->compartment, &builder->temp()); CodeGenerator codegen(builder, *builder->lir); types::AutoEnterCompilation enterCompiler(cx, types::AutoEnterCompilation::Ion); enterCompiler.initExisting(builder->recompileInfo); bool success; { // Release the worker thread lock and root the compiler for GC. AutoTempAllocatorRooter root(cx, &builder->temp()); AutoUnlockWorkerThreadState unlock(cx->runtime); success = codegen.generate(); } if (success) { if (script->hasIonScript()) mjit::ReleaseScriptCodeFromVM(cx, script); } else { // Silently ignore OOM during code generation, we're at an // operation callback and can't propagate failures. cx->clearPendingException(); } } FinishOffThreadBuilder(builder); } compilations.clear(); } static const size_t BUILDER_LIFO_ALLOC_PRIMARY_CHUNK_SIZE = 1 << 12; template <bool Compiler(IonBuilder *, MIRGraph *, AutoDestroyAllocator &)> static bool IonCompile(JSContext *cx, JSScript *script, JSFunction *fun, jsbytecode *osrPc, bool constructing) { #if JS_TRACE_LOGGING AutoTraceLog logger(TraceLogging::defaultLogger(), TraceLogging::ION_COMPILE_START, TraceLogging::ION_COMPILE_STOP, script); #endif LifoAlloc *alloc = cx->new_<LifoAlloc>(BUILDER_LIFO_ALLOC_PRIMARY_CHUNK_SIZE); if (!alloc) return false; AutoDestroyAllocator autoDestroy(alloc); TempAllocator *temp = alloc->new_<TempAllocator>(alloc); if (!temp) return false; IonContext ictx(cx, cx->compartment, temp); if (!cx->compartment->ensureIonCompartmentExists(cx)) return false; MIRGraph *graph = alloc->new_<MIRGraph>(temp); CompileInfo *info = alloc->new_<CompileInfo>(script, fun, osrPc, constructing); if (!info) return false; types::AutoEnterTypeInference enter(cx, true); TypeInferenceOracle oracle; if (!oracle.init(cx, script)) return false; AutoFlushCache afc("IonCompile"); types::AutoEnterCompilation enterCompiler(cx, types::AutoEnterCompilation::Ion); if (!enterCompiler.init(script, false, 0)) return false; AutoTempAllocatorRooter root(cx, temp); IonBuilder *builder = alloc->new_<IonBuilder>(cx, temp, graph, &oracle, info); if (!Compiler(builder, graph, autoDestroy)) { IonSpew(IonSpew_Abort, "IM Compilation failed."); return false; } return true; } bool TestIonCompile(JSContext *cx, JSScript *script, JSFunction *fun, jsbytecode *osrPc, bool constructing) { if (!IonCompile<TestCompiler>(cx, script, fun, osrPc, constructing)) { if (!cx->isExceptionPending()) ForbidCompilation(cx, script); return false; } return true; } static bool CheckFrame(StackFrame *fp) { if (fp->isEvalFrame()) { // Eval frames are not yet supported. Supporting this will require new // logic in pushBailoutFrame to deal with linking prev. // Additionally, JSOP_DEFVAR support will require baking in isEvalFrame(). IonSpew(IonSpew_Abort, "eval frame"); return false; } if (fp->isGeneratorFrame()) { // Err... no. IonSpew(IonSpew_Abort, "generator frame"); return false; } if (fp->isDebuggerFrame()) { IonSpew(IonSpew_Abort, "debugger frame"); return false; } if (fp->annotation()) { IonSpew(IonSpew_Abort, "frame is annotated"); return false; } // This check is to not overrun the stack. Eventually, we will want to // handle this when we support JSOP_ARGUMENTS or function calls. if (fp->isFunctionFrame() && (fp->numActualArgs() >= SNAPSHOT_MAX_NARGS || fp->numActualArgs() > js_IonOptions.maxStackArgs)) { IonSpew(IonSpew_Abort, "too many actual args"); return false; } return true; } static bool CheckScript(JSScript *script) { if (script->needsArgsObj()) { // Functions with arguments objects, are not supported yet. IonSpew(IonSpew_Abort, "script has argsobj"); return false; } if (!script->compileAndGo) { IonSpew(IonSpew_Abort, "not compile-and-go"); return false; } return true; } static bool CheckScriptSize(JSScript *script) { if (!js_IonOptions.limitScriptSize) return true; static const uint32_t MAX_SCRIPT_SIZE = 1500; static const uint32_t MAX_LOCALS_AND_ARGS = 256; if (script->length > MAX_SCRIPT_SIZE) { IonSpew(IonSpew_Abort, "Script too large (%u bytes)", script->length); return false; } uint32_t numLocalsAndArgs = analyze::TotalSlots(script); if (numLocalsAndArgs > MAX_LOCALS_AND_ARGS) { IonSpew(IonSpew_Abort, "Too many locals and arguments (%u)", numLocalsAndArgs); return false; } return true; } template <bool Compiler(IonBuilder *, MIRGraph *, AutoDestroyAllocator &)> static MethodStatus Compile(JSContext *cx, JSScript *script, JSFunction *fun, jsbytecode *osrPc, bool constructing) { JS_ASSERT(ion::IsEnabled(cx)); JS_ASSERT_IF(osrPc != NULL, (JSOp)*osrPc == JSOP_LOOPENTRY); if (cx->compartment->debugMode()) { IonSpew(IonSpew_Abort, "debugging"); return Method_CantCompile; } if (!CheckScript(script) || !CheckScriptSize(script)) { IonSpew(IonSpew_Abort, "Aborted compilation of %s:%d", script->filename, script->lineno); return Method_CantCompile; } if (script->ion) { if (!script->ion->method()) return Method_CantCompile; return Method_Compiled; } if (cx->methodJitEnabled) { // If JM is enabled we use getUseCount instead of incUseCount to avoid // bumping the use count twice. if (script->getUseCount() < js_IonOptions.usesBeforeCompile) return Method_Skipped; } else { if (script->incUseCount() < js_IonOptions.usesBeforeCompileNoJaeger) return Method_Skipped; } if (!IonCompile<Compiler>(cx, script, fun, osrPc, constructing)) return Method_CantCompile; // Compilation succeeded, but we invalidated right away. return script->hasIonScript() ? Method_Compiled : Method_Skipped; } } // namespace ion } // namespace js // Decide if a transition from interpreter execution to Ion code should occur. // May compile or recompile the target JSScript. MethodStatus ion::CanEnterAtBranch(JSContext *cx, HandleScript script, StackFrame *fp, jsbytecode *pc) { JS_ASSERT(ion::IsEnabled(cx)); JS_ASSERT((JSOp)*pc == JSOP_LOOPENTRY); // Skip if the script has been disabled. if (script->ion == ION_DISABLED_SCRIPT) return Method_Skipped; // Skip if the script is being compiled off thread. if (script->ion == ION_COMPILING_SCRIPT) return Method_Skipped; // Skip if the code is expected to result in a bailout. if (script->ion && script->ion->bailoutExpected()) return Method_Skipped; // Optionally ignore on user request. if (!js_IonOptions.osr) return Method_Skipped; // Mark as forbidden if frame can't be handled. if (!CheckFrame(fp)) { ForbidCompilation(cx, script); return Method_CantCompile; } // Attempt compilation. Returns Method_Compiled if already compiled. JSFunction *fun = fp->isFunctionFrame() ? fp->fun() : NULL; MethodStatus status = Compile<TestCompiler>(cx, script, fun, pc, false); if (status != Method_Compiled) { if (status == Method_CantCompile) ForbidCompilation(cx, script); return status; } if (script->ion->osrPc() != pc) return Method_Skipped; // This can GC, so afterward, script->ion is not guaranteed to be valid. if (!cx->compartment->ionCompartment()->enterJIT(cx)) return Method_Error; if (!script->ion) return Method_Skipped; return Method_Compiled; } MethodStatus ion::CanEnter(JSContext *cx, HandleScript script, StackFrame *fp, bool newType) { JS_ASSERT(ion::IsEnabled(cx)); // Skip if the script has been disabled. if (script->ion == ION_DISABLED_SCRIPT) return Method_Skipped; // Skip if the script is being compiled off thread. if (script->ion == ION_COMPILING_SCRIPT) return Method_Skipped; // Skip if the code is expected to result in a bailout. if (script->ion && script->ion->bailoutExpected()) return Method_Skipped; // If constructing, allocate a new |this| object before building Ion. // Creating |this| is done before building Ion because it may change the // type information and invalidate compilation results. if (fp->isConstructing() && fp->functionThis().isPrimitive()) { RootedObject callee(cx, &fp->callee()); RootedObject obj(cx, js_CreateThisForFunction(cx, callee, newType)); if (!obj) return Method_Skipped; fp->functionThis().setObject(*obj); } // Mark as forbidden if frame can't be handled. if (!CheckFrame(fp)) { ForbidCompilation(cx, script); return Method_CantCompile; } // Attempt compilation. Returns Method_Compiled if already compiled. JSFunction *fun = fp->isFunctionFrame() ? fp->fun() : NULL; MethodStatus status = Compile<TestCompiler>(cx, script, fun, NULL, fp->isConstructing()); if (status != Method_Compiled) { if (status == Method_CantCompile) ForbidCompilation(cx, script); return status; } // This can GC, so afterward, script->ion is not guaranteed to be valid. if (!cx->compartment->ionCompartment()->enterJIT(cx)) return Method_Error; if (!script->ion) return Method_Skipped; return Method_Compiled; } MethodStatus ion::CanEnterUsingFastInvoke(JSContext *cx, HandleScript script, uint32_t numActualArgs) { JS_ASSERT(ion::IsEnabled(cx)); // Skip if the code is expected to result in a bailout. if (!script->hasIonScript() || script->ion->bailoutExpected()) return Method_Skipped; // Don't handle arguments underflow, to make this work we would have to pad // missing arguments with |undefined|. if (numActualArgs < script->function()->nargs) return Method_Skipped; if (!cx->compartment->ensureIonCompartmentExists(cx)) return Method_Error; // This can GC, so afterward, script->ion is not guaranteed to be valid. if (!cx->compartment->ionCompartment()->enterJIT(cx)) return Method_Error; if (!script->ion) return Method_Skipped; return Method_Compiled; } static IonExecStatus EnterIon(JSContext *cx, StackFrame *fp, void *jitcode) { JS_CHECK_RECURSION(cx, return IonExec_Aborted); JS_ASSERT(ion::IsEnabled(cx)); JS_ASSERT(CheckFrame(fp)); JS_ASSERT(!fp->script()->ion->bailoutExpected()); EnterIonCode enter = cx->compartment->ionCompartment()->enterJITInfallible(); // maxArgc is the maximum of arguments between the number of actual // arguments and the number of formal arguments. It accounts for |this|. int maxArgc = 0; Value *maxArgv = NULL; int numActualArgs = 0; void *calleeToken; if (fp->isFunctionFrame()) { // CountArgSlot include |this| and the |scopeChain|. maxArgc = CountArgSlots(fp->fun()) - 1; // -1 = discard |scopeChain| maxArgv = fp->formals() - 1; // -1 = include |this| // Formal arguments are the argument corresponding to the function // definition and actual arguments are corresponding to the call-site // arguments. numActualArgs = fp->numActualArgs(); // We do not need to handle underflow because formal arguments are pad // with |undefined| values but we need to distinguish between the if (fp->hasOverflowArgs()) { int formalArgc = maxArgc; Value *formalArgv = maxArgv; maxArgc = numActualArgs + 1; // +1 = include |this| maxArgv = fp->actuals() - 1; // -1 = include |this| // The beginning of the actual args is not updated, so we just copy // the formal args into the actual args to get a linear vector which // can be copied by generateEnterJit. memcpy(maxArgv, formalArgv, formalArgc * sizeof(Value)); } calleeToken = CalleeToToken(&fp->callee()); } else { calleeToken = CalleeToToken(fp->script()); } // Caller must construct |this| before invoking the Ion function. JS_ASSERT_IF(fp->isConstructing(), fp->functionThis().isObject()); Value result = Int32Value(numActualArgs); { AssertCompartmentUnchanged pcc(cx); IonContext ictx(cx, cx->compartment, NULL); IonActivation activation(cx, fp); JSAutoResolveFlags rf(cx, RESOLVE_INFER); // Single transition point from Interpreter to Ion. enter(jitcode, maxArgc, maxArgv, fp, calleeToken, &result); } if (result.isMagic() && result.whyMagic() == JS_ION_BAILOUT) { if (!EnsureHasCallObject(cx, cx->fp())) return IonExec_Error; return IonExec_Bailout; } JS_ASSERT(fp == cx->fp()); JS_ASSERT(!cx->runtime->hasIonReturnOverride()); // The trampoline wrote the return value but did not set the HAS_RVAL flag. fp->setReturnValue(result); // Ion callers wrap primitive constructor return. if (!result.isMagic() && fp->isConstructing() && fp->returnValue().isPrimitive()) fp->setReturnValue(ObjectValue(fp->constructorThis())); JS_ASSERT_IF(result.isMagic(), result.isMagic(JS_ION_ERROR)); return result.isMagic() ? IonExec_Error : IonExec_Ok; } IonExecStatus ion::Cannon(JSContext *cx, StackFrame *fp) { JSScript *script = fp->script(); IonScript *ion = script->ion; IonCode *code = ion->method(); void *jitcode = code->raw(); #if JS_TRACE_LOGGING TraceLog(TraceLogging::defaultLogger(), TraceLogging::ION_CANNON_START, script); #endif IonExecStatus status = EnterIon(cx, fp, jitcode); #if JS_TRACE_LOGGING if (status == IonExec_Bailout) { TraceLog(TraceLogging::defaultLogger(), TraceLogging::ION_CANNON_BAIL, script); } else { TraceLog(TraceLogging::defaultLogger(), TraceLogging::ION_CANNON_STOP, script); } #endif return status; } IonExecStatus ion::SideCannon(JSContext *cx, StackFrame *fp, jsbytecode *pc) { JSScript *script = fp->script(); IonScript *ion = script->ion; IonCode *code = ion->method(); void *osrcode = code->raw() + ion->osrEntryOffset(); JS_ASSERT(ion->osrPc() == pc); #if JS_TRACE_LOGGING TraceLog(TraceLogging::defaultLogger(), TraceLogging::ION_SIDE_CANNON_START, script); #endif IonExecStatus status = EnterIon(cx, fp, osrcode); #if JS_TRACE_LOGGING if (status == IonExec_Bailout) { TraceLog(TraceLogging::defaultLogger(), TraceLogging::ION_SIDE_CANNON_BAIL, script); } else { TraceLog(TraceLogging::defaultLogger(), TraceLogging::ION_SIDE_CANNON_STOP, script); } #endif return status; } IonExecStatus ion::FastInvoke(JSContext *cx, HandleFunction fun, CallArgsList &args) { JS_CHECK_RECURSION(cx, return IonExec_Error); HandleScript script = fun->script(); IonScript *ion = script->ionScript(); IonCode *code = ion->method(); void *jitcode = code->raw(); JS_ASSERT(ion::IsEnabled(cx)); JS_ASSERT(!script->ion->bailoutExpected()); bool clearCallingIntoIon = false; StackFrame *fp = cx->fp(); // Two cases we have to handle: // // (1) fp does not begin an Ion activation. This works exactly // like invoking Ion from JM: entryfp is set to fp and fp // has the callingIntoIon flag set. // // (2) fp already begins another IonActivation, for instance: // JM -> Ion -> array_sort -> Ion // In this cas we use an IonActivation with entryfp == NULL // and prevpc != NULL. IonActivation activation(cx, NULL); if (!fp->beginsIonActivation()) { fp->setCallingIntoIon(); clearCallingIntoIon = true; activation.setEntryFp(fp); } else { JS_ASSERT(!activation.entryfp()); } activation.setPrevPc(cx->regs().pc); EnterIonCode enter = cx->compartment->ionCompartment()->enterJITInfallible(); void *calleeToken = CalleeToToken(fun); Value result = Int32Value(args.length()); JS_ASSERT(args.length() >= fun->nargs); JSAutoResolveFlags rf(cx, RESOLVE_INFER); args.setActive(); enter(jitcode, args.length() + 1, args.array() - 1, fp, calleeToken, &result); args.setInactive(); if (clearCallingIntoIon) fp->clearCallingIntoIon(); JS_ASSERT(fp == cx->fp()); JS_ASSERT(!cx->runtime->hasIonReturnOverride()); args.rval().set(result); JS_ASSERT_IF(result.isMagic(), result.isMagic(JS_ION_ERROR)); return result.isMagic() ? IonExec_Error : IonExec_Ok; } static void InvalidateActivation(FreeOp *fop, uint8 *ionTop, bool invalidateAll) { IonSpew(IonSpew_Invalidate, "BEGIN invalidating activation"); size_t frameno = 1; for (IonFrameIterator it(ionTop); !it.done(); ++it, ++frameno) { JS_ASSERT_IF(frameno == 1, it.type() == IonFrame_Exit); #ifdef DEBUG switch (it.type()) { case IonFrame_Exit: IonSpew(IonSpew_Invalidate, "#%d exit frame @ %p", frameno, it.fp()); break; case IonFrame_JS: { JS_ASSERT(it.isScripted()); IonSpew(IonSpew_Invalidate, "#%d JS frame @ %p, %s:%d (fun: %p, script: %p, pc %p)", frameno, it.fp(), it.script()->filename, it.script()->lineno, it.maybeCallee(), it.script(), it.returnAddressToFp()); break; } case IonFrame_Rectifier: IonSpew(IonSpew_Invalidate, "#%d rectifier frame @ %p", frameno, it.fp()); break; case IonFrame_Bailed_JS: JS_NOT_REACHED("invalid"); break; case IonFrame_Bailed_Rectifier: IonSpew(IonSpew_Invalidate, "#%d bailed rectifier frame @ %p", frameno, it.fp()); break; case IonFrame_Osr: IonSpew(IonSpew_Invalidate, "#%d osr frame @ %p", frameno, it.fp()); break; case IonFrame_Entry: IonSpew(IonSpew_Invalidate, "#%d entry frame @ %p", frameno, it.fp()); break; } #endif if (!it.isScripted()) continue; // See if the frame has already been invalidated. if (it.checkInvalidation()) continue; JSScript *script = it.script(); if (!script->hasIonScript()) continue; if (!invalidateAll && !script->ion->invalidated()) continue; IonScript *ionScript = script->ion; // Purge ICs before we mark this script as invalidated. This will // prevent lastJump_ from appearing to be a bogus pointer, just // in case anyone tries to read it. ionScript->purgeCaches(script->compartment()); // This frame needs to be invalidated. We do the following: // // 1. Increment the reference counter to keep the ionScript alive // for the invalidation bailout or for the exception handler. // 2. Determine safepoint that corresponds to the current call. // 3. From safepoint, get distance to the OSI-patchable offset. // 4. From the IonScript, determine the distance between the // call-patchable offset and the invalidation epilogue. // 5. Patch the OSI point with a call-relative to the // invalidation epilogue. // // The code generator ensures that there's enough space for us // to patch in a call-relative operation at each invalidation // point. // // Note: you can't simplify this mechanism to "just patch the // instruction immediately after the call" because things may // need to move into a well-defined register state (using move // instructions after the call) in to capture an appropriate // snapshot after the call occurs. ionScript->incref(); const SafepointIndex *si = ionScript->getSafepointIndex(it.returnAddressToFp()); IonCode *ionCode = ionScript->method(); JSCompartment *compartment = script->compartment(); if (compartment->needsBarrier()) { // We're about to remove edges from the JSScript to gcthings // embedded in the IonCode. Perform one final trace of the // IonCode for the incremental GC, as it must know about // those edges. ionCode->trace(compartment->barrierTracer()); } ionCode->setInvalidated(); // Write the delta (from the return address offset to the // IonScript pointer embedded into the invalidation epilogue) // where the safepointed call instruction used to be. We rely on // the call sequence causing the safepoint being >= the size of // a uint32, which is checked during safepoint index // construction. CodeLocationLabel dataLabelToMunge(it.returnAddressToFp()); ptrdiff_t delta = ionScript->invalidateEpilogueDataOffset() - (it.returnAddressToFp() - ionCode->raw()); Assembler::patchWrite_Imm32(dataLabelToMunge, Imm32(delta)); CodeLocationLabel osiPatchPoint = SafepointReader::InvalidationPatchPoint(ionScript, si); CodeLocationLabel invalidateEpilogue(ionCode, ionScript->invalidateEpilogueOffset()); IonSpew(IonSpew_Invalidate, " ! Invalidate ionScript %p (ref %u) -> patching osipoint %p", ionScript, ionScript->refcount(), (void *) osiPatchPoint.raw()); Assembler::patchWrite_NearCall(osiPatchPoint, invalidateEpilogue); } IonSpew(IonSpew_Invalidate, "END invalidating activation"); } void ion::InvalidateAll(FreeOp *fop, JSCompartment *c) { if (!c->ionCompartment()) return; CancelOffThreadIonCompile(c, NULL); FinishAllOffThreadCompilations(c->ionCompartment()); for (IonActivationIterator iter(fop->runtime()); iter.more(); ++iter) { if (iter.activation()->compartment() == c) { IonContext ictx(NULL, c, NULL); AutoFlushCache afc ("InvalidateAll", c->ionCompartment()); IonSpew(IonSpew_Invalidate, "Invalidating all frames for GC"); InvalidateActivation(fop, iter.top(), true); } } } void ion::Invalidate(types::TypeCompartment &types, FreeOp *fop, const Vector<types::RecompileInfo> &invalid, bool resetUses) { IonSpew(IonSpew_Invalidate, "Start invalidation."); AutoFlushCache afc ("Invalidate"); // Add an invalidation reference to all invalidated IonScripts to indicate // to the traversal which frames have been invalidated. bool anyInvalidation = false; for (size_t i = 0; i < invalid.length(); i++) { const types::CompilerOutput &co = *invalid[i].compilerOutput(types); if (co.isIon()) { JS_ASSERT(co.isValid()); IonSpew(IonSpew_Invalidate, " Invalidate %s:%u, IonScript %p", co.script->filename, co.script->lineno, co.ion()); // Keep the ion script alive during the invalidation and flag this // ionScript as being invalidated. This increment is removed by the // loop after the calls to InvalidateActivation. co.ion()->incref(); anyInvalidation = true; } } if (!anyInvalidation) { IonSpew(IonSpew_Invalidate, " No IonScript invalidation."); return; } for (IonActivationIterator iter(fop->runtime()); iter.more(); ++iter) InvalidateActivation(fop, iter.top(), false); // Drop the references added above. If a script was never active, its // IonScript will be immediately destroyed. Otherwise, it will be held live // until its last invalidated frame is destroyed. for (size_t i = 0; i < invalid.length(); i++) { types::CompilerOutput &co = *invalid[i].compilerOutput(types); if (co.isIon()) { JS_ASSERT(co.isValid()); JSScript *script = co.script; IonScript *ionScript = script->ionScript(); JSCompartment *compartment = script->compartment(); if (compartment->needsBarrier()) { // We're about to remove edges from the JSScript to gcthings // embedded in the IonScript. Perform one final trace of the // IonScript for the incremental GC, as it must know about // those edges. IonScript::Trace(compartment->barrierTracer(), ionScript); } ionScript->decref(fop); script->ion = NULL; co.invalidate(); // Wait for the scripts to get warm again before doing another // compile, unless we are recompiling *because* a script got hot. if (resetUses) script->resetUseCount(); } } } void ion::Invalidate(JSContext *cx, const Vector<types::RecompileInfo> &invalid, bool resetUses) { ion::Invalidate(cx->compartment->types, cx->runtime->defaultFreeOp(), invalid, resetUses); } bool ion::Invalidate(JSContext *cx, JSScript *script, bool resetUses) { JS_ASSERT(script->hasIonScript()); Vector<types::RecompileInfo> scripts(cx); if (!scripts.append(script->ionScript()->recompileInfo())) return false; Invalidate(cx, scripts, resetUses); return true; } void ion::FinishInvalidation(FreeOp *fop, JSScript *script) { if (!script->hasIonScript()) return; /* * If this script has Ion code on the stack, invalidation() will return * true. In this case we have to wait until destroying it. */ if (!script->ion->invalidated()) { types::TypeCompartment &types = script->compartment()->types; script->ion->recompileInfo().compilerOutput(types)->invalidate(); ion::IonScript::Destroy(fop, script->ion); } /* In all cases, NULL out script->ion to avoid re-entry. */ script->ion = NULL; } void ion::MarkValueFromIon(JSCompartment *comp, Value *vp) { gc::MarkValueUnbarriered(comp->barrierTracer(), vp, "write barrier"); } void ion::MarkShapeFromIon(JSCompartment *comp, Shape **shapep) { gc::MarkShapeUnbarriered(comp->barrierTracer(), shapep, "write barrier"); } void ion::ForbidCompilation(JSContext *cx, JSScript *script) { IonSpew(IonSpew_Abort, "Disabling Ion compilation of script %s:%d", script->filename, script->lineno); if (script->hasIonScript()) { // It is only safe to modify script->ion if the script is not currently // running, because IonFrameIterator needs to tell what ionScript to // use (either the one on the JSScript, or the one hidden in the // breadcrumbs Invalidation() leaves). Therefore, if invalidation // fails, we cannot disable the script. if (!Invalidate(cx, script, false)) return; } script->ion = ION_DISABLED_SCRIPT; } uint32_t ion::UsesBeforeIonRecompile(JSScript *script, jsbytecode *pc) { JS_ASSERT(pc == script->code || JSOp(*pc) == JSOP_LOOPENTRY); uint32_t minUses = js_IonOptions.usesBeforeCompile; if (JSOp(*pc) != JSOP_LOOPENTRY || !script->hasAnalysis() || js_IonOptions.eagerCompilation) return minUses; analyze::LoopAnalysis *loop = script->analysis()->getLoop(pc); if (!loop) return minUses; // It's more efficient to enter outer loops, rather than inner loops, via OSR. // To accomplish this, we use a slightly higher threshold for inner loops. // Note that we use +1 to prefer non-OSR over OSR. return minUses + (loop->depth + 1) * 100; } void AutoFlushCache::updateTop(uintptr_t p, size_t len) { IonContext *ictx = GetIonContext(); IonCompartment *icmp = ictx->compartment->ionCompartment(); AutoFlushCache *afc = icmp->flusher(); afc->update(p, len); } AutoFlushCache::AutoFlushCache(const char *nonce, IonCompartment *comp) : start_(0), stop_(0), name_(nonce), used_(false) { if (CurrentIonContext() != NULL) comp = GetIonContext()->compartment->ionCompartment(); // If a compartment isn't available, then be a nop, nobody will ever see this flusher if (comp) { if (comp->flusher()) IonSpew(IonSpew_CacheFlush, "<%s ", nonce); else IonSpewCont(IonSpew_CacheFlush, "<%s ", nonce); comp->setFlusher(this); } else { IonSpew(IonSpew_CacheFlush, "<%s DEAD>\n", nonce); } myCompartment_ = comp; } int js::ion::LabelBase::id_count = 0;
30.665403
109
0.653543
[ "object", "shape", "vector" ]
4d31379ac3ceb5550bc9f2088a0b2702f145e342
1,498
cpp
C++
isAscOrder.cpp
TabithaRoemish/Practice
cb1253c894bcc6a7d8cdde94edb4378e61ce4fd0
[ "Unlicense" ]
2
2017-06-15T22:39:50.000Z
2020-01-20T22:03:49.000Z
isAscOrder.cpp
TabithaRoemish/Practice
cb1253c894bcc6a7d8cdde94edb4378e61ce4fd0
[ "Unlicense" ]
null
null
null
isAscOrder.cpp
TabithaRoemish/Practice
cb1253c894bcc6a7d8cdde94edb4378e61ce4fd0
[ "Unlicense" ]
null
null
null
//------------------------------------------------------- // is Ascending Order - Kata 7 // Instructions: create a bool method // that checks if a vector is in ascending order // Programmer: TR //------------------------------------------------------- #include<vector> #include<iostream> #include<string> bool isAscOrder(std::vector<int> arr); //int main() //{ // int arr[] = { 3,2,1 }; // int arr1[] = { 1,2,3 }; // int arr2[] = { 1, 4, 2 }; // // std::vector<int> array0(arr, arr + sizeof(arr)/sizeof(int)); // std::vector<int> array1(arr1, arr1 + sizeof(arr1) / sizeof(int)); // std::vector<int> array2(arr2, arr2 + sizeof(arr2) / sizeof(int)); // // bool assertFalse = isAscOrder(array0); // bool assertTrue = isAscOrder(array1); // bool assertFalse2 = isAscOrder(array2); // std::string sassertFalse = (assertFalse == false) ? "False" : "True"; // std::string sassertTrue = (assertTrue == true) ? "True" : "False"; // std::string sassertFalse2 = (assertFalse2 == false) ? "False" : "True"; // // // std::cout << "assertFalse: " << sassertFalse << std::endl; // std::cout << "assertTrue: " << sassertTrue << std::endl; // std::cout << "assertFalse2: " << sassertFalse2 << std::endl; // // return 0; //} // // //bool isAscOrder(std::vector<int> arr) //{ // std::vector<int>::iterator it = arr.begin(); // std::vector<int>::iterator end = arr.end(); // end--; // while (it != arr.end()) // { // if(it != end) // it++; // if (*it < *(it - 1)) // return false; // } // // return true; //}
28.807692
74
0.551402
[ "vector" ]
2eb9e1ff244a72ebbd3432afee33e494f39fe3d3
1,001
cc
C++
third_party/blink/renderer/platform/geometry/layout_size_test.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/platform/geometry/layout_size_test.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/platform/geometry/layout_size_test.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 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/platform/geometry/layout_size.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" namespace blink { TEST(LayoutSizeTest, FitToAspectRatioDoesntOverflow) { // FitToAspectRatio() shouldn't overflow due to intermediate calculations, // for both the "constrained by width" and "constrained by height" cases. LayoutSize aspect_ratio(50000, 50000); EXPECT_EQ("1000x1000", LayoutSize(2000, 1000) .FitToAspectRatio(aspect_ratio, kAspectRatioFitShrink) .ToString()); LayoutSize size(1000, 2000); EXPECT_EQ("1000x1000", LayoutSize(1000, 2000) .FitToAspectRatio(aspect_ratio, kAspectRatioFitShrink) .ToString()); } } // namespace blink
34.517241
76
0.709291
[ "geometry" ]
2eb9ebd2ee37df9c10b88a1bdb6d30fdf0dea245
434
cpp
C++
Tutorials/10DaysOfStatistics/Day0WeightedMean/day0_weighted_mean.cpp
suzyz/HackerRank
e97f76c4b39aa448e43e30b479d9718b8b88b2d2
[ "MIT" ]
null
null
null
Tutorials/10DaysOfStatistics/Day0WeightedMean/day0_weighted_mean.cpp
suzyz/HackerRank
e97f76c4b39aa448e43e30b479d9718b8b88b2d2
[ "MIT" ]
null
null
null
Tutorials/10DaysOfStatistics/Day0WeightedMean/day0_weighted_mean.cpp
suzyz/HackerRank
e97f76c4b39aa448e43e30b479d9718b8b88b2d2
[ "MIT" ]
null
null
null
#include <cstdio> #include <iostream> #include <vector> #include <cstring> #include <climits> #include <algorithm> #include <iomanip> using namespace std; int n,d[60]; int main() { cin >> n; for (int i = 0; i < n; ++i) cin >> d[i]; double w,sum_w = 0, sum_d = 0; for (int i = 0; i < n; ++i) { cin >> w; sum_w += w; sum_d += w * d[i]; } cout << std::fixed << std::setprecision(1) << sum_d/sum_w << endl; return 0; }
15.5
67
0.569124
[ "vector" ]
2eba784f5f29c693de11f324e15a4e5adcf586e5
5,635
cpp
C++
src/containers/Grid3D.cpp
KieranCarden/godot-2.5D-isometric-map-editor
f5b3801b0efb0d6ba904c29a70bbe3b0a21d0473
[ "MIT" ]
36
2020-04-18T16:22:33.000Z
2022-01-15T13:17:38.000Z
src/containers/Grid3D.cpp
KieranCarden/godot-2.5D-isometric-map-editor
f5b3801b0efb0d6ba904c29a70bbe3b0a21d0473
[ "MIT" ]
15
2020-04-30T18:52:21.000Z
2020-11-26T11:07:46.000Z
src/containers/Grid3D.cpp
KieranCarden/godot-2.5D-isometric-map-editor
f5b3801b0efb0d6ba904c29a70bbe3b0a21d0473
[ "MIT" ]
6
2020-06-13T19:08:29.000Z
2021-06-21T09:31:51.000Z
#include <Grid3D.h> using namespace godot; void Grid3D::updateArraySize(const Vector3 &size, bool reset) { //Save old values int oldSize { internalArray.size() }; Array oldArray { internalArray }; int oldWidth { width }; int oldDepth { depth }; //Set new values width = static_cast<int>(size.x); depth = static_cast<int>(size.y); height = static_cast<int>(size.z); internalArray = Array(); for (int i = 0; i < computeArraySize(); i++) { internalArray.append((Object *) nullptr); } if (reset) { return; } for (int i = 0; i < oldSize; i++) { int x = i % oldWidth; int y = (i / oldWidth) % oldDepth; int z = i / (oldWidth * oldDepth); if (!isInRange(x, y, z)) { continue; } Object *value = oldArray[i]; if (value) { setData({static_cast<real_t>(x), static_cast<real_t>(y), static_cast<real_t>(z)}, value); } } } void Grid3D::reset() { updateArraySize({static_cast<real_t>(width), static_cast<real_t>(depth), static_cast<real_t>(height)}, true); } Object *Grid3D::getData(const Vector3 &position) { int posX = static_cast<int>(position.x); int posY = static_cast<int>(position.y); int posZ = static_cast<int>(position.z); return posX >= 0 && posX < width && posY >= 0 && posY < depth && posZ >= 0 && posZ < height ? (Object *) internalArray[posX + width * posY + width * depth * posZ] : nullptr; } void Grid3D::setData(const Vector3 &position, Object *data) { internalArray[static_cast<int>(position.x) + width * static_cast<int>(position.y) + width * depth * static_cast<int>(position.z)] = data; } bool Grid3D::insertBox(const AABB &aabb, Object *data, bool remove) { const Vector3 &position { aabb.position }; const Vector3 &size { aabb.size }; int index { getId(position) }; int sizeX = static_cast<int>(size.x); int sizeY = static_cast<int>(size.y); int sizeZ = static_cast<int>(size.z); int endX = static_cast<int>(position.x) + sizeX; int endY = static_cast<int>(position.y) + sizeY; int endZ = static_cast<int>(position.z) + sizeZ; if (endX > width || endY > depth || endZ > height) { return false; } internalArray[index] = remove ? nullptr : data; for (int i = 1; i < sizeX * sizeY * sizeZ; i++) { index += Grid3D::indexIncrementFrom(planeSquareAndJumpsFrom(size), size, i); internalArray[index] = remove ? nullptr : data; } return true; } bool Grid3D::isOverlapping(const AABB &aabb) const { int index { getId(aabb.position) }; const Vector3 &size { aabb.size }; if (index >= 0 && index < internalArray.size()) { Object *element = internalArray[index]; if (element) { return true; } for (int i = 1; i < static_cast<int>(size.x) * static_cast<int>(size.y) * static_cast<int>(size.z); i++) { index += Grid3D::indexIncrementFrom(planeSquareAndJumpsFrom(size), size, i); if (index >= 0 && index < internalArray.size()) { element = internalArray[index]; if (element) { return true; } } } } return false; } bool Grid3D::has(Object *object) const { for (int i = 0; i < internalArray.size(); i++) { if ((Object *) internalArray[i] == object) { return true; } } return false; } int Grid3D::getWidth() const { return width; } void Grid3D::setWidth(int w) { updateArraySize({ static_cast<real_t>(w), static_cast<real_t>(depth), static_cast<real_t>(height) }); } int Grid3D::getDepth() const { return depth; } void Grid3D::setDepth(int d) { updateArraySize({ static_cast<real_t>(width), static_cast<real_t>(d), static_cast<real_t>(height) }); } int Grid3D::getHeight() const { return height; } void Grid3D::setHeight(int h) { updateArraySize({ static_cast<real_t>(width), static_cast<real_t>(depth), static_cast<real_t>(h) }); } const Array &Grid3D::getInternalArray() const { return internalArray; } void Grid3D::setInternalArray(const Array& array) { internalArray = array; } void Grid3D::forEach(void (*fptr)(Object *)) { for (int i = 0; i < internalArray.size(); i++) { Object *element = internalArray[i]; if (element) { fptr(element); } } } bool Grid3D::isInRange(int x, int y, int z) const { return x < width && y < depth && z < height; } int Grid3D::getId(const Vector3 &position) const { return static_cast<int>(position.x) + width * static_cast<int>(position.y) + width * depth * static_cast<int>(position.z); } Vector3 Grid3D::getPosition3D(int id) const { return { static_cast<real_t>(id % width), static_cast<real_t>((id / width) % depth), static_cast<real_t>(id) / (width * depth) }; } Vector3 Grid3D::planeSquareAndJumpsFrom(const Vector3 &size) const { return { size.x * size.y, static_cast<real_t>(width) - size.x, width * (depth - size.y) }; } int Grid3D::indexIncrementFrom(const Vector3 &planeSquareAndJumps, const Vector3 &size, int iteration) { int increment { 0 }; increment += (iteration % static_cast<int>(size.x)) == 0 ? static_cast<int>(planeSquareAndJumps.y) : 0; increment += (iteration % static_cast<int>(planeSquareAndJumps.x)) == 0 ? static_cast<int>(planeSquareAndJumps.z) : 0; increment += 1; return increment; }
28.604061
141
0.597693
[ "object" ]
2ebec7539cf340a2a79224646ac86bf5daae61a0
1,494
hh
C++
StateObject/AudioPowerSpectrumState/audiopowerspectrumstate.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
StateObject/AudioPowerSpectrumState/audiopowerspectrumstate.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
StateObject/AudioPowerSpectrumState/audiopowerspectrumstate.hh
drewnoakes/bold-humanoid
6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../stateobject.hh" #include <vector> #include <cmath> namespace bold { class AudioPowerSpectrumState : public StateObject { public: AudioPowerSpectrumState(double maxFrequency, std::vector<float> dbs); void writeJson(rapidjson::Writer<rapidjson::StringBuffer>& writer) const override { writeJsonInternal(writer); } void writeJson(rapidjson::PrettyWriter<rapidjson::StringBuffer>& writer) const override { writeJsonInternal(writer); } void writeJson(rapidjson::Writer<WebSocketBuffer>& writer) const override { writeJsonInternal(writer); } uint getIndexForFreqHz(double frequencyHz) const; uint getMaxIndex() const { return d_dbs.size() - 1; } float getDecibelsByIndex(uint index) const { return d_dbs[index]; } private: template<typename TBuffer> void writeJsonInternal(rapidjson::Writer<TBuffer> &writer) const; double d_maxFrequency; std::vector<float> d_dbs; }; template<typename TBuffer> inline void AudioPowerSpectrumState::writeJsonInternal(rapidjson::Writer<TBuffer> &writer) const { writer.StartObject(); { writer.String("maxHertz"); writer.Double(d_maxFrequency); writer.String("dbLevels"); writer.StartArray(); { for (float const& db : d_dbs) { if (std::isinf(db)) writer.Int(-200); else writer.Double(db, "%.3f"); } } writer.EndArray(); } writer.EndObject(); } }
27.163636
122
0.671352
[ "vector" ]
2ebf63f34627259dee4d5f2a3da5c19364cdbd72
9,868
cpp
C++
tests/test_intersection.cpp
hiteshbedre/movetk
8d261f19538e28ff36cac98a89ef067f8c26f978
[ "Apache-2.0" ]
53
2020-09-09T19:52:17.000Z
2022-02-05T10:04:24.000Z
tests/test_intersection.cpp
bacusters/movetk
acbc9c5acb69dd3eb23aa7d2156ede02ed468eae
[ "Apache-2.0" ]
44
2020-09-11T17:40:30.000Z
2021-04-08T23:56:19.000Z
tests/test_intersection.cpp
aniketmitra001/movetk
cdf0c98121da6df4cadbd715fba02b05be724218
[ "Apache-2.0" ]
8
2021-02-05T21:40:07.000Z
2021-09-11T02:27:00.000Z
/* * Copyright (C) 2018-2020 HERE Europe B.V. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ // // Created by Mitra, Aniket on 2019-09-10. // #include <array> #include "catch2/catch.hpp" #if CGAL_BACKEND_ENABLED #include "movetk/geom/CGALTraits.h" #else #include "movetk/geom/BoostGeometryTraits.h" #endif #include "movetk/geom/GeometryInterface.h" #include "movetk/utils/Iterators.h" #include "movetk/utils/TrajectoryUtils.h" #include "movetk/metric/Norm.h" using namespace std; #if CGAL_BACKEND_ENABLED //============================== // Define the Number Type // For the CGAL backend, // One can choose from the // following number types typedef long double NT; //typedef CGAL::Mpzf NT; //typedef CGAL::Gmpfr NT; //typedef CGAL::Gmpq NT; //============================== //============================== // Define the Dimensions const size_t dimensions = 2; //============================== //============================== // Define the Geometry Backend typedef movetk_support::CGALTraits<NT, dimensions> CGAL_GeometryBackend; //Using the Geometry Backend define the Movetk Geometry Kernel typedef movetk_core::MovetkGeometryKernel< typename CGAL_GeometryBackend::Wrapper_CGAL_Geometry> MovetkGeometryKernel; //============================== #else //============================== // Define the Number Type // For the Boost Backend typedef long double NT; //============================== //============================== // Define the Dimensions // It is possible to choose // a higher dimension // Note: Boost Geometry Adapter supports geometry in two // dimensions only const static size_t dimensions = 2; //============================== //============================== // Define the Geometry Backend typedef movetk_support::BoostGeometryTraits<long double, dimensions> Boost_Geometry_Backend; //Using the Geometry Backend define the Movetk Geometry Kernel typedef movetk_core::MovetkGeometryKernel<typename Boost_Geometry_Backend::Wrapper_Boost_Geometry> MovetkGeometryKernel; //============================== #endif typedef movetk_support::FiniteNorm<MovetkGeometryKernel, 2> Norm; TEST_CASE("Check sphere segment intersection 1", "[sphere_segment_intersection_1]") { typedef typename MovetkGeometryKernel::NT NT; typedef typename MovetkGeometryKernel::MovetkPoint MovetkPoint; typedef movetk_core::IntersectionTraits<MovetkGeometryKernel, Norm, movetk_core::sphere_segment_intersection_tag> IntersectionTraits; movetk_core::MakeSphere<MovetkGeometryKernel> make_sphere; MovetkGeometryKernel::MovetkSphere sphere = make_sphere({5, 3}, 1.371); movetk_core::MakeSegment<MovetkGeometryKernel> make_segment; MovetkGeometryKernel::MovetkSegment segment = make_segment({2, 2}, {4, 6}); std::vector<IntersectionTraits::value_type> intersections; typedef movetk_core::movetk_back_insert_iterator<std::vector<IntersectionTraits::value_type> > OutputIterator; movetk_core::ComputeIntersections<IntersectionTraits> compute_intersections; compute_intersections(sphere, segment,OutputIterator(intersections)); REQUIRE (intersections.size() == 1); REQUIRE ( std::get<IntersectionTraits::Attributes::SIGN_DISCRIMINANT>(intersections[0]) == -1); REQUIRE ( std::get<IntersectionTraits::Attributes::SQUARED_RATIO>(intersections[0]) == -1.0); } TEST_CASE("Check sphere segment intersection 2","[sphere_segment_intersection_2]"){ typedef typename MovetkGeometryKernel::NT NT; typedef typename MovetkGeometryKernel::MovetkPoint MovetkPoint; typedef movetk_core::IntersectionTraits<MovetkGeometryKernel, Norm, movetk_core::sphere_segment_intersection_tag> IntersectionTraits; movetk_core::MakePoint<MovetkGeometryKernel> make_point; movetk_core::MakeSphere<MovetkGeometryKernel> make_sphere; MovetkGeometryKernel::MovetkSphere sphere = make_sphere({5, 3}, 2.2364778); movetk_core::MakeSegment<MovetkGeometryKernel> make_segment; MovetkGeometryKernel::MovetkSegment segment = make_segment({2, 2}, {4, 6}); std::vector<IntersectionTraits::value_type> intersections; std::vector<MovetkGeometryKernel::MovetkPoint> expected_intersection{make_point({3, 4})}; typedef movetk_core::movetk_back_insert_iterator<std::vector<IntersectionTraits::value_type> > OutputIterator; movetk_core::ComputeIntersections<IntersectionTraits> compute_intersections; compute_intersections(sphere, segment, OutputIterator(intersections) ); REQUIRE (intersections.size() == 1); std::cout<<std::get<IntersectionTraits::Attributes::POINT>(intersections[0]); std::cout<<"\n"; MovetkGeometryKernel::MovetkVector v = std::get<IntersectionTraits::Attributes::POINT>(intersections[0]) - expected_intersection[0]; REQUIRE (v * v < MOVETK_EPS); } TEST_CASE("Check sphere segment intersection 3","[sphere_segment_intersection_3]"){ typedef typename MovetkGeometryKernel::NT NT; typedef typename MovetkGeometryKernel::MovetkPoint MovetkPoint; typedef movetk_core::IntersectionTraits<MovetkGeometryKernel, Norm, movetk_core::sphere_segment_intersection_tag> IntersectionTraits; movetk_core::MakePoint<MovetkGeometryKernel> make_point; movetk_core::MakeSphere<MovetkGeometryKernel> make_sphere; MovetkGeometryKernel::MovetkSphere sphere = make_sphere({5, 3}, 2.509885); movetk_core::MakeSegment<MovetkGeometryKernel> make_segment; MovetkGeometryKernel::MovetkSegment segment = make_segment({2, 2}, {4, 6}); std::vector<IntersectionTraits::value_type> intersections; std::vector<MovetkGeometryKernel::MovetkPoint> expected_intersection{make_point({3.509808, 5.019617}), make_point({2.490192,2.980383})}; typedef movetk_core::movetk_back_insert_iterator<std::vector<IntersectionTraits::value_type> > OutputIterator; movetk_core::ComputeIntersections<IntersectionTraits> compute_intersections; compute_intersections(sphere, segment, OutputIterator(intersections) ); REQUIRE (intersections.size() == 2); std::cout<<std::get<IntersectionTraits::Attributes::POINT>(intersections[0]); std::cout<<"\n"; MovetkGeometryKernel::MovetkVector v = std::get<IntersectionTraits::Attributes::POINT>(intersections[0]) - expected_intersection[0]; REQUIRE (v * v < MOVETK_EPS); std::cout<<std::get<IntersectionTraits::Attributes::POINT>(intersections[1]); std::cout<<"\n"; v = std::get<IntersectionTraits::Attributes::POINT>(intersections[1]) - expected_intersection[1]; REQUIRE (v * v < MOVETK_EPS); } TEST_CASE("Check sphere sphere intersection 1","[sphere_sphere_intersection_1]"){ typedef typename MovetkGeometryKernel::NT NT; typedef typename MovetkGeometryKernel::MovetkPoint MovetkPoint; typedef movetk_core::IntersectionTraits<MovetkGeometryKernel, Norm, movetk_core::sphere_sphere_intersection_tag> IntersectionTraits; movetk_core::MakePoint<MovetkGeometryKernel> make_point; movetk_core::MakeSphere<MovetkGeometryKernel> make_sphere; MovetkGeometryKernel::MovetkSphere sphere1 = make_sphere({6, 6}, 5); MovetkGeometryKernel::MovetkSphere sphere2 = make_sphere({14, 10}, 5); movetk_core::ComputeIntersections<IntersectionTraits> compute_intersections; MovetkGeometryKernel::MovetkSphere sphere3 = compute_intersections(sphere1, sphere2); MovetkGeometryKernel::MovetkPoint expected_center = make_point({10, 8}); MovetkGeometryKernel::NT expected_squared_radius = 5; MovetkGeometryKernel::MovetkVector eps = sphere3.center() - expected_center; std::cout<<"Input Sphere 1: {"<<sphere1<<" }\n"; std::cout<<"Input Sphere 2: {"<<sphere2<<" }\n"; std::cout<<"Output Sphere: {"<<sphere3<<" }\n"; REQUIRE( (eps * eps) < MOVETK_EPS ); REQUIRE( abs(expected_squared_radius - sphere3.squared_radius() ) < MOVETK_EPS); } TEST_CASE("Check sphere sphere intersection 2","[sphere_sphere_intersection_2]"){ typedef typename MovetkGeometryKernel::NT NT; typedef typename MovetkGeometryKernel::MovetkPoint MovetkPoint; typedef movetk_core::IntersectionTraits<MovetkGeometryKernel, Norm, movetk_core::sphere_sphere_intersection_tag> IntersectionTraits; movetk_core::MakePoint<MovetkGeometryKernel> make_point; movetk_core::MakeSphere<MovetkGeometryKernel> make_sphere; MovetkGeometryKernel::MovetkSphere sphere1 = make_sphere({6, 6}, 2.5); MovetkGeometryKernel::MovetkSphere sphere2 = make_sphere({14, 10}, 5); movetk_core::ComputeIntersections<IntersectionTraits> compute_intersections; MovetkGeometryKernel::MovetkSphere sphere3 = compute_intersections(sphere1, sphere2); MovetkGeometryKernel::MovetkPoint expected_center = make_point({0, 0}); MovetkGeometryKernel::NT expected_squared_radius = 0; MovetkGeometryKernel::MovetkVector eps = sphere3.center() - expected_center; std::cout<<"Input Sphere 1: {"<<sphere1<<" }\n"; std::cout<<"Input Sphere 2: {"<<sphere2<<" }\n"; std::cout<<"Output Sphere: {"<<sphere3<<" }\n"; REQUIRE( (eps * eps) < MOVETK_EPS ); REQUIRE( abs(expected_squared_radius - sphere3.squared_radius() ) < MOVETK_EPS); }
48.372549
120
0.721625
[ "geometry", "vector" ]
2ec102a7ab424c2cb450a5701385bc277265f6f1
361
cpp
C++
archives/problemset/codeforces.com/137B.cpp
BoleynSu/CP-CompetitiveProgramming
cc256bf402360fe0f689fdcdc4e898473a9594dd
[ "MIT" ]
6
2019-03-23T21:06:25.000Z
2021-06-27T05:22:41.000Z
archives/problemset/codeforces.com/137B.cpp
BoleynSu/CP-CompetitiveProgramming
cc256bf402360fe0f689fdcdc4e898473a9594dd
[ "MIT" ]
1
2020-10-11T08:14:00.000Z
2020-10-11T08:14:00.000Z
archives/problemset/codeforces.com/137B.cpp
BoleynSu/CP-CompetitiveProgramming
cc256bf402360fe0f689fdcdc4e898473a9594dd
[ "MIT" ]
3
2019-03-23T21:06:31.000Z
2021-10-24T01:44:01.000Z
#include <string> #include <iostream> #include <vector> using namespace std; int main() { int n; cin>>n; vector<bool> get(n,false); int answer=0; for (int i=0;i<n;i++) { int ai; cin>>ai; if (get[ai]||ai>n) answer++; else get[ai]=true; } cout<<answer<<endl; return 0; }
15.695652
37
0.479224
[ "vector" ]
2ec1231e709918f5920cc6fdeaebf2c136d05753
627
cpp
C++
Unrest-iOS/MusicArea.cpp
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
11
2020-08-04T08:37:46.000Z
2022-03-31T22:35:15.000Z
CRAB/MusicArea.cpp
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
1
2020-12-16T16:51:52.000Z
2020-12-18T06:35:38.000Z
Unrest-iOS/MusicArea.cpp
arvindrajayadav/unrest
d89f20e95fbcdef37a47ab1454b2479522a0e43f
[ "MIT" ]
7
2020-08-04T09:34:20.000Z
2021-09-11T03:00:16.000Z
#include "stdafx.h" #include "MusicArea.h" using namespace pyrodactyl::level; void MusicArea::Load(rapidxml::xml_node<char> *node, const bool &echo) { Shape::Load(node, echo); if (NodeValid("properties", node, echo)) { auto pnode = node->first_node("properties"); for (auto n = pnode->first_node("property"); n != NULL; n = n->next_sibling("property")) { std::string name; if (LoadStr(name, "name", n, echo)) { if (name == "music") LoadBool(track, "value", n, echo); else if (name == "id") LoadNum(id, "value", n, echo); else if (name == "loops") LoadNum(loops, "value", n, echo); } } } }
26.125
90
0.61882
[ "shape" ]
2ec31d5924c2ff8b7fd0a81761ce143216008a46
1,735
hpp
C++
include/oglplus/buffer_data.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
364
2015-01-01T09:38:23.000Z
2022-03-22T05:32:00.000Z
include/oglplus/buffer_data.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
55
2015-01-06T16:42:55.000Z
2020-07-09T04:21:41.000Z
include/oglplus/buffer_data.hpp
matus-chochlik/oglplus
76dd964e590967ff13ddff8945e9dcf355e0c952
[ "BSL-1.0" ]
57
2015-01-07T18:35:49.000Z
2022-03-22T05:32:04.000Z
/** * @file oglplus/buffer_data.hpp * @brief Object wrapping data to be stored in a Buffer * * @author Matus Chochlik * * Copyright 2010-2019 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #pragma once #ifndef OGLPLUS_BUFFER_DATA_1310102147_HPP #define OGLPLUS_BUFFER_DATA_1310102147_HPP #include <oglplus/buffer_size.hpp> namespace oglplus { /// Class used for passing the size of and pointer to data to be put in a Buffer class BufferData { private: BufferSize _size; const GLvoid* _data; BufferData(const BufferData&); public: /// Construction from @p size in bytes and pointer to @p data BufferData(BufferSize size, const GLvoid* data) : _size(size) , _data(data) { } /// Construction from @p count of instances of type @c T at @p data template <typename T> BufferData(SizeType count, const T* data) : _size(count, data) , _data(data) { } /// Construction from an array with known size template <typename T, std::size_t N> BufferData(const T (&data)[N]) : _size(data) , _data(data) { } /// Construction from a std::array template <typename T, std::size_t N> BufferData(const std::array<T, N>& a) : _size(a) , _data(a.data()) { } /// Construction from a std::vector template <typename T> BufferData(const std::vector<T>& v) : _size(v) , _data(v.data()) { } GLsizeiptr Size() const { return _size.Get(); } const GLvoid* Data() const { return _data; } }; } // namespace oglplus #endif // include guard
23.133333
80
0.641499
[ "object", "vector" ]
2ec484c3d964be165d36875e00513511b53d1b13
926
cpp
C++
utils/MiscUtility.cpp
KrokusPokus/krkrz
d5eff37e0335e4756caf0061589893370766f814
[ "BSD-3-Clause" ]
572
2015-01-02T12:47:44.000Z
2022-03-28T06:06:02.000Z
utils/MiscUtility.cpp
KrokusPokus/krkrz
d5eff37e0335e4756caf0061589893370766f814
[ "BSD-3-Clause" ]
108
2015-02-24T03:06:03.000Z
2022-01-23T07:28:58.000Z
utils/MiscUtility.cpp
KrokusPokus/krkrz
d5eff37e0335e4756caf0061589893370766f814
[ "BSD-3-Clause" ]
136
2015-01-24T01:29:46.000Z
2022-03-16T17:03:43.000Z
#include "tjsCommHead.h" #include "CharacterSet.h" #ifdef _WIN32 #include <mmsystem.h> #endif //--------------------------------------------------------------------------- // TVPGetRoughTickCount // 32bit値のtickカウントを得る //--------------------------------------------------------------------------- tjs_uint32 TVPGetRoughTickCount32() { #ifdef _WIN32 return timeGetTime(); #else #error Not implemented yet. #endif } //--------------------------------------------------------------------------- bool TVPEncodeUTF8ToUTF16( std::wstring &output, const std::string &source ) { tjs_int len = TVPUtf8ToWideCharString( source.c_str(), NULL ); if(len == -1) return false; std::vector<tjs_char> outbuf( len+1, 0 ); tjs_int ret = TVPUtf8ToWideCharString( source.c_str(), &(outbuf[0])); if( ret ) { outbuf[ret] = L'\0'; output = std::wstring( &(outbuf[0]) ); return true; } return false; }
27.235294
78
0.50108
[ "vector" ]
2ec53df73fa88f752de4243c1b34e3116659f08a
1,133
hpp
C++
geometry/monotonic-dp-hull.hpp
dutinmeow/library
3501f36656795f432ac816941ec7e9548dc3d6ef
[ "MIT" ]
7
2022-01-23T07:58:19.000Z
2022-02-25T04:11:12.000Z
geometry/monotonic-dp-hull.hpp
dutinmeow/library
3501f36656795f432ac816941ec7e9548dc3d6ef
[ "MIT" ]
null
null
null
geometry/monotonic-dp-hull.hpp
dutinmeow/library
3501f36656795f432ac816941ec7e9548dc3d6ef
[ "MIT" ]
null
null
null
#include "geometry/point.hpp" #pragma region monotonic_dp_hull #ifndef MONOTONIC_DP_HULL_HPP #define MONOTONIC_DP_HULL_HPP struct monotonic_dp_hull { long long prev_x = LLONG_MIN, prev_y = 1; deque<geo::point<long long>> points; void add(const geo::point<long long> &p) { assert(points.empty() || p.x >= points.back().x); if (!points.empty() && p.x == points.back().x) { if (p.y <= points.back().y) return; points.pop_back(); } while (size() >= 2 && ((points.back() - p) ^ (points[size() - 2] - points.back())) <= 0) points.pop_back(); points.push_back(p); } void add(long long m, long long b) { add(geo::point(m, b)); } long long query(long long x, long long y = 1) { assert(size() > 0); assert(prev_x == LLONG_MIN || x * prev_y >= prev_x * y); prev_x = x, prev_y = y; while (size() >= 2 && x * (points[1].x - points[0].x) >= (points[0].y - points[1].y) * y) points.pop_front(); return points[0].x * x + points[0].y * y; } void clear() { points.clear(); prev_x = LLONG_MIN, prev_y = 1; } int size() const { return points.size(); } }; #endif #pragma endregion monotonic_dp_hull
26.97619
91
0.616946
[ "geometry" ]
2ec72fe692333b048a38637b13bac0f79744f521
2,192
cpp
C++
cpp/G3M/XPCIntensityPointColorizer.cpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
70
2015-02-06T14:39:14.000Z
2022-01-07T08:32:48.000Z
cpp/G3M/XPCIntensityPointColorizer.cpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
118
2015-01-21T10:18:00.000Z
2018-10-16T15:00:57.000Z
cpp/G3M/XPCIntensityPointColorizer.cpp
glob3mobile/g3m
2b2c6422f05d13e0855b1dbe4e0afed241184193
[ "BSD-2-Clause" ]
41
2015-01-10T22:29:27.000Z
2021-06-08T11:56:16.000Z
// // XPCIntensityPointColorizer.cpp // G3MiOSSDK // // Created by Diego Gomez-Deck on 1/21/21. // #include "XPCIntensityPointColorizer.hpp" #include "ILogger.hpp" #include "XPCMetadata.hpp" #include "XPCDimension.hpp" #include "IFactory.hpp" #include "IIntBuffer.hpp" #include "MutableColor.hpp" #include "Color.hpp" XPCIntensityPointColorizer::XPCIntensityPointColorizer(const float alpha) : XPCFixedAlphaPointColorizer(alpha), _intensityDimensionName("Intensity"), _intensityDimensionIndex(-1), _ok(false) { } XPCIntensityPointColorizer::XPCIntensityPointColorizer(const std::string& intensityDimensionName, const float alpha) : XPCFixedAlphaPointColorizer(alpha), _intensityDimensionName(intensityDimensionName), _intensityDimensionIndex(-1), _ok(false) { } XPCIntensityPointColorizer::~XPCIntensityPointColorizer() { } IIntBuffer* XPCIntensityPointColorizer::initialize(const XPCMetadata* metadata) { const size_t dimensionsCount = metadata->getDimensionsCount(); for (int i = 0; i < dimensionsCount; i++) { const std::string dimensionName = metadata->getDimension(i)->_name; if (dimensionName == _intensityDimensionName) { _intensityDimensionIndex = i; } } _ok = (_intensityDimensionIndex >= 0); if (!_ok) { ILogger::instance()->logError("Can't find Intensity dimensions"); return NULL; } IIntBuffer* requiredDimensionIndices = IFactory::instance()->createIntBuffer(1); requiredDimensionIndices->put(0, _intensityDimensionIndex); return requiredDimensionIndices; } void XPCIntensityPointColorizer::colorize(const XPCMetadata* metadata, const double heights[], const std::vector<const IByteBuffer*>* dimensionsValues, const size_t i, MutableColor& color) { if (!_ok) { color.set(1, 0, 0, 1); return; } const float intensity = metadata->getDimension(_intensityDimensionIndex )->getNormalizedValue( dimensionsValues->at(0), i ); color.set(intensity, intensity, intensity, _alpha); }
27.4
127
0.680657
[ "vector" ]
2ec996b4eaaf6b4e84cfbd2da332e343ce644889
2,510
cc
C++
iot/src/model/CreateStudioAppDomainOpenResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
iot/src/model/CreateStudioAppDomainOpenResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
iot/src/model/CreateStudioAppDomainOpenResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/iot/model/CreateStudioAppDomainOpenResult.h> #include <json/json.h> using namespace AlibabaCloud::Iot; using namespace AlibabaCloud::Iot::Model; CreateStudioAppDomainOpenResult::CreateStudioAppDomainOpenResult() : ServiceResult() {} CreateStudioAppDomainOpenResult::CreateStudioAppDomainOpenResult(const std::string &payload) : ServiceResult() { parse(payload); } CreateStudioAppDomainOpenResult::~CreateStudioAppDomainOpenResult() {} void CreateStudioAppDomainOpenResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto dataNode = value["Data"]; if(!dataNode["TenantId"].isNull()) data_.tenantId = dataNode["TenantId"].asString(); if(!dataNode["AppId"].isNull()) data_.appId = dataNode["AppId"].asString(); if(!dataNode["ProjectId"].isNull()) data_.projectId = dataNode["ProjectId"].asString(); if(!dataNode["Host"].isNull()) data_.host = dataNode["Host"].asString(); if(!dataNode["Id"].isNull()) data_.id = std::stoi(dataNode["Id"].asString()); if(!dataNode["IsBeian"].isNull()) data_.isBeian = dataNode["IsBeian"].asString(); if(!dataNode["Protocol"].isNull()) data_.protocol = dataNode["Protocol"].asString(); if(!value["Success"].isNull()) success_ = value["Success"].asString() == "true"; if(!value["Code"].isNull()) code_ = value["Code"].asString(); if(!value["ErrorMessage"].isNull()) errorMessage_ = value["ErrorMessage"].asString(); } CreateStudioAppDomainOpenResult::Data CreateStudioAppDomainOpenResult::getData()const { return data_; } std::string CreateStudioAppDomainOpenResult::getErrorMessage()const { return errorMessage_; } std::string CreateStudioAppDomainOpenResult::getCode()const { return code_; } bool CreateStudioAppDomainOpenResult::getSuccess()const { return success_; }
29.186047
94
0.740239
[ "model" ]