blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
2e52e8735f7f7aa365ffe6978190ce3caf3fddc5
e7e497b20442a4220296dea1550091a457df5a38
/main_project/ad/engine_u/src/AdStruct.h
5ba9c42268b3edf13d35118351fa7e0a8bdaf332
[]
no_license
gunner14/old_rr_code
cf17a2dedf8dfcdcf441d49139adaadc770c0eea
bb047dc88fa7243ded61d840af0f8bad22d68dee
refs/heads/master
2021-01-17T18:23:28.154228
2013-12-02T23:45:33
2013-12-02T23:45:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,021
h
AdStruct.h
/* * AdStruct.h * * Created on: Aug 25, 2010 * Author: antonio */ #ifndef ADSTRUCT_H_ #define ADSTRUCT_H_ #include <time.h> #include <vector> #include <map> #include <ext/hash_map> #include <set> #include <bitset> #include <IceUtil/RWRecMutex.h> #include <IceUtil/Mutex.h> #include <IceUtil/Shared.h> #include <IceUtil/Handle.h> #include "TaskManager.h" #include "AdTranslator.h" #include "QueryRunner.h" #include "Singleton.h" #include "Util.h" #include "AdConfig.h" #include "FeedMemcProxy/client/user_profile_client.h" #include "AdEngine.h" namespace xce { namespace ad { using namespace std; using namespace MyUtil; using namespace com::xiaonei::xce; using namespace __gnu_cxx; class StatFunc { string name_; timeval start_, end_; //static int count; public: StatFunc(string name) : name_(name) { gettimeofday(&start_, NULL); } ~StatFunc() { gettimeofday(&end_, NULL); float timeuse=1000000*(end_.tv_sec-start_.tv_sec)+end_.tv_usec -start_.tv_usec; timeuse/=1000; if(timeuse >= 20){ MCE_INFO(name_ << " time usage:" << timeuse << " ms"); } else { MCE_DEBUG(name_ << " time usage:" << timeuse << " ms"); } } }; class AdZone; typedef IceUtil::Handle<AdZone> AdZonePtr; typedef vector<AdZone> AdZoneSeq; typedef map<int, AdZonePtr> AdZoneDict; class DictNode; class DictTree; typedef IceUtil::Handle<DictNode> DictNodePtr; typedef IceUtil::Handle<DictTree> DictTreePtr; typedef hash_map<char, DictNodePtr> Char2NodeMap; class DictNode : public IceUtil::Shared { public: DictNode() { wordend_ = false; } DictNodePtr insert(const char& c, bool wordend); void GetNext2(const char& c, DictNodePtr&, bool lastisinteger , bool search_end = false); void GetNext(const char& c, DictNodePtr&, bool search_end = false); vector<AdZonePtr> referer_zones_; Char2NodeMap node_; bool wordend_; }; class DictTree : public IceUtil::Shared { public: DictTree() { root_ = new DictNode(); } void insert(const string& str, const AdZonePtr& zone_ptr); bool search(const string& str, vector<AdZonePtr>& zones); private: DictNodePtr root_; }; /***********************************************************************************************************************/ class AdGroup; typedef IceUtil::Handle<AdGroup> AdGroupPtr; typedef vector<AdGroupPtr> AdGroupSeq; class SelectedAdGroup; typedef IceUtil::Handle<SelectedAdGroup> SelectedAdGroupPtr; typedef vector<SelectedAdGroupPtr> SelectedAdGroupSeq; class AdZone : public IceUtil::Shared { public: AdZone() { member_online_status_ = 0; am_online_status_ = 0; audit_status_ = 0; delete_flag_ = 0; } bool Available(); bool FindStage(int stage); Ice::Long id(); int bp_count() const { return bp_count_; } void set_bp_count(int bp_count) { this->bp_count_ = bp_count; } int brand_count() const { return brand_count_; } void set_brand_count(int brand_count) { this->brand_count_ = brand_count; } int member_type() const { return member_type_; } void set_member_type(int member_type) { this->member_type_ = member_type; } int weight(); set<string> referers(); void set_id(Ice::Long id); void add_stage(int stage); void set_weight(int weight); void set_referer(const string& ref); void set_member_online_status(int member_online_status); void set_am_online_status(int am_online_status); void set_audit_status(int audit_status); void set_delete_flag(int delete_flag); private: Ice::Long id_; //zone id int brand_count_; // 可显示的品牌广告数 int bp_count_; // 可显示的中小自助广告数 int weight_; //广告位展示权重 set<int> stage_;//能展示这个广告位的阶段 set<string> referer_;//这个广告位请求的referer int member_type_; int member_online_status_; int am_online_status_; int audit_status_; int delete_flag_; }; const static int zone_reload_timestamp = 1 * 60 * 1000; class AdZonePool : public MyUtil::Singleton<AdZonePool> { public: AdZonePool() { trie_ = new DictTree(); } void Init(); void LoadDefaultAdGroup(map<Ice::Long, vector<AdGroupPtr> > &zone_groups); AdZoneDict GetAdZoneOrdered(const string& referer, const UserProfile& userprofile, bool hide = false); AdZoneDict GetAdZoneOrdered(const ZoneInfoMap& zone_info_map, const UserProfile& userprofile); vector<AdGroupPtr> GetDefaultGroups(Ice::Long zone_id); bool IsCompetedDefaultGroup(AdGroupPtr group, set<AdGroupPtr> &selected_ids); void GetDefaultGroupsCompete(const Ice::Long adzone,const int count, set<AdGroupPtr> selected,const vector<AdGroupPtr> &groups, set<AdGroupPtr> &ans); class ReloadTimer : public MyUtil::Timer { public: ReloadTimer() : Timer(zone_reload_timestamp) { } virtual void handle(); }; AdZonePtr GetAdZone(Ice::Long id) { map<Ice::Long, AdZonePtr>::iterator it = zone_pool_.find(id); if (it != zone_pool_.end()) { return it->second; } else { return NULL; } } private: DictTreePtr trie_; multimap<string, AdZonePtr> ref_zone_map_; map<Ice::Long, AdZonePtr> zone_pool_; map<Ice::Long, std::vector<AdGroupPtr> > default_group_pool_; IceUtil::RWRecMutex mutex_; void LoadAdzone(map<Ice::Long, AdZonePtr> & zones); void LoadAdgroupAdzoneRef(map<Ice::Long, AdZonePtr> & zones); void LoadUrlAdzoneMaping(map<Ice::Long, AdZonePtr> & zones, DictTreePtr & trie, multimap<string, AdZonePtr> & ref_zone_map); }; /***********************************************************************************************************************/ class AdStyle : public IceUtil::Shared { public: Ice::Long style_id() const { return style_id_; } void set_style_id(Ice::Long style_id) { this->style_id_ = style_id; } void set_ad_cnt( int ad_cnt){ this->ad_cnt_ = ad_cnt; } int ad_cnt() const{ return ad_cnt_; } string note() const{ return this->note_; } void set_note(string note ){ this->note_ = note; } void set_submit_time(string submit_time){ this->submit_time_ = submit_time; } string submit_time() const{ return submit_time_; } void set_big_widgets(vector<int>& big_widgets){ this->big_widgets_ = big_widgets; } vector<int> big_widgets() const{ return this->big_widgets_; } void set_small_widgets(vector<int>& small_widgets){ this->small_widgets_ = small_widgets; } vector<int> small_widgets() const{ return this->small_widgets_; } static vector<int> String2intvec(string str , string sep); private: Ice::Long style_id_; int ad_cnt_; string note_; string submit_time_; vector<int> big_widgets_; vector<int> small_widgets_; }; typedef IceUtil::Handle<AdStyle> AdStylePtr; class AdStylePool : public MyUtil::Singleton<AdStylePool> { public: void Init(); AdStylePtr GetAdStyle(Ice::Long style_id); class UpdateCheckTimer : public MyUtil::Timer { public: UpdateCheckTimer() : Timer(1 * 60 * 1000) { } virtual void handle(); }; private: map<Ice::Long, AdStylePtr> style_pool_; IceUtil::RWRecMutex mutex_; }; /***********************************************************************************************************************/ class AdExperiment : public IceUtil::Shared { public: Ice::Long experiment_id() const { return experiment_id_; } void set_experiment_id(Ice::Long experiment_id) { this->experiment_id_ = experiment_id; } void set_style_id( Ice::Long style_id){ this->style_id_ = style_id; } Ice::Long style_id() const{ return style_id_; } void set_status( int status){ this->status_ = status; } int status() const{ return status_; } void set_traffic( int traffic){ this->traffic_ = traffic; } int traffic() const{ return traffic_; } void set_zone_id( Ice::Long zone_id){ this->zone_id_ = zone_id; } Ice::Long zone_id() const{ return zone_id_; } void set_submit_time(string submit_time){ this->submit_time_ = submit_time; } string submit_time() const{ return submit_time_; } void set_modify_time(string modify_time){ this->modify_time_ = modify_time; } string modify_time() const{ return modify_time_; } private: Ice::Long experiment_id_; Ice::Long zone_id_; Ice::Long style_id_; int traffic_; int status_; string modify_time_; string submit_time_; }; typedef IceUtil::Handle<AdExperiment> AdExperimentPtr; class AdExperimentPool : public MyUtil::Singleton<AdExperimentPool> { public: void Init(); AdExperimentPtr GetAdExperiment(Ice::Long experiment_id); vector<AdExperimentPtr> ListAdExperiment(); static bool compare(AdExperimentPtr exp1 , AdExperimentPtr exp2){ if( exp1->zone_id() == exp2->zone_id()){ return exp1->traffic() < exp2->traffic(); }else{ return exp1->zone_id()< exp2->zone_id(); } } class UpdateCheckTimer : public MyUtil::Timer { public: UpdateCheckTimer() : Timer(1 * 60 * 1000) { } virtual void handle(); }; private: map<Ice::Long, AdExperimentPtr> experiment_pool_; IceUtil::RWRecMutex mutex_; }; class AdGroup : public IceUtil::Shared { public: void set_group_id(Ice::Long group_id) { group_id_ = group_id; } void set_widget_id(Ice::Long widget_id) { widget_id_ = widget_id; } void set_member_id(Ice::Long member_id) { member_id_ = member_id; } void set_campaign_id(Ice::Long campaign_id) { campaign_id_ = campaign_id; } void set_member_category(int member_category) { member_category_ = member_category; } void set_member_industry(int member_industry) { member_industry_ = member_industry; } void set_display_type(int display_type) { display_type_ = display_type; } void set_max_price(int max_price) { max_price_ = max_price; } void set_bid_unit_id(Ice::Long bid_unit_id) { bid_unit_id_ = bid_unit_id; } Ice::Long group_id() { return group_id_; } Ice::Long member_id() { return member_id_; } Ice::Long widget_id() { return widget_id_; } Ice::Long campaign_id() { return campaign_id_; } int member_category() { return member_category_; } int member_industry() { return member_industry_; } int display_type() { return display_type_; } double max_price() { return max_price_; } double calculate_cost(Ice::Long zone_id) { float cost_discount = EngineConfig::instance().GetCostDiscount(); int rand_seed = EngineConfig::instance().GetRandSeed(); double max_price = this->max_price(); double cost = ((cost_discount + rand() % rand_seed / 10000.0) * (max_price)); if(IsCpc()){ //cpc if (cost < EngineConfig::instance().sys_min_price()) { //不能低于系统最小出价 cost = EngineConfig::instance().sys_min_price(); } if (cost > max_price) { //不能大于出价 cost = max_price; } if((widget_id() == 31) && (cost < 200)) {//自助大图底价2元 cost = 200; } } else if(IsCpm()){ //cpm if (cost > max_price) { //不能大于出价 cost = max_price; } cost *= 0.001; //cpm每次pv扣费 } return cost; } Ice::Long bid_unit_id() { return bid_unit_id_; } int trans_type() const { return trans_type_; } void set_trans_type(int trans_type) { this->trans_type_ = trans_type; } bool operator >(const AdGroup& group) const { return group_id_ > group.group_id_; } bool operator ==(const AdGroup& group) const { return group_id_ == group.group_id_; } bool operator <(const AdGroup& group) const { return group_id_ < group.group_id_; } AdGroup() { bid_unit_id_ = 0; } AdGroup(Ice::Long group_id) : group_id_(group_id), member_id_(0), campaign_id_(0),widget_id_(0) { bid_unit_id_ = 0; trigger_type_ = 0; } bool IsCpc() { return trans_type_ == 10; } bool IsCpm() { return trans_type_ == 20; } public: IceUtil::RWRecMutex mutex_; Ice::Long bid_unit_id_; Ice::Long group_id_; Ice::Long member_id_; Ice::Long campaign_id_; Ice::Long widget_id_; Ice::Long creative_id_; int member_category_; int member_industry_; int display_type_;//轮播,cpm,cpc int trans_type_; // 结算方式:10:cpc,20:cpm, 0: 其他 int max_price_; double demo_ctr_; int trigger_type_; }; class CompeteRef : public MyUtil::Singleton<CompeteRef> { public: CompeteRef() : is_ready_(false) { } void Init(); void Load(); vector<Ice::Long> Get(Ice::Long campaign); bool is_ready(); class ReloadTimer : public MyUtil::Timer { public: ReloadTimer() : Timer(5 * 60 * 1000) { } virtual void handle(); }; private: map<Ice::Long, vector<Ice::Long> > ref_; IceUtil::RWRecMutex mutex_; bool is_ready_; }; class UserBind { public: Ice::Long adzone_id() const { return adzone_id_; } void set_adzone_id(Ice::Long adzone_id) { this->adzone_id_ = adzone_id; } Ice::Long user_id() const { return user_id_; } void set_user_id(Ice::Long user_id) { this->user_id_ = user_id; } bool operator >(const UserBind& ul) const { if (user_id_ != ul.user_id_) return user_id_ > ul.user_id_; return adzone_id_ > ul.adzone_id_; } bool operator ==(const UserBind& ul) const { return ( (user_id_ == ul.user_id_) && (adzone_id_ == ul.adzone_id_)); } bool operator <(const UserBind& ul) const { if(user_id_ != ul.user_id_) return user_id_ < ul.user_id_; return adzone_id_ < ul.adzone_id_; } private: Ice::Long user_id_; Ice::Long adzone_id_; }; class UserBindPool : public MyUtil::Singleton<UserBindPool> { private: typedef map<UserBind, Ice::Long> UserBindMap; public: void BindUser(int user_id, Ice::Long creative_id, Ice::Long zone_id); void UnbindUser(int user_id, Ice::Long zone_id); void NotifyBindUser(int user_id, Ice::Long creative_id, Ice::Long zone_id); void NotifyUnbindUser(int user_id, Ice::Long zone_id); void Init(); typedef UserBindMap::iterator iterator; iterator find(UserBind user_bind); // iterator begin(); iterator end(); private: UserBindMap user_bind_cache_; //UserBind --> creative_id IceUtil::RWRecMutex mutex_; }; class SelectedAdGroup : public IceUtil::Shared { public: SelectedAdGroup(AdGroupPtr p) : group_(p), cost_(0), pos_(0), selected_creative_id_(0), selected_widget_id_(0), ecpm_(0), demo_state_(-1), demo_ctr_(-1.0) { selected_creative_id_ = p->creative_id_; selected_widget_id_ = p->widget_id_; } bool operator<(const SelectedAdGroup& right) const { return group_ < right.group_; } bool operator==(const SelectedAdGroup& right) const { return group_ < right.group_; } AdGroupPtr group_; double cost_; //cost_改成double类型,否则cpm扣费可能有问题 int pos_; Ice::Long selected_creative_id_; //样式实验选中的创意 Ice::Long selected_widget_id_; //样式实验选中的widget_id double ecpm_; string append_info_; string extra_; int demo_state_; double demo_ctr_; }; class FilteredGroupList: public MyUtil::Singleton<FilteredGroupList> { public: void Init() { MCE_INFO("FilteredGroupList init start"); string file_name = "../etc/filtered_group_list"; try { ifstream config(file_name.c_str()); string line; if (config) { while (config >> line) { MCE_INFO("FilteredGroupList init group id : " << line); set_.insert(boost::lexical_cast<Ice::Long>(line)); } } } catch (Ice::Exception& e) { MCE_WARN("FilteredGroupList init error : " << e); } catch (...) { MCE_WARN("FilteredGroupList init error : unkown error \"...\""); } MCE_INFO("FilteredGroupList init end"); } bool IsNotExist(Ice::Long gid) { return set_.find(gid) == set_.end(); } private: set<Ice::Long> set_; }; } // end namespace ad } // end namespace xce #endif /* ADSTRUCT_H_ */
fdd49cbf84a5dcfb107554ccf32f060715ec4054
b9b5d9ce9048296ddad5bd58cd2e70b2bf9ca4ac
/Code/linear_eqns.cpp
48c41b0de674b83c20bb00e57d9676a641ab6306
[]
no_license
anujasaini/Accelerated-Gradient-Descent
2e77bfc40315833e3d1b9e80ce47f1691660076a
9acb45ad2e23904f9d294946f11355a18ec36d23
refs/heads/master
2022-11-06T13:37:26.208417
2020-06-24T14:27:22
2020-06-24T14:27:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,555
cpp
linear_eqns.cpp
#include <bits/stdc++.h> #include "linear_eqns.h" #include "utils.h" using namespace std; // m equations in n variables with random coeficients Equation::Equation(int m, int n){ float** coeffs = new float*[m]; for(int i=0;i<m;i++) coeffs[i] = new float[n]; float* b = new float[m]; do{ for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ float t1 = rand()%100; coeffs[i][j] = t1; } float t2 = rand()%100; b[i] = t2; } }while(determinant(coeffs,n,m)==0); float max_A = INT_MIN; float det_A = determinant(coeffs, n, n); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ if(coeffs[i][j] > max_A) max_A = coeffs[i][j]; } } for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ coeffs[i][j] = coeffs[i][j]/max_A; } b[i] = b[i]/max_A; } this->A = coeffs; this->b = b; this->m = m; this->n = n; this->stringify(); } // m equations in n variables with coeficients as given by 2D array Equation::Equation(float** coeffs, float* b, int n, int m){ this->A = coeffs; this->b = b; this->m = m; this->n = n; this->stringify(); } float* Equation::evaluate(float* values){ float* ret = new float[m]; for(int i=0;i<this->m;i++){ float value = 0.0; for(int j=0;j<this->n;j++){ value += this->A[i][j]*values[j]; } value -= this->b[i]; ret[i] = value; } return ret; } void Equation::stringify(){ for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ // if(this->A[i][j]==0) continue; cout<<this->A[i][j]<<"x"<<j<<" "; if(j!=n-1) cout<<" + "; } cout<<" = "<<this->b[i]<<endl; } }
78b0ddf23ba9ba390f2b076b48ef8ee0a1902185
8c85d929c8855337c39db8772e6b26c669451a7f
/Source/Engine/Render/BoundingBox.cpp
31978382749afb310d26845e330b8b39d187b798
[]
no_license
grokitgames/giga
6d908c2a12a6e95e6d22ef2c37520bf6d666142d
83ec3b023cebc5762f117dd35da57379d3e4b2a9
refs/heads/master
2021-01-01T19:45:49.625486
2017-11-28T02:02:37
2017-11-28T02:02:37
98,677,734
0
0
null
null
null
null
UTF-8
C++
false
false
978
cpp
BoundingBox.cpp
#include <giga-engine.h> void BoundingBox::Create(vector3 min, vector3 max) { this->min = min; this->max = max; points[POINT_NEARBOTTOMLEFT] = vector3(min.x, min.y, min.z); points[POINT_NEARBOTTOMRIGHT] = vector3(max.x, min.y, min.z); points[POINT_NEARTOPLEFT] = vector3(min.x, max.y, min.z); points[POINT_NEARTOPRIGHT] = vector3(max.x, max.y, min.z); points[POINT_FARBOTTOMLEFT] = vector3(min.x, min.y, max.z); points[POINT_FARBOTTOMRIGHT] = vector3(max.x, min.y, max.z); points[POINT_FARTOPLEFT] = vector3(min.x, max.y, max.z); points[POINT_FARTOPRIGHT] = vector3(max.x, max.y, max.z); } bool BoundingBox::Inside(vector3 point) { if (points[POINT_NEARBOTTOMLEFT].x <= point.x && points[POINT_NEARBOTTOMRIGHT].x >= point.x && points[POINT_FARTOPRIGHT].z >= point.z && points[POINT_NEARTOPRIGHT].z <= point.z) { // Point is in bounding box return(true); } return(false); }
5ae728925b0f2a850caa23ff1b66f5c68afd6b58
6834fd05e7256d99b8a36a23007b10048d59f1b3
/BUGLIFE.cpp
c61d57bb900db3bab4f443413686185d0ea5d530
[]
no_license
hunterr24/SPOJ-Solutions
d43ea61210ed13f1191b5f20cec373d8f7769ab8
944bb9562c23b5d9d74276d1c6ba3f4d98fb9ba5
refs/heads/master
2021-01-12T12:20:58.536781
2017-10-20T19:58:32
2017-10-20T19:58:32
72,443,243
1
0
null
2016-10-31T14:16:16
2016-10-31T14:16:16
null
UTF-8
C++
false
false
1,684
cpp
BUGLIFE.cpp
/* nerdyninja BUGLIFE graph: bipartite */ #include <iostream> #include <string> #include <vector> #include <algorithm> #include <sstream> #include <queue> #include <deque> #include <bitset> #include <iterator> #include <list> #include <stack> #include <map> #include <set> #include <functional> #include <numeric> #include <utility> #include <limits> #include <time.h> #include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> using namespace std; #define INF (int)1e9 #define EPS 1e-9 #define REP(i, a, b) for(int i = a; i < b; ++i) #define PB push_back #define MP make_pair typedef long long ll; typedef pair<int, int> PII; typedef vector<ll> VI; typedef vector<string> VS; typedef vector<PII> VII; const float PI = 3.1415926535897932384626433832795; const int MOD = 1000000007; VI G[2010]; int color [2010]; bool bfs(int x) { int i, j, k; queue<int> q; q.push(x); color[x] = 1; while(!q.empty()){ x = q.front(); q.pop(); j = G[x].size(); for(i = 0; i < j; i++){ k = G[x][i]; if(color[k] == color[x])return false; if(!color[k]){ color[k] = 3 - color[x]; q.push(k); } } } return true; } int main() { int i, j, x, y, t, nb, ni; scanf("%d", &t); for(int qq = 1; qq <= t; qq++){ scanf("%d %d", &nb, &ni); for(i = 1; i <= nb; i++){G[i].clear(); color[i] = 0;} for(i = 0; i < ni; i++){ scanf("%d %d", &x, &y); G[x].push_back(y); G[y].push_back(x); } for(i = 1; i <= nb; i++){ if(!color[i]){ if(bfs(i))continue; else break; } } printf("Scenario #%d:\n", qq); if(i > nb)printf("No suspicious bugs found!\n"); else printf("Suspicious bugs found!\n"); } return 0; }
06f7d6d8f64c0f625f62c7f09c353c81c6d8bc4e
f1206c4bfb8def5cda85c384bd48f9720a9aaf7a
/cpp/day2.cpp
e702dcfb785dea0da1ed7ee25a85b29886a39907
[]
no_license
troutstick/adventofcode2020
0367054978e9079305724b1242adf78502d9cde9
d1eaece540b07aefb9c39becd0afdc700773012a
refs/heads/main
2023-07-09T15:40:32.043353
2021-08-17T06:57:14
2021-08-17T06:57:14
317,465,018
0
0
null
null
null
null
UTF-8
C++
false
false
1,178
cpp
day2.cpp
#include "day2.h" #include "utils.h" #include <stdexcept> void day2(vector<string> *input) { int num_valid1 = 0; int num_valid2 = 0; string delimiter = ": "; for (string s : *input) { vector<string> *splits = split(s, delimiter); if (splits->size() != 2) { throw runtime_error("splitter should have split into two strings"); } string pw_policy = (*splits)[0]; vector<string> *policies = split(pw_policy, " "); vector<string> *min_and_max = split((*policies)[0], "-"); char ch = (*policies)[1].at(0); int min = stoi((*min_and_max)[0]); int max = stoi((*min_and_max)[1]); string pw = (*splits)[1]; int ch_count = count(pw.begin(), pw.end(), ch); if (min <= ch_count && max >= ch_count) { num_valid1++; } if ((pw.at(min-1) == ch) != (pw.at(max-1) == ch)) { num_valid2++; } delete splits; delete policies; delete min_and_max; } cout << "The answer for Day 2 Part 1 is " << num_valid1 << endl; cout << "The answer for Day 2 Part 2 is " << num_valid2 << endl; }
81fcaf0869e1294d893333e6114693e133d21693
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/enterprise/reporting/real_time_report_controller_android.cc
a216cc3cb88ee1d55788d04676d3e02e046e0733
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
1,390
cc
real_time_report_controller_android.cc
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/enterprise/reporting/real_time_report_controller_android.h" #include "chrome/browser/enterprise/reporting/legacy_tech/legacy_tech_report_generator.h" #include "chrome/browser/enterprise/reporting/legacy_tech/legacy_tech_service.h" #include "components/enterprise/browser/reporting/real_time_report_type.h" namespace enterprise_reporting { RealTimeReportControllerAndroid::RealTimeReportControllerAndroid() { LegacyTechServiceFactory::GetInstance()->SetReportTrigger( base::BindRepeating(&RealTimeReportControllerAndroid::TriggerLegacyTech, weak_factory_.GetWeakPtr())); } RealTimeReportControllerAndroid::~RealTimeReportControllerAndroid() = default; void RealTimeReportControllerAndroid::StartWatchingExtensionRequestIfNeeded() { // No-op because extensions are not supported on Android. } void RealTimeReportControllerAndroid::StopWatchingExtensionRequest() { // No-op because extensions are not supported on Android. } void RealTimeReportControllerAndroid::TriggerLegacyTech( const LegacyTechReportGenerator::LegacyTechData& data) { if (trigger_callback_) { trigger_callback_.Run(RealTimeReportType::kLegacyTech, data); } } } // namespace enterprise_reporting
44afff4f2beba8db98129820b22bb05f6fd97295
b20b8063863b692b79ef9ac7d7af3b35328c6a4b
/src/remote/pv/codec.h
32e864106fa60a7bce48d1b9541aa5079723f760
[ "MIT" ]
permissive
epics-base/pvAccessCPP
1cf5881577a57c88c980fb5c90831b8f55deab28
581d100a029e6f68f3c1830b90509b3ee5ebd7a0
refs/heads/master
2023-03-20T01:10:11.057042
2023-03-10T11:02:30
2023-03-10T11:46:32
29,925,701
11
24
NOASSERTION
2023-03-10T11:46:33
2015-01-27T17:30:29
C++
UTF-8
C++
false
false
18,438
h
codec.h
/** * Copyright - See the COPYRIGHT that is included with this distribution. * pvAccessCPP is distributed subject to a Software License Agreement found * in file LICENSE that is included with this distribution. */ #ifndef CODEC_H_ #define CODEC_H_ #include <set> #include <map> #include <deque> #include <shareLib.h> #include <osiSock.h> #include <epicsTime.h> #include <epicsThread.h> #include <epicsVersion.h> #include <epicsAtomic.h> #include <pv/byteBuffer.h> #include <pv/pvType.h> #include <pv/lock.h> #include <pv/timer.h> #include <pv/event.h> #include <pv/likely.h> #include <pv/pvaConstants.h> #include <pv/remote.h> #include <pv/security.h> #include <pv/transportRegistry.h> #include <pv/introspectionRegistry.h> #include <pv/inetAddressUtil.h> /* C++11 keywords @code struct Base { virtual void foo(); }; struct Class : public Base { virtual void foo() OVERRIDE FINAL FINAL; }; @endcode */ #ifndef FINAL # if __cplusplus>=201103L # define FINAL final # else # define FINAL # endif #endif #ifndef OVERRIDE # if __cplusplus>=201103L # define OVERRIDE override # else # define OVERRIDE # endif #endif namespace epics { namespace pvAccess { class ServerChannel; namespace detail { template<typename T> class AtomicValue { T val; public: AtomicValue() :val(0) {} inline T getAndSet(T newval) { int oldval; // epicsAtomic doesn't have unconditional swap do { oldval = epics::atomic::get(val); } while(epics::atomic::compareAndSwap(val, oldval, newval)!=oldval); return oldval; } inline T get() { return epics::atomic::get(val); } }; // treat bool as int template<> class AtomicValue<bool> { AtomicValue<int> realval; public: inline bool getAndSet(bool newval) { return this->realval.getAndSet(newval?1:0)!=0; } inline bool get() { return !!this->realval.get(); } }; class io_exception: public std::runtime_error { public: explicit io_exception(const std::string &s): std::runtime_error(s) {} }; class invalid_data_stream_exception: public std::runtime_error { public: explicit invalid_data_stream_exception( const std::string &s): std::runtime_error(s) {} }; class connection_closed_exception: public std::runtime_error { public: explicit connection_closed_exception(const std::string &s): std::runtime_error(s) {} }; enum ReadMode { NORMAL, SPLIT, SEGMENTED }; enum WriteMode { PROCESS_SEND_QUEUE, WAIT_FOR_READY_SIGNAL }; class epicsShareClass AbstractCodec : public TransportSendControl, public Transport { public: static const std::size_t MAX_MESSAGE_PROCESS; static const std::size_t MAX_MESSAGE_SEND; static const std::size_t MAX_ENSURE_SIZE; static const std::size_t MAX_ENSURE_DATA_SIZE; static const std::size_t MAX_ENSURE_BUFFER_SIZE; static const std::size_t MAX_ENSURE_DATA_BUFFER_SIZE; AbstractCodec( bool serverFlag, size_t sendBufferSize, size_t receiveBufferSize, int32_t socketSendBufferSize, bool blockingProcessQueue); virtual void processControlMessage() = 0; virtual void processApplicationMessage() = 0; virtual const osiSockAddr* getLastReadBufferSocketAddress() = 0; virtual void invalidDataStreamHandler() = 0; virtual void readPollOne()=0; virtual void writePollOne() = 0; virtual void scheduleSend() = 0; virtual void sendCompleted() = 0; virtual bool terminated() = 0; virtual int write(epics::pvData::ByteBuffer* src) = 0; virtual int read(epics::pvData::ByteBuffer* dst) = 0; virtual bool isOpen() = 0; virtual ~AbstractCodec() { } virtual void ensureData(std::size_t size) OVERRIDE FINAL; virtual void startMessage( epics::pvData::int8 command, std::size_t ensureCapacity = 0, epics::pvData::int32 payloadSize = 0) OVERRIDE FINAL; void putControlMessage( epics::pvData::int8 command, epics::pvData::int32 data); virtual void endMessage() OVERRIDE FINAL; virtual void ensureBuffer(std::size_t size) OVERRIDE FINAL; virtual void flushSerializeBuffer() OVERRIDE FINAL; virtual void flush(bool lastMessageCompleted) OVERRIDE FINAL; void processWrite(); void processRead(); void processSendQueue(); virtual void enqueueSendRequest(TransportSender::shared_pointer const & sender) OVERRIDE FINAL; void enqueueSendRequest(TransportSender::shared_pointer const & sender, std::size_t requiredBufferSize); void setSenderThread(); virtual void setRecipient(osiSockAddr const & sendTo) OVERRIDE FINAL; virtual void setByteOrder(int byteOrder) OVERRIDE FINAL; static std::size_t alignedValue(std::size_t value, std::size_t alignment); virtual bool directSerialize( epics::pvData::ByteBuffer * /*existingBuffer*/, const char* /*toSerialize*/, std::size_t /*elementCount*/, std::size_t /*elementSize*/) OVERRIDE; virtual bool directDeserialize(epics::pvData::ByteBuffer * /*existingBuffer*/, char* /*deserializeTo*/, std::size_t /*elementCount*/, std::size_t /*elementSize*/) OVERRIDE; bool sendQueueEmpty() const { return _sendQueue.empty(); } epics::pvData::int8 getRevision() const { epicsGuard<epicsMutex> G(_mutex); int8_t myver = _clientServerFlag ? PVA_SERVER_PROTOCOL_REVISION : PVA_CLIENT_PROTOCOL_REVISION; return myver < _version ? myver : _version; } protected: virtual void sendBufferFull(int tries) = 0; void send(epics::pvData::ByteBuffer *buffer); void flushSendBuffer(); virtual void setRxTimeout(bool ena) {} ReadMode _readMode; int8_t _version; int8_t _flags; int8_t _command; int32_t _payloadSize; // TODO why not size_t? epics::pvData::int32 _remoteTransportSocketReceiveBufferSize; //TODO initialize union osiSockAddr _sendTo; epicsThreadId _senderThread; WriteMode _writeMode; bool _writeOpReady; epics::pvData::ByteBuffer _socketBuffer; epics::pvData::ByteBuffer _sendBuffer; fair_queue<TransportSender> _sendQueue; private: void processHeader(); void processReadNormal(); void postProcessApplicationMessage(); void processReadSegmented(); bool readToBuffer(std::size_t requiredBytes, bool persistent); void endMessage(bool hasMoreSegments); void processSender( epics::pvAccess::TransportSender::shared_pointer const & sender); std::size_t _storedPayloadSize; std::size_t _storedPosition; std::size_t _storedLimit; std::size_t _startPosition; const std::size_t _maxSendPayloadSize; std::size_t _lastMessageStartPosition; std::size_t _lastSegmentedMessageType; int8_t _lastSegmentedMessageCommand; std::size_t _nextMessagePayloadOffset; epics::pvData::int8 _byteOrderFlag; protected: const epics::pvData::int8 _clientServerFlag; private: public: mutable epics::pvData::Mutex _mutex; }; class BlockingTCPTransportCodec: public AbstractCodec, public AuthenticationPluginControl, public std::tr1::enable_shared_from_this<BlockingTCPTransportCodec> { public: POINTER_DEFINITIONS(BlockingTCPTransportCodec); static size_t num_instances; BlockingTCPTransportCodec( bool serverFlag, Context::shared_pointer const & context, SOCKET channel, ResponseHandler::shared_pointer const & responseHandler, size_t sendBufferSize, size_t receiveBufferSize, epics::pvData::int16 priority); virtual ~BlockingTCPTransportCodec(); virtual void readPollOne() OVERRIDE FINAL; virtual void writePollOne() OVERRIDE FINAL; virtual void scheduleSend() OVERRIDE FINAL {} virtual void sendCompleted() OVERRIDE FINAL {} virtual void close() OVERRIDE FINAL; virtual void waitJoin() OVERRIDE FINAL; virtual bool terminated() OVERRIDE FINAL; virtual bool isOpen() OVERRIDE FINAL; virtual void start(); virtual int read(epics::pvData::ByteBuffer* dst) OVERRIDE FINAL; virtual int write(epics::pvData::ByteBuffer* src) OVERRIDE FINAL; virtual const osiSockAddr* getLastReadBufferSocketAddress() OVERRIDE FINAL { return &_socketAddress; } virtual void invalidDataStreamHandler() OVERRIDE FINAL; virtual std::string getType() const OVERRIDE FINAL { return std::string("tcp"); } virtual void processControlMessage() OVERRIDE FINAL { if (_command == CMD_SET_ENDIANESS) { // check 7-th bit setByteOrder(_flags < 0 ? EPICS_ENDIAN_BIG : EPICS_ENDIAN_LITTLE); } } virtual void processApplicationMessage() OVERRIDE FINAL { _responseHandler->handleResponse(&_socketAddress, shared_from_this(), _version, _command, _payloadSize, &_socketBuffer); } virtual const osiSockAddr& getRemoteAddress() const OVERRIDE FINAL { return _socketAddress; } virtual const std::string& getRemoteName() const OVERRIDE FINAL { return _socketName; } virtual std::size_t getReceiveBufferSize() const OVERRIDE FINAL { return _socketBuffer.getSize(); } virtual epics::pvData::int16 getPriority() const OVERRIDE FINAL { return _priority; } virtual void setRemoteTransportReceiveBufferSize( std::size_t remoteTransportReceiveBufferSize) OVERRIDE FINAL { _remoteTransportReceiveBufferSize = remoteTransportReceiveBufferSize; } virtual void setRemoteTransportSocketReceiveBufferSize( std::size_t socketReceiveBufferSize) OVERRIDE FINAL { _remoteTransportSocketReceiveBufferSize = socketReceiveBufferSize; } std::tr1::shared_ptr<const epics::pvData::Field> virtual cachedDeserialize(epics::pvData::ByteBuffer* buffer) OVERRIDE FINAL { return _incomingIR.deserialize(buffer, this); } virtual void cachedSerialize( const std::tr1::shared_ptr<const epics::pvData::Field>& field, epics::pvData::ByteBuffer* buffer) OVERRIDE FINAL { _outgoingIR.serialize(field, buffer, this); } virtual void flushSendQueue() OVERRIDE FINAL { } virtual bool isClosed() OVERRIDE FINAL { return !isOpen(); } void activate() { Transport::shared_pointer thisSharedPtr = shared_from_this(); _context->getTransportRegistry()->install(thisSharedPtr); start(); } virtual bool verify(epics::pvData::int32 timeoutMs) OVERRIDE; virtual void verified(epics::pvData::Status const & status) OVERRIDE; virtual void authNZMessage(epics::pvData::PVStructure::shared_pointer const & data) OVERRIDE FINAL; virtual void sendSecurityPluginMessage(epics::pvData::PVStructure::const_shared_pointer const & data) OVERRIDE FINAL; private: void receiveThread(); void sendThread(); protected: virtual void setRxTimeout(bool ena) OVERRIDE FINAL; virtual void sendBufferFull(int tries) OVERRIDE FINAL; /** * Called from close(). after start of shutdown (isOpen()==false) * but before worker thread shutdown. */ virtual void internalClose(); private: AtomicValue<bool> _isOpen; epics::pvData::Thread _readThread, _sendThread; const SOCKET _channel; protected: osiSockAddr _socketAddress; std::string _socketName; protected: Context::shared_pointer _context; IntrospectionRegistry _incomingIR; IntrospectionRegistry _outgoingIR; // active authentication exchange, if any std::string _authSessionName; AuthenticationSession::shared_pointer _authSession; public: // final info, after authentication complete. PeerInfo::const_shared_pointer _peerInfo; private: ResponseHandler::shared_pointer _responseHandler; size_t _remoteTransportReceiveBufferSize; epics::pvData::int16 _priority; protected: bool _verified; epics::pvData::Event _verifiedEvent; }; class BlockingServerTCPTransportCodec : public BlockingTCPTransportCodec, public TransportSender { public: POINTER_DEFINITIONS(BlockingServerTCPTransportCodec); protected: BlockingServerTCPTransportCodec( Context::shared_pointer const & context, SOCKET channel, ResponseHandler::shared_pointer const & responseHandler, int32_t sendBufferSize, int32_t receiveBufferSize ); public: static shared_pointer create( Context::shared_pointer const & context, SOCKET channel, ResponseHandler::shared_pointer const & responseHandler, int sendBufferSize, int receiveBufferSize) { shared_pointer thisPointer( new BlockingServerTCPTransportCodec( context, channel, responseHandler, sendBufferSize, receiveBufferSize) ); thisPointer->activate(); return thisPointer; } public: virtual bool acquire(std::tr1::shared_ptr<ClientChannelImpl> const & /*client*/) OVERRIDE FINAL { return false; } virtual void release(pvAccessID /*clientId*/) OVERRIDE FINAL {} pvAccessID preallocateChannelSID(); void depreallocateChannelSID(pvAccessID /*sid*/) {} void registerChannel( pvAccessID sid, std::tr1::shared_ptr<ServerChannel> const & channel); void unregisterChannel(pvAccessID sid); std::tr1::shared_ptr<ServerChannel> getChannel(pvAccessID sid); void getChannels(std::vector<std::tr1::shared_ptr<ServerChannel> >& channels) const; size_t getChannelCount() const; virtual bool verify(epics::pvData::int32 timeoutMs) OVERRIDE FINAL { TransportSender::shared_pointer transportSender = std::tr1::dynamic_pointer_cast<TransportSender>(shared_from_this()); enqueueSendRequest(transportSender); bool verifiedStatus = BlockingTCPTransportCodec::verify(timeoutMs); enqueueSendRequest(transportSender); return verifiedStatus; } virtual void verified(epics::pvData::Status const & status) OVERRIDE FINAL { { epicsGuard<epicsMutex> G(_mutex); _verificationStatus = status; } BlockingTCPTransportCodec::verified(status); } void authNZInitialize(const std::string& securityPluginName, const epics::pvData::PVStructure::shared_pointer& data); virtual void authenticationCompleted(epics::pvData::Status const & status, const std::tr1::shared_ptr<PeerInfo>& peer) OVERRIDE FINAL; virtual void send(epics::pvData::ByteBuffer* buffer, TransportSendControl* control) OVERRIDE FINAL; virtual ~BlockingServerTCPTransportCodec() OVERRIDE FINAL; protected: void destroyAllChannels(); virtual void internalClose() OVERRIDE FINAL; private: /** * Last SID cache. */ pvAccessID _lastChannelSID; typedef std::map<pvAccessID, std::tr1::shared_ptr<ServerChannel> > _channels_t; /** * Channel table (SID -> channel mapping). */ _channels_t _channels; mutable epics::pvData::Mutex _channelsMutex; epics::pvData::Status _verificationStatus; bool _verifyOrVerified; std::vector<std::string> advertisedAuthPlugins; }; class BlockingClientTCPTransportCodec : public BlockingTCPTransportCodec, public TransportSender, public epics::pvData::TimerCallback { public: POINTER_DEFINITIONS(BlockingClientTCPTransportCodec); protected: BlockingClientTCPTransportCodec( Context::shared_pointer const & context, SOCKET channel, ResponseHandler::shared_pointer const & responseHandler, int32_t sendBufferSize, int32_t receiveBufferSize, std::tr1::shared_ptr<ClientChannelImpl> const & client, epics::pvData::int8 remoteTransportRevision, float heartbeatInterval, int16_t priority); public: static shared_pointer create( Context::shared_pointer const & context, SOCKET channel, ResponseHandler::shared_pointer const & responseHandler, int32_t sendBufferSize, int32_t receiveBufferSize, std::tr1::shared_ptr<ClientChannelImpl> const & client, int8_t remoteTransportRevision, float heartbeatInterval, int16_t priority ) { shared_pointer thisPointer( new BlockingClientTCPTransportCodec( context, channel, responseHandler, sendBufferSize, receiveBufferSize, client, remoteTransportRevision, heartbeatInterval, priority) ); thisPointer->activate(); return thisPointer; } public: virtual void start() OVERRIDE FINAL; virtual ~BlockingClientTCPTransportCodec() OVERRIDE FINAL; virtual void timerStopped() OVERRIDE FINAL { // noop } virtual void callback() OVERRIDE FINAL; virtual bool acquire(std::tr1::shared_ptr<ClientChannelImpl> const & client) OVERRIDE FINAL; virtual void release(pvAccessID clientId) OVERRIDE FINAL; virtual void send(epics::pvData::ByteBuffer* buffer, TransportSendControl* control) OVERRIDE FINAL; void authNZInitialize(const std::vector<std::string>& offeredSecurityPlugins); virtual void authenticationCompleted(epics::pvData::Status const & status, const std::tr1::shared_ptr<PeerInfo>& peer) OVERRIDE FINAL; virtual void verified(epics::pvData::Status const & status) OVERRIDE FINAL; protected: virtual void internalClose() OVERRIDE FINAL; private: /** * Owners (users) of the transport. */ // TODO consider using TR1 hash map typedef std::map<pvAccessID, std::tr1::weak_ptr<ClientChannelImpl> > TransportClientMap_t; TransportClientMap_t _owners; /** * Connection timeout (no-traffic) flag. */ const double _connectionTimeout; bool _verifyOrEcho; // are we queued to send verify or echo? bool sendQueued; /** * Notifies clients about disconnect. */ void closedNotifyClients(); }; } } } #endif /* CODEC_H_ */
0942637aa3e9b67bea9ab3eba561782d2ccbd68c
fd7552a7fa55d2cc0d9b50f63e31ee03a11c07e2
/cppForLeetcode/822_CardFlippingGame.cpp
8e049f5cb4c722e122a4a801e0d83b38416e9fe9
[]
no_license
hanrick2000/leetCode-5
0828ad9655034b5fa90475c17f78d80ebe01d819
58ab36bb9b568c25ceafd5e3c2acae8057e3df0c
refs/heads/master
2020-12-10T16:18:10.213237
2019-06-05T09:05:49
2019-06-05T09:05:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,798
cpp
822_CardFlippingGame.cpp
#include <vector> #include <unordered_map> #include <iostream> using namespace std; class Solution { public: int flipgame(vector<int>& fronts, vector<int>& backs) { unordered_map<int, vector<int>> counter; int count = 0; for(int i : fronts) { counter[i].push_back(count); count += 1; } int result = 0x7fffffff; int front; int back; for(int i = 0; i < fronts.size(); ++i) { front = fronts[i]; back = backs[i]; if(front != back) { if (counter.count(back) == 0) { if (back < result) { result = back; } } bool same = false; for(int t : counter[front]) { if (t != i && fronts[t] == front && backs[t] == front) { same = true; } } if(!same) { if (front < result) { result = front; } } } } if(result == 0x7fffffff) return 0; return result; } }; int main(void) { vector<int> input0 = {1,2,4,-1,-1}; vector<int> input1 = {1,-1,4,1,1}; // vector<int> input0 = {1,2}; // vector<int> input1 = {1,1}; // vector<int> input0 = {1,1}; // vector<int> input1 = {1,2}; // vector<int> input0 = {1,1}; // vector<int> input1 = {2,2}; Solution sol; cout << sol.flipgame(input0,input1) << endl; }
b5acb15d45a3d00bbae418624871fa28d2d69220
0ea45528e6d305075be7794a3d6febd81ee7ba86
/src/PrimeFacorization.h
43b2c18d967e9f7b06b87e47dc964a4bebef469d
[]
no_license
mamunul/algorithm
b705d74ba6a1954e48c751bcf7f54bf21ddd18e0
8cb1492e86c62e0b9765eefcc6664d9797f06943
refs/heads/master
2021-01-17T09:25:05.428869
2016-04-05T19:24:10
2016-04-05T19:24:10
39,956,386
0
0
null
null
null
null
UTF-8
C++
false
false
558
h
PrimeFacorization.h
/* * PrimeFacorization.h * * Created on: Apr 3, 2016 * Author: Mamunul */ #ifndef PRIMEFACORIZATION_H_ #define PRIMEFACORIZATION_H_ #include <algorithm> #include <deque> #include <iostream> #include <queue> #include <stack> #include <string> #include <utility> #include <vector> #include <deque> #include <set> #include "Power.h" using namespace std; namespace src { class PrimeFacorization { public: PrimeFacorization(); virtual ~PrimeFacorization(); void primeFactors(int n); }; } /* namespace src */ #endif /* PRIMEFACORIZATION_H_ */
27ff5293f2c05ad77b4296c2035f6ef6eeda8b2a
553cd650a0af193c83866deab14a922ecd1d3613
/src/wallet/include/wallet/app/tx_controller.h
2b92fa062362e6fd06765fce76d184b15743614a
[ "MIT" ]
permissive
edwardstock/mintex
9251703ef5b5e4dc11a6baa2974fed2f972f414b
edb9a5cef4fa145921a5ceac6d981e423f893f86
refs/heads/master
2020-05-17T03:16:57.538043
2019-07-25T22:17:34
2019-07-25T22:17:34
183,473,512
1
0
null
null
null
null
UTF-8
C++
false
false
1,237
h
tx_controller.h
/*! * mintex. * app_tx * * \date 02.05.19 * \author Eduard Maximovich (edward.vstock@gmail.com) * \link https://github.com/edwardstock */ #ifndef MINTEX_TX_CONTROLLER_H #define MINTEX_TX_CONTROLLER_H #include <utility> #include "wallet/gate/repository.h" #include "wallet/app/app.h" namespace wallet { namespace cmd { class tx_controller : public wallet::command_controller { public: tx_controller(const std::shared_ptr<app> &app); std::string usage() const override; std::string get_command_name() const override; std::unordered_map<std::string, std::string> get_actions_descriptions() const override; bool before_action(const std::string &action, int argc, char **argv) override; ACTION_DECLARE(send); ACTION_DECLARE(buy); ACTION_DECLARE(sell); ACTION_DECLARE(delegate); ACTION_DECLARE(unbond); ACTION_DECLARE(autodelegate); // ACTION_DECLARE(dc); // ACTION_DECLARE(candidate); private: std::unique_ptr<wallet::secret_storage> m_storage; static void print_error_tx(const httb::response &resp, const wallet::gate::error_result &error); static void print_success_tx(const minter::hash_t &hash); }; } // cmd } // wallet #endif //MINTEX_TX_CONTROLLER_H
1470fe27e6a2544c5ef4e7136d3f558befd23772
b7140f23a9941401f1a120894ee36b1b2dd6417a
/pgHelpers.cpp
c6704700a5ec0c2f64e8a918c0aa6b57052ea86b
[]
no_license
Wire-Flies/DataDrawerCXX
4f575f4974ac2d1eed0f46863c98711ecb4ab249
9472eea38a35166f8502c78c5aff0da856abe442
refs/heads/master
2020-03-08T11:26:12.382305
2018-04-04T17:42:59
2018-04-04T17:42:59
128,097,510
0
0
null
null
null
null
UTF-8
C++
false
false
1,948
cpp
pgHelpers.cpp
#include "pgHelpers.hpp" #include <iostream> pgconn::pgconn(){ conn = new pqxx::connection( "user=wireflies " "host=localhost " "password=wireflies " "dbname=wireflies"); } pgconn::~pgconn(){ delete conn; } std::map<unsigned long long, flight> pgconn::find_flights(std::string from, std::string to){ pqxx::work work(*conn); std::string query = "SELECT flights.flight_id, snapshot_id, longitude, latitude FROM flights JOIN flight_data ON flights.flight_id = flight_data.flight_id WHERE schd_from LIKE '" + from + "' AND (real_to LIKE '" + to + "' OR (real_to IS NULL AND schd_to LIKE '" + to + "')) ORDER BY snapshot_id;"; pqxx::result r = work.exec(query); std::map<unsigned long long, flight> flights; for(int i = 0; i < r.size(); i++){ auto l = r[i]; unsigned long long id = l[0].as<unsigned long long>(0); unsigned long long snapshot_id = l[1].as<unsigned long long>(0); double longitude = l[2].as<double>(0); double latitude = l[3].as<double>(0); flights[id].positions.push_back({snapshot_id, longitude, latitude}); } return flights; } std::map<unsigned long long, flight> pgconn::find_all(){ pqxx::work work(*conn); std::string query = "SELECT flights.flight_id, snapshot_id, longitude, latitude FROM flights JOIN flight_data ON flights.flight_id = flight_data.flight_id ORDER BY snapshot_id LIMIT 4000000;"; pqxx::result r = work.exec(query); std::map<unsigned long long, flight> flights; for(int i = 0; i < r.size(); i++){ auto l = r[i]; unsigned long long id = l[0].as<unsigned long long>(0); unsigned long long snapshot_id = l[1].as<unsigned long long>(0); double longitude = l[2].as<double>(0); double latitude = l[3].as<double>(0); flights[id].positions.push_back({snapshot_id, longitude, latitude}); } return flights; }
d16d7ea909d7efb5dbed342f10406d2224182501
e7e497b20442a4220296dea1550091a457df5a38
/main_project/talk/OnlineBitmap/src/OnlineBitmapManagerI.h
f5a407ef4817fc43e5ca19f02fe400801aba3aad
[]
no_license
gunner14/old_rr_code
cf17a2dedf8dfcdcf441d49139adaadc770c0eea
bb047dc88fa7243ded61d840af0f8bad22d68dee
refs/heads/master
2021-01-17T18:23:28.154228
2013-12-02T23:45:33
2013-12-02T23:45:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,862
h
OnlineBitmapManagerI.h
#ifndef __ONLINEBITMAPMANAGER_H__ #define __ONLINEBITMAPMANAGER_H__ #include <string> #include <map> #include <vector> #include <Ice/Ice.h> #include "Singleton.h" #include "TaskManager.h" #include "OnlineBitmap.h" #include "OnlineCenter.h" #include "TalkCommon.h" #include "string.h" namespace talk{ namespace onlinebitmap{ using namespace std; using namespace MyUtil; using namespace com::xiaonei::talk::common; using namespace ::talk::online; static int BITMAP_SIZE = 0x7fffffff; class OnlineBitmapManagerI : public OnlineBitmapManager, public Singleton<OnlineBitmapManagerI>{ public: OnlineBitmapManagerI() : bitmap_(NULL) {} virtual void setUserStatByOnlineType(const UserOnlineTypePtr& onlineTypePtr, const Ice::Current& = Ice::Current()); virtual void load(const UserOnlineTypeSeq& onlineTypeSeq, const Ice::Current& = Ice::Current()); virtual void Reload(const Ice::Current& = Ice::Current()); virtual void SyncBitmap(const SyncBitmapDataPtr & sync_data, const Ice::Current& = Ice::Current()); //获取用户在线状态 virtual UserOnlineTypePtr getUserStat(Ice::Int userId, const Ice::Current& = Ice::Current()); virtual UserOnlineTypeSeq getUserStatByIdSeq(const MyUtil::IntSeq& ids, const Ice::Current& = Ice::Current()); //获取用户在线类型 virtual UserOnlineTypePtr getUserType(Ice::Int userId, const Ice::Current& = Ice::Current()); virtual UserOnlineTypeSeq getUserTypeByIdSeq(const MyUtil::IntSeq& ids, const Ice::Current& = Ice::Current()); //获取在线用户 virtual UserOnlineTypeSeq getOnlineUsers(const MyUtil::IntSeq& ids, const Ice::Current& = Ice::Current()); //获取在线用户数 virtual Ice::Int getOnlineCount(const MyUtil::IntSeq& ids, const Ice::Current& = Ice::Current()); void init(); private: char* bitmap_; }; }; }; #endif
abee1673943ff1c8b554bbcd432c3166ce1c6eab
c3b19e273e4bdea1b526c81351ca9ec25d84d74b
/heuristics/LineData.hpp
563111562d590ddb91bc742a355110ff1a793346
[]
no_license
victorwatrelos/gomoku
7d2caa0983f10d3645524657ea1f31bafa20fd03
0b0e1a327d4b9d952396ef8f565e8d02b3a32a03
refs/heads/master
2023-09-03T19:36:15.253934
2017-02-15T19:36:43
2017-02-15T19:36:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
484
hpp
LineData.hpp
#ifndef LINEDATA # define LINEDATA # include "../Board.hpp" # include "../utilities/BoardUtilities.hpp" # include "../utilities/AbstractLineData.hpp" class LineData : public AbstractLineData { public: LineData(void); LineData(const LineData &obj); LineData &operator=(const LineData &p); virtual ~LineData(void); virtual void init(const Board::Point &color, const Board *b); protected: void _endOfSeries(void); private: int _getStoneScore(void); }; #endif
34f78c98f745840f8aa2008e9bcb353cbad48be2
1e867f11e7974fc57b03d06646a7918a064fb052
/Almost all Divisors.cpp
45a7d590d1962541744698a98db54c9a529f7a26
[]
no_license
Wahed08/ACM-Problem-Solving
f4d6b3615d0f8e935583028b3642a283c502d2b1
d7bc101b51699bc165202f201bcc791687ce4fe6
refs/heads/master
2023-04-17T19:46:09.620633
2023-04-07T05:53:40
2023-04-07T05:53:40
188,804,904
2
0
null
null
null
null
UTF-8
C++
false
false
1,215
cpp
Almost all Divisors.cpp
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0),cout.tie(0); int t; cin>>t; while(t--) { int k; cin>>k; long long int arr[k],arr2[k]; vector<long long>vec; for(int i=0; i<k; i++) { cin>>arr[i]; } sort(arr,arr+k); long long int val=arr[0]*arr[k-1]; long long int cnt=0,j=0; for(int i=2; i<=sqrt(val); i++) { if(val%i==0) { if(val/i==i){ vec.push_back(i); //j++; } else { vec.push_back(i); //j++; vec.push_back(val/i); //j++; } } } //sort(arr2,arr2+k); sort(vec.begin(),vec.end()); for(int i=0; i<vec.size(); i++) { if(arr[i]==vec[i]) { cnt++; } } if(cnt==vec.size()) { cout<<val<<endl; } else cout<<-1<<endl; } return 0; }
139407f31d2d10bbe0362eb69914ab83bd775197
b30495fd5c72b70acd70f1b452b913664d1f6735
/src/Steps.h
e6b42a9a4137b6cd3d1c0716c0d65248b53d1e9b
[]
no_license
Sandy4321/FusedLasso-1
dde161ed3dc97d81db927af4aa6b8e63735e42bf
c360f7ce6acef8774dac2b6c6e8bd00069dc6380
refs/heads/master
2020-07-10T20:09:17.983761
2014-05-12T00:00:00
2014-05-12T00:00:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,255
h
Steps.h
#ifndef _STEPS_H_ #define _STEPS_H_ #include <utility> #include <vector> using namespace std; /* * Given the current betas, it finds the root of the function */ class Steps { inline static bool updateBeta(vector<double>& beta, const int pos, double& deriv, const double& slope, const double& zeroStepSize, const vector<int>& stepIdx, const vector<double>& stepSize); public: // most important application -> find the root static void findRoot(vector<double> &beta, double derivQuad, const double slope, const int pos, const double zeroStepSize, const vector<int>& stepIdx, const vector<double>& stepSize); static void findRootL1(vector<double> &beta, double derivQuad, const double hessian, const int pos, const double zeroStepSize, const vector<int>& stepIdx, const vector<double>& stepSize); static void findRootL2(vector<double> &beta, double derivQuad, const double hessian, const int pos, const double zeroStepSize, const vector<int>& l2Idx, const vector<double>& l2Mult); static void findRootHuber(vector<double> &beta, double derivQuad, const double hessian, const int pos, const double zeroStepSize, const vector<int>& huberIdx, const vector<double>& huberMult, double huberParam); }; #endif // _STEPS_H_
823c1c2ea1e427984eb6b9ba02df0e90b6b995f2
5776f9c5bfd8b9167b36376499f3397a57dce320
/DirectX11Engine/GfxUtil.h
39cb9c0268f96f0329cb94aefc00d206d5e5f2b6
[]
no_license
mister51213/DirectX11Engine
b92d40c1f13de3493c9c5054fb5fd064546d601c
a3b233cf5fababc5cd6fd794aefc20e05c5eec30
refs/heads/master
2021-09-14T12:14:46.852460
2018-02-22T13:40:57
2018-02-22T13:40:57
108,654,528
2
2
null
2017-12-24T03:21:10
2017-10-28T14:10:09
C++
UTF-8
C++
false
false
7,490
h
GfxUtil.h
//////////////////////////////////////////// // Filename: GfxUtil.h // Contains useful functions and operator overloads for working with Graphics /////////////////////////////////////////////// #pragma once #include <Windows.h> #define _XM_NO_INTRINSICS_ //#include <directxmath.h> //#include <stdlib.h> #include <d3d11.h> #include <vector> #include <string> #include "Texture.h" #include "RenderTextureClass.h" #include "GlobalIncludes.h" //#include <memory> //#include <wrl/client.h> //using namespace Microsoft::WRL; //using namespace DirectX; //using namespace std; namespace GfxUtil { constexpr float DEGTORAD = XM_PI / 180.f; // TEXT RELATED static wchar_t* charToWChar(const char* text) { const size_t size = strlen(text) +1; wchar_t* wText = new wchar_t[size]; mbstowcs(wText, text, size); return wText; } static wchar_t* charToWChar_S(const char* text) { size_t origsize = strlen(text) + 1; const size_t newsize = 100; size_t convertedChars = 0; wchar_t wcstring[newsize]; mbstowcs_s(&convertedChars, wcstring, origsize, text, _TRUNCATE); wcscat_s(wcstring, L" (wchar_t *)"); return wcstring; } // GPU PIPELINE RELATED // // VS CBUFFER TYPES struct MatrixBufferType { XMMATRIX world; XMMATRIX view; XMMATRIX projection; MatrixBufferType() { XMMATRIX world = XMMatrixIdentity(); XMMATRIX view = XMMatrixIdentity(); XMMATRIX projection = XMMatrixIdentity(); } MatrixBufferType(const XMMATRIX& wrld, const XMMATRIX& vw, const XMMATRIX& proj) { world = wrld; view = vw; projection = proj; } }; struct LightDataTemplate_VS { XMMATRIX viewMatrix; XMMATRIX projectionMatrix; XMFLOAT3 position; float padding; LightDataTemplate_VS() { viewMatrix = XMMatrixIdentity(); projectionMatrix = XMMatrixIdentity(); position = XMFLOAT3(0,0,0); padding = 0; } LightDataTemplate_VS(const XMMATRIX& view, const XMMATRIX& projection,const XMFLOAT3& pos) { viewMatrix = view; projectionMatrix = projection; position = pos; padding = 0; } LightDataTemplate_VS(const LightDataTemplate_VS& otherBuff) { viewMatrix = otherBuff.viewMatrix; projectionMatrix = otherBuff.projectionMatrix; position = otherBuff.position; } }; // PS CBUFFER TYPES struct LightDataTemplate_PS { int type; XMFLOAT3 padding; XMFLOAT4 diffuseColor; XMFLOAT3 direction; //(lookat?) //@TODO pass from VS BUFFER? float specularPower; XMFLOAT4 specularColor; LightDataTemplate_PS() { int type = 0; XMFLOAT3 padding = XMFLOAT3(); XMFLOAT4 diffuseColor = XMFLOAT4(); XMFLOAT3 direction = XMFLOAT3(); //(lookat?) //@TODO pass from VS BUFFER? float specularPower = 0; XMFLOAT4 specularColor = XMFLOAT4(); } LightDataTemplate_PS(const LightDataTemplate_PS& otherBuff) { type = otherBuff.type; diffuseColor = otherBuff.diffuseColor; direction = otherBuff.direction; specularPower = otherBuff.specularPower; specularColor = otherBuff.specularColor; } }; // DIRECT3D UTILITY FUNCTIONS template<class BufferType> static Microsoft::WRL::ComPtr<ID3D11Buffer> MakeConstantBuffer(ID3D11Device* device) { D3D11_BUFFER_DESC desc{}; desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = sizeof(BufferType); desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; desc.StructureByteStride = 0; Microsoft::WRL::ComPtr<ID3D11Buffer> buffer; ThrowHResultIf(device->CreateBuffer(&desc, nullptr, &buffer)); return buffer; } template<class BufferType> static void MapBuffer(const BufferType& inData, ID3D11Buffer* pBuffer, ID3D11DeviceContext* deviceContext) { D3D11_MAPPED_SUBRESOURCE mappedResource; ThrowHResultIf(deviceContext->Map(pBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource)); memcpy(mappedResource.pData, &inData, sizeof(BufferType)); deviceContext->Unmap(pBuffer, 0); } static D3D11_INPUT_ELEMENT_DESC MakeInputElementDesc(LPCSTR name, DXGI_FORMAT format, UINT offset = D3D11_APPEND_ALIGNED_ELEMENT) { D3D11_INPUT_ELEMENT_DESC desc; desc.SemanticName = name; desc.SemanticIndex = 0; desc.Format = format; desc.InputSlot = 0; desc.AlignedByteOffset = offset; desc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; desc.InstanceDataStepRate = 0; return desc; } static D3D11_SAMPLER_DESC MakeSamplerDesc(D3D11_TEXTURE_ADDRESS_MODE texMode = D3D11_TEXTURE_ADDRESS_WRAP) { D3D11_SAMPLER_DESC desc; desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; desc.AddressU = texMode; desc.AddressV = texMode; desc.AddressW = texMode; desc.MipLODBias = 0.0f; desc.MaxAnisotropy = 1; desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; desc.BorderColor[0] = 0; desc.BorderColor[1] = 0; desc.BorderColor[2] = 0; desc.BorderColor[3] = 0; desc.MinLOD = 0; desc.MaxLOD = D3D11_FLOAT32_MAX; return desc; } static Microsoft::WRL::ComPtr<ID3D11SamplerState> MakeSamplerState(ID3D11Device* device) { D3D11_SAMPLER_DESC desc; desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; desc.MipLODBias = 0.0f; desc.MaxAnisotropy = 1; desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; desc.BorderColor[0] = 0; desc.BorderColor[1] = 0; desc.BorderColor[2] = 0; desc.BorderColor[3] = 0; desc.MinLOD = 0; desc.MaxLOD = D3D11_FLOAT32_MAX; Microsoft::WRL::ComPtr<ID3D11SamplerState> sampler; ThrowHResultIf(device->CreateSamplerState(&desc, &sampler)); return sampler; } // CPU SIDE GFX RELATED enum EShaderType { ETEXTURE = 0, ELIGHT_DIFFUSE = 1, ELIGHT_SPECULAR = 2, EREFLECTION = 3, EWATER = 4, EFONT = 5, EDEPTH = 6, EMATERIAL_DEFAULT = 7, ESIZE = 8 }; struct SceneEffects { XMFLOAT4 ambientColor = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f); XMFLOAT4 clipPlane = XMFLOAT4(0.0f, 0.f, 0.0f, 0.0f); float fogStart = 0.f; float fogEnd = 3.f; SceneEffects() { ambientColor = XMFLOAT4(0.3f, 0.3f, 0.3f, 1.0f); clipPlane = XMFLOAT4(0.0f, 0.f, 0.0f, 0.0f); fogStart = 0.f; fogEnd = 3.f; } }; class Material { public: Material(); Material(EShaderType inShaderType, int numRenderTex); bool Initialize(ID3D11Device* device, ID3D11DeviceContext* deviceContext, EShaderType inShaderType, vector<string> fileNames); ID3D11ShaderResourceView* AddRenderTexture(ID3D11Device* const device, const int textureWidth, const int textureHeight, const float screenDepth, const float screenNear); TextureClass* GetTextureObject(); ID3D11ShaderResourceView** GetResourceArray(); void Animate(float deltaTime = 1.f); unique_ptr<TextureClass> _TextureArray; EShaderType shaderType; int texArraySize; XMFLOAT4 pixelColor = XMFLOAT4(1,1,1,1); // Effects @TODO: encapsulate into different struct bool bAnimated = false; float transparency = 0.f; float translation = 0.f; XMFLOAT2 translation2D = XMFLOAT2(0.f,0.f); float reflectRefractScale = 0.01f; float waterHeight = 2.75f; float textureScale = 1.f; float gamma = 1.f; unsigned int bBlendTexture = 0; float waterLerpRatio = .8f; // RENDER TEXTURES - for shadowing, reflection, and refraction vector<unique_ptr<RenderTextureClass>> _RenderTextures; private: int numRenderTextures = 0; }; ///////////// MATRIX MATH ///////////// XMMATRIX ComputeWorldTransform(XMFLOAT3& rotation, XMFLOAT3& scale, XMFLOAT3& translation); }
922c9d5e2b25b46244d1b7b841602caa09961554
8c6f118d3d4289db198c08ad48dccf4c54df51ef
/ArduinoCode/try_led/try_led.ino
fff005a794fbcfdf4379b26df0fd5a158a1a09e2
[]
no_license
MihaelaGadzhalova707/Diploma_Work
3deeb3cae769b26b5e5c317c8b9c920d16a3c200
03689b05ac1a8316daddd7814acfd0db1d30749c
refs/heads/master
2022-12-13T05:58:11.101621
2019-06-06T21:13:07
2019-06-06T21:13:07
161,848,890
0
0
null
2022-12-09T13:21:30
2018-12-14T22:54:49
C++
UTF-8
C++
false
false
2,804
ino
try_led.ino
#define REDPIN D0 #define GREENPIN D2 #define BLUEPIN D4 #define FADESPEED 5 // make this higher to slow down void setup() { pinMode(REDPIN, OUTPUT); pinMode(GREENPIN, OUTPUT); pinMode(BLUEPIN, OUTPUT); } void loop() { int r, g, b; // fade from blue to violet for (r = 0; r < 256; r++) { analogWrite(REDPIN, r); delay(FADESPEED); } // fade from violet to red for (b = 255; b > 0; b--) { analogWrite(BLUEPIN, b); delay(FADESPEED); } // fade from red to yellow for (g = 0; g < 256; g++) { analogWrite(GREENPIN, g); delay(FADESPEED); } // fade from yellow to green for (r = 255; r > 0; r--) { analogWrite(REDPIN, r); delay(FADESPEED); } // fade from green to teal for (b = 0; b < 256; b++) { analogWrite(BLUEPIN, b); delay(FADESPEED); } // fade from teal to blue for (g = 255; g > 0; g--) { analogWrite(GREENPIN, g); delay(FADESPEED); } } //#include <LEDstrip.h> // //LEDstrip myLEDstrip; // //const int Rpin = 3; //const int Gpin = 5; //const int Bpin = 6; // //int i; // //void setup() //{ // myLEDstrip.DefineRGBLED(Rpin,Gpin,Bpin); // // myLEDstrip.SetRedLight(255); // delay(1000); // myLEDstrip.SetGreenLight(255); // delay(1000); // myLEDstrip.SetBlueLight(255); // delay(1000); // myLEDstrip.SetWhiteLight(255); // delay(1000); // // i=0; //} // //void loop() //{ // if (i<=20) { // myLEDstrip.SetAdvRandomColour(myLEDstrip.RedVal,myLEDstrip.GreenVal,myLEDstrip.BlueVal,10); // delay(500); // } // else if (i==21) { // myLEDstrip.LEDstripOFF(); // delay(250); // myLEDstrip.SetWhiteLight(255); // delay(250); // myLEDstrip.LEDstripOFF(); // delay(250); // } // else if (i>21 && i<100) { // myLEDstrip.SetHSLrandomColour(myLEDstrip.HueVal,5); // delay(500); // } // else { // i=-1; // } // // i++; //} // //#define redPin D0 //#define greenPin D2 //#define bluePin D4 // //void setup() { // // Start off with the LED off. // setColourRgb(0,0,0); //} // //void loop() { // unsigned int rgbColour[3]; // // // Start off with red. // rgbColour[0] = 255; // rgbColour[1] = 0; // rgbColour[2] = 0; // // // Choose the colours to increment and decrement. // for (int decColour = 0; decColour < 3; decColour += 1) { // int incColour = decColour == 2 ? 0 : decColour + 1; // // // cross-fade the two colours. // for(int i = 0; i < 255; i += 1) { // rgbColour[decColour] -= 1; // rgbColour[incColour] += 1; // // setColourRgb(rgbColour[0], rgbColour[1], rgbColour[2]); // delay(5); // } // } //} // //void setColourRgb(unsigned int red, unsigned int green, unsigned int blue) { // analogWrite(redPin, red); // analogWrite(greenPin, green); // analogWrite(bluePin, blue); // }
504a598d56e1f29792e9308c0bc59811e0248f4a
a23f6be0ff14975217b8956b3b512945b5ad05e3
/include/tao/pegtl/internal/ranges.hpp
10de9d082eaeff9f24d1d8dae7a5e143ed699ec4
[ "BSL-1.0", "LicenseRef-scancode-free-unknown" ]
permissive
taocpp/PEGTL
e25327120da488d2fd5c71f180de453c66985290
788f223ee7c8377f78966c87d60b91188e3df33a
refs/heads/main
2023-09-03T01:31:39.664216
2023-07-15T10:58:53
2023-07-15T10:58:53
28,405,090
1,505
243
BSL-1.0
2023-07-15T13:34:54
2014-12-23T15:29:50
C++
UTF-8
C++
false
false
2,790
hpp
ranges.hpp
// Copyright (c) 2014-2023 Dr. Colin Hirsch and Daniel Frey // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #ifndef TAO_PEGTL_INTERNAL_RANGES_HPP #define TAO_PEGTL_INTERNAL_RANGES_HPP #include <utility> #include "bump_help.hpp" #include "enable_control.hpp" #include "failure.hpp" #include "one.hpp" #include "range.hpp" #include "../config.hpp" #include "../type_list.hpp" namespace TAO_PEGTL_NAMESPACE::internal { template< typename Char, Char Lo, Char Hi > constexpr bool validate_range( Char c ) noexcept { static_assert( Lo <= Hi, "invalid range" ); return ( Lo <= c ) && ( c <= Hi ); } template< typename Peek, typename Peek::data_t... Cs > struct ranges { using peek_t = Peek; using data_t = typename Peek::data_t; using rule_t = ranges; using subs_t = empty_list; template< std::size_t... Is > [[nodiscard]] static constexpr bool test_impl( std::index_sequence< Is... > /*unused*/, const data_t c ) noexcept { constexpr const data_t cs[] = { Cs... }; if constexpr( sizeof...( Cs ) % 2 == 0 ) { return ( validate_range< data_t, cs[ 2 * Is ], cs[ 2 * Is + 1 ] >( c ) || ... ); } else { return ( validate_range< data_t, cs[ 2 * Is ], cs[ 2 * Is + 1 ] >( c ) || ... ) || ( c == cs[ sizeof...( Cs ) - 1 ] ); } } [[nodiscard]] static constexpr bool test_one( const data_t c ) noexcept { return test_impl( std::make_index_sequence< sizeof...( Cs ) / 2 >(), c ); } [[nodiscard]] static constexpr bool test_any( const data_t c ) noexcept { return test_impl( std::make_index_sequence< sizeof...( Cs ) / 2 >(), c ); } template< typename ParseInput > [[nodiscard]] static bool match( ParseInput& in ) noexcept( noexcept( Peek::peek( in ) ) ) { if( const auto t = Peek::peek( in ) ) { if( test_one( t.data ) ) { bump_help< ranges >( in, t.size ); return true; } } return false; } }; template< typename Peek, typename Peek::data_t Lo, typename Peek::data_t Hi > struct ranges< Peek, Lo, Hi > : range< result_on_found::success, Peek, Lo, Hi > {}; template< typename Peek, typename Peek::data_t C > struct ranges< Peek, C > : one< result_on_found::success, Peek, C > {}; template< typename Peek > struct ranges< Peek > : failure {}; template< typename Peek, typename Peek::data_t... Cs > inline constexpr bool enable_control< ranges< Peek, Cs... > > = false; } // namespace TAO_PEGTL_NAMESPACE::internal #endif
af5b8b7058d04e179330eb2acdefec828e6d1c58
057a475216e9beed41983481aafcaf109bbf58da
/src/Functions/keyvaluepair/extractKeyValuePairs.cpp
34081cddb9272ddb33f24241f65b38f75d2e4776
[ "Apache-2.0" ]
permissive
ClickHouse/ClickHouse
fece5204263a5b4d693854b6039699265f1bb27f
6649328db809d51a694c358571539bc5820464be
refs/heads/master
2023-08-31T18:48:36.615225
2023-08-31T17:51:24
2023-08-31T17:51:24
60,246,359
23,878
5,449
Apache-2.0
2023-09-14T20:10:52
2016-06-02T08:28:18
C++
UTF-8
C++
false
false
10,270
cpp
extractKeyValuePairs.cpp
#include <Columns/ColumnsNumber.h> #include <Columns/ColumnMap.h> #include <Functions/FunctionFactory.h> #include <Functions/IFunction.h> #include <DataTypes/DataTypeMap.h> #include <DataTypes/DataTypeString.h> #include <Interpreters/Context.h> #include <Functions/keyvaluepair/impl/KeyValuePairExtractor.h> #include <Functions/keyvaluepair/impl/KeyValuePairExtractorBuilder.h> #include <Functions/keyvaluepair/ArgumentExtractor.h> namespace DB { template <typename Name, bool WITH_ESCAPING> class ExtractKeyValuePairs : public IFunction { auto getExtractor(const ArgumentExtractor::ParsedArguments & parsed_arguments) const { auto builder = KeyValuePairExtractorBuilder(); if constexpr (WITH_ESCAPING) { builder.withEscaping(); } if (parsed_arguments.key_value_delimiter) { builder.withKeyValueDelimiter(parsed_arguments.key_value_delimiter.value()); } if (!parsed_arguments.pair_delimiters.empty()) { builder.withItemDelimiters(parsed_arguments.pair_delimiters); } if (parsed_arguments.quoting_character) { builder.withQuotingCharacter(parsed_arguments.quoting_character.value()); } bool is_number_of_pairs_unlimited = context->getSettingsRef().extract_kvp_max_pairs_per_row == 0; if (!is_number_of_pairs_unlimited) { builder.withMaxNumberOfPairs(context->getSettingsRef().extract_kvp_max_pairs_per_row); } return builder.build(); } ColumnPtr extract(ColumnPtr data_column, std::shared_ptr<KeyValuePairExtractor> extractor) const { auto offsets = ColumnUInt64::create(); auto keys = ColumnString::create(); auto values = ColumnString::create(); uint64_t offset = 0u; for (auto i = 0u; i < data_column->size(); i++) { auto row = data_column->getDataAt(i).toView(); auto pairs_count = extractor->extract(row, keys, values); offset += pairs_count; offsets->insert(offset); } keys->validate(); values->validate(); ColumnPtr keys_ptr = std::move(keys); return ColumnMap::create(keys_ptr, std::move(values), std::move(offsets)); } public: explicit ExtractKeyValuePairs(ContextPtr context_) : context(context_) {} static constexpr auto name = Name::name; String getName() const override { return name; } static FunctionPtr create(ContextPtr context) { return std::make_shared<ExtractKeyValuePairs>(context); } ColumnPtr executeImpl(const ColumnsWithTypeAndName & arguments, const DataTypePtr &, size_t) const override { auto parsed_arguments = ArgumentExtractor::extract(arguments); auto extractor = getExtractor(parsed_arguments); return extract(parsed_arguments.data_column, extractor); } DataTypePtr getReturnTypeImpl(const DataTypes &) const override { return std::make_shared<DataTypeMap>(std::make_shared<DataTypeString>(), std::make_shared<DataTypeString>()); } bool isVariadic() const override { return true; } bool isSuitableForShortCircuitArgumentsExecution(const DataTypesWithConstInfo &) const override { return false; } std::size_t getNumberOfArguments() const override { return 0u; } ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1, 2, 3, 4}; } private: ContextPtr context; }; struct NameExtractKeyValuePairs { static constexpr auto name = "extractKeyValuePairs"; }; struct NameExtractKeyValuePairsWithEscaping { static constexpr auto name = "extractKeyValuePairsWithEscaping"; }; REGISTER_FUNCTION(ExtractKeyValuePairs) { factory.registerFunction<ExtractKeyValuePairs<NameExtractKeyValuePairs, false>>( FunctionDocumentation{ .description=R"(Extracts key-value pairs from any string. The string does not need to be 100% structured in a key value pair format; It can contain noise (e.g. log files). The key-value pair format to be interpreted should be specified via function arguments. A key-value pair consists of a key followed by a `key_value_delimiter` and a value. Quoted keys and values are also supported. Key value pairs must be separated by pair delimiters. **Syntax** ``` sql extractKeyValuePairs(data, [key_value_delimiter], [pair_delimiter], [quoting_character]) ``` **Arguments** - `data` - String to extract key-value pairs from. [String](../../sql-reference/data-types/string.md) or [FixedString](../../sql-reference/data-types/fixedstring.md). - `key_value_delimiter` - Character to be used as delimiter between the key and the value. Defaults to `:`. [String](../../sql-reference/data-types/string.md) or [FixedString](../../sql-reference/data-types/fixedstring.md). - `pair_delimiters` - Set of character to be used as delimiters between pairs. Defaults to `\space`, `,` and `;`. [String](../../sql-reference/data-types/string.md) or [FixedString](../../sql-reference/data-types/fixedstring.md). - `quoting_character` - Character to be used as quoting character. Defaults to `"`. [String](../../sql-reference/data-types/string.md) or [FixedString](../../sql-reference/data-types/fixedstring.md). **Returned values** - The extracted key-value pairs in a Map(String, String). **Examples** Query: **Simple case** ``` sql arthur :) select extractKeyValuePairs('name:neymar, age:31 team:psg,nationality:brazil') as kv SELECT extractKeyValuePairs('name:neymar, age:31 team:psg,nationality:brazil') as kv Query id: f9e0ca6f-3178-4ee2-aa2c-a5517abb9cee ┌─kv──────────────────────────────────────────────────────────────────────┐ │ {'name':'neymar','age':'31','team':'psg','nationality':'brazil'} │ └─────────────────────────────────────────────────────────────────────────┘ ``` **Single quote as quoting character** ``` sql arthur :) select extractKeyValuePairs('name:\'neymar\';\'age\':31;team:psg;nationality:brazil,last_key:last_value', ':', ';,', '\'') as kv SELECT extractKeyValuePairs('name:\'neymar\';\'age\':31;team:psg;nationality:brazil,last_key:last_value', ':', ';,', '\'') as kv Query id: 0e22bf6b-9844-414a-99dc-32bf647abd5e ┌─kv───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ {'name':'neymar','age':'31','team':'psg','nationality':'brazil','last_key':'last_value'} │ └──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ ``` **Escape sequences without escape sequences support** ``` sql arthur :) select extractKeyValuePairs('age:a\\x0A\\n\\0') as kv SELECT extractKeyValuePairs('age:a\\x0A\\n\\0') AS kv Query id: e9fd26ee-b41f-4a11-b17f-25af6fd5d356 ┌─kv────────────────────┐ │ {'age':'a\\x0A\\n\\0'} │ └───────────────────────┘ ```)"} ); factory.registerFunction<ExtractKeyValuePairs<NameExtractKeyValuePairsWithEscaping, true>>( FunctionDocumentation{ .description=R"(Same as `extractKeyValuePairs` but with escaping support. Escape sequences supported: `\x`, `\N`, `\a`, `\b`, `\e`, `\f`, `\n`, `\r`, `\t`, `\v` and `\0`. Non standard escape sequences are returned as it is (including the backslash) unless they are one of the following: `\\`, `'`, `"`, `backtick`, `/`, `=` or ASCII control characters (c <= 31). This function will satisfy the use case where pre-escaping and post-escaping are not suitable. For instance, consider the following input string: `a: "aaaa\"bbb"`. The expected output is: `a: aaaa\"bbbb`. - Pre-escaping: Pre-escaping it will output: `a: "aaaa"bbb"` and `extractKeyValuePairs` will then output: `a: aaaa` - Post-escaping: `extractKeyValuePairs` will output `a: aaaa\` and post-escaping will keep it as it is. Leading escape sequences will be skipped in keys and will be considered invalid for values. **Escape sequences with escape sequence support turned on** ``` sql arthur :) select extractKeyValuePairsWithEscaping('age:a\\x0A\\n\\0') as kv SELECT extractKeyValuePairsWithEscaping('age:a\\x0A\\n\\0') AS kv Query id: 44c114f0-5658-4c75-ab87-4574de3a1645 ┌─kv───────────────┐ │ {'age':'a\n\n\0'} │ └──────────────────┘ ```)"} ); factory.registerAlias("str_to_map", NameExtractKeyValuePairs::name, FunctionFactory::CaseInsensitive); factory.registerAlias("mapFromString", NameExtractKeyValuePairs::name); } }
23d2ffc67f0195434eeedb2b10ea48208146ab67
96e87962669d7b06bcc00d9d29955f6016548ffd
/src/JEngine/Timer.cpp
e8f71a4a3bb3a75fd37f1f6f96c81815e4b2aded
[]
no_license
jaykop/JEngine-old
f805418918ebf28e709f058ca9b3ffd869a12682
7c4540180e8ecc6c27963a550b8707dd66f9f96a
refs/heads/master
2022-07-25T10:01:03.593902
2020-05-05T10:12:14
2020-05-05T10:12:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,161
cpp
Timer.cpp
#include <ctime> #include "Timer.h" jeBegin /******************************************************************************/ /*! \brief - Start to check time */ /******************************************************************************/ void Timer::Start(void) { time_ = static_cast<float>(clock()); } /******************************************************************************/ /*! \brief - Get spent time from StartTime() moment */ /******************************************************************************/ float Timer::GetTime(void) const { return (static_cast<float>(clock()) - time_) / static_cast<float>(CLOCKS_PER_SEC); } /******************************************************************************/ /*! \brief - Get current time info (yy/mm/dd/hh/mm/ss) \return - Time instance */ /******************************************************************************/ Time Timer::GetCurrentTimeInfo() { time_t theTime = time(nullptr); tm timeBuf; localtime_s(&timeBuf, &theTime); return Time{ timeBuf.tm_year + 1900, timeBuf.tm_mon + 1, timeBuf.tm_mday, timeBuf.tm_hour, timeBuf.tm_min, timeBuf.tm_sec }; } jeEnd
568a7197169a120651cdd82e0dce92f0355303d5
3ee3160242b1e43cd1f6402d76fffb87e37e04b9
/Homework7/min.hpp
9971037bc3d04118832f63123e3ce2ae13816dda
[]
no_license
AlexanderKnight/NumericalMethods
098466db771fb3d27e6a35fae4d4d0bdd96539cb
099549e0f72abcb7ae8ebae56723ca28d4879a1c
refs/heads/master
2020-07-18T04:29:57.267029
2019-12-20T18:08:17
2019-12-20T18:08:17
206,175,737
0
0
null
null
null
null
UTF-8
C++
false
false
2,096
hpp
min.hpp
#include <vector> #include <iostream> #include <fstream> #include <string> #include <assert.h> #include <math.h> using namespace std; //#include "rf.hpp" inline double magnitude(const vector<double> A) { double mag = 0.; for(int i=0;i<A.size();i++) { mag += A[i]*A[i]; } mag = sqrt(mag); return mag; } /* class F1dim { private: const vector<double> &p; const vector<double> &xi; int n; const double (*func)(const vector<double> &x); vector<double> xt; public: F1dim(vector<double> &pp, vector<double> &xii, const double (*funcc)(const vector<double> &x)); const static double f(const double &x); }; */ class TwoDMinimum { private: const double (*func)(const double &x); const double (*TwoDFunc)(const vector<double> &x); const double (*beta)(const vector<double> &xni, const vector<double> &xnj); void steepest_descent(const double (*funcc)(const vector<double> &x), const vector<double> &x0, vector<double> &delx, const double epsilon); public: TwoDMinimum(const double (*func)(const double &x), const double (*TwoDFunc)(const vector<double> &x), const double (*beta)(const vector<double> &xni, const vector<double> &xnj)); const vector<double> FindMinimum(const double (*func)(const double &x), const double (*TwoDFunc)(const vector<double> &x), const double (*beta)(const vector<double> &xni, const vector<double> &xnj), const vector<double> &pp, const double &epsilon, const double &tol, const int &maxIt); }; inline const double FRPR (const vector<double> &xni, const vector<double> &xnj) { assert(xni.size()==xnj.size()); double num=0., denom=0.; for(int i=0;i<xni.size();i++) { num += xnj[i]*(xnj[i]-xni[i]); denom += xni[i]*xni[i]; } return max(0.,num/denom); }
b52f3e80f27a0ad0c4203910b27e9be66398a822
47ad925c5c18f3d669803d8ddeadb48a75c23578
/fse_names/MyFSEAirport.cpp
e440869c84ba633dc0cdcf459bff38e686fa2526
[]
no_license
kristian80/fse_names
e92d963703f8aa375710d0d2ca10670843ddb15f
e74518439447e17d3d91e612a91f92fd0decb82c
refs/heads/master
2020-04-14T06:29:18.401949
2019-01-02T12:38:04
2019-01-02T12:38:04
163,687,755
0
0
null
null
null
null
UTF-8
C++
false
false
114
cpp
MyFSEAirport.cpp
#include "pch.h" #include "MyFSEAirport.h" MyFSEAirport::MyFSEAirport() { } MyFSEAirport::~MyFSEAirport() { }
68baf5ff07e1ab1f831afcae102827b087ba4b57
65e3391b6afbef10ec9429ca4b43a26b5cf480af
/STEER/STEER/AliParamSolver.h
2dabe6dd761190abdff6c49488b5a2dfaecc992d
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-proprietary-license" ]
permissive
alisw/AliRoot
c0976f7105ae1e3d107dfe93578f819473b2b83f
d3f86386afbaac9f8b8658da6710eed2bdee977f
refs/heads/master
2023-08-03T11:15:54.211198
2023-07-28T12:39:57
2023-07-28T12:39:57
53,312,169
61
299
BSD-3-Clause
2023-07-28T13:19:50
2016-03-07T09:20:12
C++
UTF-8
C++
false
false
3,119
h
AliParamSolver.h
#ifndef ALIPARAMSOLVER_H #define ALIPARAMSOLVER_H /* ---------------------------------------------------------------------------------------- Class to solve a set of N linearized parametric equations of the type Eq(k): sum_i=0^n { g_i G_ik } + t_k T_k = res_k whith n "global" parameters gi and one "local" parameter (per equation) t_k. Each measured points provides 3 measured coordinates, with proper covariance matrix. Used for Newton-Raphson iteration step in solution of non-linear parametric equations F(g,t_k) - res_k = 0, with G_ik = dF(g,t_k)/dg_i and T_k = dF(g,t_k)/dt_k Solution is obtained by elimination of local parameters via large (n+N) matrix partitioning Author: ruben.shahoyan@cern.ch -------------------------------------------------------------------------------------------*/ #include <TObject.h> class AliSymMatrix; class AliParamSolver: public TObject { public: enum {kBitGloSol=BIT(14),kBitLocSol=BIT(15),kBitCInv=BIT(16)}; enum {kXX=0,kXY=1,kXZ=2,kYX=kXY,kYY=3,kYZ=4,kZX=kXZ,kZY=kYZ,kZZ=5}; enum {kX,kY,kZ}; AliParamSolver(); AliParamSolver(Int_t maxglo,Int_t locsize=16); AliParamSolver(const AliParamSolver& src); AliParamSolver& operator=(const AliParamSolver& src); ~AliParamSolver(); // void AddEquation(const Double_t* dGl,const Double_t *dLc,const Double_t *res,const Double_t *covI,Double_t sclErrI=-1.); void AddConstraint(Int_t parID, Double_t val, Double_t err2inv); Bool_t Solve(Bool_t obtainCov=kFALSE); Bool_t SolveGlobals(Bool_t obtainCov=kFALSE); Bool_t SolveLocals(); void SetMaxGlobal(Int_t n); void SetNGlobal(Int_t n); void Clear(Option_t* = ""); void Print(Option_t* = "") const; // Int_t GetNGlobal() const {return fNGlobal;} Int_t GetMaxGlobal() const {return fMaxGlobal;} AliSymMatrix* GetCovMatrix(); Double_t* GetLocals() const {return (Double_t*)fSolLoc;} Double_t* GetGlobals() const {return (Double_t*)fSolGlo;} protected: void Init(Int_t npini=16); void ExpandStorage(Int_t newSize); protected: AliSymMatrix* fMatrix; // final matrix for global parameters (C in MP) Double_t* fSolGlo; // solution for globals ( vector a in MP) Double_t* fSolLoc; // solution for locals ( vector alpha in MP) Int_t fMaxGlobal; // max number of globals can process Int_t fNGlobal; // number of globals Int_t fNPoints; // number of added points (=number of local parameters) // // temp storage Int_t fMaxPoints; // buffer size for storage Double_t* fRHSGlo; // RHS of globals (vector b in MP) Double_t* fRHSLoc; // RHS of locals (vector beta in MP) Double_t* fMatGamma; // diagonals of local partition (Gamma_i in MP) Double_t* fMatG; // off-diagonals of local partition (G_i in MP) Double_t* fCovDGl; // temporary matrix of cov*dR/dGlo // ClassDef(AliParamSolver,0) }; #endif
4a2ac890134269f3c620e879d3be498ccaf80c1e
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/CondCore/CondDB/interface/KeyListProxy.h
f543ef97e1d3a826b4ccafaa619c83b9f12264d1
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C++
false
false
1,583
h
KeyListProxy.h
#ifndef CondCore_CondDB_KeyListProxy_h #define CondCore_CondDB_KeyListProxy_h #include "CondCore/CondDB/interface/PayloadProxy.h" #include "CondCore/CondDB/interface/KeyList.h" #include <memory> #include <vector> #include <string> namespace cond { struct Iov_t; namespace persistency { class Session; template <> class PayloadProxy<cond::persistency::KeyList> : public PayloadProxy<std::vector<cond::Time_t>> { public: typedef std::vector<cond::Time_t> DataT; typedef PayloadProxy<DataT> super; explicit PayloadProxy(Iov_t const* mostRecentCurrentIov, Session const* mostRecentSession, std::shared_ptr<std::vector<Iov_t>> const* mostRecentRequests, const char* source = nullptr) : super(mostRecentCurrentIov, mostRecentSession, mostRecentRequests, source), m_keyList() { if (source) m_name = source; } ~PayloadProxy() override {} void initKeyList(PayloadProxy const& originalPayloadProxy) { m_keyList.init(originalPayloadProxy.m_keyList); } // dereference (does not load) const KeyList& operator()() const { return m_keyList; } void loadMore(CondGetter const& getter) override { m_keyList.init(getter.get(m_name)); } protected: void loadPayload() override { super::loadPayload(); m_keyList.setKeys(super::operator()()); } private: std::string m_name; KeyList m_keyList; }; } // namespace persistency } // namespace cond #endif
791cc138e9ecdea707501810bba7c0ef8569e1dc
e41cb758ce46b7b0fef6221febc1844b3a7583d1
/rain.h
23a98a360282c4978450b6e89ba0b824377957ef
[]
no_license
rianta9/Botngu
7e341eabe520153d093b9e22ad1c678ff97e4f15
4e5f64f08d70702125f919a59b043d0cfe0b6904
refs/heads/master
2021-07-06T19:22:13.971346
2020-11-27T12:50:14
2020-11-27T12:50:14
210,623,897
0
0
null
null
null
null
UTF-8
C++
false
false
196
h
rain.h
#pragma once #include<bits/stdc++.h> #include<Windows.h> #include<time.h> #include<thread> #include<chrono> using std::this_thread::sleep_for; using std::chrono::milliseconds; void runrain();
239a4379d8123ed3b81f3d4039c9ef2d951af105
8075e5fd3dc9f0781c26a671c2b97e5741eeff28
/inc/grayvalley/smd/SMDSubscription.hh
656cc739461c5ba712f7df5b587761cdf762387a
[ "Apache-2.0" ]
permissive
grayvalley/smd
d246855a197a9a732760de6ec1326e92933ddfc6
b70993787d5233e0ff390950cf05e77775c8b126
refs/heads/main
2023-02-22T16:11:33.108068
2021-01-25T22:43:35
2021-01-25T22:43:35
316,050,780
0
0
Apache-2.0
2021-01-25T22:44:10
2020-11-25T20:49:42
C++
UTF-8
C++
false
false
1,555
hh
SMDSubscription.hh
/* * Copyright 2020 Juha-Samuli Hellén * * 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 GVT_SMD_SUBSCRIPTION_HH #define GVT_SMD_SUBSCRIPTION_HH #include <nlohmann/json.hpp> #include <grayvalley/core/Macros.hh> #include <grayvalley/core/ISubscription.hh> namespace GVT::SMD { class SMDSubscription: public ISubscription { public: /** * Generate SMD style subscription string. * * @return: subscription string. */ std::string generate_payload() const override; }; } namespace GVT::SMD { std::string SMDSubscription::generate_payload() const { if (empty()){ throw std::runtime_error("Subscription was empty!"); } nlohmann::json payload = {{"op", "subscribe"}}; auto args = nlohmann::json::array(); for(auto item: m_items){ args.push_back(item); } payload["args"] = args; auto result = payload.dump(); return result; } } #endif //GVT_SMD_SUBSCRIPTION_HH
2c7dd3c70aa346e29bb1f91db48a3e8eabb8df00
9d565954121e39dabf80417affc99b99c68c5f1a
/ros/src/simple_distrib/src/listen_talker.cpp
e3a6b45f2a764fd0798787bab3d2cf933ef5a813
[ "MIT" ]
permissive
BH1SCW/ComP
dc9b8348bbf62edc20d22e850648cf9827e7aa60
021440aa98aa03ee3b86ed3db196b95477b9f80b
refs/heads/master
2023-08-25T07:17:12.148813
2021-11-02T09:39:58
2021-11-02T09:39:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
802
cpp
listen_talker.cpp
#include "ros/ros.h" #include "std_msgs/String.h" #include "simple_distrib/Test.h" #include <fstream> #include <vector> #include <signal.h> #include<numeric> using namespace std; ros::Publisher pub; string node_name = ros::this_node::getName(); void chatterCallback1(const simple_distrib::Test::ConstPtr& msg) { cout<<to_string((ros::Time::now() - msg->header.stamp).toNSec())<<endl; pub.publish(msg); } int main(int argc, char **argv) { ros::init(argc, argv, "listen_talker"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("msg", 1, chatterCallback1,ros::TransportHints().udp().maxDatagramSize(1500)); //UDP // ros::Subscriber sub = n.subscribe("msg", 1, chatterCallback1); //TCP pub= n.advertise<simple_distrib::Test>("msg_back",1); ros::spin(); return 0; }
609538f484d8a02c3178f2376d482a54db372084
f3d7998e1b9a781730c6509dce0835ba5e0051ca
/Cuentaatras0/main.cpp
1d24c05d62baf077107a3ac87c79bdac6ef16110
[]
no_license
codigopublico/netbeans
43453eeb192bad32a081d996889c71a3e2dff71e
a5aca58f7f0ecdc43fb0d4c8d4e8b68496aed421
refs/heads/master
2021-01-19T15:05:09.665897
2017-09-04T23:33:47
2017-09-04T23:33:47
100,942,570
0
0
null
null
null
null
UTF-8
C++
false
false
399
cpp
main.cpp
/* * File: main.cpp * Author: prog * * Created on 1 de agosto de 2017, 13:42 */ #include <cstdlib> #include <iostream> using namespace std; /* * */ int main(int argc, char** argv) { int cont = 100; while (cont > 0) { cont--; std::cout << "Cuidado no descontarse, voy por la iteracion numero ... " << cont << "\n"; } return 0; }
57146b7225c567acf20727b2ee79414e6a41d690
0695314fce393f6abdd322241db4294e237e351c
/src/Enchantments.cpp
fbe4c8b95bb176458302eab1e0bc95cab8f23703
[ "Apache-2.0" ]
permissive
cuberite/cuberite
df468fe78e4f8e383e1229fe9bea799dff6fc501
eda440e0db028587975c867dbacb513d80df4dca
refs/heads/master
2023-08-31T17:55:40.563231
2023-08-21T11:49:46
2023-08-21T11:49:46
11,693,709
4,815
990
NOASSERTION
2023-08-21T11:49:47
2013-07-26T19:56:59
C++
UTF-8
C++
false
false
36,563
cpp
Enchantments.cpp
// Enchantments.cpp // Implements the cEnchantments class representing a storage for item enchantments and stored-enchantments #include "Globals.h" #include "Enchantments.h" #include "WorldStorage/FastNBT.h" #include "FastRandom.h" #include "Noise/Noise.h" #include "BlockType.h" cEnchantments::cEnchantments(void) { // Nothing needed yet, but the constructor needs to be declared and impemented in order to be usable } cEnchantments::cEnchantments(const AString & a_StringSpec) { AddFromString(a_StringSpec); } void cEnchantments::Add(const cEnchantments & a_Other) { for (cEnchantments::cMap::const_iterator itr = a_Other.m_Enchantments.begin(), end = a_Other.m_Enchantments.end(); itr != end; ++itr) { SetLevel(itr->first, itr->second); } // for itr - a_Other.m_Enchantments[] } void cEnchantments::AddFromString(const AString & a_StringSpec) { // Add enchantments in the stringspec; if a specified enchantment already exists, overwrites it // Split the StringSpec into separate declarations, each in the form "id=lvl": AStringVector Decls = StringSplit(a_StringSpec, ";"); for (AStringVector::const_iterator itr = Decls.begin(), end = Decls.end(); itr != end; ++itr) { // Split each declaration into the id and lvl part: if (itr->empty()) { // The decl is empty (may happen if there's an extra semicolon at the end), ignore silently continue; } AStringVector Split = StringSplitAndTrim(*itr, "="); if (Split.size() != 2) { // Malformed decl LOG("%s: Malformed enchantment decl: \"%s\", skipping.", __FUNCTION__, itr->c_str()); continue; } int id = StringToEnchantmentID(Split[0]); if (id < 0) { LOG("%s: Failed to parse enchantment \"%s\", skipping.", __FUNCTION__, Split[0].c_str()); continue; } unsigned int lvl; if (!StringToInteger(Split[1], lvl)) { // Level failed to parse LOG("%s: Failed to parse enchantment level \"%s\", skipping.", __FUNCTION__, Split[1].c_str()); continue; } SetLevel(id, lvl); } // for itr - Decls[] } size_t cEnchantments::Count() const { return m_Enchantments.size(); } AString cEnchantments::ToString() const { // Serialize all the enchantments into a string AString res; for (cEnchantments::cMap::const_iterator itr = m_Enchantments.begin(), end = m_Enchantments.end(); itr != end; ++itr) { res.append(fmt::format(FMT_STRING("{}={};"), itr->first, itr->second)); } // for itr - m_Enchantments[] return res; } unsigned int cEnchantments::GetLevel(int a_EnchantmentID) const { // Return the level for the specified enchantment; 0 if not stored cMap::const_iterator itr = m_Enchantments.find(a_EnchantmentID); if (itr != m_Enchantments.end()) { return itr->second; } // Not stored, return zero return 0; } void cEnchantments::SetLevel(int a_EnchantmentID, unsigned int a_Level) { // Sets the level for the specified enchantment, adding it if not stored before or removing it if level <= 0 if (a_Level == 0) { // Delete enchantment, if present: cMap::iterator itr = m_Enchantments.find(a_EnchantmentID); if (itr != m_Enchantments.end()) { m_Enchantments.erase(itr); } } else { // Add / overwrite enchantment m_Enchantments[a_EnchantmentID] = a_Level; } } void cEnchantments::Clear(void) { m_Enchantments.clear(); } bool cEnchantments::IsEmpty(void) const { return m_Enchantments.empty(); } unsigned int cEnchantments::GetLevelCap(int a_EnchantmentID) { switch (a_EnchantmentID) { case enchProtection: return 4; case enchFireProtection: return 4; case enchFeatherFalling: return 4; case enchBlastProtection: return 4; case enchProjectileProtection: return 4; case enchRespiration: return 3; case enchAquaAffinity: return 1; case enchThorns: return 3; case enchDepthStrider: return 3; case enchSharpness: return 5; case enchSmite: return 5; case enchBaneOfArthropods: return 5; case enchKnockback: return 2; case enchFireAspect: return 2; case enchLooting: return 3; case enchEfficiency: return 5; case enchSilkTouch: return 1; case enchUnbreaking: return 3; case enchFortune: return 3; case enchPower: return 5; case enchPunch: return 2; case enchFlame: return 1; case enchInfinity: return 1; case enchLuckOfTheSea: return 3; case enchLure: return 3; } LOGWARNING("Unknown enchantment ID %d", a_EnchantmentID); return 0; } int cEnchantments::GetXPCostMultiplier(int a_EnchantmentID, bool FromBook) { if (FromBook) { switch (a_EnchantmentID) { case enchProtection: return 1; case enchFireProtection: return 1; case enchFeatherFalling: return 1; case enchBlastProtection: return 2; case enchProjectileProtection: return 1; case enchRespiration: return 2; case enchAquaAffinity: return 2; case enchThorns: return 4; case enchDepthStrider: return 2; case enchSharpness: return 1; case enchSmite: return 1; case enchBaneOfArthropods: return 1; case enchKnockback: return 1; case enchFireAspect: return 2; case enchLooting: return 2; case enchEfficiency: return 1; case enchSilkTouch: return 4; case enchUnbreaking: return 1; case enchFortune: return 1; case enchPower: return 1; case enchPunch: return 2; case enchFlame: return 2; case enchInfinity: return 4; case enchLuckOfTheSea: return 2; case enchLure: return 2; } } else // Without book { switch (a_EnchantmentID) { case enchProtection: return 1; case enchFireProtection: return 2; case enchFeatherFalling: return 2; case enchBlastProtection: return 4; case enchProjectileProtection: return 2; case enchRespiration: return 4; case enchAquaAffinity: return 4; case enchThorns: return 8; case enchDepthStrider: return 4; case enchSharpness: return 1; case enchSmite: return 2; case enchBaneOfArthropods: return 2; case enchKnockback: return 2; case enchFireAspect: return 4; case enchLooting: return 4; case enchEfficiency: return 1; case enchSilkTouch: return 8; case enchUnbreaking: return 2; case enchFortune: return 4; case enchPower: return 1; case enchPunch: return 4; case enchFlame: return 4; case enchInfinity: return 8; case enchLuckOfTheSea: return 4; case enchLure: return 4; } } LOGWARNING("Unknown enchantment ID %d", a_EnchantmentID); return 0; } bool cEnchantments::CanAddEnchantment(int a_EnchantmentID) const { if (GetLevel(a_EnchantmentID) > 0) { return true; } static const std::vector<std::set<int> > IncompatibleEnchantments = { // Armor { enchProtection, enchFireProtection, enchBlastProtection, enchProjectileProtection }, // Tool { enchFortune, enchSilkTouch }, // Sword { enchSharpness, enchSmite, enchBaneOfArthropods }, // Boots // {enchDepthStrider, enchFrostWalker}, // Bow // {enchInfinity, enchMending} }; for (const auto & excl: IncompatibleEnchantments) { if (excl.count(a_EnchantmentID) != 0) { // See if we also have any of the enchantments for (auto ench: excl) { if (GetLevel(ench) > 0) { return false; } } } } return true; } int cEnchantments::StringToEnchantmentID(const AString & a_EnchantmentName) { static const struct { int m_Value; const char * m_Name; } EnchantmentNames[] = { { enchProtection, "Protection" }, { enchFireProtection, "FireProtection" }, { enchFeatherFalling, "FeatherFalling" }, { enchBlastProtection, "BlastProtection" }, { enchProjectileProtection, "ProjectileProtection" }, { enchRespiration, "Respiration" }, { enchAquaAffinity, "AquaAffinity" }, { enchThorns, "Thorns" }, { enchDepthStrider, "DepthStrider" }, { enchSharpness, "Sharpness" }, { enchSmite, "Smite" }, { enchBaneOfArthropods, "BaneOfArthropods" }, { enchKnockback, "Knockback" }, { enchFireAspect, "FireAspect" }, { enchLooting, "Looting" }, { enchEfficiency, "Efficiency" }, { enchSilkTouch, "SilkTouch" }, { enchUnbreaking, "Unbreaking" }, { enchFortune, "Fortune" }, { enchPower, "Power" }, { enchPunch, "Punch" }, { enchFlame, "Flame" }, { enchInfinity, "Infinity" }, { enchLuckOfTheSea, "LuckOfTheSea" }, { enchLure, "Lure" }, } ; // First try to parse as a number: int id = atoi(a_EnchantmentName.c_str()); if ((id != 0) || (a_EnchantmentName == "0")) { return id; } // It wasn't a number, do a lookup: for (size_t i = 0; i < ARRAYCOUNT(EnchantmentNames); i++) { if (NoCaseCompare(EnchantmentNames[i].m_Name, a_EnchantmentName) == 0) { return EnchantmentNames[i].m_Value; } } // for i - EnchantmentNames[] return -1; } bool cEnchantments::operator ==(const cEnchantments & a_Other) const { return m_Enchantments == a_Other.m_Enchantments; } bool cEnchantments::operator !=(const cEnchantments & a_Other) const { return m_Enchantments != a_Other.m_Enchantments; } void cEnchantments::AddItemEnchantmentWeights(cWeightedEnchantments & a_Enchantments, short a_ItemType, unsigned a_EnchantmentLevel) { if (ItemCategory::IsSword(a_ItemType)) { // Sharpness if ((a_EnchantmentLevel >= 34) && (a_EnchantmentLevel <= 54)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchSharpness, 4); } else if ((a_EnchantmentLevel >= 23) && (a_EnchantmentLevel <= 43)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchSharpness, 3); } else if ((a_EnchantmentLevel >= 12) && (a_EnchantmentLevel <= 32)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchSharpness, 2); } else if ((a_EnchantmentLevel >= 1) && (a_EnchantmentLevel <= 21)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchSharpness, 1); } // Smite if ((a_EnchantmentLevel >= 29) && (a_EnchantmentLevel <= 49)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchSmite, 4); } else if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 41)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchSmite, 3); } else if ((a_EnchantmentLevel >= 13) && (a_EnchantmentLevel <= 33)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchSmite, 2); } else if ((a_EnchantmentLevel >= 5) && (a_EnchantmentLevel <= 25)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchSmite, 1); } // Bane of Arthropods if ((a_EnchantmentLevel >= 29) && (a_EnchantmentLevel <= 49)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchBaneOfArthropods, 4); } else if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 41)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchBaneOfArthropods, 3); } else if ((a_EnchantmentLevel >= 13) && (a_EnchantmentLevel <= 33)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchBaneOfArthropods, 2); } else if ((a_EnchantmentLevel >= 5) && (a_EnchantmentLevel <= 25)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchBaneOfArthropods, 1); } // Knockback if ((a_EnchantmentLevel >= 25) && (a_EnchantmentLevel <= 75)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchKnockback, 2); } else if ((a_EnchantmentLevel >= 5) && (a_EnchantmentLevel <= 55)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchKnockback, 1); } // Fire Aspect if ((a_EnchantmentLevel >= 30) && (a_EnchantmentLevel <= 80)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFireAspect, 2); } else if ((a_EnchantmentLevel >= 10) && (a_EnchantmentLevel <= 60)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFireAspect, 1); } // Looting if ((a_EnchantmentLevel >= 33) && (a_EnchantmentLevel <= 83)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchLooting, 3); } else if ((a_EnchantmentLevel >= 24) && (a_EnchantmentLevel <= 74)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchLooting, 2); } else if ((a_EnchantmentLevel >= 15) && (a_EnchantmentLevel <= 65)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchLooting, 1); } } else if (ItemCategory::IsTool(a_ItemType)) { // Efficiency if ((a_EnchantmentLevel >= 31) && (a_EnchantmentLevel <= 81)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchEfficiency, 4); } else if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 71)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchEfficiency, 3); } else if ((a_EnchantmentLevel >= 11) && (a_EnchantmentLevel <= 61)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchEfficiency, 2); } else if ((a_EnchantmentLevel >= 1) && (a_EnchantmentLevel <= 51)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchEfficiency, 1); } // Silk Touch if ((a_EnchantmentLevel >= 15) && (a_EnchantmentLevel <= 65)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchSilkTouch, 1); } // Fortune if ((a_EnchantmentLevel >= 33) && (a_EnchantmentLevel <= 83)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFortune, 3); } else if ((a_EnchantmentLevel >= 24) && (a_EnchantmentLevel <= 74)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFortune, 2); } else if ((a_EnchantmentLevel >= 15) && (a_EnchantmentLevel <= 65)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFortune, 1); } } else if (ItemCategory::IsArmor(a_ItemType)) { // Protection if ((a_EnchantmentLevel >= 34) && (a_EnchantmentLevel <= 54)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchProtection, 4); } else if ((a_EnchantmentLevel >= 23) && (a_EnchantmentLevel <= 43)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchProtection, 3); } else if ((a_EnchantmentLevel >= 12) && (a_EnchantmentLevel <= 32)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchProtection, 2); } else if ((a_EnchantmentLevel >= 1) && (a_EnchantmentLevel <= 21)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchProtection, 1); } // Fire Protection if ((a_EnchantmentLevel >= 34) && (a_EnchantmentLevel <= 46)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFireProtection, 4); } else if ((a_EnchantmentLevel >= 26) && (a_EnchantmentLevel <= 38)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFireProtection, 3); } else if ((a_EnchantmentLevel >= 18) && (a_EnchantmentLevel <= 30)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFireProtection, 2); } else if ((a_EnchantmentLevel >= 10) && (a_EnchantmentLevel <= 22)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFireProtection, 1); } // Blast Protection if ((a_EnchantmentLevel >= 29) && (a_EnchantmentLevel <= 41)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchBlastProtection, 4); } else if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 33)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchBlastProtection, 3); } else if ((a_EnchantmentLevel >= 13) && (a_EnchantmentLevel <= 25)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchBlastProtection, 2); } else if ((a_EnchantmentLevel >= 5) && (a_EnchantmentLevel <= 17)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchBlastProtection, 1); } // Projectile Protection if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 36)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchProjectileProtection, 4); } else if ((a_EnchantmentLevel >= 15) && (a_EnchantmentLevel <= 30)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchProjectileProtection, 3); } else if ((a_EnchantmentLevel >= 9) && (a_EnchantmentLevel <= 24)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchProjectileProtection, 2); } else if ((a_EnchantmentLevel >= 3) && (a_EnchantmentLevel <= 18)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchProjectileProtection, 1); } // Thorns if ((a_EnchantmentLevel >= 50) && (a_EnchantmentLevel <= 100)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchThorns, 3); } else if ((a_EnchantmentLevel >= 30) && (a_EnchantmentLevel <= 80)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchThorns, 2); } else if ((a_EnchantmentLevel >= 10) && (a_EnchantmentLevel <= 60)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchThorns, 1); } if (ItemCategory::IsHelmet(a_ItemType)) { // Respiration if ((a_EnchantmentLevel >= 30) && (a_EnchantmentLevel <= 60)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchRespiration, 3); } else if ((a_EnchantmentLevel >= 20) && (a_EnchantmentLevel <= 50)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchRespiration, 2); } else if ((a_EnchantmentLevel >= 10) && (a_EnchantmentLevel <= 40)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchRespiration, 1); } // Aqua Affinity if ((a_EnchantmentLevel >= 1) && (a_EnchantmentLevel <= 41)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchAquaAffinity, 1); } } else if (ItemCategory::IsBoots(a_ItemType)) { // Feather Fall if ((a_EnchantmentLevel >= 23) && (a_EnchantmentLevel <= 33)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFeatherFalling, 4); } else if ((a_EnchantmentLevel >= 17) && (a_EnchantmentLevel <= 27)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFeatherFalling, 3); } else if ((a_EnchantmentLevel >= 11) && (a_EnchantmentLevel <= 21)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFeatherFalling, 2); } else if ((a_EnchantmentLevel >= 5) && (a_EnchantmentLevel <= 15)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFeatherFalling, 1); } // Depth Strider if ((a_EnchantmentLevel >= 30) && (a_EnchantmentLevel <= 45)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchDepthStrider, 3); } else if ((a_EnchantmentLevel >= 20) && (a_EnchantmentLevel <= 35)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchDepthStrider, 2); } else if ((a_EnchantmentLevel >= 10) && (a_EnchantmentLevel <= 25)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchDepthStrider, 1); } } } else if (a_ItemType == E_ITEM_BOW) { // Power if ((a_EnchantmentLevel >= 31) && (a_EnchantmentLevel <= 46)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchPower, 4); } else if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 36)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchPower, 3); } else if ((a_EnchantmentLevel >= 11) && (a_EnchantmentLevel <= 26)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchPower, 2); } else if ((a_EnchantmentLevel >= 1) && (a_EnchantmentLevel <= 16)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchPower, 1); } // Punch if ((a_EnchantmentLevel >= 32) && (a_EnchantmentLevel <= 57)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchPunch, 2); } else if ((a_EnchantmentLevel >= 12) && (a_EnchantmentLevel <= 37)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchPunch, 1); } // Flame and Infinity if ((a_EnchantmentLevel >= 20) && (a_EnchantmentLevel <= 50)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFlame, 1); AddEnchantmentWeightToVector(a_Enchantments, 1, enchInfinity, 1); } } else if (a_ItemType == E_ITEM_FISHING_ROD) { // Luck of the Sea and Lure if ((a_EnchantmentLevel >= 33) && (a_EnchantmentLevel <= 83)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchLuckOfTheSea, 3); AddEnchantmentWeightToVector(a_Enchantments, 1, enchLure, 3); } else if ((a_EnchantmentLevel >= 24) && (a_EnchantmentLevel <= 74)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchLuckOfTheSea, 2); AddEnchantmentWeightToVector(a_Enchantments, 1, enchLure, 2); } else if ((a_EnchantmentLevel >= 15) && (a_EnchantmentLevel <= 65)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchLuckOfTheSea, 1); AddEnchantmentWeightToVector(a_Enchantments, 1, enchLure, 1); } } else if (a_ItemType == E_ITEM_BOOK) { // All Enchantments // Sharpness if ((a_EnchantmentLevel >= 34) && (a_EnchantmentLevel <= 54)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchSharpness, 4); } else if ((a_EnchantmentLevel >= 23) && (a_EnchantmentLevel <= 43)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchSharpness, 3); } else if ((a_EnchantmentLevel >= 12) && (a_EnchantmentLevel <= 32)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchSharpness, 2); } else if ((a_EnchantmentLevel >= 1) && (a_EnchantmentLevel <= 21)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchSharpness, 1); } // Smite if ((a_EnchantmentLevel >= 29) && (a_EnchantmentLevel <= 49)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchSmite, 4); } else if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 41)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchSmite, 3); } else if ((a_EnchantmentLevel >= 13) && (a_EnchantmentLevel <= 33)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchSmite, 2); } else if ((a_EnchantmentLevel >= 5) && (a_EnchantmentLevel <= 25)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchSmite, 1); } // Bane of Arthropods if ((a_EnchantmentLevel >= 29) && (a_EnchantmentLevel <= 49)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchBaneOfArthropods, 4); } else if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 41)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchBaneOfArthropods, 3); } else if ((a_EnchantmentLevel >= 13) && (a_EnchantmentLevel <= 33)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchBaneOfArthropods, 2); } else if ((a_EnchantmentLevel >= 5) && (a_EnchantmentLevel <= 25)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchBaneOfArthropods, 1); } // Knockback if ((a_EnchantmentLevel >= 25) && (a_EnchantmentLevel <= 75)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchKnockback, 2); } else if ((a_EnchantmentLevel >= 5) && (a_EnchantmentLevel <= 55)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchKnockback, 1); } // Fire Aspect if ((a_EnchantmentLevel >= 30) && (a_EnchantmentLevel <= 80)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFireAspect, 2); } else if ((a_EnchantmentLevel >= 10) && (a_EnchantmentLevel <= 60)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFireAspect, 1); } // Looting if ((a_EnchantmentLevel >= 33) && (a_EnchantmentLevel <= 83)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchLooting, 3); } else if ((a_EnchantmentLevel >= 24) && (a_EnchantmentLevel <= 74)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchLooting, 2); } else if ((a_EnchantmentLevel >= 15) && (a_EnchantmentLevel <= 65)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchLooting, 1); } // Efficiency if ((a_EnchantmentLevel >= 31) && (a_EnchantmentLevel <= 81)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchEfficiency, 4); } else if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 71)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchEfficiency, 3); } else if ((a_EnchantmentLevel >= 11) && (a_EnchantmentLevel <= 61)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchEfficiency, 2); } else if ((a_EnchantmentLevel >= 1) && (a_EnchantmentLevel <= 51)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchEfficiency, 1); } // Silk Touch if ((a_EnchantmentLevel >= 15) && (a_EnchantmentLevel <= 65)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchSilkTouch, 1); } // Fortune if ((a_EnchantmentLevel >= 33) && (a_EnchantmentLevel <= 83)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFortune, 3); } else if ((a_EnchantmentLevel >= 24) && (a_EnchantmentLevel <= 74)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFortune, 2); } else if ((a_EnchantmentLevel >= 15) && (a_EnchantmentLevel <= 65)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFortune, 1); } // Protection if ((a_EnchantmentLevel >= 34) && (a_EnchantmentLevel <= 54)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchProtection, 4); } else if ((a_EnchantmentLevel >= 23) && (a_EnchantmentLevel <= 43)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchProtection, 3); } else if ((a_EnchantmentLevel >= 12) && (a_EnchantmentLevel <= 32)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchProtection, 2); } else if ((a_EnchantmentLevel >= 1) && (a_EnchantmentLevel <= 21)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchProtection, 1); } // Fire Protection if ((a_EnchantmentLevel >= 34) && (a_EnchantmentLevel <= 46)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFireProtection, 4); } else if ((a_EnchantmentLevel >= 26) && (a_EnchantmentLevel <= 38)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFireProtection, 3); } else if ((a_EnchantmentLevel >= 18) && (a_EnchantmentLevel <= 30)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFireProtection, 2); } else if ((a_EnchantmentLevel >= 10) && (a_EnchantmentLevel <= 22)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFireProtection, 1); } // Blast Protection if ((a_EnchantmentLevel >= 29) && (a_EnchantmentLevel <= 41)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchBlastProtection, 4); } else if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 33)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchBlastProtection, 3); } else if ((a_EnchantmentLevel >= 13) && (a_EnchantmentLevel <= 25)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchBlastProtection, 2); } else if ((a_EnchantmentLevel >= 5) && (a_EnchantmentLevel <= 17)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchBlastProtection, 1); } // Projectile Protection if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 36)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchProjectileProtection, 4); } else if ((a_EnchantmentLevel >= 15) && (a_EnchantmentLevel <= 30)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchProjectileProtection, 3); } else if ((a_EnchantmentLevel >= 9) && (a_EnchantmentLevel <= 24)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchProjectileProtection, 2); } else if ((a_EnchantmentLevel >= 3) && (a_EnchantmentLevel <= 18)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchProjectileProtection, 1); } // Thorns if ((a_EnchantmentLevel >= 50) && (a_EnchantmentLevel <= 100)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchThorns, 3); } else if ((a_EnchantmentLevel >= 30) && (a_EnchantmentLevel <= 80)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchThorns, 2); } else if ((a_EnchantmentLevel >= 10) && (a_EnchantmentLevel <= 60)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchThorns, 1); } // Respiration if ((a_EnchantmentLevel >= 30) && (a_EnchantmentLevel <= 60)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchRespiration, 3); } else if ((a_EnchantmentLevel >= 20) && (a_EnchantmentLevel <= 50)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchRespiration, 2); } else if ((a_EnchantmentLevel >= 10) && (a_EnchantmentLevel <= 40)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchRespiration, 1); } // Aqua Affinity if ((a_EnchantmentLevel >= 1) && (a_EnchantmentLevel <= 41)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchAquaAffinity, 1); } // Feather Fall if ((a_EnchantmentLevel >= 23) && (a_EnchantmentLevel <= 33)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFeatherFalling, 4); } else if ((a_EnchantmentLevel >= 17) && (a_EnchantmentLevel <= 27)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFeatherFalling, 3); } else if ((a_EnchantmentLevel >= 11) && (a_EnchantmentLevel <= 21)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFeatherFalling, 2); } else if ((a_EnchantmentLevel >= 5) && (a_EnchantmentLevel <= 15)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchFeatherFalling, 1); } // Power if ((a_EnchantmentLevel >= 31) && (a_EnchantmentLevel <= 46)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchPower, 4); } else if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 36)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchPower, 3); } else if ((a_EnchantmentLevel >= 11) && (a_EnchantmentLevel <= 26)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchPower, 2); } else if ((a_EnchantmentLevel >= 1) && (a_EnchantmentLevel <= 16)) { AddEnchantmentWeightToVector(a_Enchantments, 10, enchPower, 1); } // Punch if ((a_EnchantmentLevel >= 32) && (a_EnchantmentLevel <= 57)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchPunch, 2); } else if ((a_EnchantmentLevel >= 12) && (a_EnchantmentLevel <= 37)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchPunch, 1); } // Flame and Infinity if ((a_EnchantmentLevel >= 20) && (a_EnchantmentLevel <= 50)) { AddEnchantmentWeightToVector(a_Enchantments, 2, enchFlame, 1); AddEnchantmentWeightToVector(a_Enchantments, 1, enchInfinity, 1); } // Luck of the Sea and Lure if ((a_EnchantmentLevel >= 33) && (a_EnchantmentLevel <= 83)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchLuckOfTheSea, 3); AddEnchantmentWeightToVector(a_Enchantments, 1, enchLure, 3); } else if ((a_EnchantmentLevel >= 24) && (a_EnchantmentLevel <= 74)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchLuckOfTheSea, 2); AddEnchantmentWeightToVector(a_Enchantments, 1, enchLure, 2); } else if ((a_EnchantmentLevel >= 15) && (a_EnchantmentLevel <= 65)) { AddEnchantmentWeightToVector(a_Enchantments, 1, enchLuckOfTheSea, 1); AddEnchantmentWeightToVector(a_Enchantments, 1, enchLure, 1); } } // Unbreaking if ((a_EnchantmentLevel >= 21) && (a_EnchantmentLevel <= 71)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchUnbreaking, 3); } else if ((a_EnchantmentLevel >= 13) && (a_EnchantmentLevel <= 63)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchUnbreaking, 2); } else if ((a_EnchantmentLevel >= 5) && (a_EnchantmentLevel <= 55)) { AddEnchantmentWeightToVector(a_Enchantments, 5, enchUnbreaking, 1); } } void cEnchantments::AddEnchantmentWeightToVector(cWeightedEnchantments & a_Enchantments, int a_Weight, int a_EnchantmentID, unsigned int a_EnchantmentLevel) { cWeightedEnchantment weightedenchantment; weightedenchantment.m_Weight = a_Weight; cEnchantments enchantment; enchantment.SetLevel(a_EnchantmentID, a_EnchantmentLevel); weightedenchantment.m_Enchantments = enchantment; a_Enchantments.push_back(weightedenchantment); } void cEnchantments::RemoveEnchantmentWeightFromVector(cWeightedEnchantments & a_Enchantments, int a_EnchantmentID) { for (cWeightedEnchantments::iterator it = a_Enchantments.begin(); it != a_Enchantments.end(); ++it) { if ((*it).m_Enchantments.GetLevel(a_EnchantmentID) > 0) { a_Enchantments.erase(it); break; } } } void cEnchantments::RemoveEnchantmentWeightFromVector(cWeightedEnchantments & a_Enchantments, const cEnchantments & a_Enchantment) { for (cWeightedEnchantments::iterator it = a_Enchantments.begin(); it != a_Enchantments.end(); ++it) { if ((*it).m_Enchantments == a_Enchantment) { a_Enchantments.erase(it); break; } } } void cEnchantments::CheckEnchantmentConflictsFromVector( cWeightedEnchantments & a_Enchantments, const cEnchantments & a_FirstEnchantment ) { if (a_FirstEnchantment.GetLevel(cEnchantments::enchProtection) > 0) { RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchFireProtection); RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchBlastProtection); RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchProjectileProtection); } else if (a_FirstEnchantment.GetLevel(cEnchantments::enchFireProtection) > 0) { RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchProtection); RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchBlastProtection); RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchProjectileProtection); } else if (a_FirstEnchantment.GetLevel(cEnchantments::enchBlastProtection) > 0) { RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchProtection); RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchFireProtection); RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchProjectileProtection); } else if (a_FirstEnchantment.GetLevel(cEnchantments::enchProjectileProtection) > 0) { RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchProtection); RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchFireProtection); RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchBlastProtection); } else if (a_FirstEnchantment.GetLevel(cEnchantments::enchSharpness) > 0) { RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchSmite); RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchBaneOfArthropods); } else if (a_FirstEnchantment.GetLevel(cEnchantments::enchSmite) > 0) { RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchSharpness); RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchBaneOfArthropods); } else if (a_FirstEnchantment.GetLevel(cEnchantments::enchBaneOfArthropods) > 0) { RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchSharpness); RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchSmite); } else if (a_FirstEnchantment.GetLevel(cEnchantments::enchSilkTouch) > 0) { RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchFortune); } else if (a_FirstEnchantment.GetLevel(cEnchantments::enchFortune) > 0) { RemoveEnchantmentWeightFromVector(a_Enchantments, cEnchantments::enchSilkTouch); } } cEnchantments cEnchantments::GetRandomEnchantmentFromVector(const cWeightedEnchantments & a_Enchantments, MTRand & a_Random) { int AllWeights = 0; for (const auto & Enchantment: a_Enchantments) { AllWeights += Enchantment.m_Weight; } int RandomNumber = a_Random.RandInt(AllWeights - 1); for (const auto & Enchantment: a_Enchantments) { RandomNumber -= Enchantment.m_Weight; if (RandomNumber < 0) { return Enchantment.m_Enchantments; } } return cEnchantments(); } cEnchantments cEnchantments::SelectEnchantmentFromVector(const cWeightedEnchantments & a_Enchantments, int a_Seed) { // Sum up all the enchantments' weights: int AllWeights = 0; for (const auto & Enchantment : a_Enchantments) { AllWeights += Enchantment.m_Weight; } // If there's no weight for any of the enchantments, return an empty enchantment if (AllWeights <= 0) { return cEnchantments(); } // Pick a random enchantment: cNoise Noise(a_Seed); int RandomNumber = Noise.IntNoise1DInt(AllWeights) / 7 % AllWeights; for (const auto & Enchantment : a_Enchantments) { RandomNumber -= Enchantment.m_Weight; if (RandomNumber <= 0) { return Enchantment.m_Enchantments; } } // No enchantment picked, return an empty one (we probably shouldn't ever get here): return cEnchantments(); }
8b8fc3dde0859e4fbc5f5c2591cdc5a0d7686561
75a574cc626abb6106d749cc55c7acd28e672594
/Algorithm.vNext/LogTest.cpp
0f8a0e3d6eeb1e119224da3f1e9334b38730e0f9
[]
no_license
PeterGH/temp
6b247e0f95ac3984d61459e0648421253d11bdc3
0427b6614880e8c596cca0350a02fda08fb28176
refs/heads/master
2020-03-31T16:10:30.114748
2018-11-19T03:48:53
2018-11-19T03:48:53
152,365,449
0
0
null
null
null
null
UTF-8
C++
false
false
1,807
cpp
LogTest.cpp
#include "Test.h" void LogTest::Init(void) { Add("Default", [&]() { Logger().WriteError("Error: %d\n", LogLevel::Error); Logger().WriteWarning("Warning: %d\n", LogLevel::Warning); Logger().WriteInformation("Information: %d\n", LogLevel::Information); Logger().WriteVerbose("Verbose: %d\n", LogLevel::Verbose); }); Add("Error", [&]() { ostringstream os; Log log(os, LogLevel::Error); log.WriteVerbose("Verbose"); ASSERT1(0 == os.str().length()); log.WriteInformation("Information"); ASSERT1(0 == os.str().length()); log.WriteWarning("Warning"); ASSERT1(0 == os.str().length()); log.WriteError("Error"); ASSERT1(5 <= os.str().length()); }); Add("Warning", [&]() { ostringstream os; Log log(os, LogLevel::Warning); log.WriteVerbose("Verbose"); ASSERT1(0 == os.str().length()); log.WriteInformation("Information"); ASSERT1(0 == os.str().length()); log.WriteWarning("Warning"); ASSERT1(7 <= os.str().length()); log.WriteError("Error"); ASSERT1(12 <= os.str().length()); }); Add("Information", [&]() { ostringstream os; Log log(os, LogLevel::Information); log.WriteVerbose("Verbose"); ASSERT1(0 == os.str().length()); log.WriteInformation("Information"); ASSERT1(11 <= os.str().length()); log.WriteWarning("Warning"); ASSERT1(18 <= os.str().length()); log.WriteError("Error"); ASSERT1(23 <= os.str().length()); }); Add("Verbose", [&]() { ostringstream os; Log log(os, LogLevel::Verbose); log.WriteVerbose("Verbose"); ASSERT1(7 <= os.str().length()); log.WriteInformation("Information"); ASSERT1(18 == os.str().length()); log.WriteWarning("Warning"); ASSERT1(25 <= os.str().length()); log.WriteError("Error"); ASSERT1(30 <= os.str().length()); }); }
5bdbe720f1b4096b296de31f2edae967831da213
dc959ef10c45b4f3cd2cba9def34548c1072ff52
/loginscreen/ListContact.cpp
39dd16c570edbe1bcc11dd06a62149aec83971ec
[]
no_license
Tchaokko/babel
000ae020521d78840d7df7d0da4803e2f173372f
f84bcf1fc8c153ce9beb00bcad6e5d698285f93f
refs/heads/master
2021-01-01T17:10:31.671403
2014-11-09T14:44:34
2014-11-09T14:44:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
411
cpp
ListContact.cpp
#include <qlistwidget.h> #include <QtWidgets\qmainwindow.h> #include <QtWidgets\qapplication.h> #include "ListContact.h" #include "qlayout.h" ListContact::ListContact(QMainWindow *window) { QListWidget *listWidget = new QListWidget(window); new QListWidgetItem(("Oak"), listWidget); new QListWidgetItem(("fire"), listWidget); new QListWidgetItem(("test"), listWidget); } ListContact::~ListContact() { }
679f531b6fefefd2cf44a1a6e740e9d2f6733bd2
514bca1be3424df5cfefbec52fb70e28746f3302
/src/attendeedata.h
1ef1381e70066b0f04c9ce3e914f7349ed8dff34
[ "CC0-1.0", "BSD-3-Clause" ]
permissive
KDE/incidenceeditor
5daaada63054c26e58577347c5212e73514f71fb
d79c28455ce176a8d71dfa7701d6ec3c037f664c
refs/heads/master
2023-08-31T11:45:44.656132
2023-08-28T02:13:06
2023-08-28T02:13:06
47,668,356
7
3
null
2018-07-11T02:44:29
2015-12-09T04:26:33
C++
UTF-8
C++
false
false
1,233
h
attendeedata.h
/* SPDX-FileCopyrightText: 2010 Casey Link <unnamedrambler@gmail.com> SPDX-FileCopyrightText: 2009-2010 Klaralvdalens Datakonsult AB, a KDAB Group company <info@kdab.net> SPDX-License-Identifier: LGPL-2.0-or-later */ #pragma once #include <Libkdepim/MultiplyingLine> #include <KCalendarCore/Attendee> namespace IncidenceEditorNG { class AttendeeData : public KPIM::MultiplyingLineData, public KCalendarCore::Attendee { public: using Ptr = QSharedPointer<AttendeeData>; using List = QList<AttendeeData::Ptr>; AttendeeData(const QString &name, const QString &email, bool rsvp = false, Attendee::PartStat status = Attendee::None, Attendee::Role role = Attendee::ReqParticipant, const QString &uid = QString()) : KCalendarCore::Attendee(name, email, rsvp, status, role, uid) { } explicit AttendeeData(const KCalendarCore::Attendee &attendee) : KCalendarCore::Attendee(attendee) { } void clear() override; Q_REQUIRED_RESULT bool isEmpty() const override; /** * Return a copy of the attendee data */ Q_REQUIRED_RESULT KCalendarCore::Attendee attendee() const; }; }
d76ccd63aa9e2ff5219d8bd61828f5b68b6afb6f
547717a8c4098389c8e0870c9f3a3f5e430b9f7e
/gpgraph_test.cc
2b12bf617c86bad777146c202c4275cfc7a4d394
[]
no_license
atn34/gpgraph
3c8497b277a4bb281419d56127e9a69511ae5748
dc78d3f439bb868f916ecdd6c623aa677ba9cbe3
refs/heads/master
2021-07-12T22:20:31.889078
2017-10-14T16:14:58
2017-10-14T16:14:58
106,625,331
0
0
null
2017-10-13T21:28:19
2017-10-12T00:40:26
C++
UTF-8
C++
false
false
1,690
cc
gpgraph_test.cc
#include "gmock/gmock.h" #include "gtest/gtest.h" #include "gpgraph.h" TEST(Cycle, NoCycle) { GpGraph<1> g(3); g.add_edge(0, 1); g.add_edge(0, 2); g.add_edge(1, 2); EXPECT_FALSE(g.find_cycle()); } TEST(Cycle, CycleDontReport) { GpGraph<1> g(3); g.add_edge(0, 1); g.add_edge(1, 2); g.add_edge(2, 0); EXPECT_TRUE(g.find_cycle()); } TEST(Cycle, NoCycleReport) { GpGraph<> g(3); g.add_edge(0, 1); g.add_edge(0, 2); g.add_edge(1, 2); std::vector<int> cycle; EXPECT_FALSE(g.find_cycle(&cycle)); } TEST(Cycle, CycleReport1) { GpGraph<> g(3); g.add_edge(0, 1); g.add_edge(1, 2); g.add_edge(2, 0); std::vector<int> cycle; ASSERT_TRUE(g.find_cycle(&cycle)); EXPECT_THAT(cycle, testing::ElementsAre(2, 1, 0)); } TEST(Cycle, CycleReport2) { GpGraph<8> g(5); g.add_edge(0, 1); g.add_edge(0, 4); g.add_edge(1, 2); g.add_edge(1, 3); g.add_edge(1, 4); g.add_edge(2, 0); std::vector<int> cycle; ASSERT_TRUE(g.find_cycle(&cycle)); EXPECT_THAT(cycle, testing::ElementsAre(2, 1, 0)); } TEST(TopoSort, NoCycle) { GpGraph<1> g(4); // Tree edges g.add_edge(0, 1); g.add_edge(1, 2); g.add_edge(2, 3); // Forward edges g.add_edge(0, 2); g.add_edge(0, 3); g.add_edge(1, 3); std::vector<int> sorted; ASSERT_TRUE(g.topo_sort(&sorted)); EXPECT_THAT(sorted, testing::ElementsAre(0, 1, 2, 3)); } TEST(TopoSort, Cycle) { GpGraph<1> g(3); g.add_edge(0, 1); g.add_edge(1, 2); g.add_edge(2, 0); std::vector<int> sorted; EXPECT_FALSE(g.topo_sort(&sorted)); } TEST(EdgeData, Weights) { struct Edge { explicit Edge(int w) : weight(w) {} int weight; }; GpGraph<1, Edge> g(3); g.add_edge(0, 1, 100); }
a134aa86b94121531fb0eb60d4c7deca6b9276fe
fc04a37e98357819ceb97bc9e00076d2a6fb2849
/LanguageBarrier/GameText.cpp
e030013a220fe19bed6d7e5d442cfdd1b43d4197
[ "MIT" ]
permissive
grechnik/LanguageBarrier
deb8100779da6ab7d8529f59cefadf75c6a5de5a
798c57bbfade8f56f0be72a9b399ef0ee2b6213f
refs/heads/master
2021-01-21T18:46:51.320066
2019-10-31T20:07:41
2019-10-31T20:07:41
92,081,894
5
2
null
2017-05-22T17:43:45
2017-05-22T17:43:45
null
UTF-8
C++
false
false
47,886
cpp
GameText.cpp
#include "GameText.h" #include <list> #include <vector> #include "Game.h" #include "LanguageBarrier.h" #include "SigScan.h" typedef struct __declspec(align(4)) { char gap0[316]; int somePageNumber; char gap140[12]; const char *pString; } Sc3_t; // this is my own, not from the game typedef struct { int lines; int length; int textureStartX[lb::MAX_PROCESSED_STRING_LENGTH]; int textureStartY[lb::MAX_PROCESSED_STRING_LENGTH]; int textureWidth[lb::MAX_PROCESSED_STRING_LENGTH]; int textureHeight[lb::MAX_PROCESSED_STRING_LENGTH]; int displayStartX[lb::MAX_PROCESSED_STRING_LENGTH]; int displayStartY[lb::MAX_PROCESSED_STRING_LENGTH]; int displayEndX[lb::MAX_PROCESSED_STRING_LENGTH]; int displayEndY[lb::MAX_PROCESSED_STRING_LENGTH]; int color[lb::MAX_PROCESSED_STRING_LENGTH]; int glyph[lb::MAX_PROCESSED_STRING_LENGTH]; uint8_t linkNumber[lb::MAX_PROCESSED_STRING_LENGTH]; int linkCharCount; int linkCount; int curLinkNumber; int curColor; bool error; } ProcessedSc3String_t; // also my own typedef struct { const char *start; const char *end; uint16_t cost; bool startsWithSpace; bool endsWithLinebreak; } StringWord_t; typedef struct __declspec(align(4)) { int linkNumber; int displayX; int displayY; int displayWidth; int displayHeight; } LinkMetrics_t; typedef struct { int field_0; int field_4; int drawNextPageNow; int pageLength; int field_10; char field_14; char field_15; char field_16; char field_17; int field_18; int field_1C; int field_20; int field_24; int field_28; int field_2C; int field_30; int field_34; int field_38; int fontNumber[lb::MAX_DIALOGUE_PAGE_LENGTH]; int charColor[lb::MAX_DIALOGUE_PAGE_LENGTH]; int charOutlineColor[lb::MAX_DIALOGUE_PAGE_LENGTH]; char glyphCol[lb::MAX_DIALOGUE_PAGE_LENGTH]; char glyphRow[lb::MAX_DIALOGUE_PAGE_LENGTH]; char glyphOrigWidth[lb::MAX_DIALOGUE_PAGE_LENGTH]; char glyphOrigHeight[lb::MAX_DIALOGUE_PAGE_LENGTH]; __int16 charDisplayX[lb::MAX_DIALOGUE_PAGE_LENGTH]; __int16 charDisplayY[lb::MAX_DIALOGUE_PAGE_LENGTH]; __int16 glyphDisplayWidth[lb::MAX_DIALOGUE_PAGE_LENGTH]; __int16 glyphDisplayHeight[lb::MAX_DIALOGUE_PAGE_LENGTH]; char field_BBBC[lb::MAX_DIALOGUE_PAGE_LENGTH]; int field_C38C[lb::MAX_DIALOGUE_PAGE_LENGTH]; char charDisplayOpacity[lb::MAX_DIALOGUE_PAGE_LENGTH]; } DialoguePage_t; typedef void(__cdecl *DrawDialogueProc)(int fontNumber, int pageNumber, int opacity, int xOffset, int yOffset); static DrawDialogueProc gameExeDrawDialogue = NULL; // = (DrawDialogueProc)0x44B500; static DrawDialogueProc gameExeDrawDialogueReal = NULL; typedef void(__cdecl *DrawDialogue2Proc)(int fontNumber, int pageNumber, int opacity); static DrawDialogue2Proc gameExeDrawDialogue2 = NULL; // = (DrawDialogue2Proc)0x44B0D0; static DrawDialogue2Proc gameExeDrawDialogue2Real = NULL; typedef int(__cdecl *DialogueLayoutRelatedProc)(int unk0, int *unk1, int *unk2, int unk3, int unk4, int unk5, int unk6, int yOffset, int lineHeight); static DialogueLayoutRelatedProc gameExeDialogueLayoutRelated = NULL; // = (DialogueLayoutRelatedProc)0x448790; static DialogueLayoutRelatedProc gameExeDialogueLayoutRelatedReal = NULL; typedef void(__cdecl *DrawGlyphProc)(int textureId, float glyphInTextureStartX, float glyphInTextureStartY, float glyphInTextureWidth, float glyphInTextureHeight, float displayStartX, float displayStartY, float displayEndX, float displayEndY, int color, uint32_t opacity); static DrawGlyphProc gameExeDrawGlyph = NULL; // = (DrawGlyphProc)0x42F950; static DrawGlyphProc gameExeDrawGlyphReal = NULL; typedef void(__cdecl *DrawGlyphMaskedProc)(int fontTextureId, int maskTextureId, float glyphInTextureStartX, float glyphInTextureStartY, float glyphInTextureWidth, float glyphInTextureHeight, float glyphInMaskStartX, float glyphInMaskStartY, float displayStartX, float displayStartY, float displayEndX, float displayEndY, int color, uint32_t opacity); static DrawGlyphMaskedProc gameExeDrawGlyphMasked = NULL; static DrawGlyphMaskedProc gameExeDrawGlyphMaskedReal = NULL; typedef void(__cdecl *DrawGlyphMaskedProc2)(int fontTextureId, int maskTextureId, float glyphInTextureStartX, float glyphInTextureStartY, float glyphInTextureWidth, float glyphInTextureHeight, float displayStartX, float displayStartY, float displayEndX, float displayEndY, int color, uint32_t opacity); static DrawGlyphMaskedProc2 gameExeDrawGlyphMasked2 = NULL; static DrawGlyphMaskedProc2 gameExeDrawGlyphMasked2Real = NULL; typedef int(__cdecl *DrawRectangleProc)(float X, float Y, float width, float height, int color, uint32_t opacity); static DrawRectangleProc gameExeDrawRectangle = NULL; // = (DrawRectangleProc)0x42F890; typedef int(__cdecl *DrawPhoneTextProc)(int textureId, int xOffset, int yOffset, int lineLength, char *sc3string, int lineSkipCount, int lineDisplayCount, int color, int baseGlyphSize, int opacity); static DrawPhoneTextProc gameExeDrawPhoneText = NULL; // = (DrawPhoneTextProc)0x444F70; static DrawPhoneTextProc gameExeDrawPhoneTextReal = NULL; typedef int(__cdecl *GetSc3StringDisplayWidthProc)(const char *string, unsigned int maxCharacters, int baseGlyphSize); static GetSc3StringDisplayWidthProc gameExeGetSc3StringDisplayWidthFont1 = NULL; // = (GetSc3StringDisplayWidthProc)0x4462E0; static GetSc3StringDisplayWidthProc gameExeGetSc3StringDisplayWidthFont1Real = NULL; static GetSc3StringDisplayWidthProc gameExeGetSc3StringDisplayWidthFont2 = NULL; // = (GetSc3StringDisplayWidthProc)0x4461F0; static GetSc3StringDisplayWidthProc gameExeGetSc3StringDisplayWidthFont2Real = NULL; typedef int(__cdecl *Sc3EvalProc)(Sc3_t *sc3, int *pOutResult); static Sc3EvalProc gameExeSc3Eval = NULL; // = (Sc3EvalProc)0x4181D0; typedef int(__cdecl *GetLinksFromSc3StringProc)(int xOffset, int yOffset, int lineLength, char *sc3string, int lineSkipCount, int lineDisplayCount, int baseGlyphSize, LinkMetrics_t *result); static GetLinksFromSc3StringProc gameExeGetLinksFromSc3String = NULL; // = (GetLinksFromSc3StringProc)0x445EA0; static GetLinksFromSc3StringProc gameExeGetLinksFromSc3StringReal = NULL; typedef int(__cdecl *DrawInteractiveMailProc)( int textureId, int xOffset, int yOffset, signed int lineLength, char *sc3string, unsigned int lineSkipCount, unsigned int lineDisplayCount, int color, unsigned int baseGlyphSize, int opacity, int unselectedLinkColor, int selectedLinkColor, int selectedLink); static DrawInteractiveMailProc gameExeDrawInteractiveMail = NULL; // = (DrawInteractiveMailProc)0x4453D0; static DrawInteractiveMailProc gameExeDrawInteractiveMailReal = NULL; typedef int(__cdecl *DrawLinkHighlightProc)( int xOffset, int yOffset, int lineLength, char *sc3string, unsigned int lineSkipCount, unsigned int lineDisplayCount, int color, unsigned int baseGlyphSize, int opacity, int selectedLink); static DrawLinkHighlightProc gameExeDrawLinkHighlight = NULL; // = (DrawLinkHighlightProc)0x444B90; static DrawLinkHighlightProc gameExeDrawLinkHighlightReal = NULL; typedef int(__cdecl *GetSc3StringLineCountProc)(int lineLength, char *sc3string, unsigned int baseGlyphSize); static GetSc3StringLineCountProc gameExeGetSc3StringLineCount = NULL; // = (GetSc3StringLineCountProc)0x442790; static GetSc3StringLineCountProc gameExeGetSc3StringLineCountReal = NULL; typedef void(__cdecl *GetVisibleLinksProc)( unsigned lineLength, const char *sc3string, unsigned lineSkipCount, unsigned lineDisplayCount, unsigned baseGlyphSize, char *result); static GetVisibleLinksProc gameExeGetVisibleLinks = NULL; static uintptr_t gameExeDialogueLayoutWidthLookup1 = NULL; static uintptr_t gameExeDialogueLayoutWidthLookup1Return = NULL; static uintptr_t gameExeDialogueLayoutWidthLookup2 = NULL; static uintptr_t gameExeDialogueLayoutWidthLookup2Return = NULL; static uintptr_t gameExeDialogueLayoutWidthLookup3 = NULL; static uintptr_t gameExeDialogueLayoutWidthLookup3Return = NULL; static uintptr_t gameExeTipsListWidthLookup = NULL; static uintptr_t gameExeTipsListWidthLookupReturn = NULL; static uintptr_t gameExeNewTipWidthLookup = NULL; static uintptr_t gameExeNewTipWidthLookupReturn = NULL; static uintptr_t gameExeTipAltTitleWidthLookup = NULL; static uintptr_t gameExeTipAltTitleWidthLookupReturn = NULL; static uintptr_t gameExeDialogueSetLineBreakFlags = NULL; static uintptr_t gameExeDialogueSetLineBreakFlagsReturn = NULL; static DialoguePage_t *gameExeDialoguePages = NULL; // (DialoguePage_t *)0x164D680; static uint8_t *gameExeGlyphWidthsFont1 = NULL; // = (uint8_t *)0x52C7F0; static uint8_t *gameExeGlyphWidthsFont2 = NULL; // = (uint8_t *)0x52E058; static int *gameExeColors = NULL; // = (int *)0x52E1E8; static uint8_t *gameExeBacklogHighlightHeight = NULL; // = (uint8_t *)0x435DD4; static uint8_t *gameExeLineBreakFlags = NULL; static uint8_t widths[lb::TOTAL_NUM_CHARACTERS]; static uint8_t charFlags[lb::TOTAL_NUM_CHARACTERS]; static std::string fontBuffers[4]; static bool hasSplitFont = false; // MSVC doesn't like having these inside namespaces __declspec(naked) void dialogueLayoutWidthLookup1Hook() { __asm { movzx edx, widths[ecx] jmp gameExeDialogueLayoutWidthLookup1Return } } __declspec(naked) void dialogueLayoutWidthLookup2Hook() { __asm { push ebx movzx ebx, [lb::FONT_ROW_LENGTH] add eax, ebx movzx ecx, widths[eax] sub eax, ebx pop ebx jmp gameExeDialogueLayoutWidthLookup2Return } } __declspec(naked) void dialogueLayoutWidthLookup3Hook() { __asm { movzx ecx, widths[edx] jmp gameExeDialogueLayoutWidthLookup3Return } } __declspec(naked) void tipsListWidthLookupHook() { __asm { movzx eax, widths[edx] jmp gameExeTipsListWidthLookupReturn } } __declspec(naked) void newTipWidthLookupHook() { __asm { movzx edi, widths[edx] jmp gameExeNewTipWidthLookupReturn } } __declspec(naked) void tipAltTitleWidthLookupHook() { __asm { movzx ecx, widths[edx] jmp gameExeTipAltTitleWidthLookupReturn } } __declspec(naked) void dialogueSetLineBreakFlagsHook() { __asm { test charFlags[esi], 1 jz nope mov ecx, [gameExeLineBreakFlags] test charFlags[edx], 1 jz noprev or byte ptr [eax+ecx], 9 noprev: test charFlags[edi], 1 jz nope or byte ptr [eax+ecx], 0Ah nope: jmp gameExeDialogueSetLineBreakFlagsReturn } } namespace lb { void __cdecl drawGlyphHook(int textureId, float glyphInTextureStartX, float glyphInTextureStartY, float glyphInTextureWidth, float glyphInTextureHeight, float displayStartX, float displayStartY, float displayEndX, float displayEndY, int color, uint32_t opacity); void __cdecl drawGlyphMaskedHook(int fontTextureId, int maskTextureId, float glyphInTextureStartX, float glyphInTextureStartY, float glyphInTextureWidth, float glyphInTextureHeight, float glyphInMaskStartX, float glyphInMaskStartY, float displayStartX, float displayStartY, float displayEndX, float displayEndY, int color, uint32_t opacity); void __cdecl drawGlyphMasked2Hook(int fontTextureId, int maskTextureId, float glyphInTextureStartX, float glyphInTextureStartY, float glyphInTextureWidth, float glyphInTextureHeight, float displayStartX, float displayStartY, float displayEndX, float displayEndY, int color, uint32_t opacity); void __cdecl drawDialogueHook(int fontNumber, int pageNumber, uint32_t opacity, int xOffset, int yOffset); void __cdecl drawDialogue2Hook(int fontNumber, int pageNumber, uint32_t opacity); int __cdecl dialogueLayoutRelatedHook(int unk0, int *unk1, int *unk2, int unk3, int unk4, int unk5, int unk6, int yOffset, int lineHeight); int __cdecl drawPhoneTextHook(int textureId, int xOffset, int yOffset, int lineLength, char *sc3string, int lineSkipCount, int lineDisplayCount, int color, int baseGlyphSize, int opacity); void semiTokeniseSc3String(const char *sc3string, std::list<StringWord_t> &words, int baseGlyphSize, int lineLength); void processSc3TokenList(int xOffset, int yOffset, int lineLength, std::list<StringWord_t> &words, int lineCount, int color, int baseGlyphSize, ProcessedSc3String_t *result, bool measureOnly, float multiplier, int lastLinkNumber, int curLinkNumber, int currentColor, bool truncateExcessWord = false); int __cdecl getSc3StringDisplayWidthHook(const char *sc3string, unsigned int maxCharacters, int baseGlyphSize); int __cdecl getLinksFromSc3StringHook(int xOffset, int yOffset, int lineLength, char *sc3string, int lineSkipCount, int lineDisplayCount, int baseGlyphSize, LinkMetrics_t *result); int __cdecl drawInteractiveMailHook(int textureId, int xOffset, int yOffset, signed int lineLength, char *string, unsigned int lineSkipCount, unsigned int lineDisplayCount, int color, unsigned int glyphSize, int opacity, int unselectedLinkColor, int selectedLinkColor, int selectedLink); int __cdecl drawLinkHighlightHook(int xOffset, int yOffset, int lineLength, char *sc3string, unsigned int lineSkipCount, unsigned int lineDisplayCount, int color, unsigned int baseGlyphSize, int opacity, int selectedLink); void __cdecl getVisibleLinksHook(unsigned lineLength, const char *sc3string, unsigned lineSkipCount, unsigned lineDisplayCount, unsigned baseGlyphSize, char *result); int __cdecl getSc3StringLineCountHook(int lineLength, char *sc3string, unsigned int baseGlyphSize); // There are a bunch more functions like these but I haven't seen them get hit // during debugging and the original code *mostly* works okay if it recognises // western text as variable-width // (which some functions do, and others don't, except for symbols (also used in // Western translations) it considers full-width) void gameTextInit() { // gee I sure hope nothing important ever goes in OUTLINE_TEXTURE_ID... try { // assigned texture ids should be consistent with fixTextureForSplitFont fontBuffers[2] = slurpFile("languagebarrier\\font_a.png"); fontBuffers[3] = slurpFile("languagebarrier\\font_b.png"); fontBuffers[0] = slurpFile("languagebarrier\\font-outline_a.png"); fontBuffers[1] = slurpFile("languagebarrier\\font-outline_b.png"); hasSplitFont = true; for (int i = 0; i < 4; i++) { gameLoadTexture(OUTLINE_TEXTURE_ID + i, &(fontBuffers[i][0]), fontBuffers[i].size()); } LanguageBarrierLog("split font loaded"); } catch (std::runtime_error&) { LanguageBarrierLog("failed to load split font"); } if (!hasSplitFont) { fontBuffers[0] = slurpFile("languagebarrier\\font-outline.png"); gameLoadTexture(OUTLINE_TEXTURE_ID, &(fontBuffers[0][0]), fontBuffers[0].size()); } // the game loads this asynchronously - I'm not sure how to be notified it's // done and I can free the buffer // so I'll just do it in a hook if (hasSplitFont) { scanCreateEnableHook( "game", "drawGlyph", (uintptr_t *)&gameExeDrawGlyph, (LPVOID)drawGlyphHook, (LPVOID *)&gameExeDrawGlyphReal); scanCreateEnableHook( "game", "drawGlyphMasked", (uintptr_t*)&gameExeDrawGlyphMasked, (LPVOID)drawGlyphMaskedHook, (LPVOID*)&gameExeDrawGlyphMaskedReal); scanCreateEnableHook("game", "drawGlyphMasked2", (uintptr_t*)&gameExeDrawGlyphMasked2, (LPVOID)drawGlyphMasked2Hook, (LPVOID*)&gameExeDrawGlyphMasked2Real); } else { gameExeDrawGlyph = (DrawGlyphProc)sigScan("game", "drawGlyph"); } gameExeDrawRectangle = (DrawRectangleProc)sigScan("game", "drawRectangle"); gameExeSc3Eval = (Sc3EvalProc)sigScan("game", "sc3Eval"); gameExeBacklogHighlightHeight = (uint8_t *)sigScan("game", "backlogHighlightHeight"); if (gameExeBacklogHighlightHeight) { // gameExeBacklogHighlightHeight is (negative) offset (from vertical end of // glyph): // add eax,-0x22 (83 C0 DE) -> add eax,-0x17 (83 C0 E9) DWORD oldProtect; VirtualProtect(gameExeBacklogHighlightHeight, 1, PAGE_READWRITE, &oldProtect); *gameExeBacklogHighlightHeight = 0xE9; VirtualProtect(gameExeBacklogHighlightHeight, 1, oldProtect, &oldProtect); } scanCreateEnableHook( "game", "drawDialogue", (uintptr_t *)&gameExeDrawDialogue, (LPVOID)drawDialogueHook, (LPVOID *)&gameExeDrawDialogueReal); scanCreateEnableHook( "game", "drawDialogue2", (uintptr_t *)&gameExeDrawDialogue2, (LPVOID)drawDialogue2Hook, (LPVOID *)&gameExeDrawDialogue2Real); scanCreateEnableHook("game", "dialogueLayoutRelated", (uintptr_t *)&gameExeDialogueLayoutRelated, (LPVOID)dialogueLayoutRelatedHook, (LPVOID *)&gameExeDialogueLayoutRelatedReal); scanCreateEnableHook( "game", "drawPhoneText", (uintptr_t *)&gameExeDrawPhoneText, (LPVOID)drawPhoneTextHook, (LPVOID *)&gameExeDrawPhoneTextReal); // The following both have the same pattern and 'occurrence: 0' in the // signatures.json. // That's because after you hook one, the first match goes away. scanCreateEnableHook("game", "getSc3StringDisplayWidthFont1", (uintptr_t *)&gameExeGetSc3StringDisplayWidthFont1, (LPVOID)getSc3StringDisplayWidthHook, (LPVOID *)&gameExeGetSc3StringDisplayWidthFont1Real); scanCreateEnableHook("game", "getSc3StringDisplayWidthFont2", (uintptr_t *)&gameExeGetSc3StringDisplayWidthFont2, (LPVOID)getSc3StringDisplayWidthHook, (LPVOID *)&gameExeGetSc3StringDisplayWidthFont2Real); scanCreateEnableHook("game", "getLinksFromSc3String", (uintptr_t *)&gameExeGetLinksFromSc3String, (LPVOID)getLinksFromSc3StringHook, (LPVOID *)&gameExeGetLinksFromSc3StringReal); scanCreateEnableHook("game", "drawInteractiveMail", (uintptr_t *)&gameExeDrawInteractiveMail, (LPVOID)drawInteractiveMailHook, (LPVOID *)&gameExeDrawInteractiveMailReal); scanCreateEnableHook( "game", "drawLinkHighlight", (uintptr_t *)&gameExeDrawLinkHighlight, (LPVOID)drawLinkHighlightHook, (LPVOID *)&gameExeDrawLinkHighlightReal); scanCreateEnableHook("game", "getVisibleLinks", (uintptr_t *)&gameExeGetVisibleLinks, (LPVOID)getVisibleLinksHook, NULL); scanCreateEnableHook("game", "getSc3StringLineCount", (uintptr_t *)&gameExeGetSc3StringLineCount, (LPVOID)getSc3StringLineCountHook, (LPVOID *)&gameExeGetSc3StringLineCountReal); gameExeDialoguePages = (DialoguePage_t *)(*((uint32_t *)((uint8_t *)(gameExeDrawDialogue) + 0x18)) - 0xC); gameExeGlyphWidthsFont1 = *(uint8_t **)((uint8_t *)(gameExeDrawPhoneText) + 0x83); gameExeGlyphWidthsFont2 = *(uint8_t **)((uint8_t *)(gameExeDrawPhoneText) + 0x74); gameExeColors = (int *)(*(uint32_t *)((uint8_t *)(gameExeDrawPhoneText) + 0x272) - 0x4); scanCreateEnableHook("game", "dialogueLayoutWidthLookup1", &gameExeDialogueLayoutWidthLookup1, dialogueLayoutWidthLookup1Hook, NULL); gameExeDialogueLayoutWidthLookup1Return = (uintptr_t)((uint8_t *)gameExeDialogueLayoutWidthLookup1 + 0x27); scanCreateEnableHook("game", "dialogueLayoutWidthLookup2", &gameExeDialogueLayoutWidthLookup2, dialogueLayoutWidthLookup2Hook, NULL); gameExeDialogueLayoutWidthLookup2Return = (uintptr_t)((uint8_t *)gameExeDialogueLayoutWidthLookup2 + 0x12); scanCreateEnableHook("game", "dialogueLayoutWidthLookup3", &gameExeDialogueLayoutWidthLookup3, dialogueLayoutWidthLookup3Hook, NULL); gameExeDialogueLayoutWidthLookup3Return = (uintptr_t)((uint8_t *)gameExeDialogueLayoutWidthLookup3 + 0x7); scanCreateEnableHook("game", "tipsListWidthLookup", &gameExeTipsListWidthLookup, tipsListWidthLookupHook, NULL); gameExeTipsListWidthLookupReturn = (uintptr_t)((uint8_t *)gameExeTipsListWidthLookup + 0x14); scanCreateEnableHook("game", "dialogueSetLineBreakFlags", &gameExeDialogueSetLineBreakFlags, dialogueSetLineBreakFlagsHook, NULL); gameExeLineBreakFlags = (uint8_t *)(*(uint32_t *)((uint8_t *)gameExeDialogueSetLineBreakFlags + 0x12)); gameExeDialogueSetLineBreakFlagsReturn = (uintptr_t)((uint8_t *)gameExeDialogueSetLineBreakFlags + 0x26); scanCreateEnableHook("game", "newTipWidthLookup", &gameExeNewTipWidthLookup, newTipWidthLookupHook, NULL); gameExeNewTipWidthLookupReturn = (uintptr_t)((uint8_t *)gameExeNewTipWidthLookup + 0x13); scanCreateEnableHook("game", "tipAltTitleWidthLookup", &gameExeTipAltTitleWidthLookup, tipAltTitleWidthLookupHook, NULL); gameExeTipAltTitleWidthLookupReturn = (uintptr_t)((uint8_t *)gameExeTipAltTitleWidthLookup + 0x18); FILE *widthsfile = fopen("languagebarrier\\widths.bin", "rb"); fread(widths, 1, TOTAL_NUM_CHARACTERS, widthsfile); fclose(widthsfile); memcpy(gameExeGlyphWidthsFont1, widths, GLYPH_RANGE_FULLWIDTH_START); memcpy(gameExeGlyphWidthsFont2, widths, GLYPH_RANGE_FULLWIDTH_START); FILE *charFlagsFile = fopen("languagebarrier\\charflags.bin", "rb"); if (charFlagsFile) { fread(charFlags, 1, TOTAL_NUM_CHARACTERS, charFlagsFile); fclose(charFlagsFile); } else { // fallback to default: english letters and digits memset(charFlags + 1, 1, 26 + 26 + 10); memset(charFlags + 0x80, 1, 26 + 26 + 10); } } int __cdecl dialogueLayoutRelatedHook(int unk0, int *unk1, int *unk2, int unk3, int unk4, int unk5, int unk6, int yOffset, int lineHeight) { // release buffers // let's just do this here, should be loaded by now... for (int i = 0; i < 4; i++) fontBuffers[i] = std::string{}; return gameExeDialogueLayoutRelatedReal( unk0, unk1, unk2, unk3, unk4, unk5, unk6, yOffset + DIALOGUE_REDESIGN_YOFFSET_SHIFT, lineHeight + DIALOGUE_REDESIGN_LINEHEIGHT_SHIFT); } static void fixTextureForSplitFont(int& textureId, float& y) { bool shouldCorrect = false; if (textureId == FIRST_FONT_ID || textureId == FIRST_FONT_ID + 1) { textureId = OUTLINE_TEXTURE_ID + 2; shouldCorrect = true; } else if (textureId == OUTLINE_TEXTURE_ID) { // call from our own code shouldCorrect = true; } if (shouldCorrect && y >= 4080) { textureId++; y -= 4080; } } void __cdecl drawGlyphHook(int textureId, float glyphInTextureStartX, float glyphInTextureStartY, float glyphInTextureWidth, float glyphInTextureHeight, float displayStartX, float displayStartY, float displayEndX, float displayEndY, int color, uint32_t opacity) { // this hook should be installed only if hasSplitFont is true fixTextureForSplitFont(textureId, glyphInTextureStartY); gameExeDrawGlyphReal(textureId, glyphInTextureStartX, glyphInTextureStartY, glyphInTextureWidth, glyphInTextureHeight, displayStartX, displayStartY, displayEndX, displayEndY, color, opacity); } // used for main text on Tips screen, decay effect for long texts at boundaries of view area // maskTextureId is always 0x9D = TIPSMASK.DDS void __cdecl drawGlyphMaskedHook(int fontTextureId, int maskTextureId, float glyphInTextureStartX, float glyphInTextureStartY, float glyphInTextureWidth, float glyphInTextureHeight, float glyphInMaskStartX, float glyphInMaskStartY, float displayStartX, float displayStartY, float displayEndX, float displayEndY, int color, uint32_t opacity) { fixTextureForSplitFont(fontTextureId, glyphInTextureStartY); gameExeDrawGlyphMaskedReal(fontTextureId, maskTextureId, glyphInTextureStartX, glyphInTextureStartY, glyphInTextureWidth, glyphInTextureHeight, glyphInMaskStartX, glyphInMaskStartY, displayStartX, displayStartY, displayEndX, displayEndY, color, opacity); } // used for the backlog, decay effect for boundaries of view area // same as drawGlyphMaskedHook, glyphInMaskStartX/Y are taken from displayStartX/Y // maskTextureId is always 0x9B = BLOGMASK.DDS void __cdecl drawGlyphMasked2Hook(int fontTextureId, int maskTextureId, float glyphInTextureStartX, float glyphInTextureStartY, float glyphInTextureWidth, float glyphInTextureHeight, float displayStartX, float displayStartY, float displayEndX, float displayEndY, int color, uint32_t opacity) { fixTextureForSplitFont(fontTextureId, glyphInTextureStartY); gameExeDrawGlyphMasked2Real(fontTextureId, maskTextureId, glyphInTextureStartX, glyphInTextureStartY, glyphInTextureWidth, glyphInTextureHeight, displayStartX, displayStartY, displayEndX, displayEndY, color, opacity); } void __cdecl drawDialogueHook(int fontNumber, int pageNumber, uint32_t opacity, int xOffset, int yOffset) { DialoguePage_t *page = &gameExeDialoguePages[pageNumber]; for (int i = 0; i < page->pageLength; i++) { if (fontNumber == page->fontNumber[i]) { int displayStartX = (page->charDisplayX[i] + xOffset) * COORDS_MULTIPLIER; int displayStartY = (page->charDisplayY[i] + yOffset) * COORDS_MULTIPLIER; uint32_t _opacity = (page->charDisplayOpacity[i] * opacity) >> 8; if (page->charOutlineColor[i] != -1) { gameExeDrawGlyph( OUTLINE_TEXTURE_ID, FONT_CELL_WIDTH * page->glyphCol[i] * COORDS_MULTIPLIER, FONT_CELL_HEIGHT * page->glyphRow[i] * COORDS_MULTIPLIER, page->glyphOrigWidth[i] * COORDS_MULTIPLIER + (2 * OUTLINE_EXTRA_X), page->glyphOrigHeight[i] * COORDS_MULTIPLIER, displayStartX - OUTLINE_EXTRA_X, displayStartY, displayStartX + (COORDS_MULTIPLIER * page->glyphDisplayWidth[i]) + OUTLINE_EXTRA_X, displayStartY + (COORDS_MULTIPLIER * page->glyphDisplayHeight[i]), page->charOutlineColor[i], _opacity); } gameExeDrawGlyph( fontNumber + FIRST_FONT_ID, FONT_CELL_WIDTH * page->glyphCol[i] * COORDS_MULTIPLIER, FONT_CELL_HEIGHT * page->glyphRow[i] * COORDS_MULTIPLIER, page->glyphOrigWidth[i] * COORDS_MULTIPLIER, page->glyphOrigHeight[i] * COORDS_MULTIPLIER, displayStartX, displayStartY, displayStartX + (COORDS_MULTIPLIER * page->glyphDisplayWidth[i]), displayStartY + (COORDS_MULTIPLIER * page->glyphDisplayHeight[i]), page->charColor[i], _opacity); } } } void __cdecl drawDialogue2Hook(int fontNumber, int pageNumber, uint32_t opacity) { // dunno if this is ever actually called but might as well drawDialogueHook(fontNumber, pageNumber, opacity, 0, 0); } void semiTokeniseSc3String(const char *sc3string, std::list<StringWord_t> &words, int baseGlyphSize, int lineLength) { lineLength -= 2 * PHONE_X_PADDING; Sc3_t sc3; int sc3evalResult; StringWord_t word = {sc3string, NULL, 0, false, false}; char c; while (sc3string != NULL) { c = *sc3string; switch (c) { case -1: word.end = sc3string - 1; words.push_back(word); return; case 0: word.end = sc3string - 1; word.endsWithLinebreak = true; words.push_back(word); word = {++sc3string, NULL, 0, false, false}; break; case 4: sc3.pString = sc3string + 1; gameExeSc3Eval(&sc3, &sc3evalResult); sc3string = sc3.pString; break; case 9: case 0xB: case 0x1E: sc3string++; break; default: int glyphId = (uint8_t)sc3string[1] + ((c & 0x7f) << 8); int glyphWidth = (baseGlyphSize * widths[glyphId]) / FONT_CELL_WIDTH; if (glyphId == GLYPH_ID_FULLWIDTH_SPACE || glyphId == GLYPH_ID_HALFWIDTH_SPACE) { word.end = sc3string - 1; words.push_back(word); word = {sc3string, NULL, (uint16_t)glyphWidth, true, false}; } else { if (word.cost + glyphWidth > lineLength) { word.end = sc3string - 1; words.push_back(word); word = {sc3string, NULL, 0, false, false}; } word.cost += glyphWidth; } sc3string += 2; break; } } } void processSc3TokenList(int xOffset, int yOffset, int lineLength, std::list<StringWord_t> &words, int lineCount, int color, int baseGlyphSize, ProcessedSc3String_t *result, bool measureOnly, float multiplier, int lastLinkNumber, int curLinkNumber, int currentColor, bool truncateExcessWord) { Sc3_t sc3; int sc3evalResult; // some padding, to make things look nicer. // note that with more padding (e.g. xOffset += 5, lineLength -= 10) an extra // empty line may appear at the start of a mail // I'm not 100% sure why that is, and this'll probably come back to bite me // later, but whatever... xOffset += PHONE_X_PADDING; lineLength -= 2 * PHONE_X_PADDING; memset(result, 0, sizeof(ProcessedSc3String_t)); int curProcessedStringLength = 0; int curLineLength = 0; int spaceCost = (widths[GLYPH_ID_FULLWIDTH_SPACE] * baseGlyphSize) / FONT_CELL_WIDTH; for (auto it = words.begin(); it != words.end(); it++) { if (result->lines >= lineCount) { words.erase(words.begin(), it); break; } int wordCost = it->cost - ((curLineLength == 0 && it->startsWithSpace == true) ? spaceCost : 0); if (curLineLength + wordCost > lineLength) { if (!(truncateExcessWord && result->lines + 1 == lineCount)) { if (curLineLength != 0 && it->startsWithSpace == true) wordCost -= spaceCost; result->lines++; curLineLength = 0; } } if (result->lines >= lineCount) { words.erase(words.begin(), it); break; }; char c; const char *sc3string = (curLineLength == 0 && it->startsWithSpace == true) ? it->start + 2 : it->start; while (sc3string <= it->end) { c = *sc3string; switch (c) { case -1: goto afterWord; break; case 0: goto afterWord; break; case 4: sc3.pString = sc3string + 1; gameExeSc3Eval(&sc3, &sc3evalResult); sc3string = sc3.pString; if (color) currentColor = gameExeColors[2 * sc3evalResult]; else currentColor = gameExeColors[2 * sc3evalResult + 1]; break; case 9: curLinkNumber = ++lastLinkNumber; sc3string++; break; case 0xB: curLinkNumber = NOT_A_LINK; sc3string++; break; case 0x1E: sc3string++; break; default: int glyphId = (uint8_t)sc3string[1] + ((c & 0x7f) << 8); int i = result->length; if (result->lines >= lineCount) break; if (curLinkNumber != NOT_A_LINK) { result->linkCharCount++; } uint16_t glyphWidth = (baseGlyphSize * widths[glyphId]) / FONT_CELL_WIDTH; if (curLineLength + glyphWidth > lineLength) { // possible only for the last word if truncateExcessWord result->lines++; goto afterWord; } curLineLength += glyphWidth; if (!measureOnly) { // anything that's part of an array needs to go here, otherwise we // get buffer overflows with long mails result->linkNumber[i] = curLinkNumber; result->glyph[i] = glyphId; result->textureStartX[i] = FONT_CELL_WIDTH * multiplier * (glyphId % FONT_ROW_LENGTH); result->textureStartY[i] = FONT_CELL_HEIGHT * multiplier * (glyphId / FONT_ROW_LENGTH); result->textureWidth[i] = widths[glyphId] * multiplier; result->textureHeight[i] = FONT_CELL_HEIGHT * multiplier; result->displayStartX[i] = (xOffset + (curLineLength - glyphWidth)) * multiplier; result->displayStartY[i] = (yOffset + (result->lines * baseGlyphSize)) * multiplier; result->displayEndX[i] = (xOffset + curLineLength) * multiplier; result->displayEndY[i] = (yOffset + ((result->lines + 1) * baseGlyphSize)) * multiplier; result->color[i] = currentColor; } result->length++; sc3string += 2; break; } } afterWord: if (it->endsWithLinebreak) { result->lines++; curLineLength = 0; } } if (curLineLength == 0) result->lines--; result->linkCount = lastLinkNumber + 1; result->curColor = currentColor; result->curLinkNumber = curLinkNumber; } int __cdecl drawPhoneTextHook(int textureId, int xOffset, int yOffset, int lineLength, char *sc3string, int lineSkipCount, int lineDisplayCount, int color, int baseGlyphSize, int opacity) { ProcessedSc3String_t str; if (!lineLength) lineLength = DEFAULT_LINE_LENGTH; bool truncateExcessWord = (lineSkipCount == 0 && lineDisplayCount == 1); std::list<StringWord_t> words; semiTokeniseSc3String(sc3string, words, baseGlyphSize, lineLength); processSc3TokenList(xOffset, yOffset, lineLength, words, lineSkipCount, color, baseGlyphSize, &str, true, COORDS_MULTIPLIER, -1, NOT_A_LINK, color); processSc3TokenList(xOffset, yOffset, lineLength, words, lineDisplayCount, color, baseGlyphSize, &str, false, COORDS_MULTIPLIER, str.linkCount - 1, str.curLinkNumber, str.curColor, truncateExcessWord); for (int i = 0; i < str.length; i++) { gameExeDrawGlyph(textureId, str.textureStartX[i], str.textureStartY[i], str.textureWidth[i], str.textureHeight[i], str.displayStartX[i], str.displayStartY[i], str.displayEndX[i], str.displayEndY[i], str.color[i], opacity); } return str.lines; } int __cdecl getSc3StringDisplayWidthHook(const char *sc3string, unsigned int maxCharacters, int baseGlyphSize) { if (!maxCharacters) maxCharacters = DEFAULT_MAX_CHARACTERS; Sc3_t sc3; int sc3evalResult; int result = 0; int i = 0; signed char c; while (i <= maxCharacters && (c = *sc3string) != -1) { if (c == 4) { sc3.pString = sc3string + 1; gameExeSc3Eval(&sc3, &sc3evalResult); sc3string = sc3.pString; } else if (c < 0) { int glyphId = (uint8_t)sc3string[1] + ((c & 0x7f) << 8); result += (baseGlyphSize * widths[glyphId]) / FONT_CELL_WIDTH; i++; sc3string += 2; } } return result; } int __cdecl getLinksFromSc3StringHook(int xOffset, int yOffset, int lineLength, char *sc3string, int lineSkipCount, int lineDisplayCount, int baseGlyphSize, LinkMetrics_t *result) { ProcessedSc3String_t str; if (!lineLength) lineLength = DEFAULT_LINE_LENGTH; lineLength -= 2; // see the comment in getSc3StringLineCountHook std::list<StringWord_t> words; semiTokeniseSc3String(sc3string, words, baseGlyphSize, lineLength); processSc3TokenList(xOffset, yOffset, lineLength, words, lineSkipCount, 0, baseGlyphSize, &str, true, 1.0f, -1, NOT_A_LINK, 0); processSc3TokenList(xOffset, yOffset, lineLength, words, lineDisplayCount, 0, baseGlyphSize, &str, false, 1.0f, str.linkCount - 1, str.curLinkNumber, str.curColor); int j = 0; int processedChars = 0; for (int i = 0; i < str.length; i++) { if (str.linkNumber[i] != NOT_A_LINK) { // merge consequent characters in one rectangle; the engine has the limit of 20 rectangles per link if (j && str.linkNumber[i] == result[j - 1].linkNumber && str.displayStartX[i] == result[j - 1].displayX + result[j - 1].displayWidth && str.displayStartY[i] == result[j - 1].displayY && str.displayEndY[i] == result[j - 1].displayY + result[j - 1].displayHeight) { result[j - 1].displayWidth = str.displayEndX[i] - result[j - 1].displayX; } else { result[j].linkNumber = str.linkNumber[i]; result[j].displayX = str.displayStartX[i]; result[j].displayY = str.displayStartY[i]; result[j].displayWidth = str.displayEndX[i] - str.displayStartX[i]; result[j].displayHeight = str.displayEndY[i] - str.displayStartY[i]; j++; } processedChars++; if (processedChars >= str.linkCharCount) break; } } return j; } // This is also used for @channel threads int __cdecl drawInteractiveMailHook(int textureId, int xOffset, int yOffset, signed int lineLength, char *sc3string, unsigned int lineSkipCount, unsigned int lineDisplayCount, int color, unsigned int baseGlyphSize, int opacity, int unselectedLinkColor, int selectedLinkColor, int selectedLink) { ProcessedSc3String_t str; if (!lineLength) lineLength = DEFAULT_LINE_LENGTH; std::list<StringWord_t> words; semiTokeniseSc3String(sc3string, words, baseGlyphSize, lineLength); processSc3TokenList(xOffset, yOffset, lineLength, words, lineSkipCount, color, baseGlyphSize, &str, true, COORDS_MULTIPLIER, -1, NOT_A_LINK, color); processSc3TokenList(xOffset, yOffset, lineLength, words, lineDisplayCount, color, baseGlyphSize, &str, false, COORDS_MULTIPLIER, str.linkCount - 1, str.curLinkNumber, str.curColor); for (int i = 0; i < str.length; i++) { int curColor = str.color[i]; if (str.linkNumber[i] != NOT_A_LINK) { if (str.linkNumber[i] == selectedLink) curColor = selectedLinkColor; else curColor = unselectedLinkColor; gameExeDrawGlyph( textureId, UNDERLINE_GLYPH_X, UNDERLINE_GLYPH_Y, str.textureWidth[i], str.textureHeight[i], str.displayStartX[i], str.displayStartY[i], str.displayEndX[i], str.displayEndY[i], curColor, opacity); } gameExeDrawGlyph(textureId, str.textureStartX[i], str.textureStartY[i], str.textureWidth[i], str.textureHeight[i], str.displayStartX[i], str.displayStartY[i], str.displayEndX[i], str.displayEndY[i], curColor, opacity); } return str.lines; } int __cdecl drawLinkHighlightHook(int xOffset, int yOffset, int lineLength, char *sc3string, unsigned int lineSkipCount, unsigned int lineDisplayCount, int color, unsigned int baseGlyphSize, int opacity, int selectedLink) { ProcessedSc3String_t str; if (!lineLength) lineLength = DEFAULT_LINE_LENGTH; std::list<StringWord_t> words; semiTokeniseSc3String(sc3string, words, baseGlyphSize, lineLength); processSc3TokenList(xOffset, yOffset, lineLength, words, lineSkipCount, color, baseGlyphSize, &str, true, COORDS_MULTIPLIER, -1, NOT_A_LINK, color); processSc3TokenList(xOffset, yOffset, lineLength, words, lineDisplayCount, color, baseGlyphSize, &str, false, COORDS_MULTIPLIER, str.linkCount - 1, str.curLinkNumber, str.curColor); if (selectedLink == NOT_A_LINK) return str.lines; for (int i = 0; i < str.length; i++) { if (str.linkNumber[i] == selectedLink) { gameExeDrawRectangle(str.displayStartX[i], str.displayStartY[i], str.displayEndX[i] - str.displayStartX[i], str.displayEndY[i] - str.displayStartY[i], color, opacity); } } return str.lines; } // This is used to process keyboard up/down arrows in mails, // moving to the next/prev link or scrolling depending on results void __cdecl getVisibleLinksHook(unsigned lineLength, const char *sc3string, unsigned lineSkipCount, unsigned lineDisplayCount, unsigned baseGlyphSize, char *result) { ProcessedSc3String_t str; if (!lineLength) lineLength = DEFAULT_LINE_LENGTH; lineLength -= 2; // see the comment in getSc3StringLineCountHook std::list<StringWord_t> words; semiTokeniseSc3String(sc3string, words, baseGlyphSize, lineLength); processSc3TokenList(0, 0, lineLength, words, lineSkipCount, 0, baseGlyphSize, &str, true, COORDS_MULTIPLIER, -1, NOT_A_LINK, 0); size_t firstVisibleLink = (str.curLinkNumber == NOT_A_LINK ? str.linkCount : str.curLinkNumber); processSc3TokenList(0, 0, lineLength, words, lineDisplayCount, 0, baseGlyphSize, &str, true, COORDS_MULTIPLIER, str.linkCount - 1, str.curLinkNumber, str.curColor); for (size_t i = firstVisibleLink; i < str.linkCount; i++) result[i] = 1; } // This is used to set bounds for scrolling int __cdecl getSc3StringLineCountHook(int lineLength, char *sc3string, unsigned int baseGlyphSize) { ProcessedSc3String_t str; if (!lineLength) lineLength = DEFAULT_LINE_LENGTH; // The game calls getSc3StringLineCount() with lineLength == 0xFE for mail subject // and lineLength == 0x116 for mail body; // after that, the game calls drawPhoneTextHook with lineLength == 0xFC and 0x114 respectively. // The difference is probably not important for the in-game fixed-width font, // but once in a while it changes the layout generated by our algorithm. // // Note: if they will actually fix the arguments in the game, // we will operate with less-than-needed lines, and // this code could occasionally generate an extra empty line; // this is acceptable unlike an inaccessible last line that happens // if we operate with greater-than-needed lines. lineLength -= 2; std::list<StringWord_t> words; semiTokeniseSc3String(sc3string, words, baseGlyphSize, lineLength); processSc3TokenList(0, 0, lineLength, words, LINECOUNT_DISABLE_OR_ERROR, 0, baseGlyphSize, &str, true, 1.0f, -1, NOT_A_LINK, 0); return str.lines + 1; } }
7943de4d702900918630298af902862608da8f99
34d44a9ca7e6eb63495247ed2aed146b55f1c7db
/QuestionAns/wfb/1816.cc
1966cbb35ddf66aefa3593c3ee0445be0b68e9f8
[]
no_license
sdustlug/OpenJudge
2419c00824f29144864571e1d25c9de1a09350d2
a6550441691470df505f6a971bc9661ced1b0773
refs/heads/master
2023-09-03T11:48:01.041727
2021-10-18T13:47:57
2021-10-18T13:47:57
418,521,703
1
0
null
null
null
null
UTF-8
C++
false
false
2,395
cc
1816.cc
#include <iostream> #include <vector> using namespace std; class Matrix{ friend ostream& operator << (ostream& os,const Matrix& m){ if(m.r_ == 0 || m.c_ == 0) os<<"Error"<<endl; else { for(int i=0; i<m.r_; ++i) { for(int j=0; j<m.c_; ++j){ if(j) os<<" "; os<<m.m_[i][j]; } os<<endl; } } return os; } friend istream& operator >> (istream& is,Matrix& m){ is>>m.r_; is>>m.c_; m.m_ = new int*[m.r_]; for(int i=0; i<m.r_; ++i){ m.m_[i] = new int[m.c_]; for(int j=0; j<m.c_; ++j) is>>m.m_[i][j]; } return is; } public: Matrix() : r_(0),c_(0){} Matrix(int **m,int r,int c) : m_(m),r_(r),c_(c){} Matrix operator+(const Matrix& a) { if(r_ != a.r_ || c_ != a.c_) { Matrix c; return c; } int **m = new int*[r_]; for(int i=0; i<r_; ++i){ m[i] = new int[c_]; for(int j=0; j<c_; ++j){ m[i][j] = m_[i][j] + a.m_[i][j]; } } Matrix c(m,r_,c_); return c; } Matrix operator*(const Matrix& a){ if(c_ != a.r_) { Matrix c; return c; } int **m = new int*[r_]; for(int i=0; i<r_; ++i) m[i] = new int[c_]; for(int i=0; i<r_; ++i){ for(int j=0; j<a.c_; ++j){ m[i][j] = 0; for(int k=0; k<c_; ++k){ m[i][j] += m_[i][k] * a.m_[k][j]; } } } Matrix c(m,r_,a.c_); return c; } private: int **m_; int r_; int c_; }; int main() { int cases, i; cin>>cases; for (i = 0; i < cases; i++) { Matrix A, B, C, D; cin>>A>>B; C = A + B; D = A * B; cout<<"Case "<<i + 1<<":"<<endl; cout<<C<<endl; cout<<D; } return 0; } /************************************************************** Problem: 1816 User: 201601011420 Language: C++ Result: Accepted Time:8 ms Memory:1268 kb ****************************************************************/
c1aa602552dae49673ffc7886dc3b01b38026b30
86124d40ca4714bac5a89d45dc8dd657413d7667
/CG_Online/src/main.cpp
1e45325a04903e33e19a51ddd735b0719053316f
[]
no_license
jianming1481/3d-recognition
d6fbbcef88181e6a4032b3540701454b1cdcce9e
2e5bbdcc047813a6e194cf192fcca40a3dccd7bd
refs/heads/master
2021-01-20T06:42:54.429579
2017-05-01T10:55:12
2017-05-01T10:55:12
89,913,360
0
0
null
null
null
null
UTF-8
C++
false
false
4,880
cpp
main.cpp
#pragma once #include "../include/Recongnition3D.h" #include "ros/ros.h" #include <sensor_msgs/PointCloud2.h> #include <iostream> #include <string> #include <sstream> using namespace std; #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl_ros/transforms.h> #include <pcl_conversions/pcl_conversions.h> #include <boost/thread/thread.hpp> class SimpleRealSenseViewer { public: SimpleRealSenseViewer() : viewer("Cloud Viewer") { ROS_INFO("Initialize SimeleRealSenseViewer Class"); model = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType> ()); model_keypoints = pcl::PointCloud<PointType>::Ptr (new pcl::PointCloud<PointType> ()); model_descriptors = pcl::PointCloud<DescriptorType>::Ptr (new pcl::PointCloud<DescriptorType> ()); frames_saved = 0; start_cg = false; ncluster = 0; } void keyboardEventOccurred(const pcl::visualization::KeyboardEvent& Event,void* nothing) { if (Event.getKeySym() == "space" && Event.keyDown()) std::cout<<"space"<<endl; } boost::shared_ptr<pcl::visualization::CloudViewer> createViewer() { boost::shared_ptr<pcl::visualization::CloudViewer> v (new pcl::visualization::CloudViewer("3D Viewer")); v->registerKeyboardCallback<SimpleRealSenseViewer>(&SimpleRealSenseViewer::keyboardEventOccurred, *this); return(v); } void cloud_cb( const sensor_msgs::PointCloud2::ConstPtr& input){ pcl::PCLPointCloud2 pcl_pc2; pcl_conversions::toPCL(*input,pcl_pc2); pcl::PointCloud<pcl::PointXYZRGBA>::Ptr temp_cloud(new pcl::PointCloud<pcl::PointXYZRGBA>); pcl::fromPCLPointCloud2(pcl_pc2,*temp_cloud); if (!viewer.wasStopped()) { viewer.showCloud(temp_cloud); if ( start_cg ) { pcl::PointCloud<pcl::PointXYZRGBA>::Ptr copycloud (new pcl::PointCloud<pcl::PointXYZRGBA>); if (frames_saved == 1) { int id = 0; cout << "Input object ID:\n"; cin >> id; LoadPCDFile(model,id); LoadTXTData(model_descriptors, model_keypoints, id); } pcl::copyPointCloud(*temp_cloud, *copycloud); Recongnition3D recg3d; recg3d.InputCloud(model, copycloud); recg3d.InputFeature(model_descriptors, model_keypoints); recg3d.RecongnitionPipeline(); start_cg = false; } } // run(); } void run () { char c; char data[2]; long size = 0; int i = 1; c = getchar(); if ( c == 'r' ) { frames_saved++; cout << "frame " << frames_saved << ".\n"; start_cg = true; sprintf(data, "%d", frames_saved); } } void SetInputDirectory(string outdir) { OUT_DIR = outdir; cout << "Directory is " << OUT_DIR << endl; } void SetFrameNumber(int framenum) { frame_number = framenum; } void LoadPCDFile(pcl::PointCloud<PointType>::Ptr &model,int idx) { std::stringstream pcdpath; pcdpath << OUT_DIR.c_str() << "cloud_cluster_1_" << idx << ".pcd"; cout << "PCD Path = " << pcdpath.str() << endl; if (pcl::io::loadPCDFile<PointType>(pcdpath.str(), *model) < 0) { std::cout << "Error loading model cloud." << std::endl; } } void LoadTXTData(pcl::PointCloud<DescriptorType>::Ptr &model_descriptors, pcl::PointCloud<PointType>::Ptr &model_keypoints, int idx) { int nfeat = 0; int featidx = 0; std::vector<int> featidex; std::stringstream txtpath; txtpath << OUT_DIR.c_str() << "cshot_1_" << idx << ".txt"; cout << "TXT Path = " << txtpath.str() << endl; ifstream fin(txtpath.str()); fin >> nfeat; model_descriptors->resize(nfeat); for (int i = 0; i < nfeat; i++) { fin >> featidx; featidex.push_back(featidx); for (int j = 0; j < 9; j++) { fin >> model_descriptors->points[i].rf[j]; } for (int k = 0; k < 1344; k++) { fin >> model_descriptors->points[i].descriptor[k]; } } pcl::copyPointCloud(*model, featidex, *model_keypoints); } pcl::visualization::CloudViewer viewer; private: pcl::PointCloud<PointType>::Ptr model; pcl::PointCloud<PointType>::Ptr model_keypoints; pcl::PointCloud<DescriptorType>::Ptr model_descriptors; int frames_saved; bool start_cg; string OUT_DIR; int ncluster; int frame_number; }; int main(int argc,char **argv) { ros::init(argc, argv, "RS_TrainMain"); ros::NodeHandle n; SimpleRealSenseViewer v; ros::Subscriber cloud_sub = n.subscribe("/camera/depth/points", 1, &SimpleRealSenseViewer::cloud_cb,&v); boost::thread* thr = new boost::thread(boost::bind(&SimpleRealSenseViewer::run, &v)); v.SetInputDirectory("/home/iclab-giga/catkin_ws/devel/lib/CG_Online/"); ros::Rate loop_rate(100); ros::spin(); }
efa90b75b16b4f1e7cf4d8ed07aaa897bd84589d
e56a1c7e0a55fe29965192bce7256f621b51b7db
/启发式评估.cpp
ea5ddc77bebdf5367fc297ae54c4a6b2bfc7c8fd
[]
no_license
DS201810/DS_C-
9953e83294d79ab24c9b438a1673aee47774be3d
07d07d23aa66f39d87f92235c5d2246ab716af62
refs/heads/master
2021-05-21T14:11:24.287397
2020-04-15T08:29:21
2020-04-15T08:29:21
252,677,310
0
0
null
null
null
null
GB18030
C++
false
false
16,210
cpp
启发式评估.cpp
#include<iostream> #include<vector> #include<stdlib.h> using namespace std; class Board{ public: int comScore; int humScore; int x; int y; }; struct Score{ int ONE=5; //活一 int BLOCKED_ONE=1;//眠一 int TWO=150;//活二 int MIST_TWO=100;//朦胧二 int BLOCKED_TWO=10;//眠二 int THREE= 350; int MIST_THREE=180; int BLOCKED_THREE=150; int FOUR=900; int BLOCKED_FOUR= 460; int FIVE=1000; int BLOCKED_FIVE:500; int SIX=10000; }; bool hasNeighbor (int x,int y,int distance,int count,int board[19][19]) { //判断是否有邻居 int len = 19; int startX = x-distance; int endX = x+distance; int startY = y-distance; int endY = y+distance; for(int i=startX;i<=endX;i++) { if(i<0||i>=len) continue; for(int j=startY;j<=endY;j++) { if(j<0||j>=len) continue; if(i==x && j==y) continue; if(board[i][j] != 2) { count --; if(count <= 0) return true; } } } return false; } int Toscore(int count,int block,int empty){ Score score; if(empty <= 0) { if(count >= 6) return score.SIX; if(block == 0) { switch(count) { case 1: return score.ONE; case 2: return score.TWO; case 3: return score.THREE; case 4: return score.FOUR; case 5: return score.FIVE; } } if(block == 1) { switch(count) { case 1: return score.BLOCKED_ONE; case 2: return score.BLOCKED_TWO; case 3: return score.BLOCKED_THREE; case 4: return score.BLOCKED_FOUR; case 5: return score.BLOCKED_FIVE; } } } else if(empty == 1 || empty == count-1) { //第1个是空位 if(count >= 6) { return score.SIX; } if(block == 0) { switch(count) { case 2: return score.TWO/2; case 3: return score.MIST_TWO; case 4: return score.MIST_THREE; case 5: return score.FOUR; } } if(block == 1) { switch(count) { case 2: return score.BLOCKED_TWO; case 3: return score.BLOCKED_THREE; case 4: return score.BLOCKED_FOUR; case 5: return score.BLOCKED_FIVE; } } } else if(empty == 2 || empty == count-2) { //第二个是空位 if(count >= 7) { return score.FIVE; } if(block ==0) { switch(count) { case 3: return score.MIST_TWO; case 4: return score.THREE; case 5: return score.BLOCKED_FOUR; case 6: return score.FOUR; } } if(block == 1) { switch(count) { case 3: return score.BLOCKED_THREE; case 4: return score.BLOCKED_FOUR; case 5: return score.BLOCKED_FOUR; case 6: return score.FOUR; } } if(block == 2) { switch(count) { case 4: return 0; case 5:return 0; case 6: return score.BLOCKED_FOUR; } } } else if(empty ==3 || empty == count-3) { if(count >= 9) { return score.SIX; } if(block == 0) { switch(count) { case 4:return score.THREE; case 5: return score.THREE; case 6: return score.BLOCKED_FOUR; case 7: return score.FOUR; case 8:return score.FIVE; } } if(block == 1) { switch(count) { case 4:return score.BLOCKED_THREE; case 5:return score.THREE; case 6: return score.BLOCKED_FOUR; case 7: return score.FOUR; case 8:return score.BLOCKED_FIVE; } } if(block == 2) { switch(count) { case 4: return 0; case 5:return 0; case 6:return score.BLOCKED_THREE; case 7: return score.BLOCKED_FOUR; } } } else if(empty == 4 || empty == count-4) { if(count >= 10) { return score.SIX; } if(block == 0) { switch(count) { case 5:return score.FOUR; case 6:return score.FOUR; case 7:return score.FOUR; case 8: return score.FOUR; case 9:return score.FIVE; } } if(block == 1) { switch(count) { case 4:return score.BLOCKED_FOUR; case 5:return score.BLOCKED_FOUR; case 6:return score.BLOCKED_FOUR; case 7: return score.BLOCKED_FOUR; case 8: return score.FOUR; case 9: return score.BLOCKED_FIVE; } } if(block == 2) { switch(count) { case 5:return score.BLOCKED_TWO; case 6:return score.BLOCKED_THREE; case 7:return score.BLOCKED_FOUR; case 8: return score.BLOCKED_FOUR; case 9:return score.BLOCKED_FIVE; } } } else if(empty == 5 || empty == count-5) { if(count>=11) return score.SIX; if(block==0){ switch(count){ case 6:return score.FIVE; case 7:return score.FIVE; case 8:return score.FIVE; case 9:return score.FOUR*2; case 10:return score.FIVE*2; } } if(block==1){ switch(count){ case 6:return score.BLOCKED_FIVE; case 7:return score.BLOCKED_FIVE; case 8:return score.BLOCKED_FIVE; case 9:return score.BLOCKED_FOUR*2; case 10:return score.FIVE*2; } } if(block==2){ switch(count){ case 6:return score.BLOCKED_FOUR; case 7:return score.BLOCKED_FOUR; case 8:return score.BLOCKED_FOUR; case 9:return score.BLOCKED_FOUR*2; case 10:return score.FIVE*2; } } } else if(empty == 6 || empty == count-6) return score.SIX; return 0; } int scorePoint(int x,int y,int role,int board[19][19]){ Board b; int scorecache[2][19][19][4]; int result=0; int count = 0; int block = 0; int empty=0; int secondCount = 0; //另一个方向的count //方向为横向 count = 1; block = 0; empty = -1; secondCount=0; for(int i=y+1;true;i++){ if(i>=19) {block++; break; } if(board[x][i]==2){ if(empty==-1&&i<18&&board[x][i+1]==role) {empty=count; continue; } else break; } if(board[x][i]==role){ count++; continue; } else{ block++; break; } } for(int i=y-1;true;i--){ if(i<0){ block++; break; } if(board[x][i]==2){ if(empty == -1 && i>0 && board[x][i-1] == role) { empty = 0; //注意这里是0,因为是从右往左走的 continue; } else break; } if(board[x][i]==role){ secondCount++; if (empty != -1 ) {empty ++; //注意这里,如果左边又多了己方棋子,那么empty的位置就变大了 continue;}} else { block ++; break; } } count=count+secondCount; scorecache[role][x][y][0]=Toscore(count,block,empty); result=result+scorecache[role][x][y][0]; //方向为竖向 count = 1; block = 0; empty = -1; secondCount=0; for(int i=x+1;true;i++){ if(i>=19) {block++; break; } if(board[i][y]==2){ if(empty==-1&&i<18&&board[x+1][y]==role) {empty=count; continue; } else break; } if(board[i][y]==role){ count++; continue; } else{ block++; break; } } for(int i=x-1;true;i--){ if(i<0){ block++; break; } if(board[i][y]==2){ if(empty == -1 && i>0 && board[x-1][y] == role) { empty = 0; //注意这里是0,因为是从右往左走的 continue; } else break; } if(board[i][y]==role){ secondCount++; if (empty != -1 ) { empty ++; //empty的位置变大 continue;}} else { block ++; break; } } count=count+secondCount; scorecache[role][x][y][1]=Toscore(count,block,empty); result=result+scorecache[role][x][y][1]; //方向为↘向 count = 1; block = 0; empty = -1; secondCount=0; for(int i=1;true;i++){ int m=x+i; int n=y+i; if(m>=19||n>=19) {block++; break; } if(board[m][n]==2){ if(empty==-1&&(m<18&&n<18)&&board[m+1][n+1]==role) {empty=count; continue; } else break; } if(board[m][n]==role){ count++; continue; } else{ block++; break; } } for(int i=1;true;i++){ int m=x-i; int n=y-i; if(m<0||n<0){ block++; break; } if(board[m][n]==2){ if(empty == -1 && m>0&&n>0 && board[m-1][n-1] == role) { empty = 0; //注意这里是0,因为是从右往左走的 continue; } else break; } if(board[m][n]==role){ secondCount++; if (empty != -1 ) {empty ++; //注意这里,如果左边又多了己方棋子,那么empty的位置就变大了 continue;}} else { block ++; break; } } count=count+secondCount; scorecache[role][x][y][2]=Toscore(count,block,empty); result=result+scorecache[role][x][y][2]; //方向为↙向 count = 1; block = 0; empty = -1; secondCount=0; for(int i=1;true;i++){ int m=x+i; int n=y-i; if(m>=19||n>=19||m<0||n<0) {block++; break; } if(board[m][n]==2){ if(empty==-1&&(m<18&&n>0)&&board[m+1][n-1]==role) {empty=count; continue; } else break; } if(board[m][n]==role){ count++; continue; } else{ block++; break; } } for(int i=1;true;i++){ int m=x-i; int n=y+i; if(m<0||n>=19){ block++; break; } if(board[m][n]==2){ if(empty == -1 && m>0&&n>0 && board[m-1][n+1] == role) { empty = 0; //注意这里是0,因为是从右往左走的 continue; } else break; } if(board[m][n]==role){ secondCount++; if (empty != -1 ) { empty ++; //注意这里,如果左边又多了己方棋子,那么empty的位置就变大了 continue;}} else { block ++; break; } } count=count+secondCount; scorecache[role][x][y][3]=Toscore(count,block,empty); result=result+scorecache[role][x][y][3]; return result; } Board* gen(int role,int computerside,int board[19][19]){ //role为当前需要评估的角色 //computerside为己方执棋颜色 //board为局面 Board p; Score S; vector<Board> comsix; vector<Board> humsix; vector<Board> comfives; vector<Board> humfives; vector<Board> comfours; vector<Board> humfours; vector<Board> comblockedfours ; vector<Board> humblockedfours ; vector<Board> comtwothrees; vector<Board> humtwothrees; vector<Board> comthrees ; vector<Board> humthrees ; vector<Board> comtwos ; vector<Board> humtwos; vector<Board> neighbors; int com[19][19]; int hum[19][19]; for(int i=0;i<19;i++) for(int j=0;j<19;j++){ if(board[i][j] == 2) { //必须是有邻居的才行 int cs = scorePoint(i, j, computerside,board);//己方分数 int hs = scorePoint( i, j, 1-computerside,board);//对方分数 com[i][j] = cs; hum[i][j] = hs; } else if (board[i][j] ==computerside) { // 对己方打分,敌人此位置分数为0 com[i][j] = scorePoint( i, j,computerside,board); hum[i][j] = 0; } else if (board[i][j] ==1-computerside) { // 对敌方打分,电脑位置分数为0 hum[i][j] = scorePoint(i, j, 1-computerside,board); com[i][j] = 0;} if(board[i][j]==2){ p.humScore=hum[i][j]; p.comScore=com[i][j]; p.x=i; p.y=j; if(p.comScore>=S.SIX){ comsix.push_back(p); }else if(p.humScore>=S.SIX) { humsix.push_back(p); } else if(p.comScore >= S.FIVE) {//电脑能不能连成5 comfives.push_back(p); } else if(p.humScore >= S.FIVE) {//玩家能不能连成5 humfives.push_back(p); } else if(p.comScore >= S.FOUR) { comfours.push_back(p); } else if(p.humScore >= S.FOUR) { humfours.push_back(p); } else if(p.comScore >= S.BLOCKED_FOUR) { comblockedfours.push_back(p); } else if(p.humScore >= S.BLOCKED_FOUR) { humblockedfours.push_back(p); } else if(p.comScore >= 2*S.THREE) { //能成双三也行 comtwothrees.push_back(p); } else if(p.humScore >= 2*S.THREE) { humtwothrees.push_back(p); } else if(p.comScore >= S.THREE) { comthrees.push_back(p); } else if(p.humScore>= S.THREE) { humthrees.push_back(p); } else if(p.comScore >= S.TWO) { comtwos.push_back(p); } else if(p.humScore >= S.TWO) { humtwos.push_back(p); } else neighbors.push_back(p); } } //如果成六,是必杀棋,直接返回 if(!comsix.empty()) { return &comsix[0]; } if(role==computerside&&!comfives.empty()) return &comfives[0]; if(role==1-computerside&&!humfives.empty()) return &humfives[0]; // 自己能活四,则直接活四,不考虑冲四 if (role ==computerside && !comfours.empty()) return &comfours[0]; if (role ==1-computerside && !humfours.empty()) return &humfours[0]; // 对面有活四冲四,自己冲四都没,则只考虑对面活四 (此时对面冲四就不用考虑了) if (role ==computerside && !humfours.empty() && comblockedfours.empty()) return &humfours[0]; if (role ==1-computerside && !comfours.empty() && humblockedfours.empty()) return &comfours[0]; // 对面有活四自己有冲四,则都考虑下 vector<Board> fours; vector<Board>blockedfours; if(role==computerside){ fours.insert(fours.end(),comfours.begin(),comfours.end()); fours.insert(fours.end(),humfours.begin(),humfours.end()); blockedfours.insert(blockedfours.end(), comblockedfours.begin(),comblockedfours.end()); blockedfours.insert(blockedfours.end(),humblockedfours.begin(),humblockedfours.end()); } else{ fours.insert(fours.end(),humfours.begin(),humfours.end()); fours.insert(fours.end(),comfours.begin(),comfours.end()); blockedfours.insert(blockedfours.end(),humblockedfours.begin(),humblockedfours.end()); blockedfours.insert(blockedfours.end(),comblockedfours.begin(),comblockedfours.end()); } if (!fours.empty()) {vector<Board> sum; sum.insert(sum.end(),fours.begin(),fours.end()); sum.insert(sum.end(),blockedfours.begin(),blockedfours.end()); return &sum[0]; } vector<Board> result; if (role == computerside) { result.insert(result.end(),comtwothrees.begin(),comtwothrees.end()); result.insert(result.end(),humtwothrees.begin(),humtwothrees.end()); result.insert(result.end(),comblockedfours.begin(),comblockedfours.end()); result.insert(result.end(),humblockedfours.begin(),humblockedfours.end()); result.insert(result.end(),comthrees.begin(),comthrees.end()); result.insert(result.end(),humthrees.begin(),humthrees.end()); } if (role ==1-computerside) { result.insert(result.end(),humtwothrees.begin(),humtwothrees.end()); result.insert(result.end(),comtwothrees.begin(),comtwothrees.end()); result.insert(result.end(),humblockedfours.begin(),humblockedfours.end()); result.insert(result.end(),comblockedfours.begin(),comblockedfours.end()); result.insert(result.end(),humthrees.begin(),humthrees.end()); result.insert(result.end(),comthrees.begin(),comthrees.end()); } //双三很特殊,因为能形成双三的不一定比一个活三强 if(!comtwothrees.empty() || !humtwothrees.empty()) { return &result[0]; } // 只返回大于等于活三的棋 vector<Board> twos; if (role ==computerside) { twos.insert(twos.end(),comtwos.begin(),comtwos.end()); twos.insert(twos.end(),humtwos.begin(),humtwos.end());} else { twos.insert(twos.end(),humtwos.begin(),humtwos.end()); twos.insert(twos.end(),comtwos.begin(),comtwos.end()); } return &result[0]; }
5cacfbbb4b4b7c83d44658465a71323fddff79d2
975142ac6ec86cebb53de5e6e070fd8596379eaa
/GrassTagFileConverter.cpp
4e49aa80e0cb8d9e6c8bd6df9ef5135adeda4e39
[]
no_license
ivandro/Nightmare-s-lair
9d66527c56a62c045a1ad2d64451ef2bdc37ea71
33a474be5ef5f476a29a7487fad0e4ed07be48cb
refs/heads/master
2016-09-06T07:00:29.032471
2011-12-05T19:39:55
2011-12-05T19:39:55
2,674,324
0
0
null
null
null
null
UTF-8
C++
false
false
403
cpp
GrassTagFileConverter.cpp
#include "GrassTagFileConverter.h" namespace example { GrassTagFileConverter::GrassTagFileConverter() { tagFileMap[ TEXTURE_WALL ] = "Images\\Wall\\dirtyWall\\grass.tga"; tagFileMap[ TEXTURE_FLOOR ] = "Images\\Grass\\Grass2.jpg"; } GrassTagFileConverter::~GrassTagFileConverter() {} std::string GrassTagFileConverter::convert( TextureTags tag ) { return tagFileMap[ tag ]; } }
9801c4737af84dc2487b2d2ba8970d38f4586d0d
4c9d1123d1016fbcf7778491a3ef52cca5b687a1
/IDAutomaton.cpp
58ab4373afee402b1d1c1b8bc64f8096f9d903e2
[ "MIT" ]
permissive
Chuychuychuy98/project-2-parser
b04b8dab66ba2c6e810b013171c02f2a568c2082
f068c62ee16ce988268dc481de669d01881e3168
refs/heads/main
2023-08-23T04:57:52.391597
2021-10-02T02:51:32
2021-10-02T02:51:32
409,445,730
0
0
null
null
null
null
UTF-8
C++
false
false
509
cpp
IDAutomaton.cpp
// // Created by Chandler Rowe on 9/13/21. // #include "IDAutomaton.h" void IDAutomaton::S0(const std::string &input) { if (isalpha(input[index])) { index++; inputRead++; S1(input); } else { Serr(); } } void IDAutomaton::S1(const std::string &input) { if ((int)input.size() <= index || isspace(input[index])) { return; } else if (isalnum(input[index])) { index++; inputRead++; S1(input); } else { } }
57747457f52bb6cfb931f062bfc858715906ea29
362d81bc451933bad0fa2b07c6bfb42137599ae1
/linux/platform/s5p4418/apps/diagnostic/inc/debug_window.h
57969e8e81eda9b1d82f06a2286563e1f3e26c76
[]
no_license
Jiazhiy/android
b5f749172f6098be8632e2bd1a542d8a4d42a356
a64750ecbdb01422ddeb9ff5504c50de729dfd6e
refs/heads/master
2022-12-20T22:52:18.702185
2020-09-19T03:49:54
2020-09-19T03:49:54
296,186,694
0
1
null
null
null
null
UTF-8
C++
false
false
2,675
h
debug_window.h
#ifndef __debug_window_h__ #define __debug_window_h__ #include <SDL/SDL.h> #include <SDL/SDL_ttf.h> // nexell diagnostic configuration interface #include <diag_config.h> #include <utils.h> #define MAX_LINE_BUFFER 255 #define MAX_LINES 128 typedef struct LINE_BUFFER{ char msg[MAX_LINE_BUFFER+1]; char size; }LINE_BUFFER; class DebugWindow { public: DebugWindow(SDL_Rect *rect, int fontSize) : m_Surface(NULL) , m_Font(NULL) , m_FontSize(fontSize) , m_PosX( rect->x ) , m_PosY( rect->y ) , m_Lines( 0 ), m_Head( 0 ), m_Tail( 0 ) { const SDL_VideoInfo *info = SDL_GetVideoInfo(); m_Surface = SDL_SetVideoMode( info->current_w, info->current_h, info->vfmt->BitsPerPixel, SDL_SWSURFACE ); m_Font = TTF_OpenFont(m_DiagCfg.GetFont(), fontSize); m_Rect.x = rect->x; m_Rect.y = rect->y; m_Rect.w = rect->w; m_Rect.h = rect->h; m_FontHeight = TTF_FontHeight( m_Font ); m_MaxDspLines = (m_Rect.h-m_Rect.y) / m_FontHeight; Clear(); } virtual ~DebugWindow() { if( m_Font ) TTF_CloseFont( m_Font ); if( m_Surface ) SDL_FreeSurface( m_Surface ); } void DrawMessage( const char *msg ) { int len = strlen(msg); LINE_BUFFER *lineBuf = &m_MsgBuffer[m_Tail]; if( len > MAX_LINE_BUFFER ){ len = MAX_LINE_BUFFER; strncpy( lineBuf->msg, msg, len ); }else strcpy( lineBuf->msg, msg ); lineBuf->size = len; m_Lines ++; m_Tail = (m_Tail+1)%m_MaxDspLines; if( m_Lines > m_MaxDspLines ){ m_Lines = m_MaxDspLines; m_Head = (m_Head+1)%m_MaxDspLines; SDL_FillRect( m_Surface, &m_Rect, SDL_MapRGB(m_Surface->format, 0x00, 0x00, 0x00 ) ); } UpdateScreen(); } void Clear() { m_Tail = m_Head = 0; m_Lines = 0; SDL_FillRect( m_Surface, &m_Rect, SDL_MapRGB(m_Surface->format, 0x00, 0x00, 0x00 ) ); } private: void UpdateScreen() { int i; int tmp = m_Head; LINE_BUFFER *lineBuf; SDL_Rect rect; // Draw Lines & Update Screen SDL_Color fgColor = { 0xFF, 0xFF, 0xFF, 0 }; rect.x = m_Rect.x; rect.w = m_Rect.w; rect.h = m_FontHeight; for( i=0 ; i<m_Lines ; i++ ) { rect.y = i* m_FontHeight + m_Rect.y; lineBuf = &m_MsgBuffer[tmp]; tmp = (tmp+1)%m_MaxDspLines; DrawString2( m_Surface, m_Font, lineBuf->msg, rect, fgColor, 0, 0 ); // Don't Need Alignment } SDL_Flip( m_Surface ); } private: SDL_Surface *m_Surface; TTF_Font *m_Font; int m_FontSize; SDL_Rect m_Rect; int m_FontHeight; int m_PosX, m_PosY; NX_DiagConfig m_DiagCfg; // Configuration Util // Message Buffer int m_MaxDspLines; // Max Displable Lines int m_Lines; struct LINE_BUFFER m_MsgBuffer[MAX_LINES]; int m_Head, m_Tail; }; #endif // __debug_window_h__
3b2d946c23ed88f26c9679af9d8785e72cb3b90f
d396171b05504dec8e9b70a7ad0e6badd11f5d2b
/ceee/ie/plugin/bho/webrequest_notifier.cc
beb4c609df924b966b6b0b7946ca3c14c9d4dfdf
[]
no_license
madecoste/ceee
6e312b18b28e2c39418f769a274e71c9f592943b
30efa2b3ea7b4cef459b4763686bd0664aa7798f
refs/heads/master
2016-09-05T18:26:19.713716
2011-02-02T20:02:52
2011-02-02T20:02:52
32,116,269
2
0
null
null
null
null
UTF-8
C++
false
false
30,726
cc
webrequest_notifier.cc
// 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. // // Web request notifier implementation. #include "ceee/ie/plugin/bho/webrequest_notifier.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "chrome_frame/function_stub.h" #include "chrome_frame/utils.h" namespace { const wchar_t kUrlMonModuleName[] = L"urlmon.dll"; const char kWinINetModuleName[] = "wininet.dll"; const char kInternetSetStatusCallbackAFunctionName[] = "InternetSetStatusCallbackA"; const char kInternetSetStatusCallbackWFunctionName[] = "InternetSetStatusCallbackW"; const char kInternetConnectAFunctionName[] = "InternetConnectA"; const char kInternetConnectWFunctionName[] = "InternetConnectW"; const char kHttpOpenRequestAFunctionName[] = "HttpOpenRequestA"; const char kHttpOpenRequestWFunctionName[] = "HttpOpenRequestW"; const char kHttpSendRequestAFunctionName[] = "HttpSendRequestA"; const char kHttpSendRequestWFunctionName[] = "HttpSendRequestW"; const char kInternetReadFileFunctionName[] = "InternetReadFile"; } // namespace WebRequestNotifier::WebRequestNotifier() : internet_status_callback_stub_(NULL), start_count_(0), initialize_state_(NOT_INITIALIZED), broker_rpc_client_(true), webrequest_events_funnel_(&broker_rpc_client_) { } WebRequestNotifier::~WebRequestNotifier() { DCHECK_EQ(start_count_, 0); } bool WebRequestNotifier::ConnectBroker() { if (broker_rpc_client_.is_connected()) return true; HRESULT hr = broker_rpc_client_.Connect(true); DCHECK(SUCCEEDED(hr)); return SUCCEEDED(hr); } bool WebRequestNotifier::RequestToStart() { { CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); start_count_++; if (initialize_state_ != NOT_INITIALIZED) return initialize_state_ != FAILED_TO_INITIALIZE; initialize_state_ = INITIALIZING; } bool success = false; do { if (!ConnectBroker()) break; // We are not going to unpatch any of the patched WinINet functions or the // status callback function. Instead, we pin our DLL in memory so that all // the patched functions can be accessed until the process goes away. PinModule(); PatchWinINetFunction(kInternetSetStatusCallbackAFunctionName, &internet_set_status_callback_a_patch_, InternetSetStatusCallbackAPatch); PatchWinINetFunction(kInternetSetStatusCallbackWFunctionName, &internet_set_status_callback_w_patch_, InternetSetStatusCallbackWPatch); if (!HasPatchedOneVersion(internet_set_status_callback_a_patch_, internet_set_status_callback_w_patch_)) { break; } PatchWinINetFunction(kInternetConnectAFunctionName, &internet_connect_a_patch_, InternetConnectAPatch); PatchWinINetFunction(kInternetConnectWFunctionName, &internet_connect_w_patch_, InternetConnectWPatch); if (!HasPatchedOneVersion(internet_connect_a_patch_, internet_connect_w_patch_)) { break; } PatchWinINetFunction(kHttpOpenRequestAFunctionName, &http_open_request_a_patch_, HttpOpenRequestAPatch); PatchWinINetFunction(kHttpOpenRequestWFunctionName, &http_open_request_w_patch_, HttpOpenRequestWPatch); if (!HasPatchedOneVersion(http_open_request_a_patch_, http_open_request_w_patch_)) { break; } PatchWinINetFunction(kHttpSendRequestAFunctionName, &http_send_request_a_patch_, HttpSendRequestAPatch); PatchWinINetFunction(kHttpSendRequestWFunctionName, &http_send_request_w_patch_, HttpSendRequestWPatch); if (!HasPatchedOneVersion(http_send_request_a_patch_, http_send_request_w_patch_)) { break; } PatchWinINetFunction(kInternetReadFileFunctionName, &internet_read_file_patch_, InternetReadFilePatch); if (!internet_read_file_patch_.is_patched()) break; success = true; } while (false); { CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); initialize_state_ = success ? SUCCEEDED_TO_INITIALIZE : FAILED_TO_INITIALIZE; } return success; } void WebRequestNotifier::RequestToStop() { CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (start_count_ <= 0) { NOTREACHED(); return; } start_count_--; if (start_count_ == 0) { // It is supposed that every handle must be closed using // InternetCloseHandle(). However, IE seems to leak handles in some (rare) // cases. For example, when the current page is a JPG or GIF image and the // user refreshes the page. // If that happens, the server_map_ and request_map_ won't be empty. LOG_IF(WARNING, !server_map_.empty() || !request_map_.empty()) << "There are Internet handles that haven't been closed when " << "WebRequestNotifier stops."; for (RequestMap::iterator iter = request_map_.begin(); iter != request_map_.end(); ++iter) { TransitRequestToNextState(RequestInfo::ERROR_OCCURRED, &iter->second); } server_map_.clear(); request_map_.clear(); } } void WebRequestNotifier::PatchWinINetFunction( const char* name, app::win::IATPatchFunction* patch_function, void* handler) { DWORD error = patch_function->Patch(kUrlMonModuleName, kWinINetModuleName, name, handler); // The patching operation is either successful, or failed cleanly. DCHECK(error == NO_ERROR || !patch_function->is_patched()); } INTERNET_STATUS_CALLBACK STDAPICALLTYPE WebRequestNotifier::InternetSetStatusCallbackAPatch( HINTERNET internet, INTERNET_STATUS_CALLBACK callback) { WebRequestNotifier* instance = ProductionWebRequestNotifier::GetInstance(); INTERNET_STATUS_CALLBACK new_callback = instance->HandleBeforeInternetSetStatusCallback(internet, callback); return ::InternetSetStatusCallbackA(internet, new_callback); } INTERNET_STATUS_CALLBACK STDAPICALLTYPE WebRequestNotifier::InternetSetStatusCallbackWPatch( HINTERNET internet, INTERNET_STATUS_CALLBACK callback) { WebRequestNotifier* instance = ProductionWebRequestNotifier::GetInstance(); INTERNET_STATUS_CALLBACK new_callback = instance->HandleBeforeInternetSetStatusCallback(internet, callback); return ::InternetSetStatusCallbackW(internet, new_callback); } HINTERNET STDAPICALLTYPE WebRequestNotifier::InternetConnectAPatch( HINTERNET internet, LPCSTR server_name, INTERNET_PORT server_port, LPCSTR user_name, LPCSTR password, DWORD service, DWORD flags, DWORD_PTR context) { WebRequestNotifier* instance = ProductionWebRequestNotifier::GetInstance(); instance->HandleBeforeInternetConnect(internet); HINTERNET server = ::InternetConnectA(internet, server_name, server_port, user_name, password, service, flags, context); instance->HandleAfterInternetConnect(server, CA2W(server_name), server_port, service); return server; } HINTERNET STDAPICALLTYPE WebRequestNotifier::InternetConnectWPatch( HINTERNET internet, LPCWSTR server_name, INTERNET_PORT server_port, LPCWSTR user_name, LPCWSTR password, DWORD service, DWORD flags, DWORD_PTR context) { WebRequestNotifier* instance = ProductionWebRequestNotifier::GetInstance(); instance->HandleBeforeInternetConnect(internet); HINTERNET server = ::InternetConnectW(internet, server_name, server_port, user_name, password, service, flags, context); instance->HandleAfterInternetConnect(server, server_name, server_port, service); return server; } HINTERNET STDAPICALLTYPE WebRequestNotifier::HttpOpenRequestAPatch( HINTERNET connect, LPCSTR verb, LPCSTR object_name, LPCSTR version, LPCSTR referrer, LPCSTR* accept_types, DWORD flags, DWORD_PTR context) { HINTERNET request = ::HttpOpenRequestA(connect, verb, object_name, version, referrer, accept_types, flags, context); WebRequestNotifier* instance = ProductionWebRequestNotifier::GetInstance(); instance->HandleAfterHttpOpenRequest(connect, request, verb, CA2W(object_name), flags); return request; } HINTERNET STDAPICALLTYPE WebRequestNotifier::HttpOpenRequestWPatch( HINTERNET connect, LPCWSTR verb, LPCWSTR object_name, LPCWSTR version, LPCWSTR referrer, LPCWSTR* accept_types, DWORD flags, DWORD_PTR context) { HINTERNET request = ::HttpOpenRequestW(connect, verb, object_name, version, referrer, accept_types, flags, context); WebRequestNotifier* instance = ProductionWebRequestNotifier::GetInstance(); instance->HandleAfterHttpOpenRequest(connect, request, CW2A(verb), object_name, flags); return request; } BOOL STDAPICALLTYPE WebRequestNotifier::HttpSendRequestAPatch( HINTERNET request, LPCSTR headers, DWORD headers_length, LPVOID optional, DWORD optional_length) { WebRequestNotifier* instance = ProductionWebRequestNotifier::GetInstance(); instance->HandleBeforeHttpSendRequest(request); return ::HttpSendRequestA(request, headers, headers_length, optional, optional_length); } BOOL STDAPICALLTYPE WebRequestNotifier::HttpSendRequestWPatch( HINTERNET request, LPCWSTR headers, DWORD headers_length, LPVOID optional, DWORD optional_length) { WebRequestNotifier* instance = ProductionWebRequestNotifier::GetInstance(); instance->HandleBeforeHttpSendRequest(request); return ::HttpSendRequestW(request, headers, headers_length, optional, optional_length); } void CALLBACK WebRequestNotifier::InternetStatusCallbackPatch( INTERNET_STATUS_CALLBACK original, HINTERNET internet, DWORD_PTR context, DWORD internet_status, LPVOID status_information, DWORD status_information_length) { WebRequestNotifier* instance = ProductionWebRequestNotifier::GetInstance(); instance->HandleBeforeInternetStatusCallback(original, internet, context, internet_status, status_information, status_information_length); original(internet, context, internet_status, status_information, status_information_length); } BOOL STDAPICALLTYPE WebRequestNotifier::InternetReadFilePatch( HINTERNET file, LPVOID buffer, DWORD number_of_bytes_to_read, LPDWORD number_of_bytes_read) { BOOL result = ::InternetReadFile(file, buffer, number_of_bytes_to_read, number_of_bytes_read); WebRequestNotifier* instance = ProductionWebRequestNotifier::GetInstance(); instance->HandleAfterInternetReadFile(file, result, number_of_bytes_read); return result; } INTERNET_STATUS_CALLBACK WebRequestNotifier::HandleBeforeInternetSetStatusCallback( HINTERNET internet, INTERNET_STATUS_CALLBACK internet_callback) { CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (IsNotRunning()) return internet_callback; if (internet_callback == NULL) return NULL; if (internet_status_callback_stub_ == NULL) { return CreateInternetStatusCallbackStub(internet_callback); } else { if (internet_status_callback_stub_->argument() != reinterpret_cast<uintptr_t>(internet_callback)) { NOTREACHED(); return CreateInternetStatusCallbackStub(internet_callback); } else { return reinterpret_cast<INTERNET_STATUS_CALLBACK>( internet_status_callback_stub_->code()); } } } void WebRequestNotifier::HandleBeforeInternetConnect(HINTERNET internet) { CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (IsNotRunning()) return; if (internet_status_callback_stub_ == NULL) { INTERNET_STATUS_CALLBACK original_callback = ::InternetSetStatusCallbackA(internet, NULL); if (original_callback != NULL) { INTERNET_STATUS_CALLBACK new_callback = CreateInternetStatusCallbackStub( original_callback); ::InternetSetStatusCallbackA(internet, new_callback); } } } // NOTE: this method must be called within a lock. INTERNET_STATUS_CALLBACK WebRequestNotifier::CreateInternetStatusCallbackStub( INTERNET_STATUS_CALLBACK original_callback) { DCHECK(original_callback != NULL); internet_status_callback_stub_ = FunctionStub::Create( reinterpret_cast<uintptr_t>(original_callback), InternetStatusCallbackPatch); // internet_status_callback_stub_ is not NULL if the function stub is // successfully created. if (internet_status_callback_stub_ != NULL) { return reinterpret_cast<INTERNET_STATUS_CALLBACK>( internet_status_callback_stub_->code()); } else { NOTREACHED(); return original_callback; } } void WebRequestNotifier::HandleAfterInternetConnect(HINTERNET server, const wchar_t* server_name, INTERNET_PORT server_port, DWORD service) { if (service != INTERNET_SERVICE_HTTP || server == NULL || IS_INTRESOURCE(server_name) || wcslen(server_name) == 0) { return; } CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (IsNotRunning()) return; // It is not possible that the same connection handle is opened more than // once. DCHECK(server_map_.find(server) == server_map_.end()); ServerInfo server_info; server_info.server_name = server_name; server_info.server_port = server_port; server_map_.insert( std::make_pair<HINTERNET, ServerInfo>(server, server_info)); } void WebRequestNotifier::HandleAfterHttpOpenRequest(HINTERNET server, HINTERNET request, const char* method, const wchar_t* path, DWORD flags) { if (server == NULL || request == NULL) return; CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (IsNotRunning()) return; // It is not possible that the same request handle is opened more than once. DCHECK(request_map_.find(request) == request_map_.end()); ServerMap::iterator server_iter = server_map_.find(server); // It is possible to find that we haven't recorded the connection handle to // the server, if we patch WinINet functions after the InternetConnect call. // In that case, we will ignore all events related to requests happening on // that connection. if (server_iter == server_map_.end()) return; RequestInfo request_info; // TODO(yzshen@google.com): create the request ID. request_info.server_handle = server; request_info.method = method == NULL ? "GET" : method; if (!ConstructUrl((flags & INTERNET_FLAG_SECURE) != 0, server_iter->second.server_name.c_str(), server_iter->second.server_port, path, &request_info.url)) { NOTREACHED(); return; } request_map_.insert( std::make_pair<HINTERNET, RequestInfo>(request, request_info)); } void WebRequestNotifier::HandleBeforeHttpSendRequest(HINTERNET request) { CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (IsNotRunning()) return; RequestMap::iterator request_iter = request_map_.find(request); if (request_iter != request_map_.end()) { request_iter->second.before_request_time = base::Time::Now(); TransitRequestToNextState(RequestInfo::WILL_NOTIFY_BEFORE_REQUEST, &request_iter->second); } } void WebRequestNotifier::HandleBeforeInternetStatusCallback( INTERNET_STATUS_CALLBACK original, HINTERNET internet, DWORD_PTR context, DWORD internet_status, LPVOID status_information, DWORD status_information_length) { switch (internet_status) { case INTERNET_STATUS_HANDLE_CLOSING: { CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (IsNotRunning()) return; // We don't know whether we are closing a server or a request handle. As a // result, we have to test both server_map_ and request_map_. ServerMap::iterator server_iter = server_map_.find(internet); if (server_iter != server_map_.end()) { server_map_.erase(server_iter); } else { RequestMap::iterator request_iter = request_map_.find(internet); if (request_iter != request_map_.end()) { // TODO(yzshen@google.com): For now, we don't bother // checking whether the content of the response has // completed downloading in this case. Have to make // improvement if the requirement for more accurate // webRequest.onCompleted notifications emerges. TransitRequestToNextState(RequestInfo::NOTIFIED_COMPLETED, &request_iter->second); request_map_.erase(request_iter); } } break; } case INTERNET_STATUS_REQUEST_SENT: { CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (IsNotRunning()) return; RequestMap::iterator request_iter = request_map_.find(internet); if (request_iter != request_map_.end()) { TransitRequestToNextState(RequestInfo::NOTIFIED_REQUEST_SENT, &request_iter->second); } break; } case INTERNET_STATUS_REDIRECT: { DWORD status_code = 0; bool result = QueryHttpInfoNumber(internet, HTTP_QUERY_STATUS_CODE, &status_code); { CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (IsNotRunning()) return; RequestMap::iterator request_iter = request_map_.find(internet); if (request_iter != request_map_.end()) { RequestInfo& info = request_iter->second; if (result) { info.status_code = status_code; TransitRequestToNextState(RequestInfo::NOTIFIED_HEADERS_RECEIVED, &info); info.original_url = info.url; info.url = CA2W(reinterpret_cast<PCSTR>(status_information)); TransitRequestToNextState(RequestInfo::NOTIFIED_BEFORE_REDIRECT, &info); } else { TransitRequestToNextState(RequestInfo::ERROR_OCCURRED, &info); } } } break; } case INTERNET_STATUS_REQUEST_COMPLETE: { DWORD status_code = 0; DWORD content_length = 0; RequestInfo::MessageLengthType length_type = RequestInfo::UNKNOWN_MESSAGE_LENGTH_TYPE; bool result = QueryHttpInfoNumber(internet, HTTP_QUERY_STATUS_CODE, &status_code) && DetermineMessageLength(internet, status_code, &content_length, &length_type); { CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (IsNotRunning()) return; RequestMap::iterator request_iter = request_map_.find(internet); if (request_iter != request_map_.end() && request_iter->second.state == RequestInfo::NOTIFIED_REQUEST_SENT) { RequestInfo& info = request_iter->second; if (result) { info.status_code = status_code; info.content_length = content_length; info.length_type = length_type; TransitRequestToNextState(RequestInfo::NOTIFIED_HEADERS_RECEIVED, &info); if (info.length_type == RequestInfo::NO_MESSAGE_BODY) TransitRequestToNextState(RequestInfo::NOTIFIED_COMPLETED, &info); } else { TransitRequestToNextState(RequestInfo::ERROR_OCCURRED, &info); } } } break; } case INTERNET_STATUS_CONNECTED_TO_SERVER: { // TODO(yzshen@google.com): get IP information. break; } case INTERNET_STATUS_SENDING_REQUEST: { CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (IsNotRunning()) return; // Some HttpSendRequest() calls don't actually make HTTP requests, and the // corresponding request handles are closed right after the calls. // In that case, we ignore them totally, and don't send // webRequest.onBeforeRequest notifications. RequestMap::iterator request_iter = request_map_.find(internet); if (request_iter != request_map_.end() && request_iter->second.state == RequestInfo::WILL_NOTIFY_BEFORE_REQUEST) { TransitRequestToNextState(RequestInfo::NOTIFIED_BEFORE_REQUEST, &request_iter->second); } break; } default: { break; } } } void WebRequestNotifier::HandleAfterInternetReadFile( HINTERNET request, BOOL result, LPDWORD number_of_bytes_read) { if (!result || number_of_bytes_read == NULL) return; CComCritSecLock<CComAutoCriticalSection> lock(critical_section_); if (IsNotRunning()) return; RequestMap::iterator iter = request_map_.find(request); if (iter != request_map_.end()) { RequestInfo& info = iter->second; // We don't update the length_type field until we reach the last request // of the redirection chain. As a result, the check below also prevents us // from firing webRequest.onCompleted before the last request in the // chain. if (info.length_type == RequestInfo::CONTENT_LENGTH_HEADER) { info.read_progress += *number_of_bytes_read; if (info.read_progress >= info.content_length && info.state == RequestInfo::NOTIFIED_HEADERS_RECEIVED) { DCHECK(info.read_progress == info.content_length); TransitRequestToNextState(RequestInfo::NOTIFIED_COMPLETED, &info); } } } } // Currently this method is always called within a lock. bool WebRequestNotifier::ConstructUrl(bool https, const wchar_t* server_name, INTERNET_PORT server_port, const wchar_t* path, std::wstring* url) { if (url == NULL || server_name == NULL || wcslen(server_name) == 0) return false; url->clear(); url->append(https ? L"https://" : L"http://"); url->append(server_name); bool need_port = server_port != INTERNET_INVALID_PORT_NUMBER && (https ? server_port != INTERNET_DEFAULT_HTTPS_PORT : server_port != INTERNET_DEFAULT_HTTP_PORT); if (need_port) { static const int kMaxPortLength = 10; wchar_t buffer[kMaxPortLength]; if (swprintf(buffer, kMaxPortLength, L":%d", server_port) == -1) return false; url->append(buffer); } url->append(path); return true; } bool WebRequestNotifier::QueryHttpInfoNumber(HINTERNET request, DWORD info_flag, DWORD* value) { DCHECK(value != NULL); *value = 0; DWORD size = sizeof(info_flag); return ::HttpQueryInfo(request, info_flag | HTTP_QUERY_FLAG_NUMBER, value, &size, NULL) ? true : false; } bool WebRequestNotifier::DetermineMessageLength( HINTERNET request, DWORD status_code, DWORD* length, RequestInfo::MessageLengthType* type) { // Please see http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 // for how the length of a message is determined. DCHECK(length != NULL && type != NULL); *length = 0; *type = RequestInfo::UNKNOWN_MESSAGE_LENGTH_TYPE; std::wstring method; // Request methods are case-sensitive. if ((status_code >= 100 && status_code < 200) || status_code == 204 || status_code == 304 || (QueryHttpInfoString(request, HTTP_QUERY_REQUEST_METHOD, &method) && method == L"HEAD")) { *type = RequestInfo::NO_MESSAGE_BODY; return true; } std::wstring transfer_encoding; // All transfer-coding values are case-insensitive. if (QueryHttpInfoString(request, HTTP_QUERY_TRANSFER_ENCODING, &transfer_encoding) && _wcsicmp(transfer_encoding.c_str(), L"entity") != 0) { *type = RequestInfo::VARIABLE_MESSAGE_LENGTH; return true; } DWORD content_length = 0; if (QueryHttpInfoNumber(request, HTTP_QUERY_CONTENT_LENGTH, &content_length)) { *type = RequestInfo::CONTENT_LENGTH_HEADER; *length = content_length; return true; } *type = RequestInfo::VARIABLE_MESSAGE_LENGTH; return true; } bool WebRequestNotifier::QueryHttpInfoString(HINTERNET request, DWORD info_flag, std::wstring* value) { DCHECK(value != NULL); value->clear(); DWORD size = 20; scoped_array<wchar_t> buffer(new wchar_t[size]); BOOL result = ::HttpQueryInfo(request, info_flag, reinterpret_cast<LPVOID>(buffer.get()), &size, NULL); if (!result && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { buffer.reset(new wchar_t[size]); result = ::HttpQueryInfo(request, info_flag, reinterpret_cast<LPVOID>(buffer.get()), &size, NULL); } if (!result) return false; *value = buffer.get(); return true; } // NOTE: this method must be called within a lock. void WebRequestNotifier::TransitRequestToNextState( RequestInfo::State next_state, RequestInfo* info) { // TODO(yzshen@google.com): generate and fill in missing parameters // for notifications. DCHECK(info != NULL); bool fire_on_error_occurred = false; switch (info->state) { case RequestInfo::BEGIN: if (next_state != RequestInfo::WILL_NOTIFY_BEFORE_REQUEST && next_state != RequestInfo::ERROR_OCCURRED) { next_state = RequestInfo::ERROR_OCCURRED; // We don't fire webRequest.onErrorOccurred in this case, since the // first event for any request has to be webRequest.onBeforeRequest. } break; case RequestInfo::WILL_NOTIFY_BEFORE_REQUEST: if (next_state == RequestInfo::NOTIFIED_BEFORE_REQUEST) { webrequest_events_funnel().OnBeforeRequest( info->id, info->url.c_str(), info->method.c_str(), info->tab_handle, "other", info->before_request_time); } else if (next_state != RequestInfo::ERROR_OCCURRED) { next_state = RequestInfo::ERROR_OCCURRED; // We don't fire webRequest.onErrorOccurred in this case, since the // first event for any request has to be webRequest.onBeforeRequest. } break; case RequestInfo::NOTIFIED_BEFORE_REQUEST: case RequestInfo::NOTIFIED_BEFORE_REDIRECT: if (next_state == RequestInfo::NOTIFIED_REQUEST_SENT) { webrequest_events_funnel().OnRequestSent( info->id, info->url.c_str(), info->ip.c_str(), base::Time::Now()); } else { if (next_state != RequestInfo::ERROR_OCCURRED) next_state = RequestInfo::ERROR_OCCURRED; fire_on_error_occurred = true; } break; case RequestInfo::NOTIFIED_REQUEST_SENT: if (next_state == RequestInfo::NOTIFIED_HEADERS_RECEIVED) { webrequest_events_funnel().OnHeadersReceived( info->id, info->url.c_str(), info->status_code, base::Time::Now()); } else { if (next_state != RequestInfo::ERROR_OCCURRED) next_state = RequestInfo::ERROR_OCCURRED; fire_on_error_occurred = true; } break; case RequestInfo::NOTIFIED_HEADERS_RECEIVED: if (next_state == RequestInfo::NOTIFIED_BEFORE_REDIRECT) { webrequest_events_funnel().OnBeforeRedirect( info->id, info->original_url.c_str(), info->status_code, info->url.c_str(), base::Time::Now()); } else if (next_state == RequestInfo::NOTIFIED_COMPLETED) { webrequest_events_funnel().OnCompleted( info->id, info->url.c_str(), info->status_code, base::Time::Now()); } else { if (next_state != RequestInfo::ERROR_OCCURRED) next_state = RequestInfo::ERROR_OCCURRED; fire_on_error_occurred = true; } break; case RequestInfo::NOTIFIED_COMPLETED: // The webRequest.onCompleted notification is supposed to be the last // event sent for a given request. As a result, if the request is already // in the NOTIFIED_COMPLETED state, we just keep it in that state without // sending any further notification. // // When a request handle is closed, we consider transiting the state to // NOTIFIED_COMPLETED. If there is no response body or we have completed // reading the response body, the request has already been in this state. // In that case, we will hit this code path. next_state = RequestInfo::NOTIFIED_COMPLETED; break; case RequestInfo::ERROR_OCCURRED: next_state = RequestInfo::ERROR_OCCURRED; break; default: NOTREACHED(); break; } if (fire_on_error_occurred) { webrequest_events_funnel().OnErrorOccurred( info->id, info->url.c_str(), L"", base::Time::Now()); } info->state = next_state; } // static ProductionWebRequestNotifier* ProductionWebRequestNotifier::GetInstance() { return Singleton<ProductionWebRequestNotifier>::get(); }
ce6eea586e962098e8da2ea3e81d045dd02ac93e
6df55146e2551f576805f9dba17bc9dc1bdc8d70
/day7.cpp
e6872926f1ec0366b9e3f20427777a6600d152ff
[]
no_license
92FS/DailyCodingProblems
c0fbe9d0671a7349e7cf7818c81608bbb5d9a81d
0d61134b8841d66e1e64875a7ea0219a9386ab9c
refs/heads/master
2020-04-25T10:55:25.186828
2019-07-01T02:26:12
2019-07-01T02:26:12
172,726,913
0
0
null
null
null
null
UTF-8
C++
false
false
828
cpp
day7.cpp
/* Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. You can assume that the messages are decodable. For example, '001' is not allowed. */ #include <string> #include <iostream> using namespace std; int toChar(int); int possible(int); int main(){ int j; cout << "input a string of integers: "; cin >> j; cout << possible(j) << endl; return 0; } int possible(int n){ string test = to_string(n); int count = 0; for(int i = 0; i < test.length(); ++i){ ++count; if(i == test.length()) continue; for(int j = i+1; j < test.length(); ++j){ if(test[i] == 1) ++count; else if(test[i] == 2 && test[j] <= 6) ++count; } } return count; }
f83f33fed8c1086ab181e43fbf5e22b3d9ce988a
19803c700507ee48f532f97dfe24a1178505b97d
/cm_sq1_1.cpp
9aa4e052b0e4f44bfc7c45d2f74b031625d9525a
[]
no_license
annusachan24/Codes
d36ff19a748fd85b57ee4506d998e21f2b153076
12dad8edf23da08816a38ec3450e65145da1fe73
refs/heads/master
2020-09-16T06:32:57.067613
2016-09-10T11:32:42
2016-09-10T11:32:42
67,857,007
0
0
null
null
null
null
UTF-8
C++
false
false
432
cpp
cm_sq1_1.cpp
#include<bits/stdc++.h> using namespace std; #define ll long long #define rep(i,n) for(ll i=0;i<n;i++) int main() { int n,k,count=0,j,m=0; cin>>n; int ideal[n]; queue <int> c; rep(i,n) { cin>>k; c.push(k); } rep(i,n) cin>>ideal[i]; while(m<n) { if(ideal[m]==c.front()) { c.pop(); count++; m++; } else { j=c.front(); c.pop(); c.push(j); count++; } } cout<<count; return 0; }
13aff4af5def18b52c03de499016eb1852def12b
9dae4d0e933f25104fad3a6138f4d24e22bdc03c
/vodsim/vod/Overlay.cpp
b5c8ce5222e8f861fab6d3f6f2916267291936f6
[]
no_license
Romantic-LiXuefeng/FALPS
6b487d5c56c87ddd915f1cd9fb9a41dce769bb9a
eac63c4efc3933c0592a4064e3cec073f18d4ed9
refs/heads/master
2021-12-25T02:46:47.002419
2017-12-25T14:07:07
2017-12-25T14:07:07
null
0
0
null
null
null
null
GB18030
C++
false
false
15,605
cpp
Overlay.cpp
#include "Vod.h" ////////////////////////////////////////////////////////////////////////// //邻居节点组织 addr_t VodApp::eraseNeightbors() { if (m_intreastingNB.size()<0.9*NEIGHTBOR_COUNT) return INVALID_ADDR; intreasting_nb_map_t::iterator nbItr(m_intreastingNB.begin()); rate_Bps_t minContribute=INT_MAX; intreasting_nb_map_t::iterator minNbItr(m_intreastingNB.end()); for(;nbItr!=m_intreastingNB.end();++nbItr) { NeightborInfo& info=nbItr->second; rate_Bps_t contribute=info.contribute.getSpeed(); if (contribute<minContribute) { minContribute=contribute; minNbItr=nbItr; } } if (minContribute<INT_MAX &&minContribute<0.06*MEDIA_BPS &&minNbItr->second.beNbTime+15<NOW() ) { addr_t ip=minNbItr->first; m_intreastingNB.erase(minNbItr); return ip; } return INVALID_ADDR; } void VodApp::updataNeightbors() { //本应该是向一节点或者IS发送合作节点请求消息 //这里仿真数据调度策略,索引算法忽略 time_s_t targetPlayingPoint=m_player.playingPoint(); if (m_player.playingSeqNum()<0) targetPlayingPoint=0; bucket_id_t bucket=playingPoint2DynamicBucketID(targetPlayingPoint); if(bucket!=m_dynamicBucket) m_intreastingNB.clear(); //1.是否将服务器加入为邻居? m_supperNeightbor.ability=(int)(1.2*(MEDIA_BPS/PIECE_LEN)*PIECE_REQUEST_CYCLE_TIME); if (addr()<8) m_supperBeNeightbor=true; else m_supperBeNeightbor=false; //2.删除一效率低的节点 addr_t erasedNbr=eraseNeightbors(); //3.查找合作节点 //从本身所在桶获得节点 list<addr_t>& lst= s_dynamicBucketMap[m_playingChannelID][bucket]; if (!lst.empty()&&m_intreastingNB.size()<NEIGHTBOR_COUNT) { //向各个节点发送邻居请求 list<addr_t>::iterator itr(lst.begin()); for (size_t i=0;i<lst.size()&&m_intreastingNB.size()<NEIGHTBOR_COUNT;++i,++itr) { VodApp* thatApp=(VodApp*)(Node::get(*itr)->app()); time_s_t hisPlayingPoint=thatApp->m_player.playingPoint(); if (m_intreastingNB.find(*itr)==m_intreastingNB.end() &&(abs(hisPlayingPoint-targetPlayingPoint)<16 ||hisPlayingPoint-targetPlayingPoint<20 &&hisPlayingPoint-targetPlayingPoint>0) &&*itr!=erasedNbr &&Rand01()<1.0/(1+m_intreastingNB.size()) &&*itr!=addr() ) { m_intreastingNB[*itr]=NeightborInfo(); sendNeightborRequest(*itr); } } } //自身进入本桶(相当于IS将本节点其加入索引数据库) if(bucket!=m_dynamicBucket) { leaveFromCurrentDynamicBucket(); lst.push_back(addr()); m_dynamicBucket=bucket; } //从右桶获得节点 if (m_intreastingNB.size()<NEIGHTBOR_COUNT) { if (targetPlayingPoint+BUCKET_TIME+1<MEDIA_TIME) { list<addr_t>& lst=s_dynamicBucketMap[m_playingChannelID][playingPoint2DynamicBucketID(targetPlayingPoint+BUCKET_TIME+1)]; if (!lst.empty()&&m_intreastingNB.size()<NEIGHTBOR_COUNT) { //向各个合作节点发送自身的缓存map情况 list<addr_t>::iterator itr(lst.begin()); for (size_t i=0;i<lst.size()&&m_intreastingNB.size()<NEIGHTBOR_COUNT;++i,++itr) { VodApp* thatApp=(VodApp*)(Node::get(*itr)->app()); time_s_t hisPlayingPoint=thatApp->m_player.playingPoint(); if (m_intreastingNB.find(*itr)==m_intreastingNB.end() &&(abs(hisPlayingPoint-targetPlayingPoint)<16 ||hisPlayingPoint-targetPlayingPoint<20 &&hisPlayingPoint-targetPlayingPoint>0) &&*itr!=erasedNbr &&Rand01()<1.0/(1+m_intreastingNB.size()) &&*itr!=addr() ) { m_intreastingNB[*itr]=NeightborInfo(); sendNeightborRequest(*itr); } } } } } //从左桶获得节点 if (m_intreastingNB.size()<NEIGHTBOR_COUNT) { if (targetPlayingPoint-BUCKET_TIME-1>0) { list<addr_t>& lst=s_dynamicBucketMap[m_playingChannelID][playingPoint2DynamicBucketID(targetPlayingPoint-BUCKET_TIME-1)]; if (!lst.empty()&&m_intreastingNB.size()<NEIGHTBOR_COUNT) { //向各个合作节点发送自身的缓存map情况 list<addr_t>::reverse_iterator itr(lst.rbegin()); for (size_t i=0;i<lst.size()&&m_intreastingNB.size()<NEIGHTBOR_COUNT;++i,++itr) { VodApp* thatApp=(VodApp*)(Node::get(*itr)->app()); time_s_t hisPlayingPoint=thatApp->m_player.playingPoint(); if (m_intreastingNB.find(*itr)==m_intreastingNB.end() &&(abs(hisPlayingPoint-targetPlayingPoint)<16 ||hisPlayingPoint-targetPlayingPoint<20 &&hisPlayingPoint-targetPlayingPoint>0) &&*itr!=erasedNbr &&Rand01()<1.0/(1+m_intreastingNB.size()) &&*itr!=addr() ) { m_intreastingNB[*itr]=NeightborInfo(); sendNeightborRequest(*itr); } } } } } } void VodApp::onNeightborRequestMsg(Packet* pkt) { VodApp* thatApp=(VodApp*)(Node::get(pkt->srcAddr())->app()); time_s_t hisPlayingPoint=thatApp->m_player.playingPoint(); time_s_t myPlayingPoint=m_player.playingPoint(); time_s_t playintPointDisstense=abs(myPlayingPoint-hisPlayingPoint); // 如果[(合作节点集较小)或者(可以删除某低效率节点)]并且[播放点相近] if ((m_intreastingNB.size()<NEIGHTBOR_COUNT||eraseNeightbors()!=INVALID_ADDR) &&playintPointDisstense<BUFFER_TIME) { map<addr_t,NeightborInfo>::iterator itr=m_intreastingNB.find(pkt->srcAddr()); if (itr==m_intreastingNB.end()) m_intreastingNB[pkt->srcAddr()]=NeightborInfo(); } } ////////////////////////////////////////////////////////////////////////// //父节点组织 addr_t VodApp::eraseFathers(bool must) { //如果(父节点的个数过多且满足一定概率)或下载带宽超出了自己带宽能力的0.9 if (m_fathers.size()>=FATHER_COUNT) { father_map_t::iterator faItr(m_fathers.begin()); father_map_t::iterator eraseItr(m_fathers.end()); rate_Bps_t minContribute=INT_MAX; addr_t minFa=INVALID_ADDR; //rate_Bps_t allContribte=0; for(;faItr!=m_fathers.end();++faItr) { FatherInfo& info=faItr->second; rate_Bps_t contribute=info.contribute.getSpeed(); //allContribte+=contribute; if (contribute<minContribute) { minContribute=contribute; minFa=faItr->first; eraseItr=faItr; } } if (must ||(eraseItr!=m_fathers.end()&&minContribute<0.1*MEDIA_BPS&&Rand01()<0.8*(1-1.0/(1+m_fathers.size())))) { m_fathers.erase(eraseItr); //发送给父节点要求断开 sendTo(CONTROL_MSG_LEN,minFa,Packet::newPacket(MSG_NOT_BE_MY_FATHER)); // m_uselessPush=0; // m_usefulPush=0; return minFa; } } return INVALID_ADDR; } void VodApp::updataFathers() { //如果近期上行带宽小于最大出口带宽的0.9并且子结点个数过少,则搜索子节点 rate_Bps_t downAllRate=m_downlinkAllRate.getSpeed(); rate_Bps_t neightborContrib=m_neightborsContribute.getSpeed(); rate_Bps_t usefulPushedRate=m_usefulPushedRate.getSpeed(); if (downAllRate>0.98*m_maxDownloadRate &&downAllRate>MEDIA_BPS &&Rand01()<0.2) { eraseFathers(true); return; } if (m_fathers.size()<=FATHER_COUNT &&downAllRate<1.2*MEDIA_BPS &&neightborContrib<0.92*MEDIA_BPS &&usefulPushedRate<0.10*MEDIA_BPS ) { addr_t erasedNbr=eraseFathers(); time_s_t myPlayingPoint=m_player.playingPoint(); if (m_player.playingSeqNum()<0) myPlayingPoint=0; bucket_id_t bucket=playingPoint2DynamicBucketID(myPlayingPoint); if(bucket!=m_dynamicBucket) m_intreastingNB.clear(); //从本身所在桶获得节点 list<addr_t>& lst= s_dynamicBucketMap[m_playingChannelID][bucket]; if (!lst.empty()&&m_fathers.size()<FATHER_COUNT) { //向各个节点发送邻居请求 list<addr_t>::iterator itr(lst.begin()); for (size_t i=0;i<lst.size()&&m_fathers.size()<FATHER_COUNT;++i,++itr) { VodApp* thatApp=(VodApp*)(Node::get(*itr)->app()); time_s_t hisPlayingPoint=thatApp->m_player.playingPoint(); if (m_intreastingNB.find(*itr)==m_intreastingNB.end() &&m_fathers.find(*itr)==m_fathers.end() &&*itr!=erasedNbr &&(hisPlayingPoint-myPlayingPoint)>16 &&(hisPlayingPoint-myPlayingPoint)<BUFFER_TIME &&Rand01()<0.8*(1.0/(1+m_fathers.size())) &&*itr!=addr() ) { m_fathers[*itr]=FatherInfo(); //发送给父节点 sendTo(CONTROL_MSG_LEN,*itr,Packet::newPacket(MSG_BE_MY_FATHER)); //向父节点发送PUSH区间 piece_id_t s=m_maxknownPiece+20.0/PLAY_TIME_PER_PIECE; piece_id_t e=m_player.playingSeqNum()+1+300/PLAY_TIME_PER_PIECE; RangeMsg* data=new RangeMsg; data->range.first=s; data->range.second=e; sendTo(CONTROL_MSG_LEN,*itr,Packet::newPacket(MSG_RANGE,data)); } } } //从右桶获得节点 if (m_fathers.size()<FATHER_COUNT) { if (myPlayingPoint+BUCKET_TIME+1<MEDIA_TIME) { list<addr_t>& lst=s_dynamicBucketMap[m_playingChannelID][playingPoint2DynamicBucketID(myPlayingPoint+BUCKET_TIME+1)]; if (!lst.empty()&&m_fathers.size()<FATHER_COUNT) { //向各个合作节点发送自身的缓存map情况 list<addr_t>::reverse_iterator itr(lst.rbegin()); for (size_t i=0;i<lst.size()&&m_fathers.size()<FATHER_COUNT;++i,++itr) { VodApp* thatApp=(VodApp*)(Node::get(*itr)->app()); time_s_t hisPlayingPoint=thatApp->m_player.playingPoint(); if (m_intreastingNB.find(*itr)==m_intreastingNB.end() &&m_fathers.find(*itr)==m_fathers.end() &&*itr!=erasedNbr &&(hisPlayingPoint-myPlayingPoint)>16 &&(hisPlayingPoint-myPlayingPoint)<BUFFER_TIME &&Rand01()<0.8*(1.0/(1+m_fathers.size())) &&*itr!=addr() ) { m_fathers[*itr]=FatherInfo(); sendTo(CONTROL_MSG_LEN,*itr,Packet::newPacket(MSG_BE_MY_FATHER)); //向父节点发送PUSH区间 piece_id_t s=m_maxknownPiece+20.0/PLAY_TIME_PER_PIECE; piece_id_t e=m_player.playingSeqNum()+1+BUFFER_TIME/PLAY_TIME_PER_PIECE; RangeMsg* data=new RangeMsg; data->range.first=s; data->range.second=e; sendTo(CONTROL_MSG_LEN,*itr,Packet::newPacket(MSG_RANGE,data)); } } } } } } } void VodApp::onChildToFatherConnectMsg(Packet* pkt) { if (m_children.find(pkt->srcAddr())!=m_children.end()) return; eraseChildren(); //如果下行带宽使用率很高,拒绝 if ( m_children.size()>=CHILDREN_COUNT ||m_maxUpRate<MEDIA_BPS ||m_maxUpRate/m_children.size()<0.3*MEDIA_TIME ) { //发送给节点要求断开 sendTo(CONTROL_MSG_LEN,pkt->srcAddr(),Packet::newPacket(MSG_NOT_BE_MY_CHILD)); } else { m_children[pkt->srcAddr()]=ChildInfo(); } } void VodApp::onChildToFatherDisconnectMsg(Packet* pkt) { m_children.erase(pkt->srcAddr()); } ////////////////////////////////////////////////////////////////////////// //子点组织 addr_t VodApp::eraseChildren() { //如果(子节点的个数过多且满足一定概率)或上载带宽不足自己上行带宽能力的0.9 if (m_children.size()>=CHILDREN_COUNT //m_outgoingRate.getSpeed()>0.9*m_maxUpRate ) { child_map_t::iterator chItr(m_children.begin()); child_map_t::iterator eraseItr(m_children.end()); rate_Bps_t minContribute=INT_MAX; addr_t minCh=INVALID_ADDR; //rate_Bps_t allContribte=0; for(;chItr!=m_children.end();++chItr) { ChildInfo& info=chItr->second; rate_Bps_t contribute=info.contribute.getSpeed(); //allContribte+=contribute; if (contribute<minContribute) { minContribute=contribute; minCh=chItr->first; eraseItr=chItr; } } if (eraseItr!=m_children.end()&&minContribute<0.1*MEDIA_BPS&&Rand01()<0.4) { m_children.erase(eraseItr); //发送给子节点要求断开 sendTo(CONTROL_MSG_LEN,minCh,Packet::newPacket(MSG_NOT_BE_MY_CHILD)); return minCh; } } return INVALID_ADDR; } void VodApp::onFatherToChildDisconnectMsg(Packet* pkt) { m_fathers.erase(pkt->srcAddr()); } void VodApp::findNewChildren() { child_map_t::iterator chItr(m_children.begin()); for(;chItr!=m_children.end();++chItr) chItr->second.pusedCntCurrCycle; //addr_t erasedNbr=eraseChildren(); ////如果近期上行带宽小于最大出口带宽的0.9并且子结点个数过少,则搜索子节点 //if (m_children.size()<CHILDREN_COUNT // &&m_outgoingRate.getSpeed()<0.9*m_maxUpRate // ) //{ // time_s_t myPlayingPoint=m_player.playingPoint(); // if (m_player.playingSeqNum()<0) // myPlayingPoint=0; // bucket_id_t bucket=playingPoint2DynamicBucketID(myPlayingPoint); // if(bucket!=m_dynamicBucket) // m_neighbors.clear(); // //从本身所在桶获得节点 // list<addr_t>& lst= // s_dynamicBucketMap[m_playingChannelID][bucket]; // if (!lst.empty()&&m_children.size()<CHILDREN_COUNT) // { // //向各个节点发送邻居请求 // list<addr_t>::reverse_iterator itr(lst.rbegin()); // for (size_t i=0;i<lst.size()&&m_children.size()<CHILDREN_COUNT;++i,++itr) // { // VodApp* thatApp=(VodApp*)(Node::get(*itr)->app()); // time_s_t hisPlayingPoint=thatApp->m_player.playingPoint(); // if (m_neighbors.find(*itr)==m_neighbors.end() // &&m_children.find(*itr)==m_children.end() // &&*itr!=erasedNbr // &&(myPlayingPoint-hisPlayingPoint)>URGENT_1_REQUEST_TIME // &&(myPlayingPoint-hisPlayingPoint)<BUFFER_TIME // ) // { // m_children[*itr]=ChildInfo(); // //发送给子节点 // sendTo(CONTROL_MSG_LEN,*itr,Packet::newPacket(MSG_BE_MY_CHILD)); // } // } // } // //从左桶获得节点 // if (m_children.size()<CHILDREN_COUNT) // { // if (myPlayingPoint-BUCKET_TIME-1>0) // { // list<addr_t>& lst=s_dynamicBucketMap[m_playingChannelID][playingPoint2DynamicBucketID(myPlayingPoint-BUCKET_TIME-1)]; // if (!lst.empty()&&m_children.size()<CHILDREN_COUNT) // { // //向各个节点发送邻居请求 // list<addr_t>::iterator itr(lst.begin()); // for (size_t i=0;i<lst.size()&&m_children.size()<CHILDREN_COUNT;++i,++itr) // { // VodApp* thatApp=(VodApp*)(Node::get(*itr)->app()); // time_s_t hisPlayingPoint=thatApp->m_player.playingPoint(); // if (m_neighbors.find(*itr)==m_neighbors.end() // &&m_children.find(*itr)==m_children.end() // &&*itr!=erasedNbr // &&(myPlayingPoint-hisPlayingPoint)>URGENT_1_REQUEST_TIME // &&(myPlayingPoint-hisPlayingPoint)<BUFFER_TIME // ) // { // m_children[*itr]=ChildInfo(); // //发送给子节点 // sendTo(CONTROL_MSG_LEN,*itr,Packet::newPacket(MSG_BE_MY_CHILD)); // } // } // } // } // } //} } void VodApp::onFatherToChildConnectMsg(Packet* pkt) { if (m_fathers.find(pkt->srcAddr())!=m_fathers.end()) return; //如果下行带宽使用率很高,拒绝 if (m_downlinkAllRate.getSpeed()>0.7*m_maxDownloadRate //||m_neighbors.find(pkt->srcAddr())!=m_neighbors.end() ||m_player.state()==Player::PLAYING&&m_player.continuousTime()<2.0 ) { //发送给父节点要求断开 sendTo(CONTROL_MSG_LEN,pkt->srcAddr(),Packet::newPacket(MSG_NOT_BE_MY_FATHER)); } else { if(m_fathers.size()<FATHER_COUNT ||eraseChildren()!=INVALID_ADDR) { m_fathers[pkt->srcAddr()]=FatherInfo(); //向父节点发送PUSH区间 piece_id_t s=m_maxknownPiece+10.0/PLAY_TIME_PER_PIECE; piece_id_t e=m_player.playingSeqNum()+1+BUFFER_TIME/PLAY_TIME_PER_PIECE; RangeMsg* data=new RangeMsg; data->range.first=s; data->range.second=e; sendTo(CONTROL_MSG_LEN,pkt->srcAddr(),Packet::newPacket(MSG_RANGE,data)); } else { //发送给父节点要求断开 sendTo(CONTROL_MSG_LEN,pkt->srcAddr(),Packet::newPacket(MSG_NOT_BE_MY_FATHER)); } } } void VodApp::onRangeMsg(Packet* pkt) { RangeMsg* data=(RangeMsg*)(pkt->data()); child_map_t::iterator itr(m_children.find(pkt->srcAddr())); if (itr!=m_children.end()) itr->second.range=data->range; }
02c2bbb419efd9552b3acf4e7fd2f02cea8112f4
75254a6dccf97f64b284008c382fbbdc3b46c2e2
/src/GoToAction.h
60d6793f4868a3795a83eeac9bbaaa22d0757d07
[ "MIT" ]
permissive
danielfx90/TenazAyuda
f146f54dd17878792d25424b6806ebb29b16f946
3966007ba664fcee4834c6267f27864dc5a26f2a
refs/heads/develop
2021-01-15T09:42:42.335838
2016-12-08T20:02:19
2016-12-08T20:02:19
67,305,882
0
0
null
2016-12-08T20:05:33
2016-09-03T18:38:25
C++
UTF-8
C++
false
false
248
h
GoToAction.h
#ifndef GoToAction_h #define GoToAction_h #include "Action.h" class GoToAction : public Action { protected: int* positions; int positionsQuantity; virtual void act(); public: GoToAction(int* positions, int positionsQuantity); }; #endif
6d05d8267db5fe04f261fa2cbcf281938e827ccb
0865adce3ffdff4625b288b1cf4c1a96901ec34a
/PROBLEM 2.cpp
15db0bc42c1b541af4c6e35b1a6747cb55cf317d
[]
no_license
jasmingea/Experiment-2
5f8f200d4784ae93a8a7edb186062262e6e0d7d2
789ecc15877da59f4c28be68e7d870ad955e5b25
refs/heads/master
2020-05-19T06:18:33.903243
2019-05-04T08:41:37
2019-05-04T08:41:37
184,871,134
0
0
null
null
null
null
UTF-8
C++
false
false
897
cpp
PROBLEM 2.cpp
#include <iostream> #include <conio.h> using namespace std; int main() { int totalbill, gall, previous, recent, unpBal, totalbill2, charge, consumption, latecharge; charge = 35; consumption = 1.10; latecharge = 20; cout << "What is the meter reading (in gallons) taken last month?" << " "; cin >> previous; cout << "What is the meter reading (in gallons) taken this month?" << " "; cin >> recent; cout << "Enter your remaining balance: (none, enter 0)" << " "; cin >> unpBal; totalbill = charge + consumption*(recent-previous) + unpBal; if (unpBal > 0) { totalbill2 = totalbill + 20 + unpBal; cout << "Your total bill for the last month and this month is with your unpaid balance is:" << " " << totalbill2; } else { cout << "Your total bill for the last month and this month is:" << " " << totalbill; } _getch(); return 0; }
34cbb6f96b792f4de8f64b1cf2c90154682d9d64
55fc82f73ff5bbeec8016860d45e80388251dcec
/Server/SocketInfo.cpp
d5541632076282ebcbe071f63160c86cda367b4b
[]
no_license
Logasdf/Server
264e2f9aff38044565ffc467f0c7f31d646c79e0
e2ef1cb3ad088694e5e22571b1cdf3ae02e23e8b
refs/heads/master
2020-04-08T18:27:04.264632
2019-02-04T10:26:28
2019-02-04T10:26:28
159,608,644
0
0
null
2019-01-21T12:49:45
2018-11-29T04:42:27
C++
UHC
C++
false
false
1,259
cpp
SocketInfo.cpp
#include "SocketInfo.h" #include "ErrorHandle.h" #include <cassert> SocketInfo::SocketInfo() { socket = INVALID_SOCKET; recvBuf = NULL; sendBuf = NULL; } SocketInfo::~SocketInfo() { } void SocketInfo::GetIpAndPort(char pIpAddress[], int & port) { /* 필요가 없어진듯? SOCKADDR_IN addr; int addrSize = sizeof(addr); ZeroMemory(&addr, addrSize); getpeername(socket, (SOCKADDR*)&addr, &addrSize); //inet_ntop(AF_INET, &addr, pIpAddress, sizeof(pIpAddress)); port = ntohs(addr.sin_port); CopyMemory(pIpAddress, inet_ntoa(addr.sin_addr), 20); printf("%s:%d\n", inet_ntoa(addr.sin_addr), port); */ } SocketInfo* SocketInfo::AllocateSocketInfo(const SOCKET& socket) { SocketInfo* lpSocketInfo = new SocketInfo(); assert(lpSocketInfo != NULL); lpSocketInfo->socket = socket; lpSocketInfo->recvBuf = IOInfo::AllocateIoInfo(); lpSocketInfo->sendBuf = IOInfo::AllocateIoInfo(); return lpSocketInfo; } void SocketInfo::DeallocateSocketInfo(SocketInfo* lpSocketInfo) { assert(lpSocketInfo != NULL); if (lpSocketInfo->recvBuf != NULL) IOInfo::DeallocateIoInfo(lpSocketInfo->recvBuf); if (lpSocketInfo->sendBuf != NULL) IOInfo::DeallocateIoInfo(lpSocketInfo->sendBuf); lpSocketInfo->socket = INVALID_SOCKET; delete lpSocketInfo; }
070af61d76178f9255bd317a7cac9ab8c50302f2
a49ab550b23c20ff4affc68eb63e262df9aef373
/CarpeDiem/resultsend.h
b3510993b018020c2abed49f8345e654270909c3
[]
no_license
DenDiem/ATM-CarpeDiem
6715583c98962f574d865ac64d243b640260f66d
08d08f9a645d26247739291b4587f27af1ff8241
refs/heads/master
2020-04-02T18:19:54.281374
2018-12-03T10:55:55
2018-12-03T10:55:55
154,695,952
0
0
null
null
null
null
UTF-8
C++
false
false
399
h
resultsend.h
#ifndef RESULTSEND_H #define RESULTSEND_H #include <QDialog> class OperationWindow; namespace Ui { class ResultSend; } class ResultSend : public QDialog { Q_OBJECT public: explicit ResultSend(QWidget *parent = 0,unsigned cs = 0); ~ResultSend(); private slots: void on_pushButton_2_clicked(); private: Ui::ResultSend *ui; OperationWindow *_op; }; #endif // RESULTSEND_H
7e50e4e589ab88f6ec756fa04f79a7de71cf22d3
d7d040481472d1e1e8c2e304cd4ac4f87e248b77
/001_GFG/DSA Problems/Arrays/progA10_Missing number in array.cpp
61091b0af3682fc39a02cc0be4ade967480a71ce
[]
no_license
Sahil1515/Competitive-Coding
9f24dec518f565074cb14ce65e1c2ebd162a49db
2bd2a2257c8cac5a5c00b37e79bbb68a24e186d4
refs/heads/master
2023-06-12T20:48:19.342064
2021-06-30T02:20:16
2021-06-30T02:20:16
290,392,677
0
0
null
null
null
null
UTF-8
C++
false
false
647
cpp
progA10_Missing number in array.cpp
using namespace std; #include<bits/stdc++.h> int main() { //code int t,n; scanf("%d",&t); while(t!=0) { scanf("%d",&n); int * arr=(int *)malloc((n-1)*sizeof(int)); for(int i=0;i<n-1;i++) { scanf("%d",&arr[i]); } long long int sum=accumulate(arr,arr+(n-1),0); long long int sum1=0; sum1=((n)*(n+1))/2; printf("%lld\n",sum1-sum); t--; } return 0; } // Given an array C of size N-1 and given that there are // numbers from 1 to N with one element missing, // the missing number is to be found. // Input: // 2 // 5 // 1 2 3 5 // 10 // 1 2 3 4 5 6 7 8 10 // Output: // 4 // 9
958383f0063d38b80e5ed799e0678c2698af7b8b
73e5d2812ec4aa07dc9eacf11decb6a73e907d64
/src/MIT_alice/MAUIRulerWidget.h
a0dcbdb74a5e96521e4d2c2b6d64a38d5c080778
[ "MIT" ]
permissive
midasitdev/aliceui
cdf781f84e2d488d0cc7083aa3c783937459ba76
3693018021892bcccbc66f29b931d9736db6f9dc
refs/heads/master
2020-04-24T06:51:27.386806
2020-03-05T23:55:48
2020-03-05T23:55:48
171,779,938
10
5
NOASSERTION
2019-03-08T00:07:41
2019-02-21T01:44:39
C++
UTF-8
C++
false
false
2,591
h
MAUIRulerWidget.h
#pragma once #include "AUIDrawableWidget.h" #include "MAUIRulerDrawableDef.h" #include "MAUIRulerDrawableDef.h" namespace mit { namespace alice { class MAUIRulerDrawable; class ALICEUI_API MAUIRulerWidget : public AUIDrawableWidget { using SuperWidget = AUIDrawableWidget; public: MAUIRulerWidget(); ~MAUIRulerWidget() override; ////////////////////////////////////////////////////////////////////////// // Drawable protected: MAUIRulerDrawable* const GetRulerDrawable() const; private: std::shared_ptr< MAUIRulerDrawable > m_pRulerDrawable; ////////////////////////////////////////////////////////////////////////// // Ruler Padding public: void SetRulerPadding( SkScalar l, SkScalar t, SkScalar r, SkScalar b ); ////////////////////////////////////////////////////////////////////////// // Location public: void SetLocation( AUIRulerLocation location ); AUIRulerLocation GetLocation() const; ////////////////////////////////////////////////////////////////////////// // Ref Position public: void SetRefPos( SkScalar pos ); SkScalar GetRefPos() const; ////////////////////////////////////////////////////////////////////////// // Basis & Scale public: void SetScale( SkScalar val); void SetBasis( SkScalar val ); void SetGradationSize( SkScalar val ); SkScalar GetScale() const; SkScalar GetBasis() const; SkScalar GetGradationSize() const; ////////////////////////////////////////////////////////////////////////// // Text public: void SetMaxTextWidth( SkScalar val ); void SetMaxTextHeight( SkScalar val ); void SetTextSize( SkScalar size ); SkScalar GetMaxTextWidth() const; SkScalar GetMaxTextHeight() const; SkScalar GetTextSize() const; ////////////////////////////////////////////////////////////////////////// // Color Option public: void SetLineColor( SkColor color ); void SetTextColor( SkColor color ); SkColor GetLineColor() const; SkColor GetTextColor() const; // Marking public: void SetUseMarking(bool val); bool IsUseMarking() const; }; } }
a152b8ede7410d616e381e06fc4512afbe891889
8efe005ac9cbc202ef1db530954f142933a4b184
/0803/thread_pool/thread_pool.h
690ad48916646f483dac87b091f0223fcfb5a85b
[]
no_license
dasima/WD
e58ec753003d28df5420942ed14f090cd9456ecb
f7f6f3dd3ea8faef982cb72279021118c91935f8
refs/heads/master
2021-01-19T03:18:35.707357
2014-08-27T01:34:04
2014-08-27T01:34:04
21,316,067
1
0
null
null
null
null
UTF-8
C++
false
false
899
h
thread_pool.h
#ifndef THREAD_POOL_H #define THREAD_POOL_H #include "non_copyable.h" #include "mutex_lock.h" #include "condition.h" #include "ptr_vector.h" #include <queue> #include <functional> class Thread; class ThreadPool : private NonCopyable { public: typedef std::function<void()> Task; ThreadPool(size_t, size_t); ~ThreadPool(); void start();//启动线程池 void stop();//停止线程池 void addTask(const Task &); Task getTask(); private: void runInThread();//线程池内线程的回调函数 mutable MutexLock mutex_; Condition empty_; Condition full_; size_t queue_size_;//队列大小 std::queue<Task> queue_; size_t pool_size_;//线程池大小 PtrVector<Thread> threads_; bool is_started_;//线程池是否开启 }; #endif /*THREAD_POOL_H*/
287b924f335fb8807c2d45c0249e6dffb9491898
93294d148df93b4378f59ac815476919273d425f
/src/AGC/AGCGame.h
27963fcc687c7930172a66aa138d269fa2e730bf
[ "MIT" ]
permissive
FreeAllegiance/Allegiance
f1addb3b26efb6b8518705a0b0300974820333c3
3856ebcd8c35a6d63dbf398a4bc7f0264d6c823c
refs/heads/master
2023-07-06T17:53:24.363387
2023-06-29T00:24:26
2023-06-29T00:24:26
98,829,929
86
34
MIT
2023-06-28T03:57:34
2017-07-30T23:09:14
C++
UTF-8
C++
false
false
1,092
h
AGCGame.h
#ifndef __AGCGame_h__ #define __AGCGame_h__ ///////////////////////////////////////////////////////////////////////////// // AGCGame.h : Declaration of the IAGCGameImpl and CAGCGame // #include "resource.h" #include "IAGCGameImpl.h" ///////////////////////////////////////////////////////////////////////////// // CAGCGame class ATL_NO_VTABLE CAGCGame : public IAGCGameImpl<CAGCGame, ImissionIGC, IAGCGame, &LIBID_AGCLib>, public ISupportErrorInfo, public CComCoClass<CAGCGame, &CLSID_AGCGame> { // Declarations public: DECLARE_REGISTRY_RESOURCEID(IDR_AGCGame) DECLARE_PROTECT_FINAL_CONSTRUCT() // Interface Map public: BEGIN_COM_MAP(CAGCGame) COM_INTERFACE_ENTRIES_IAGCGameImpl() COM_INTERFACE_ENTRY(ISupportErrorInfo) END_COM_MAP() // Category Map public: BEGIN_CATEGORY_MAP(CAGCGame) IMPLEMENTED_CATEGORY(CATID_AGC) END_CATEGORY_MAP() // ISupportErrorInfo Interface Methods public: STDMETHODIMP InterfaceSupportsErrorInfo(REFIID riid); }; ///////////////////////////////////////////////////////////////////////////// #endif // !__AGCGame_h__
df412b97eb2bf790e19e44732f0a1b936780944e
96cb8fc3f97c7f1db554fa7184ca1ec4c107a22c
/dataobjects/XmlFileDecoder.cpp
122de3b72d5191ae38a63210c9cc7583b0c54517
[ "BSD-2-Clause" ]
permissive
Zackmon/SeventhUmbral
f8493a4ae62f6fe10e656d49b999dd3fb63582be
25580111b361d2fdc2c15fd2cd150e4c763ca774
refs/heads/master
2022-01-11T12:43:26.081530
2021-12-23T17:01:28
2021-12-23T17:01:28
439,861,352
0
0
NOASSERTION
2021-12-19T12:46:13
2021-12-19T12:46:12
null
UTF-8
C++
false
false
1,509
cpp
XmlFileDecoder.cpp
#include "XmlFileDecoder.h" std::vector<uint8> CXmlFileDecoder::Decode(Framework::CStream& inputStream) { uint32 srcLength = inputStream.GetLength(); std::vector<uint8> srcData; srcData.resize(srcLength); inputStream.Read(srcData.data(), srcLength); if(srcData.size() == 0) return srcData; if(srcData[srcLength - 1] != 0xF1) { return srcData; } std::vector<uint8> dstData; uint32 dstLength = srcLength - 1; dstData.resize(dstLength); int32 encodedLength = srcLength - 1; memcpy(dstData.data(), srcData.data(), encodedLength); ScrambleBuffer(dstData.data(), encodedLength); int16 xA = static_cast<int16>(encodedLength * 7); int16 xB = *reinterpret_cast<int16*>(dstData.data() + 6) ^ 0x6C6D; int16* dstEnd = reinterpret_cast<int16*>(dstData.data() + encodedLength - 1); { int16* ptr = reinterpret_cast<int16*>(dstData.data()); while(ptr < dstEnd) { (*ptr) ^= xA; ptr += 2; } } { int16* ptr = reinterpret_cast<int16*>(dstData.data() + 2); while(ptr < dstEnd) { (*ptr) ^= xB; ptr += 2; } } if(encodedLength & 1) { *(dstData.data() + encodedLength - 1) ^= static_cast<uint8>(xA); *(dstData.data() + encodedLength - 1) ^= static_cast<uint8>(xB); } return dstData; } void CXmlFileDecoder::ScrambleBuffer(uint8* buffer, size_t bufferSize) { uint8* ptr = buffer; uint8* end = buffer + bufferSize - 1; while(ptr < end) { std::swap(*ptr, *end); ptr += 2; end -= 2; } }
b8bf1ad6ec99170acd56f79da68ca8c6cfb57741
e871a7899456f0e8010316e563af893902165d79
/mbot_factory_firmware.ino
090f1f0bf9a3753610c7e015cd74a0a5fc78f1e2
[ "CC0-1.0" ]
permissive
tiggi78/mBotEnhanced
405ab573629f02cac30731c444989f0b29e9b599
38da9660fe606d7300436e6c080151c2110a4122
refs/heads/master
2023-01-06T12:22:00.907532
2022-12-29T23:25:24
2022-12-29T23:25:24
249,823,335
1
0
null
null
null
null
UTF-8
C++
false
false
31,624
ino
mbot_factory_firmware.ino
/************************************************************************* * File Name : mbot_factory_firmware.ino * Author : Ander, Mark Yan * Updated : Ander, Mark Yan * Version : V06.01.009 * Date : 21/06/2017 * Description : Firmware for Makeblock Electronic modules with Scratch. * License : CC-BY-SA 3.0 * Copyright (C) 2013 - 2017 Maker Works Technology Co., Ltd. All right reserved. * http://www.makeblock.cc/ **************************************************************************/ #include <Wire.h> #include <MeMCore.h> #include <Arduino.h> #include "SerialHandler.h" #include "MotorHandler.h" #include "simpleScheduler.h" #include "AnalogHandler.h" /* * MCU peripherals usage * Timer0 (8 bit) * Arduino millis() handling. Fast PWM mode, /64 prescaler, 0xFF overflow * * Timer1 (16 bit) * servo lib * * Timer2 (8 bit) * tone() * MeIR Infrared sender (receiver) * * UART * Arduino buffered serial communcation (UART/USB & Bluetooth moudule) with interrupt * */ /* Device of readSensor() function */ enum device_e { VERSION = 0, ULTRASONIC_SENSOR = 1, TEMPERATURE_SENSOR = 2, LIGHT_SENSOR = 3, POTENTIONMETER = 4, JOYSTICK = 5, GYRO = 6, SOUND_SENSOR = 7, RGBLED = 8, SEVSEG = 9, MOTOR = 10, SERVO = 11, ENCODER = 12, IR = 13, IRREMOTE = 14, PIRMOTION = 15, INFRARED = 16, LINEFOLLOWER = 17, IRREMOTECODE = 18, SHUTTER = 20, LIMITSWITCH = 21, BUTTON = 22, HUMITURE = 23, FLAMESENSOR = 24, GASSENSOR = 25, COMPASS = 26, TEMPERATURE_SENSOR_1 = 27, DIGITAL = 30, ANALOG = 31, PWM = 32, SERVO_PIN = 33, TONE = 34, BUTTON_INNER = 35, ULTRASONIC_ARDUINO = 36, PULSEIN = 37, STEPPER = 40, LEDMATRIX = 41, TIMER = 50, TOUCH_SENSOR = 51, JOYSTICK_MOVE = 52, COMMON_COMMONCMD = 60, ENCODER_BOARD = 61, ENCODER_PID_MOTION = 62, PM25SENSOR = 63 }; //Secondary command (COMMON_COMMONCMD) #define SET_STARTER_MODE 0x10 #define SET_AURIGA_MODE 0x11 #define SET_MEGAPI_MODE 0x12 #define GET_BATTERY_POWER 0x70 #define GET_AURIGA_MODE 0x71 #define GET_MEGAPI_MODE 0x72 //Read type (ENCODER_BOARD) #define ENCODER_BOARD_POS 0x01 #define ENCODER_BOARD_SPEED 0x02 //Secondary command (ENCODER_PIN_MOTOON) #define ENCODER_BOARD_POS_MOTION 0x01 #define ENCODER_BOARD_SPEED_MOTION 0x02 #define ENCODER_BOARD_PWM_MOTION 0x03 #define ENCODER_BOARD_SET_CUR_POS_ZERO 0x04 #define ENCODER_BOARD_CAR_POS_MOTION 0x05 //Secondary command (PM25SENSOR) #define GET_PM1_0 0x01 #define GET_PM2_5 0x02 #define GET_PM10 0x03 /* Local functions */ void parseData(); void LedsOff(); void readSensor( enum device_e device ); void runModule( enum device_e device ); void getIRCommand(); /* GLOBALS (peripehrals) */ MeRGBLed rgb( 0, 16 ); MeRGBLed internalRGB( PORT_7, 2 ); MeUltrasonicSensor ultr( PORT_3 ); MeLineFollower line( PORT_2 ); MeLEDMatrix ledMx; MeIR ir; MeJoystick joystick; MeBuzzer buzzer; MeTemperature ts; Me7SegmentDisplay seg; MePort generalDevice; Servo servo; /* TONE NOTES */ #define NTDL1 147 #define NTDL2 165 #define NTDL3 175 #define NTDL4 196 #define NTDL5 221 #define NTDL6 248 #define NTDL7 278 #define NTD1 294 #define NTD2 330 #define NTD3 350 #define NTD4 393 #define NTD5 441 #define NTD6 495 #define NTD7 556 #define NTDH1 589 #define NTDH2 661 #define NTDH3 700 #define NTDH4 786 #define NTDH5 882 #define NTDH6 990 #define NTDH7 112 /* motor_sta values */ enum motorStatus_e { STOP = 0, RUN_F = 0x01, RUN_B = 0x01 << 1, RUN_L = 0x01 << 2, RUN_R = 0x01 << 3, } motorStatus = STOP; enum motorStatus_e prevMotorStatus = STOP; /* Offset for motor speeed (when pushing on remote control) */ int minSpeed = 48; /* Multiplaction factor for motor speed (when pushing on remote control) */ int factor = 23; /* controlFlag vales */ enum controlFlag_e { BLUE_TOOTH = 0, IR_CONTROLER = 1 } controlflag = IR_CONTROLER; /* mode values */ enum modes_e { MODE_A, MODE_B, MODE_C } mode = MODE_A; /* typedef struct MeModule { int16_t device; int16_t port; int16_t slot; int16_t pin; int16_t index; float values[3]; } MeModule; */ String mVersion = "06.01.009"; double lastTime = 0.0; double currentTime = 0.0; int analogs[8] = {A0, A1, A2, A3, A4, A5, A6, A7}; uint8_t command_index = 0; /* * Protocol: 0xFF 0x55 <DATALEN> <data1> <data2> ... <dataN> * */ void serialHandle() { static byte index = 0; static byte dataLen = 0; static boolean isStart = false; static unsigned char prevc = 0; boolean isAvailable = false; char serialRead = readSerial( isAvailable ); if( isAvailable ) { unsigned char c = serialRead & 0xff; if( ( c == 0x55 ) && ( isStart == false ) ) { if( prevc == 0xff ) { index = 1; isStart = true; } } else { prevc = c; if( isStart ) { if( index == 2 ) { dataLen = c; } else if( index > 2 ) { dataLen--; } writeBuffer( index, c ); } } index++; if( index >= BUFFER_LEN ) { index = 0; isStart = false; } if( isStart && ( dataLen == 0 ) && ( index > 3 ) ) { isStart = false; parseData(); index = 0; } } } void buzzerOn() { buzzer.tone( 500, 1000 ); } void buzzerOff() { buzzer.noTone(); } void getIRCommand() { static unsigned long time = millis(); uint8_t punti; if( ir.decode() ) { uint32_t value = ir.value; time = millis(); Serial.print( time ); Serial.print( " | IRVALUE: " ); String hex( value, 16 ); Serial.println( hex ); switch( ( value >> 16 ) & 0xff ) { case IR_BUTTON_A: controlflag = IR_CONTROLER; ChangeSpeed( 220 ); mode = MODE_A; Stop(); LedsOff(); cli(); buzzer.tone( NTD1, 300 ); sei(); internalRGB.setColor( 10, 10, 10 ); internalRGB.show(); break; case IR_BUTTON_B: controlflag = IR_CONTROLER; ChangeSpeed( 200 ); mode = MODE_B; Stop(); LedsOff(); cli(); buzzer.tone( NTD2, 300 ); sei(); internalRGB.setColor( 0, 10, 0 ); internalRGB.show(); break; case IR_BUTTON_C: controlflag = IR_CONTROLER; ChangeSpeed( 200 ); mode = MODE_C; Stop(); LedsOff(); cli(); buzzer.tone( NTD3, 300 ); sei(); internalRGB.setColor( 0, 0, 10 ); internalRGB.show(); break; case IR_BUTTON_D: TurnLeft(); delay( random( 2000, 5000 ) ); Stop(); delay( 1000 ); punti = random( 1, 10 ); ChangeSpeed( 150 ); switch( punti ) { case 1: Forward(); break; case 2: Backward(); break; case 3: TurnLeft(); break; case 4: TurnRight(); break; case 5: internalRGB.setColor( 200, 0, 0 ); internalRGB.show(); break; case 6: internalRGB.setColor( 140, 60, 0 ); internalRGB.show(); break; case 7: internalRGB.setColor( 255, 240, 0 ); internalRGB.show(); break; case 8: internalRGB.setColor( 0, 200, 0 ); internalRGB.show(); break; case 9: internalRGB.setColor( 0, 0, 200 ); internalRGB.show(); break; case 10: internalRGB.setColor( 92, 53, 102 ); internalRGB.show(); break; } delay( 1500 ); Stop(); LedsOff(); cli(); buzzer.tone( NTDL1, 200 ); buzzer.tone( NTD1, 200 ); buzzer.tone( NTDH1, 200 ); sei(); break; case IR_BUTTON_E: { internalRGB.setColor( random( 255 ), random( 255 ), random( 255 ) ); internalRGB.show(); } break; case IR_BUTTON_SETTING: break; case IR_BUTTON_PLUS: controlflag = IR_CONTROLER; if( mode == MODE_A ) { motorStatus = RUN_F; internalRGB.setColor( 10, 10, 0 ); internalRGB.show(); } break; case IR_BUTTON_MINUS: controlflag = IR_CONTROLER; if( mode == MODE_A ) { motorStatus = RUN_B; internalRGB.setColor( 10, 0, 0 ); internalRGB.show(); } break; case IR_BUTTON_NEXT: controlflag = IR_CONTROLER; if( mode == MODE_A ) { motorStatus = RUN_R; internalRGB.setColor( 1, 10, 10, 0 ); internalRGB.show(); } break; case IR_BUTTON_PREVIOUS: controlflag = IR_CONTROLER; if( mode == MODE_A ) { motorStatus = RUN_L; internalRGB.setColor( 2, 10, 10, 0 ); internalRGB.show(); } break; case IR_BUTTON_9: controlflag = IR_CONTROLER; cli(); buzzer.tone( NTDH2, 300 ); sei(); ChangeSpeed( factor * 9 + minSpeed ); break; case IR_BUTTON_8: controlflag = IR_CONTROLER; cli(); buzzer.tone( NTDH1, 300 ); sei(); ChangeSpeed( factor * 8 + minSpeed ); break; case IR_BUTTON_7: controlflag = IR_CONTROLER; cli(); buzzer.tone( NTD7, 300 ); sei(); ChangeSpeed( factor * 7 + minSpeed ); break; case IR_BUTTON_6: controlflag = IR_CONTROLER; cli(); buzzer.tone( NTD6, 300 ); sei(); ChangeSpeed( factor * 6 + minSpeed ); break; case IR_BUTTON_5: controlflag = IR_CONTROLER; cli(); buzzer.tone( NTD5, 300 ); sei(); ChangeSpeed( factor * 5 + minSpeed ); break; case IR_BUTTON_4: controlflag = IR_CONTROLER; cli(); buzzer.tone( NTD4, 300 ); sei(); ChangeSpeed( factor * 4 + minSpeed ); break; case IR_BUTTON_3: controlflag = IR_CONTROLER; cli(); buzzer.tone( NTD3, 300 ); sei(); ChangeSpeed( factor * 3 + minSpeed ); break; case IR_BUTTON_2: controlflag = IR_CONTROLER; cli(); buzzer.tone( NTD2, 300 ); sei(); ChangeSpeed( factor * 2 + minSpeed ); break; case IR_BUTTON_1: controlflag = IR_CONTROLER; cli(); buzzer.tone( NTD1, 300 ); sei(); ChangeSpeed( factor * 1 + minSpeed ); break; case IR_BUTTON_0: controlflag = IR_CONTROLER; cli(); buzzer.tone( NTDH1, 200 ); buzzer.tone( NTD1, 200 ); buzzer.tone( NTDL1, 200 ); sei(); ChangeSpeed( 0 ); internalRGB.setColor( 255, 255, 255 ); internalRGB.show(); break; } } else if( ( controlflag == IR_CONTROLER ) && ( ( millis() - time ) > 120 ) ) { motorStatus = STOP; time = millis(); if( mode == MODE_A ) { internalRGB.setColor( 10, 10, 10 ); internalRGB.show(); } else if( mode == MODE_B ) { internalRGB.setColor( 0, 10, 0 ); internalRGB.show(); } else if( mode == MODE_C ) { internalRGB.setColor( 0, 0, 10 ); internalRGB.show(); } } } void LedsOff() { internalRGB.setColor( 0, 0, 0 ); internalRGB.show(); } void modeA() { switch( motorStatus ) { case RUN_F: Forward(); prevMotorStatus = motorStatus; break; case RUN_B: Backward(); prevMotorStatus = motorStatus; break; case RUN_L: TurnLeft(); prevMotorStatus = motorStatus; break; case RUN_R: TurnRight(); prevMotorStatus = motorStatus; break; case STOP: if( prevMotorStatus != motorStatus ) { prevMotorStatus = motorStatus; Stop(); LedsOff(); } break; } } void modeB() { uint16_t high = 20; uint16_t low = 10; double dist = ultr.distanceCm( false ); uint16_t d = ( uint16_t ) dist; uint8_t randNumber = random( 2 ); if( ( d > high ) || ( d == 0 ) ) { Forward(); //Serial.println( "Forward" ); } else if( ( d > low ) && ( d < high ) ) { switch( randNumber ) { case 0: TurnLeft(); delay( 300 ); //Serial.println( "Left 300" ); break; case 1: TurnRight(); delay( 300 ); //Serial.println( "Right 300" ); break; } } else // (d < low) { switch( randNumber ) { case 0: TurnLeft(); delay( 800 ); //Serial.println( "Left 800" ); break; case 1: TurnRight(); delay( 800 ); //Serial.println( "Right 800" ); break; } } delay( 100 ); } void modeC() { static int LineFollowFlag = 0; uint8_t val; val = line.readSensors(); if( getSpeed() > 230 ) { ChangeSpeed( 230 ); } switch( val ) { case S1_IN_S2_IN: Forward(); LineFollowFlag = 10; break; case S1_IN_S2_OUT: Forward(); if( LineFollowFlag > 1 ) { LineFollowFlag--; } break; case S1_OUT_S2_IN: Forward(); if( LineFollowFlag < 20 ) { LineFollowFlag++; } break; case S1_OUT_S2_OUT: if( LineFollowFlag == 10 ) { Backward(); } if( LineFollowFlag < 10 ) { TurnLeft2(); } if( LineFollowFlag > 10 ) { TurnRight2(); } break; } } /* action values of parseData()*/ enum action_e { GET = 1, RUN = 2, RESET = 4, START = 5 }; void parseData() { //isStart = false; int idx = readBuffer( 3 ); command_index = ( uint8_t ) idx; enum action_e action = ( enum action_e )readBuffer( 4 ); enum device_e device = ( enum device_e )readBuffer( 5 ); switch( action ) { case GET: { if( device != ULTRASONIC_SENSOR ) { writeHead(); writeSerial( idx ); } readSensor( device ); writeEnd(); } break; case RUN: { runModule( device ); callOK(); } break; case RESET: { //reset Stop(); LedsOff(); buzzerOff(); callOK(); } break; case START: { //start callOK(); } break; } } void runModule( device_e device ) { //0xff 0x55 0x6 0x0 0x2 0x22 0x9 0x0 0x0 0xa int port = readBuffer( 6 ); int pin = port; switch( device ) { case MOTOR: { controlflag = BLUE_TOOTH; int16_t speed = readShort( 7 ); setMotor( ( port == M1 ) ? M_LEFT : M_RIGHT, speed ); } break; case JOYSTICK: { controlflag = BLUE_TOOTH; int16_t leftSpeed = readShort( 6 ); int16_t rightSpeed = readShort( 8 ); setMotors( leftSpeed, rightSpeed ); } break; case RGBLED: { controlflag = BLUE_TOOTH; int16_t slot = readBuffer( 7 ); int16_t idx = readBuffer( 8 ); int16_t r = readBuffer( 9 ); int16_t g = readBuffer( 10 ); int16_t b = readBuffer( 11 ); if( ( rgb.getPort() != port ) || rgb.getSlot() != slot ) { rgb.reset( port, slot ); } if( idx > 0 ) { rgb.setColorAt( idx - 1, r, g, b ); } else { rgb.setColor( r, g, b ); } rgb.show(); } break; case SERVO: { int16_t slot = readBuffer( 7 ); pin = slot == 1 ? mePort[port].s1 : mePort[port].s2; int16_t v = readBuffer( 8 ); if( ( v >= 0 ) && ( v <= 180 ) ) { servo.attach( pin ); servo.write( v ); } } break; case SEVSEG: { if( seg.getPort() != port ) { seg.reset( port ); } float v = readFloat( 7 ); seg.display( v ); } break; case LEDMATRIX: { if( ledMx.getPort() != port ) { ledMx.reset( port ); } int16_t action = readBuffer( 7 ); if( action == 1 ) { int16_t px = readBuffer( 8 ); int16_t py = readBuffer( 9 ); int16_t len = readBuffer( 10 ); char* s = readString( 11, len ); ledMx.drawStr( px, py, s ); } else if( action == 2 ) { int16_t px = readBuffer( 8 ); int16_t py = readBuffer( 9 ); uint8_t* ss = readUint8( 10, 16 ); ledMx.drawBitmap( px, py, 16, ss ); } else if( action == 3 ) { int16_t point = readBuffer( 8 ); int16_t hours = readBuffer( 9 ); int16_t minutes = readBuffer( 10 ); ledMx.showClock( hours, minutes, point ); } else if( action == 4 ) { ledMx.showNum( readFloat( 8 ), 3 ); } } break; case LIGHT_SENSOR: { if( generalDevice.getPort() != port ) { generalDevice.reset( port ); } int16_t v = readBuffer( 7 ); generalDevice.dWrite1( v ); } break; case IR: { String Str_data; int16_t len = readBuffer( 2 ) - 3; for( int16_t i = 0; i < len; i++ ) { Str_data += ( char ) readBuffer( 6 + i ); } ir.sendString( Str_data ); Str_data = ""; } break; case SHUTTER: { if( generalDevice.getPort() != port ) { generalDevice.reset( port ); } int v = readBuffer( 7 ); if( v < 2 ) { generalDevice.dWrite1( v ); } else { generalDevice.dWrite2( v - 2 ); } } break; case DIGITAL: { pinMode( pin, OUTPUT ); int v = readBuffer( 7 ); digitalWrite( pin, v ); } break; case PWM: { pinMode( pin, OUTPUT ); int v = readBuffer( 7 ); analogWrite( pin, v ); } break; case TONE: { int hz = readShort( 6 ); int tone_time = readShort( 8 ); if( hz > 0 ) { buzzer.tone( hz, tone_time ); } else { buzzer.noTone(); } } break; case SERVO_PIN: { int v = readBuffer( 7 ); if( ( v >= 0 ) && ( v <= 180 ) ) { servo.attach( pin ); servo.write( v ); } } break; case TIMER: { lastTime = millis() / 1000.0; } break; default: break; } } void readSensor( enum device_e device ) { /************************************************** ff 55 len idx action device port slot data a 0 1 2 3 4 5 6 7 8 0xff 0x55 0x4 0x3 0x1 0x1 0x1 0xa ***************************************************/ float value = 0.0; int port, slot, pin; port = readBuffer( 6 ); pin = port; switch( device ) { case ULTRASONIC_SENSOR: { /* if( ultr.getPort() != port ) { ultr.reset( port ); } */ value = ( float ) ultr.distanceCm(); writeHead(); writeSerial( command_index ); sendFloat( value ); //Serial.println( value ); } break; case TEMPERATURE_SENSOR: { slot = readBuffer( 7 ); if( ( ts.getPort() != port ) || ( ts.getSlot() != slot ) ) { ts.reset( port, slot ); } value = ts.temperature(); sendFloat( value ); } break; case LIGHT_SENSOR: case SOUND_SENSOR: case POTENTIONMETER: { if( generalDevice.getPort() != port ) { generalDevice.reset( port ); pinMode( generalDevice.pin2(), INPUT ); } value = generalDevice.aRead2(); sendFloat( value ); } break; case JOYSTICK: { slot = readBuffer( 7 ); if( joystick.getPort() != port ) { joystick.reset( port ); } value = joystick.read( slot ); sendFloat( value ); } break; case IR: { // if(ir.getPort() != port) // { // ir.reset(port); // } // if(irReady) // { // sendString(irBuffer); // irReady = false; // irBuffer = ""; // } } break; case IRREMOTE: { // unsigned char r = readBuffer(7); // if((millis()/1000.0 - lastIRTime) > 0.2) // { // sendByte(0); // } // else // { // sendByte(irRead == r); // } // irRead = 0; // irIndex = 0; } break; case IRREMOTECODE: { // sendByte(irRead); // irRead = 0; // irIndex = 0; } break; case PIRMOTION: { if( generalDevice.getPort() != port ) { generalDevice.reset( port ); pinMode( generalDevice.pin2(), INPUT ); } value = generalDevice.dRead2(); sendFloat( value ); } break; case LINEFOLLOWER: { if( generalDevice.getPort() != port ) { generalDevice.reset( port ); pinMode( generalDevice.pin1(), INPUT ); pinMode( generalDevice.pin2(), INPUT ); } value = generalDevice.dRead1() * 2 + generalDevice.dRead2(); sendFloat( value ); } break; case LIMITSWITCH: { slot = readBuffer( 7 ); if( ( generalDevice.getPort() != port ) || ( generalDevice.getSlot() != slot ) ) { generalDevice.reset( port, slot ); } if( slot == 1 ) { pinMode( generalDevice.pin1(), INPUT_PULLUP ); value = !generalDevice.dRead1(); } else { pinMode( generalDevice.pin2(), INPUT_PULLUP ); value = !generalDevice.dRead2(); } sendFloat( value ); } break; case BUTTON_INNER: { pin = analogs[pin]; char s = readBuffer( 7 ); pinMode( pin, INPUT ); boolean currentPressed = !( analogRead( pin ) > 10 ); sendByte( s ^ ( currentPressed ? 1 : 0 ) ); //buttonPressed = currentPressed; } break; case GYRO: { // int axis = readBuffer(7); // gyro.update(); // if(axis == 1) // { // value = gyro.getAngleX(); // sendFloat(value); // } // else if(axis == 2) // { // value = gyro.getAngleY(); // sendFloat(value); // } // else if(axis == 3) // { // value = gyro.getAngleZ(); // sendFloat(value); // } } break; case VERSION: { sendString( mVersion ); } break; case DIGITAL: { pinMode( pin, INPUT ); sendFloat( digitalRead( pin ) ); } break; case ANALOG: { pin = analogs[pin]; pinMode( pin, INPUT ); sendFloat( analogRead( pin ) ); } break; case TIMER: { sendFloat( currentTime ); } break; default: break; } } #define INTERNAL_LED 13 #define INTERNAL_BUTTON 7 void blink( void* arg ) { static bool toggle = TRUE; toggle = !toggle; digitalWrite( INTERNAL_LED, toggle ); } void setup() { delay( 5 ); Stop(); LedsOff(); pinMode( INTERNAL_LED, OUTPUT ); pinMode( INTERNAL_BUTTON, INPUT ); digitalWrite( INTERNAL_LED, HIGH ); delay( 300 ); digitalWrite( INTERNAL_LED, LOW ); /* Initialize random seed one time */ randomSeed( analogRead( A6 ) ); AnalogHandler::begin(); simpleScheduler::addTask( 250, MeUltrasonicSensor::triggerTask, &ultr ); simpleScheduler::addTask( 100, AnalogHandler::task ); internalRGB.reset( PORT_7, SLOT2 ); internalRGB.setColor( 10, 0, 0 ); internalRGB.show(); //buzzer.tone( NTD1, 300 ); delay( 300 ); internalRGB.setColor( 0, 10, 0 ); internalRGB.show(); //buzzer.tone( NTD2, 300 ); delay( 300 ); internalRGB.setColor( 0, 0, 10 ); internalRGB.show(); //buzzer.tone( NTD3, 300 ); delay( 300 ); internalRGB.setColor( 10, 10, 10 ); internalRGB.show(); Serial.begin( 115200 ); buzzer.noTone(); ir.begin(); Serial.println( "[mBotEnhanced]" ); Serial.print( "Version: " ); Serial.println( mVersion ); //ledMx.setBrightness( 6 ); //ledMx.setColorIndex( 1 ); } void loop() { static boolean buttonWasPressed = false; getIRCommand(); serialHandle(); uint32_t elapsed = millis(); static uint32_t lastPrinted = 0; float Vref = 5.0; if( elapsed - lastPrinted > 200 ) { lastPrinted = elapsed; Serial.print( "ELAPSED: " ); Serial.println( elapsed ); Serial.print( "MODE: " ); Serial.println( char( 'A' + mode ) ); Serial.println( "TASKS" ); for( uint8_t i = 0; i < MAX_TASKS; ++i ) { Serial.print( i ); Serial.print( ": " ); Serial.println( simpleScheduler::getTaskDuration( i ) ); } Serial.println( "ANALOGS" ); Vref = 1.1 * 1023.0 / AnalogHandler::getValue( 9 ); Serial.print( "Vref: " ); Serial.println( Vref ); for( uint8_t i = 0; i < MAX_ANALOGS; ++i ) { Serial.print( i ); Serial.print( ": " ); Serial.print( AnalogHandler::getValue( i ) ); Serial.print( "\t" ); Serial.println( AnalogHandler::getValue( i ) * ( Vref / 1023.0 ) ); } Serial.print( "DISTANCE [cm]: " ); Serial.println( ultr.distanceCm( false ) ); } /* Check if internal button was pressed. Executes actions only one time * even if the button remain pressed */ //bool buttonPressed = !( analogRead( INTERNAL_BUTTON ) > 100 ); bool buttonPressed = !( AnalogHandler::getValue( INTERNAL_BUTTON ) > 100 ); if( buttonPressed != buttonWasPressed ) { buttonWasPressed = buttonPressed; /* If button is pressed now, change mode*/ if( buttonPressed == true ) { if( mode == MODE_A ) { mode = MODE_B; ChangeSpeed( 200 ); Stop(); LedsOff(); cli(); buzzer.tone( NTD2, 50 ); sei(); buzzer.noTone(); internalRGB.setColor( 0, 10, 0 ); internalRGB.show(); } else if( mode == MODE_B ) { mode = MODE_C; ChangeSpeed( 200 ); Stop(); LedsOff(); cli(); buzzer.tone( NTD2, 50 ); sei(); buzzer.noTone(); internalRGB.setColor( 0, 0, 10 ); internalRGB.show(); } else if( mode == MODE_C ) { mode = MODE_A; ChangeSpeed( 220 ); Stop(); LedsOff(); cli(); buzzer.tone( NTD1, 50 ); sei(); buzzer.noTone(); internalRGB.setColor( 10, 10, 10 ); internalRGB.show(); } } } switch( mode ) { case MODE_A: modeA(); break; case MODE_B: modeB(); break; case MODE_C: modeC(); break; } }
95239654d96f41ad91cf519b91e5e81eeab0d3ae
45154dfe316699b375ee5f4a5527296378af9d78
/src/databases/mysql/core/RowFormats.h
9d11db8553a2942b2ead1e5f8f8f36d5345c7e92
[ "MIT" ]
permissive
victormwenda/dbcrudgen-cpp
163d9c7da966dd84f5fc71810151c1973e5e60c5
0447c50bd8560e1865f0aa3ef53c7d0ffe07d435
refs/heads/master
2023-05-03T10:44:35.668694
2023-04-20T13:29:06
2023-04-20T13:29:51
92,381,769
0
2
null
null
null
null
UTF-8
C++
false
false
425
h
RowFormats.h
/** * @author Victor Mwenda * @author vmwenda.vm@gmail.com * * Created by victor on 6/15/17. * C/C++ Laptop */ #ifndef DBCRUDGEN_CPP_ROWFORMATS_H #define DBCRUDGEN_CPP_ROWFORMATS_H namespace dbcrudgen { namespace db { namespace mysql { enum class MYSQLRowFormats { FIXED, DYNAMIC, COMPRESSED, REDUNDANT, COMPACT }; } } }; #endif //DBCRUDGEN_CPP_ROWFORMATS_H
b93a47d92d346aec4da3a30c20c54f5ff95a582d
163ce03134f6ab6169e19f9df4ee8a0bf45d8452
/NavControl/ultraSonic.h
ac417589dabc8c347955c9308eb8690e34f159f0
[]
no_license
ottodude125/EmmaNavControl
108e31e1ccb9ca221d33ad6aa73358451d6ada2b
004b41469539e51f522556acd89c391f21648d73
refs/heads/master
2021-01-02T09:02:01.268234
2012-08-03T15:56:11
2012-08-03T15:56:11
3,392,995
0
0
null
null
null
null
UTF-8
C++
false
false
960
h
ultraSonic.h
/* * Created 1/25/11 * Developed by and tested by * * Jonathan Katon * * Mike B. * * The Ultrasonic Sensor source code obtains the latest distance readings from * given sensors and writes it into the most recent array location */ #ifndef ultraSonic_h #define ultraSonic_h #include "Arduino.h" #include "defines.h" class ultraSonicSensorPair { public: // Constructor ultraSonicSensorPair(int pin1, int pin2); // method it initialize the Ultrasonic Sensors and set them cycling void setupUsSensor(int Rx, int Bw); // get current distance float getUltrasonicDistance(); // array holding the measured distances from sensors float distance[2][numUssDistances]; // array holding the float values of two sensors converted into byte values to be transmitted to emma brain byte ussDistances4Brain[4]; private: int analogPin1; int analogPin2; }; #endif
0b3cfafbf3c689563f6ecb8f26ad3b6ef42d508e
486c7e8a16a1d5419bc7a385dd4d043558ee04ef
/VmpcPlugin/Source/ThirdParty/include/mpc/src/sequencer/SystemExclusiveEvent.cpp
9f87e953b9d835f41e9a85f4aa8fa087d501381f
[]
no_license
izzyreal/vmpc-unreal-plugin
73751fcd825ffe777fd08c7b651ef374aeb7c2fa
338ae3373956b88473d804ca75f081a756382f11
refs/heads/master
2023-04-11T02:24:46.902201
2021-04-28T20:39:10
2021-04-28T20:39:10
113,060,206
0
0
null
null
null
null
UTF-8
C++
false
false
1,029
cpp
SystemExclusiveEvent.cpp
#include <sequencer/SystemExclusiveEvent.hpp> using namespace mpc::sequencer; using namespace std; SystemExclusiveEvent::SystemExclusiveEvent() { bytes = vector<char>(2); } void SystemExclusiveEvent::setByteA(int i) { if(i < 0 || i > 255) return; bytes[0] = i; setChanged(); notifyObservers(string("stepeditor")); } int SystemExclusiveEvent::getByteA() { return bytes[0]; } void SystemExclusiveEvent::setByteB(int i) { if(i < 0 || i > 255) return; bytes[1] = i; setChanged(); notifyObservers(string("stepeditor")); } int SystemExclusiveEvent::getByteB() { return bytes[1]; } void SystemExclusiveEvent::setBytes(vector<char>* ba) { bytes = *ba; } vector<char>* SystemExclusiveEvent::getBytes() { return &bytes; } void SystemExclusiveEvent::CopyValuesTo(std::weak_ptr<Event> dest) { Event::CopyValuesTo(dest); auto lDest = dynamic_pointer_cast<SystemExclusiveEvent>(dest.lock()); lDest->setBytes(getBytes()); lDest->setByteA(getByteA()); lDest->setByteB(getByteB()); }
e8d988b23437414705985285f6fe6ab5665e62b7
5fc1a7d8e5d4ebc20c96a7ffe6b9635a3d755d91
/src/fccm.h
83c9f0eebad1d0d6bd11feef12d79df0c8d926a9
[]
no_license
ntyaan/clustering
db20a4983df370794d32d4d8e683e5f90fce9186
c95e76d4dcc5bdaf5efaf19fc5bc77490db2b9d1
refs/heads/master
2021-07-14T21:27:36.465152
2018-12-20T07:31:40
2018-12-20T07:31:40
143,392,497
1
1
null
null
null
null
UTF-8
C++
false
false
488
h
fccm.h
#include"klfcm.h" #ifndef __FCCM__ #define __FCCM__ class FCCM: public KLFCM{ protected: double FuzzifierLambda2; public: FCCM(int dimension, int data_number, int centers_number, double fuzzifierLambda, double fuzzifierLambda2); double &fuzzifierLambda2(void); virtual void revise_dissimilarities(void); virtual void revise_centers(void); virtual void initialize_centers_dissimilarities(int index); virtual void set_objective(void); }; #endif
eec311326474273f9a55f13e632896dd70969ab2
f4892c12c0e2ffdfbd678176dc8fa03f051314c4
/tiledb/sm/enums/query_condition_combination_op.h
df449e491b0210a838907c6786df0b21de96e666
[ "MIT" ]
permissive
TileDB-Inc/TileDB
06c15bcf6e3c62b191a6daa40fb33b41af2bdcdc
fddbe978d50ea7c9706fb0b7ca403c47986a4909
refs/heads/dev
2023-09-04T01:18:20.642838
2023-08-31T19:23:04
2023-09-02T14:36:02
86,868,560
1,779
204
MIT
2023-09-14T14:40:20
2017-03-31T23:44:23
C++
UTF-8
C++
false
false
4,811
h
query_condition_combination_op.h
/** * @file query_condition_combination_op.h * * @section LICENSE * * The MIT License * * @copyright Copyright (c) 2021-2022 TileDB, Inc. * * 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. * * @section DESCRIPTION * * This defines the tiledb QueryConditionCombinationOp enum that maps to * tiledb_query_condition_combination_op_t C-api enum. */ #ifndef TILEDB_QUERY_CONDITION_COMBINATION_OP_H #define TILEDB_QUERY_CONDITION_COMBINATION_OP_H #include <cassert> #include "tiledb/common/status.h" #include "tiledb/sm/misc/constants.h" #include "tiledb/stdx/utility/to_underlying.h" using namespace tiledb::common; namespace tiledb { namespace sm { /** Defines the query condition ops. */ enum class QueryConditionCombinationOp : uint8_t { #define TILEDB_QUERY_CONDITION_COMBINATION_OP_ENUM(id) id #include "tiledb/sm/c_api/tiledb_enum.h" #undef TILEDB_QUERY_CONDITION_COMBINATION_OP_ENUM }; /** * Returns the string representation of the input QueryConditionCombinationOp * type. */ inline const std::string& query_condition_combination_op_str( QueryConditionCombinationOp query_condition_combination_op) { switch (query_condition_combination_op) { case QueryConditionCombinationOp::AND: return constants::query_condition_combination_op_and_str; case QueryConditionCombinationOp::OR: return constants::query_condition_combination_op_or_str; case QueryConditionCombinationOp::NOT: return constants::query_condition_combination_op_not_str; default: return constants::empty_str; } } /** Returns the query condition_op given a string representation. */ inline Status query_condition_combination_op_enum( const std::string& query_condition_combination_op_str, QueryConditionCombinationOp* query_condition_combination_op) { if (query_condition_combination_op_str == constants::query_condition_combination_op_and_str) *query_condition_combination_op = QueryConditionCombinationOp::AND; else if ( query_condition_combination_op_str == constants::query_condition_combination_op_or_str) *query_condition_combination_op = QueryConditionCombinationOp::OR; else if ( query_condition_combination_op_str == constants::query_condition_combination_op_not_str) *query_condition_combination_op = QueryConditionCombinationOp::NOT; else { return Status_Error( "Invalid QueryConditionCombinationOp " + query_condition_combination_op_str); } return Status::Ok(); } inline void ensure_qc_combo_op_is_valid( QueryConditionCombinationOp query_condition_combo_op) { auto qc_combo_op_enum{::stdx::to_underlying(query_condition_combo_op)}; if (qc_combo_op_enum > 2) { throw std::runtime_error( "Invalid Query Condition Op " + std::to_string(qc_combo_op_enum)); } } inline void ensure_qc_combo_op_string_is_valid( const std::string& qc_combo_op_str) { QueryConditionCombinationOp qc_combo_op = QueryConditionCombinationOp::AND; Status st{query_condition_combination_op_enum(qc_combo_op_str, &qc_combo_op)}; if (!st.ok()) { throw std::runtime_error( "Invalid Query Condition Op string \"" + qc_combo_op_str + "\""); } ensure_qc_combo_op_is_valid(qc_combo_op); } /** Returns the negated combination op given a combination op. */ inline QueryConditionCombinationOp negate_qc_combination_op( const QueryConditionCombinationOp op) { switch (op) { case QueryConditionCombinationOp::AND: return QueryConditionCombinationOp::OR; case QueryConditionCombinationOp::OR: return QueryConditionCombinationOp::AND; default: throw std::runtime_error("negate_qc_combination_op: Invalid op."); } } } // namespace sm } // namespace tiledb #endif // TILEDB_QUERY_CONDITION_COMBINATION_OP_H
47557523a8a1d30cdd1a9d51216c8b0af48fa3b3
c818639aa7e74821ca20850e05829468657062d0
/hackerrank/algorithms/strings/sherlock-and-anagrams.cpp
79d2a365924dca3f14d61e841d644385df31fb70
[]
no_license
SolverX/problem_solving
685adbf23bf0abf1c80771469476f1184e44fbef
d807f34e1ea848af4ac8397d45cf06749e51bc1d
refs/heads/master
2016-09-06T16:13:44.338085
2015-06-11T05:04:33
2015-06-11T05:04:33
31,899,751
0
0
null
null
null
null
UTF-8
C++
false
false
1,158
cpp
sherlock-and-anagrams.cpp
#include <iostream> #include <algorithm> #include <vector> #include <map> #include <string> #include <utility> #include <cstdio> #include <cstring> #include <cmath> #include <cctype> #include <cstdlib> #include <bitset> using namespace std; #define VISITED 2 #define EXPLORED 1 #define UN_VISISTED 0 typedef unsigned long long ull; typedef unsigned long ul; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; string s; bool isAnagram(string a,string b){ sort(a.begin(),a.end()); sort(b.begin(),b.end()); return a==b; } long countAnagramPair(string s){ int len=s.length(),cnt=0; for(int i=0;i<len;i++){ for(int j=i;j<len;j++){ int diff = j-i; string a = s.substr(i,diff+1); for(int k=i+1;k<len-diff;k++){ string b = s.substr(k,diff+1); // cout<<a<<" "<<b<<endl; if(isAnagram(a,b)) cnt++; } } } return cnt; } int main(){ freopen("in.txt","rt",stdin); int T; cin>>T; while(T--){ cin>>s; cout<<countAnagramPair(s)<<endl; } return 0; }
8a46fb6c79f2a5a30d0095ef76fa8f1e07ae5800
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
/out/release/gen/net/net_jni_headers/DnsStatus_jni.h
1a62e126c24ee9e96822ec35334a690eb453d649
[ "BSD-3-Clause" ]
permissive
xueqiya/chromium_src
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
refs/heads/main
2022-07-30T03:15:14.818330
2021-01-16T16:47:22
2021-01-16T16:47:22
330,115,551
1
0
null
null
null
null
UTF-8
C++
false
false
3,776
h
DnsStatus_jni.h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file is autogenerated by // base/android/jni_generator/jni_generator.py // For // org/chromium/net/DnsStatus #ifndef org_chromium_net_DnsStatus_JNI #define org_chromium_net_DnsStatus_JNI #include <jni.h> #include "../../../../../base/android/jni_generator/jni_generator_helper.h" // Step 1: Forward declarations. JNI_REGISTRATION_EXPORT extern const char kClassPath_org_chromium_net_DnsStatus[]; const char kClassPath_org_chromium_net_DnsStatus[] = "org/chromium/net/DnsStatus"; // Leaking this jclass as we cannot use LazyInstance from some threads. JNI_REGISTRATION_EXPORT std::atomic<jclass> g_org_chromium_net_DnsStatus_clazz(nullptr); #ifndef org_chromium_net_DnsStatus_clazz_defined #define org_chromium_net_DnsStatus_clazz_defined inline jclass org_chromium_net_DnsStatus_clazz(JNIEnv* env) { return base::android::LazyGetClass(env, kClassPath_org_chromium_net_DnsStatus, &g_org_chromium_net_DnsStatus_clazz); } #endif // Step 2: Constants (optional). // Step 3: Method stubs. namespace net { namespace android { static std::atomic<jmethodID> g_org_chromium_net_DnsStatus_getDnsServers(nullptr); static base::android::ScopedJavaLocalRef<jobjectArray> Java_DnsStatus_getDnsServers(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_chromium_net_DnsStatus_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_chromium_net_DnsStatus_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getDnsServers", "()[[B", &g_org_chromium_net_DnsStatus_getDnsServers); jobjectArray ret = static_cast<jobjectArray>(env->CallObjectMethod(obj.obj(), call_context.base.method_id)); return base::android::ScopedJavaLocalRef<jobjectArray>(env, ret); } static std::atomic<jmethodID> g_org_chromium_net_DnsStatus_getPrivateDnsActive(nullptr); static jboolean Java_DnsStatus_getPrivateDnsActive(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_chromium_net_DnsStatus_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_chromium_net_DnsStatus_clazz(env), false); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getPrivateDnsActive", "()Z", &g_org_chromium_net_DnsStatus_getPrivateDnsActive); jboolean ret = env->CallBooleanMethod(obj.obj(), call_context.base.method_id); return ret; } static std::atomic<jmethodID> g_org_chromium_net_DnsStatus_getPrivateDnsServerName(nullptr); static base::android::ScopedJavaLocalRef<jstring> Java_DnsStatus_getPrivateDnsServerName(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_chromium_net_DnsStatus_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_chromium_net_DnsStatus_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getPrivateDnsServerName", "()Ljava/lang/String;", &g_org_chromium_net_DnsStatus_getPrivateDnsServerName); jstring ret = static_cast<jstring>(env->CallObjectMethod(obj.obj(), call_context.base.method_id)); return base::android::ScopedJavaLocalRef<jstring>(env, ret); } } // namespace android } // namespace net // Step 4: Generated test functions (optional). #endif // org_chromium_net_DnsStatus_JNI
e0e846cab56272db61ba4224ae87c93dcaa17327
3a0c6853c494347443209b7ff6bb8e2346569391
/DAlisaBobIKonfeti.cpp
15ef524ea766a5638710235e25ceb23c4aad71e3
[]
no_license
agul/contest-tasks
9b6e5656f66394d3aba4442087d3fd27746c201f
739ded97b34f9767433bb85744877de787ace636
refs/heads/master
2023-03-27T19:32:06.490883
2021-03-30T17:06:25
2021-03-30T17:06:25
259,159,370
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
cpp
DAlisaBobIKonfeti.cpp
#include "base/header.hpp" class DAlisaBobIKonfeti { public: void solve(std::istream& in, std::ostream& out) { int testsCount; in >> testsCount; for (int test : range(testsCount)) { int n; in >> n; auto a = make_vector<int>(n, 0); in >> a; int steps = 0; int alice = 0; int bob = 0; int last = 0; int left = 0; int right = n - 1; while (left <= right) { int sum = 0; if (steps & 1) { while (left <= right && sum <= last) { sum += a[right]; --right; } bob += sum; } else { while (left <= right && sum <= last) { sum += a[left]; ++left; } alice += sum; } last = sum; ++steps; } out << steps << " " << alice << " " << bob << std::endl; } } static constexpr bool kUseCustomChecker = false; bool check(std::string input, std::string expected_output, std::string actual_output) { return true; } static constexpr size_t kGeneratedTestsCount = 0; static void generate_test(std::ostream& test) {} private: size_t test_id_ = 0; };
746f19a079fad1feaf95617fe0c50b3642f5a689
ed0b7587a7a1dd4b4e97adbd8d8c129585bc6365
/Graph/src/UnionFindSet.cpp
034441d971fcb2ed4f4b56f17a42a41c499f8c10
[]
no_license
MaxEntroy/data-structure
456160e66317203d819d47afef9a4860498650d3
84668cc9fae9ab403a36cf764b97792df9e20085
refs/heads/master
2021-06-27T08:03:53.056130
2017-09-11T07:15:52
2017-09-11T07:15:52
103,101,722
0
0
null
null
null
null
UTF-8
C++
false
false
738
cpp
UnionFindSet.cpp
#include <iostream> #include "UnionFindSet.h" Status make_set( int* tree, int n ){ if( !tree || n < 1 ){ std::cerr << "Invalid arguments!" << std::endl; return ERROR; } for( int i = 1; i <= n; ++i ){ tree[i] = -1; } return OK; } int find_set( int* tree, int i ){ if( !tree || i < 1 ) return 0; if( -1 == tree[i] ) return i; else{ int ret = find_set( tree, tree[i] ); tree[i] = ret; return ret; } } bool union_set( int* tree, int i, int j ){ if( !tree || i < 1 || j < 1 ){ std::cerr << "Invalid arguments" << std::endl; return ERROR; } int a = find_set( tree, i ); int b = find_set( tree, j ); if( a != b ){ tree[b] = a; return true; } else return false; }
b2aec05e37656f0cdacdfac5c2370cb2816f896d
b2d9ecdafec33c1bcd4f0975cd713b10d13d3b2a
/dependencies/utf8rewind-1.2.1/source/documentation/overview.hpp
a9519dd1f73530ac84b4d05bf3869c6377a3f438
[ "MIT" ]
permissive
knight666/dodexample
c49d4944ca0017fc4d9fce4d94dd805676f8c415
f304a6d13907389cef16cc2f711c3a2d25f01f7e
refs/heads/master
2022-11-08T01:13:41.875942
2015-09-29T08:52:39
2015-09-29T08:52:39
275,504,480
0
0
null
null
null
null
UTF-8
C++
false
false
6,657
hpp
overview.hpp
/*! \mainpage Overview \tableofcontents \section introduction Introduction `utf8rewind` is a cross-platform and open source C library designed to extend the default string handling functions and add support for UTF-8 encoded text. \section example Example \code{.c} #include "utf8rewind.h" int main(int argc, char** argv) { const char* input = "Hello World!"; static const size_t output_size = 256; char output[output_size]; wchar_t output_wide[output_size]; const char* input_seek; size_t converted_size; int32_t errors; memset(output, 0, output_size * sizeof(char)); memset(output_wide, 0, output_size * sizeof(wchar_t)); // Convert input to uppercase: // // "Hello World!" -> "HELLO WORLD!" converted_size = utf8toupper( input, strlen(input), output, output_size - 1, &errors); if (converted_size == 0 || errors != UTF8_ERR_NONE) { return -1; } // Convert UTF-8 input to wide (UTF-16 or UTF-32) encoded text: // // "HELLO WORLD!" -> L"HELLO WORLD!" converted_size = utf8towide( output, strlen(output), output_wide, (output_size - 1) * sizeof(wchar_t), &errors); if (converted_size == 0 || errors != UTF8_ERR_NONE) { return -1; } // Seek in input: // // Hello World!" -> "World!" input_seek = utf8seek(input, input, 6, SEEK_SET); return 0; } \endcode \section features Features * **Conversion to and from UTF-8** - `utf8rewind` provides functions for converting from and to [wide](\ref widetoutf8), [UTF-16](\ref utf16toutf8) and [UTF-32](\ref utf32toutf8) encoded text. * **Case mapping** - The library also provides functionality for converting text to [uppercase](\ref utf8toupper), [lowercase](\ref utf8tolower) and [titlecase](\ref utf8totitle). * **Normalization** - With #utf8normalize, you can normalize UTF-8 encoded text to NFC, NFD, NFKC or NFKD without converting it to UTF-32 first. * **Seeking** - Using #utf8seek, you can seek forwards and backwards in UTF-8 encoded text. * **Cross-platform** - `utf8rewind` is written in plain C, which means it can be used on any platform with a compliant C compiler. Currently, Windows, Linux and Mac versions are available. * **Easy to integrate** - The library consists of only 13 public functions and requires no initialization. Any C or C++ project can add `utf8rewind` without breaking existing code. * **Simple bindings** - No structs are used in the public interface, only pointers. Even if you don't use C, if the language of your choice allows bindings to C functions (e.g. Python), you can benefit from integrating `utf8rewind` into your project. * **No heap allocations** - All allocations in `utf8rewind` happen on the stack. You provide the memory, without having to override `malloc`. This makes the library perfectly tailored to game engines, integrated systems and other performance-critical or memory-constrained projects. * **Safety** - Over 2300 automated unit and integration tests guarantee the safety and security of the library. For a full summary of the interface, please refer to the [interface page](\ref utf8rewind.h). \section license Licensing This project is licensed under the MIT license, a full copy of which should have been provided with the project. \section building Building the project All supported platforms use [GYP](http://code.google.com/p/gyp/) to generate a solution. This generated solution can be used to compile the project and its dependencies. \subsection building-windows Building on Windows with Visual Studio \note You will need to have Visual Studio 2010 or above installed. Open a command window at the project's root. If you have multiple versions of Visual Studio installed, you must first specify the version you want to use: set GYP_MSVS_VERSION=2012 Use GYP to generate a solution: tools\gyp\gyp --depth utf8rewind.gyp Open the solution in Visual Studio. You can use the different build configurations to generate a static library. \subsection building-linux Building on Linux with GCC Open a command window at the project's root. Ensure you have all dependencies installed using your preferred package manager: sudo apt-get install gcc g++ gyp doxygen Use GYP to generate a Makefile: gyp --depth=. utf8rewind.gyp Build the project using `make`: make For a release build, specify the build type: make BUILDTYPE=Release \note The generated Makefile does not contain a "clean" target. In order to do a full rebuild, you must delete the files in the "output" directory manually. \subsection building-mac Building on Mac OS X with XCode \note Building on Mac OS X is currently untested. Please let us know if you can help us in this regard. Open a command window at the project's root. Use GYP to generate a solution: tools\gyp\gyp --depth utf8rewind.gyp Open the solution in XCode and you can build the library and tests. \subsection running-tests Running the tests After generating a solution, build and run the "tests-rewind" project. Verify that all tests pass on your system configuration before continuing. \section helping-out Helping out As a user, you can help the project in a number of ways, in order of difficulty: * **Use it** - By using the library, you are helping the project spread. It is very important to us to have the project be used by as many different projects as possible. This will allow us to create better public interfaces. * **Spread the word** - If you find `utf8rewind` useful, recommend it to your friends or coworkers. * **Complain** - No library is perfect and `utf8rewind` is no exception. If you find a fault but lack the means (time, resources, etc.) to fix it, sending complaints to the proper channels can help the project out a lot. * **Write a failing test** - If a feature is not working as intended, you can prove it by writing a failing test. By sending the test to us, we can make the adjustments necessary for it to pass. * **Write a patch** - Patches include a code change that help tests to pass. A patch must always include a set of tests that fail to pass without the patch. All patches will be reviewed and possibly cleaned up before being accepted. \section contact Contact For inquiries, complaints and patches, please contact `{quinten}{lansu} {at} {gmail}.{com}`. Remove the brackets to get a valid e-mail address. */
0c5e8bb7cd84df42542c7eb8e629644d1bda01df
aa3cd466346cdc9c2dbd4e554b4a6b5e5843e618
/Lab 5/Lab 5.1a/while3.cpp
4475e6ce4ab5f5d7cd8ffb67c35042b6479e062f
[]
no_license
laconde/lab5
1420d5dd63a5eab417c3b5e6eb2d004b0894cae0
99ab6566e21ae80bcfc360227061ce41846fd343
refs/heads/main
2023-07-15T23:12:51.365271
2021-08-12T02:29:41
2021-08-12T02:29:41
395,171,450
0
0
null
null
null
null
UTF-8
C++
false
false
521
cpp
while3.cpp
// Alberto Conde // September 16, 2020 #include <iostream> #include <string> using namespace std; int main() { char letter; do { cout << "Please enter a letter\n"; cout << "Enter 'y' to exit the program\n"; cin >> letter; cout << "The letter you entered is " << letter << endl; } while (letter != 'y'); return 0; } // When you replace it with a do-while loop, the do-while performs the first iteration even when the expression is false.
cddb7082fd91a3f24fb8c72204cda8d8fdd16c82
0fb0caffbc733db88d8d91b48999b4cf7647a41a
/include/NN_basis_function.hpp
4e186e8f4f07954f6c446c2f0e27260c0b63f0af
[ "MIT" ]
permissive
DiegoAE/BOSD
9b0c225ee53d35cd497fa075e7ac837c1129d5a8
a7ce88462c64c540ba2922d16eb6f7eba8055b47
refs/heads/master
2021-07-15T16:05:36.831765
2020-04-20T19:04:58
2020-04-20T19:04:58
169,775,311
20
2
null
null
null
null
UTF-8
C++
false
false
1,482
hpp
NN_basis_function.hpp
#ifndef NN_BASIS_FUNCTION_H #define NN_BASIS_FUNCTION_H #include <mlpack/core.hpp> #include <mlpack/methods/ann/layer/layer.hpp> #include <mlpack/methods/ann/ffn.hpp> #include <mlpack/methods/ann/init_rules/random_init.hpp> #include <mlpack/methods/ann/loss_functions/mean_squared_error.hpp> #include <armadillo> #include <json.hpp> #include <robotics/basis_functions.hpp> namespace hsmm { typedef mlpack::ann::FFN<mlpack::ann::MeanSquaredError<>, mlpack::ann::RandomInitialization> NNmodel; class ScalarNNBasis : public robotics::ScalarBasisFun { public: ScalarNNBasis(arma::ivec hidden_units_per_layer, int njoints); ScalarNNBasis(nlohmann::json &stream); NNmodel& getNeuralNet() const; // Takes into account also the input and output layers. int getNumberLayers() const; std::pair<arma::mat, arma::vec> getOutputLayerParams() const; void setNeuralNet(NNmodel &neural_net); arma::vec eval(double t) const; // TODO. arma::vec deriv(double time, unsigned int order) const; unsigned int dim() const; nlohmann::json to_stream() const; ~ScalarNNBasis() = default; private: arma::ivec hidden_units_per_layer_; mlpack::ann::Linear<>* output_layer_ = nullptr; mutable NNmodel neural_net_; int neural_net_outputs_; }; }; #endif
270dfd081e4169c6b3074f616f7dc75eaf080647
d42607e659397dbb8c94980e3b18537867763521
/include/TextExt.h
1b5ff9c62aa3ae9457706e769432d6698d120ecd
[]
no_license
igorJarek/SourceStructAnalyzer
300339d93db8e644e66bc80f290f05ad389675a7
29ed80a4297b2b8bbb674a785e10d5be930aeec9
refs/heads/master
2020-08-29T19:45:30.548331
2020-01-10T01:10:51
2020-01-10T01:10:51
218,152,621
1
0
null
2019-12-29T13:19:26
2019-10-28T21:55:53
C++
UTF-8
C++
false
false
3,362
h
TextExt.h
#ifndef TEXTEXT_H #define TEXTEXT_H #include <SFML/Graphics/Export.hpp> #include <SFML/Graphics/Drawable.hpp> #include <SFML/Graphics/Transformable.hpp> #include <SFML/Graphics/Font.hpp> #include <SFML/Graphics/Rect.hpp> #include <SFML/Graphics/VertexArray.hpp> #include <SFML/System/String.hpp> #include <string> #include <vector> #include <Typedefs.h> using namespace sf; class TextExt : public Drawable, public Transformable { public: enum Style { Regular = 0, ///< Regular characters, no style Bold = 1 << 0, ///< Bold characters Italic = 1 << 1, ///< Italic characters Underlined = 1 << 2, ///< Underlined characters StrikeThrough = 1 << 3 ///< Strike through characters }; TextExt(); TextExt(const String& string, const Font& font, unsigned int characterSize = 30); void setString(const String& string); void setFont(const Font& font); void setCharacterSize(unsigned int size); void setLineSpacing(float spacingFactor); void setLetterSpacing(float spacingFactor); void setStyle(Uint32 style); void setFillColor(const Color& color); void setOutlineColor(const Color& color); void setOutlineThickness(float thickness); void changeCharacterColor(const sf::Color& newColor, uint64_t position, uint64_t offset = 0); void changeCharactersColor(const sf::Color& newColor, Pos position, uint64_t offset = 0); const String& getString() const; const Font* getFont() const; unsigned int getCharacterSize() const; float getLetterSpacing() const; float getLineSpacing() const; Uint32 getStyle() const; const Color& getFillColor() const; const Color& getOutlineColor() const; float getOutlineThickness() const; Vector2f findCharacterPos(std::size_t index) const; FloatRect getLocalBounds() const; FloatRect getGlobalBounds() const; private: virtual void draw(RenderTarget& target, RenderStates states) const; void ensureGeometryUpdate() const; String m_string; ///< String to display const Font* m_font; ///< Font used to display the string unsigned int m_characterSize; ///< Base size of characters, in pixels float m_letterSpacingFactor; ///< Spacing factor between letters float m_lineSpacingFactor; ///< Spacing factor between lines Uint32 m_style; ///< Text style (see Style enum) Color m_fillColor; ///< Text fill color Color m_outlineColor; ///< Text outline color float m_outlineThickness; ///< Thickness of the text's outline mutable VertexArray m_vertices; ///< Vertex array containing the fill geometry mutable VertexArray m_outlineVertices; ///< Vertex array containing the outline geometry mutable FloatRect m_bounds; ///< Bounding rectangle of the text (in local coordinates) mutable bool m_geometryNeedUpdate; ///< Does the geometry need to be recomputed? }; #endif // TEXTEXT_H
8dd315f9b15cc0cd68152511d953b0c6a37db499
0530b4a0c19644d5e679c94cada4039054a96477
/ThreadCommunication.h
75f172aec61e90e39dd40cb7635edc84842fdbaa
[ "MIT" ]
permissive
Gotbread/TwitchGambleBot
b99ac8b3cb7da22c6402893aa17e7fd2dc63bd2f
6a1b5a155b60635041abeefffd46352dbb4f589c
refs/heads/master
2021-07-10T05:11:38.990686
2018-09-22T14:06:57
2018-09-22T14:06:57
149,881,932
1
0
null
null
null
null
UTF-8
C++
false
false
4,866
h
ThreadCommunication.h
#pragma once #include <functional> #include <vector> #include <thread> #include <queue> #include <mutex> #include <condition_variable> #ifdef _WINDOWS void SetThreadName(const char* threadName); const char *CleanName(const char *name); #endif template<class T> class Signal { public: Signal() : signaled(false) { } Signal(const Signal &other) = default; void Set(T t) { std::lock_guard<std::mutex> guard(mut); signaled = true; data = t; cond.notify_one(); } T Wait() { std::unique_lock<std::mutex> lock(mut); cond.wait(lock, [&] {return signaled; }); signaled = false; return data; } private: std::condition_variable cond; std::mutex mut; bool signaled; T data; }; class ThreadManager; class ThreadInterface { public: ThreadInterface(); virtual ~ThreadInterface(); virtual void Run(Signal<bool> *init_signal, Signal<bool> *run_signal) = 0; virtual void ExitThread() = 0; virtual void WaitThread() = 0; protected: friend class ThreadManager; }; template<class T> using AsyncFunction = std::function<void(T *)>; template<class T> struct MessageQueue { enum Reason { ReasonNone, ReasonData, ReasonExit }; MessageQueue() : wakeup_reason(ReasonNone), should_exit(false) { } void Add(AsyncFunction<T> &&func) { std::lock_guard<std::mutex> guard(mut); function_queue.push(std::move(func)); wakeup_reason = ReasonData; cond.notify_one(); } void Exit() { std::lock_guard<std::mutex> guard(mut); should_exit = true; wakeup_reason = ReasonExit; cond.notify_one(); } Reason Wait(AsyncFunction<T> &func) { std::unique_lock<std::mutex> lock(mut); if (should_exit) return ReasonExit; if (!function_queue.empty()) { func.swap(function_queue.front()); function_queue.pop(); return ReasonData; } // buddifix 03.09.2018 do { cond.wait(lock); } while (wakeup_reason == ReasonNone); if (should_exit) return ReasonExit; if (!function_queue.empty()) { func.swap(function_queue.front()); function_queue.pop(); return ReasonData; } return ReasonNone; } size_t Size() { std::unique_lock<std::mutex> lock(mut); return function_queue.size(); } Reason wakeup_reason; bool should_exit; std::mutex mut; std::condition_variable cond; std::queue<AsyncFunction<T>> function_queue; }; template<class T, class QueueType = MessageQueue<T>> class BaseThread : public ThreadInterface { public: typedef QueueType Queue; template<typename F, typename ...Args> static void RPC(F f, Args&& ...args) { queue.Add(std::bind(f, std::placeholders::_1, std::forward<Args>(args)...)); } static size_t QueueSize() { return queue.Size(); } virtual bool OnInit() { return true; } virtual void OnStart() { } virtual void OnExit() { } virtual void OnOtherEvent(typename Queue::Reason) { } std::thread::id GetThreadID() { return thread.get_id(); } static std::thread::id GetFirstThreadID() { return first_thread_id; } private: void Run(Signal<bool> *init_signal, Signal<bool> *run_signal) override { thread = std::thread(&BaseThread<T, QueueType>::ThreadFunc, this, init_signal, run_signal); } void ExitThread() override { queue.Exit(); } void WaitThread() override { thread.join(); } void ThreadFunc(Signal<bool> *init_signal, Signal<bool> *run_signal) { { #ifdef _WINDOWS #ifdef _DEBUG SetThreadName(CleanName(typeid(T).name())); #endif #endif std::lock_guard<std::mutex> lock(thread_id_mutex); if (first_thread_id != std::thread::id()) first_thread_id = GetThreadID(); } init_signal->Set(OnInit()); bool run = run_signal->Wait(); init_signal->Set(true); if (!run) return; OnStart(); for (;;) { AsyncFunction<T> func; auto reason = queue.Wait(func); if (reason == queue.ReasonData) { func(static_cast<T *>(this)); } else if (reason == queue.ReasonExit) { break; } else { OnOtherEvent(reason); } } OnExit(); } static Queue queue; static std::thread::id first_thread_id; static std::mutex thread_id_mutex; std::thread thread; }; class ThreadManager { public: static bool Run(); static void Exit(); static void Wait(); private: friend class ThreadInterface; static void AddThread(ThreadInterface *thread); static void RemoveThread(ThreadInterface *thread); static std::vector<ThreadInterface *> threads; }; template<class T, class QueueType> QueueType BaseThread<T, QueueType>::queue; template<class T, class QueueType> std::thread::id BaseThread<T, QueueType>::first_thread_id; template<class T, class QueueType> std::mutex BaseThread<T, QueueType>::thread_id_mutex;
9b84f0c84a403b281882129c878c8767213e5753
a1d634c8c9808d9eae81bc2514ee5817af677b18
/Example/src/PtCorrectionProducerLocal.cc
0e6e171bb801e0adee081a731dd7f0eaab09f047
[]
no_license
artus-analysis/Artus
eaeeec4e36b167e72275176076edc7167d304607
9170dd2f0e7664f43231243aee79f3e0a0657a0a
refs/heads/master
2022-08-11T12:12:23.166211
2019-12-17T18:18:51
2020-01-22T12:49:14
23,577,702
7
25
null
2020-01-21T12:45:19
2014-09-02T12:27:01
C++
UTF-8
C++
false
false
660
cc
PtCorrectionProducerLocal.cc
#include "Artus/Example/interface/PtCorrectionProducerLocal.h" std::string PtCorrectionProducerLocal::GetProducerId() const { return "pt_correction_local"; } void PtCorrectionProducerLocal::Init(setting_type const& settings, metadata_type& metadata) { ProducerBase<TraxTypes>::Init(settings, metadata); } void PtCorrectionProducerLocal::Produce(event_type const& event, product_type & product, setting_type const& settings, metadata_type const& metadata) const { // m_floatPtSim_corrected has been set by the global producer before product.m_floatPtSim_corrected = product.m_floatPtSim_corrected * settings.GetProducerPtCorrectionFactorLocal(); }
951ac3aae95c9c97e49a05f4f656ffdd2a8e033e
3abeb67b77d2571413965c810aef1094105da288
/out/cdt.h
66dec204ce3d774202c93255480b653955f241e4
[]
no_license
edgeofmoon/GraphView2017
a9ca6b03472cb6acab9d2da5b08dcea03af84c27
3c274700d9ca3df5c8e6b56a976edb6f4c07a556
refs/heads/master
2021-09-04T06:48:07.797881
2018-01-16T21:16:09
2018-01-16T21:16:09
108,027,930
0
0
null
null
null
null
UTF-8
C++
false
false
10,381
h
cdt.h
// file name: cdt.h // including all the data structure used in // constrained delaunay triangultaion(CDT). // // author: Zhihua Wang (zhihua@cs.nyu.edu) // date: Dec 12, 2002 /*************************************************************/ //#define OUTPUT //#define DEBUG //#define DETECT_COLLINEAR_DEGENERACY #pragma once #define COMMENT_ON #define NOT_SUPPORT_SAME_X #undef NOT_SUPPORT_SAME_X // ************************************************************* // predefinitions // ************************************************************* #include <math.h> #include "geom2d.h" #include "myMacro.h" // ************************************************************* // io utility // ************************************************************* #include <stdio.h> #include <stdlib.h> #include <assert.h> #define BLANK ' ' #define TAB '\t' #define noff_keyword "NOFF" #define LINE_LENGTH 80 #define NO_ERR 1 #define ERR_IMPORT_FILE -1 #define ERR_CANNOT_OPEN_FILE -2 #define ERR_NOT_VALID_FORMAT -3 #define ERR_WRONG_VERTEX_NUMBER -4 #define ERR_WRONG_FACE_NUMBER -4 void reportWarning(char* str,int line,char* file); void reportError(char* str,int line,char* file); // ************************************************************* // primitives // data structure // ************************************************************* #define NON_CONSTRANED -1 // type value of non constrained edge (see below) #define CONSTRAINED 1 #define VIRTUAL 0 #define SEPOFFSET 1 // some value >0 to make offset #define MAX_Y HUGE_VAL #define MIN_Y -HUGE_VAL // my Face class myFace; typedef myFace* FPointer; // end my Face class Mesh; class Vertex; class Halfedge; class Edge; class EdgeList; class Slab; class Quad; struct Window; typedef Mesh* MeshPointer; typedef Vertex* VPointer; typedef Halfedge* HePointer; typedef Edge* EPointer; typedef EdgeList* EListPointer; typedef Slab* SPointer; typedef Quad* QPointer; typedef Window* WPointer; // planar graph class Mesh{ HePointer getHullHalfedge(VPointer v,int sep_index,bool lowside); HePointer getHullHalfedgeNextTo(HePointer _he,VPointer v,int l,int sep_index,int r,bool lowside); void findInitialCandidatePair(WPointer w, VPointer &p0,VPointer &q0, HePointer &p_he,HePointer &q_he, bool lowside); EPointer advancePairToBridge(WPointer w,VPointer p0,VPointer q0,HePointer p_he,HePointer q_he,bool lowside); public: int v_num; //the number of vertices read from input VPointer* v_array; // the array pointing to the vertices double* sep_array; // x-value of vertical separate lines int e_num; // numver of edges int ce_num; // number of constrained edges read from input EListPointer e_head,e_tail; //bounding box (mins.x, maxs.x) * (mins.y maxs,y) Point maxs; Point mins; //bounding utility VPointer vlb,vlt; //left most, btm and top vertex added manually VPointer vrb,vrt; EPointer sky_e; EPointer eth_e; //slab head SPointer s_head; // SPointer s_tail; Mesh(); EPointer addEdge(VPointer v1,VPointer v2,int type=NON_CONSTRANED, bool isExt = false); void deleteEdge(EPointer e); int initSlabs(); int mergeSlabs(); void mergeSlabPair(SPointer ls); void sortVertices(); int import2OFFFile(char* sf); int export2OFFFile(char* sf,char* f=NULL); EPointer findBridge(WPointer w,bool lowside); EPointer findNextBaseEdge(WPointer w,EPointer e); void buildCDTOfWindow(WPointer w); int buildCDT(); void display(); MeshPointer copy(); }; //vertex class Vertex{ private: ////members int valence; int index; // index in x coordinate order ////functions public: ////members ////topology HePointer out_he; //out halfedge pointer ////geometry Point pos; //// external edge idx int extIdx; ////functions //constructor Vertex(double _x,double _y,int i, int _extIdx = -1); // Vertex(const Point &p=O,int i=0); ~Vertex(); //field access int getIndex()const {return index;}; //not user interface, only used by exportXXFile() void setIndex(int _i){index=_i;}; //not user interface, only used by exportXXFile() //initOutHalfedgeList(); void addToOutHalfedgeList(HePointer he); // not an interface for user void deleteFromOutHalfedgeList(HePointer he); //not an interface for use HePointer findOutHalfedgeInRing(VPointer v2); HePointer findInHalfedgeInRing(VPointer v2); HePointer addHalfedge(VPointer v2,EPointer e);// not an interface to user, only called by addEdge() int getValence()const{return valence;}; };// of Vertex // Halfedge class Halfedge{ public: ////members //topology VPointer v; // vertex pointer to front v(fv) //back v(bv) is pre_he->v // pointer to the face FPointer f; EPointer e; // edge pointer HePointer inv_he; // opposite halfedge pointer HePointer next_he; //next halfedge HePointer pre_he; //pre halfedge //geometry //normalized direction vector // double v[Dimension]; Vector d;//direction from back v to front v ////functions Halfedge(VPointer _v=NULL,EPointer _e=NULL):v(_v),e(_e){inv_he=next_he=pre_he=NULL;d.x=0;d.y=0;f = NULL;}; ~Halfedge(); //field access //topology query VPointer getBackVertex() const{return inv_he->v;}; VPointer getFrontVertex() const{return v;}; };// of Halfedge // Edge class Edge{ public: //members //topology //he[0] is always from left to right //he[1] is always from right to left HePointer he[2]; //halfedge pointer pair, he[0]->v->pos.x > he[1]'s //scene level EListPointer iter; //type, can be constrained or nonconstrained int type; bool isExternal; //functions Edge(VPointer v1,VPointer v2,int type=NON_CONSTRANED, bool isExt = false); ~Edge(); //field access //topology query //if an Edge exists, there must be 2 Halfedge VPointer getOneVertex()const {return he[0]->v;}; VPointer getTheOtherVertex()const{return he[1]->v;}; };// of Edge class EdgeList{ public: EPointer e; EListPointer next; EdgeList(EPointer _e):e(_e){e->iter=this;next=NULL;}; }; //slab class Slab{ public: int l,r; // indices of left and right separate line QPointer q_head,q_tail; // head of list of quads SPointer next; // next slab //methords //constructor with li as left index and ri as right index Slab(int li,int ri); void pushBackQuad(QPointer q); }; // quad class Quad{ public: // highest and lowest vertices in the quad VPointer top_v,btm_v; // top and bottom long edges of this quad (refer to long edge above) HePointer top_he;// top half-edge from right to left HePointer btm_he;// bottom half-edge from left to right // indices of left and right vertical line int l,r; // y value corresponding to the intersection of top_v and top_he double top_y; // y value corresponding to the intersection of btm_v and btm_he double btm_y; // y value of four cornor double left_top_y; double left_btm_y; double right_top_y; double right_btm_y; QPointer next; // next quad in the list for this slab //methords // constructor with highv as hv, lowv as lv, t as top and b as btm Quad(VPointer highv,VPointer lowv,HePointer t,HePointer b,int _l,int _r); Quad(); void updateLongEdge(EPointer e); void computeCornorY(double lx,double rx); }; struct Window{ // int m; //middle separate line index QPointer lq,rq; // left and right quad //-1 :left above right //0 : identical // 1: left below right int upsign,downsign; //sign indicating the intersection situation for lq,rq's top,btm halfedges }; //given two quad which share a separate line, return their intersection window //return null if no intersection and set lgr to true if lq is above rq WPointer getWindow(QPointer lq,QPointer rq,bool &lgr); //primitives in computational geometry /****************************************************************** Given ratio of (xq-x1)/(xq-x2), assume xq!=x2 Return: never be 1 =0 :xq eq x1 <0 : xq in middle of x1,x2 0< <1: x1 is in middle of xq,x2 >1 :x2 is in middle of xq,x1 ******************************************************************/ /* //#EXACT double getLambda(double xq,double x1,doube x2) { assert(xq-x2); return((xq-x1)/(xq-x2)); } */ /****************************************************************** is xq in between x1,x2, assume xq not eq x1 or x2 ******************************************************************/ bool inBetween(double xq,double x1,double x2); /****************************************************************** Given two vertices on a line, get the y-value of vertex on line whose x-vaule is given too. Using line equation (y-y1)/(x-x1)=(y2-y1)/(x2-x1) y*(x2-x1)=(x-x1)*(y2-y1)+y1*(x2-x1)=(x-x1)*y2+y1*(x2-x) ******************************************************************/ //#EXACT double yOfLineGivenX(double x1,double y1,double x2,double y2,double x) ; /****************************************************************** Point on the side of radial line: (x,y)'s position according to radial line (ox,oy) to (x1,y1) return value: -1 left 0 on line 1 right ******************************************************************/ //#EXACT this function requires exact computation int pointToLine(double x,double y,double ox,double oy,double x1,double y1); /* The side of (px,py) to the circumcircle of three points (ax,ay), (bx,by) and (cx,cy) return value: -1 outside 0 on the circle 1 inside */ //#EXACT this function requires exact computation int pointToCircle(double px,double py, double ax,double ay, double bx,double by, double cx,double cy); /* primitive test on whether q(xq,yq) falls in the angle from op1((xo,yo)->(x1,y1)) to op2((xo,yo)->(x2,y2)) return value: -2 collinear to op2 here COLLINEAR stands for ONLY half of the line -1 collinear to op1 0 outside 1 yes, inside */ //#EXACT this function requires exact computation int pointInAngle(double xo,double yo, double xq,double yq, double x1,double y1, double x2,double y2); // ************************************************************* // sort algorithm used to sort vertices by x value // ************************************************************* //***************** quick sort functions begin ********************** // for partition void swap(VPointer* array,int i,int j); // for quick sort int partition(VPointer* array,int p,int r); // quick sort // input :from is the index where sort begins // count is the index of where sort ends // usually quicksort(array,0,n-1) void quicksort(VPointer* array,int from,int to);
e7f300cafa6aee4961c802aa57b8976217a66f39
2b05184d5ca2f52ab72293768e2ef19a71fc2340
/main.cpp
be6db76f01b958696463eaf68ca1d24ec45ae735
[]
no_license
MvictorPmatos/Indice_remissivo_em_Cpp
3536acece62b9b27228f1ae639502ce3c5fcd918
b6642254b852b377619180c37109ce0ca67c0416
refs/heads/main
2023-06-24T05:19:13.992787
2021-07-25T01:31:09
2021-07-25T01:31:09
389,232,872
0
0
null
null
null
null
UTF-8
C++
false
false
4,153
cpp
main.cpp
#include <iostream> #include <fstream> #include <string> #include <cctype> #include <algorithm> #include <vector> #include <list> #include <stack> #include "cNode.h" #include "cRedBlackTree.h" #define LINHAS 15 #define PAGINAS 50 #define TEXTO 12000 using namespace std; std::string f(std::string w){ char v[] = {'.', ',', '"', '?', '!', ':', '"'}; for(int i=0; i<7; i++){ w.erase(std::remove(w.begin(), w.end(), v[i]), w.end()); } transform(w.begin(), w.end(), w.begin(), ::tolower); return w; } int main(int argv, char** argc) { std::string arquivo = "pequeno.txt"; std::string chave = "chave-pequeno0.txt"; std::ifstream ifs(arquivo); std::ifstream arq(chave); std::string p; int c; std::string palavraC; std::string w; int count = 0; std::string word; cRedBlackTree arv; if (!arq) { std::cout << "Não foi possível abrir o arquivo de chaves. Rodaremos o algoritmo padrão do programa! " <<std::endl; if (!ifs) { std::cout << "Não é possível abrir o arquivo do texto" <<std::endl; exit(EXIT_FAILURE); } while (ifs >> w) count++; ifs.close(); /*Se o arquivo é pequeno ou médio armazena apenas as linhas */ ifs.open(arquivo); if ( !ifs ) return 0; int linha = 1; int pagina =1; if(count < TEXTO){ count = 0; while ( ifs >> word ){ arv.insertNode(f(word),linha); count++; if(count == LINHAS){ linha++; count = 0; } } } /* Se o arquivo é grande armazena apenas páginas*/ else{ linha =1; count = 0; while(ifs >> word){ arv.insertNode(f(word), pagina); count++; if(count == LINHAS){ linha++; count = 0; if(linha == PAGINAS){ pagina++; linha = 0; } } } } /* Gera o arquivo de saída */ std::ofstream indice("indice.txt"); arv.serialise(indice); indice.close(); return 0; } else{ while (arq >> p) c++; arq.close(); arq.open(chave); if ( !arq ) return 0; while ( arq >> palavraC ){ arv.insertNode(palavraC); } if (!ifs) { std::cout << "Não é possível abrir o arquivo do texto" <<std::endl; exit(EXIT_FAILURE); } while (ifs >> w) count++; ifs.close(); /*Se o arquivo é pequeno ou médio armazena apenas as linhas */ ifs.open(arquivo); if ( !ifs ) return 0; int tam = count; int linha = 1; int pagina =1; if(count < TEXTO){ count = 0; while ( ifs >> word ){ if(arv.searchValue(f(word))){ //Método que guarda linha arv.insertLine(f(word), linha); } count++; if(count == LINHAS){ linha++; count = 0; } } } /* Se o arquivo é grande armazena apenas páginas*/ else{ linha =1; count = 0; while(ifs >> word){ if(arv.searchValue(f(word))){ arv.insertLine(f(word), pagina); } count++; if(count == LINHAS){ linha++; count = 0; if(linha == PAGINAS){ pagina++; linha = 0; } } } } /* Gera o arquivo de saída */ std::ofstream indice("indice.txt"); arv.serialise(indice); indice.close(); return 0; } return 0; }
8e50578ca451661be399a0b9073bb708443791e9
846d9e0b9cb847946ba600a91e62d364b53848f3
/2020-sp-a-hw7-tgfnzb-master/2020-sp-a-hw7-tgfnzb-master/MyHeap.h
3956a99f18ad5d60ecad26624e45bccb678df08f
[ "MIT" ]
permissive
thomasfan100/DataStructure
a50337ecbbce057bb0cb852cbde2e2cf061d4571
4a69da72b8ae12aaa18363061528094c114a324b
refs/heads/main
2023-07-11T03:29:36.693942
2021-08-21T19:03:21
2021-08-21T19:03:21
383,929,467
0
0
null
null
null
null
UTF-8
C++
false
false
1,651
h
MyHeap.h
// You don't need to have a MyHeap.hpp, but you could if you want // Declare, and/or implement your heap class here. // If you are having a hard time figuring out how to start, look at the past assignments. #ifndef MYHEAP_H #define MYHEAP_H #include <iostream> using namespace std; void get_identity(std::string &my_id); template <typename T> class MyHeap { private: T *heap; // Pointer to the heap array int maxsize; // Maximum size of the heap int num; // Number of elements now in the heap public: MyHeap(); MyHeap(const T array[],const int size); MyHeap(const MyHeap<T> &the_heap); ~MyHeap(); MyHeap<T> & operator =(MyHeap<T> &the_heap); //accesses the top element T top() const; //removes the top element void pop(); //inserts element and sorts the underlying container void push(const int elem); void reserve(); //checks whether the underlying container is empty bool empty() const; //returns the number of elements int size() const; //any internal functions you like (reserve, shrink_to_fit, etc.) //You WILL need to have internal functions to dynamically reserve more space for your array if it fills up, and if //it becomes less than 1/4 full, to shrink the internal array size to fit. void shrink_to_fit(); void siftdown(const int pos); int leftchild(const int pos) const; int rightchild(const int pos) const; int parent(const int pos) const; }; #include "MyHeap.hpp" #endif
dc65e9362a9d2c214cf29f17c9eeca551910d9b1
d675342d7a2ea9a72a6229eade62193ab9371bd0
/Cpp_01/ex06/HumanB.hpp
08c6ab4cf45c3b92a406ec351d077257e120788b
[]
no_license
RomanEmelin/Cpp
435c8cc95d888e663f3031109c53f1425ad27031
664129d5ae02059f1c0b2340f541499a40664311
refs/heads/master
2023-04-01T21:49:27.359758
2021-04-08T10:04:56
2021-04-08T10:04:56
351,886,623
0
0
null
null
null
null
UTF-8
C++
false
false
312
hpp
HumanB.hpp
#ifndef CPP_HUMANB_HPP #define CPP_HUMANB_HPP #include "Weapon.hpp" #include <iostream> #include <string> class HumanB { private: const Weapon *_weapon; const std::string _name; public: HumanB(const std::string name); ~HumanB(); void setWeapon(Weapon &weapon); void attack(); }; #endif //CPP_HUMANB_H
d5d13b7d8c71f7d33346b263727ca47234d6d4ea
af95d23650896ad616fe65d8dffe468949b716d2
/11marchc++/prog3.cpp
12687744d9595cc126f85b29b0dbbcfab1628b0a
[]
no_license
manvirajawat/C-Programs
99fbd2184a8b76c92dd95296ce2198a2ee8db37a
7e31ed8948b7dd518e13914e1cbf198881e8fc59
refs/heads/master
2023-01-23T19:38:27.955804
2020-12-03T11:41:49
2020-12-03T11:41:49
318,174,037
0
0
null
null
null
null
UTF-8
C++
false
false
431
cpp
prog3.cpp
#include<iostream> using namespace std; namespace mySpace1 { int a=10; void show() { cout<<"Show value of a in mySpace1 :"<<a<<endl; } } namespace mySpace2 { int a=20; void show() { cout<<"Show value of a in mySpace2 :"<<a<<endl; } } /*using namespace mySpace1; int main() { show(); }*/ /*using namespace mySpace2; int main() { show(); }*/ int main() { mySpace1::show(); mySpace2::show(); }
628e1fd522c2551ebc493d67dd05babc1d95ad13
66c148b4282ebc4b8fa85049eb062028170ebdb3
/GlobalProject/Week12AbstractVirtual/LocalHeaders/Polinom.h
910aa4d1cb19d49e009fda19746995c1129c7df4
[]
no_license
KonstantinovD/Basics-of-CPP-BSU-2017
5de3749e364d371097a60d57116dc71c25fd51ee
6c5b413bf5c01b7fe2a90f953b529245f3e966b1
refs/heads/master
2021-09-08T06:28:58.654521
2018-03-07T22:08:02
2018-03-07T22:08:02
106,162,710
0
0
null
null
null
null
UTF-8
C++
false
false
578
h
Polinom.h
#pragma once #include "Array.h" class Polinom: public Array{ public: const static int MAX_ARRAY_SIZE = 100; private: int degree; protected: void updateDegree();//Iterate array from the last element public: Polinom(int size, int initialValue = 0); Polinom(const Polinom&); Polinom& operator=(const Polinom&); Polinom& operator+=(const Polinom&); Polinom& operator-=(const Polinom&); bool operator==(Polinom&); double calculate(double x); public: int& operator[](int i); int getSize(){ return size; } int getDegree(); };
83aac2c08c8fd24eef1c8f22127a84bc714e1565
cff81ff659ad529706dc9ba1befbc68d8ae5ad26
/hr_waiter.cpp
6510a837ce86112a313b0801e60982b62cae49f2
[]
no_license
iishipatel/Competetive-Programming
9dafb3e49e60daee0f7dfca7f88ea23fd0777507
2ece5d282e753aee38d503bc5102baffa0141b2f
refs/heads/master
2020-08-05T23:03:48.027950
2019-10-08T12:02:27
2019-10-08T12:02:27
212,747,647
1
0
null
2019-10-04T06:12:08
2019-10-04T06:12:06
null
UTF-8
C++
false
false
1,028
cpp
hr_waiter.cpp
/* Author : Abhinav Modified : 17-12-2017 02:46:50 AM */ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector<ll> vi; const ll mod = 1e9+7; vi pr; void SieveOfEratosthenes(int n){ bool prime[n+1]; memset(prime, true, sizeof(prime)); for (int p=2; p*p<=n; p++){ if (prime[p] == true){ for (int i=p*2; i<=n; i += p) prime[i] = false; } } for (int p=2; p<=n; p++) if (prime[p]) pr.emplace_back(p); } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); SieveOfEratosthenes(1000000); ll n,q,i,top; cin >> n >> q; vi v(n); for(int i=0; i<n; i++) cin >> v[i]; i = 0; while(q-- > 0){ reverse(v.begin(), v.end()); top = v.size()-1; while(top >= 0){ if(v[top] % pr[i] == 0){ cout << v[top] << "\n"; v.erase(v.begin()+top); } top--; } i++; } if(v.size()!=0){ reverse(v.begin(), v.end()); for(int i=0; i<v.size(); i++) cout << v[i] << "\n"; } return 0; }
5b32720d8b2d3353ac82ab32270e665cd1f1b4b2
bdba151d20f8949bd7d027435274f872b35249bb
/codechef/dsa learning series/getting started/raju and his trip.cpp
f9a95d829d2a464efbfe90ad372b5fb2c1fe1f07
[ "MIT" ]
permissive
JayeshPadhiar/CodeChef
85f7b4e01d4b1ae485372a150115c6b4ce199464
ae9cf05173b88945b4a6cb1f761e42fcfc7245b7
refs/heads/main
2023-08-07T16:46:10.312382
2021-09-15T06:47:36
2021-09-15T06:47:36
368,400,816
2
0
null
null
null
null
UTF-8
C++
false
false
478
cpp
raju and his trip.cpp
/* * Raju is planning to visit his favourite restaurant. * He shall travel to it by bus. Only the buses whose numbers are divisible by 5 or by 6 shall take him to his destination. * You are given a bus number N. * Find if Raju can take the bus or not. * Print YES if he can take the bus, otherwise print NO. */ #include <iostream> using namespace std; int main() { int n; cin>>n; if((n%6==0) || (n%5==0)) { cout<<"YES"; } else { cout<<"NO"; } return 0; }
f411f69e1e15a5d532daca3e0417dd2f875576bd
a7dab63324ab28eb24937bdd429c1828cd835306
/src/python/lib/graph/agglo/agglo.cxx
d3997232f7da361f7d9ccca7c9f2695ae5429e2a
[ "MIT" ]
permissive
DerThorsten/nifty
e8005325467430bc8eb60517756c0eadf1669d4a
c4bd4cd90f20e68f0dbd62587aba28e4752a0ac1
refs/heads/master
2022-04-29T01:07:05.914460
2021-12-20T23:20:15
2021-12-20T23:20:15
50,250,104
42
20
MIT
2022-03-29T10:34:50
2016-01-23T17:43:51
C++
UTF-8
C++
false
false
1,028
cxx
agglo.cxx
#include <pybind11/pybind11.h> #include <iostream> #define FORCE_IMPORT_ARRAY #include "xtensor-python/pyarray.hpp" #include "xtensor-python/pyvectorize.hpp" namespace py = pybind11; PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); namespace nifty{ namespace graph{ namespace agglo{ void exportMergeRules(py::module &); void exportAgglomerativeClustering(py::module &); void exportGaspAgglomerativeClustering(py::module &); void exportDualAgglomerativeClustering(py::module &); void exportLiftedAgglomerativeClusteringPolicy(py::module &); } } } PYBIND11_MODULE(_agglo, module) { xt::import_numpy(); py::options options; options.disable_function_signatures(); module.doc() = "agglo submodule of nifty.graph"; using namespace nifty::graph::agglo; exportMergeRules(module); exportAgglomerativeClustering(module); exportGaspAgglomerativeClustering(module); exportDualAgglomerativeClustering(module); exportLiftedAgglomerativeClusteringPolicy(module); }
b4b51ecd1d80c27b583c9e8f505496738e8fc280
879681c994f1ca9c8d2c905a4e5064997ad25a27
/root-2.3.0/run/tutorials/multiphase/twoPhaseEulerFoam/RAS/bubbleColumn/3/U.water
0b56ee6cd364b33c18903702e4fd4b752c2b36a6
[]
no_license
MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu
3828272d989d45fb020e83f8426b849e75560c62
daeb870be81275e8a81f5cbac4ca1906a9bc69c0
refs/heads/master
2020-05-17T16:36:41.848261
2015-04-18T09:29:48
2015-04-18T09:29:48
34,159,882
1
0
null
null
null
null
UTF-8
C++
false
false
48,492
water
U.water
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "3"; object U.water; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 1875 ( (0.119457 -0.295044 0) (0.166208 -0.260693 0) (0.26683 -0.218538 0) (0.339392 -0.179599 0) (0.376368 -0.13842 0) (0.39979 -0.11373 0) (0.390486 -0.0902741 0) (0.353161 -0.0693063 0) (0.288611 -0.0558587 0) (0.214911 -0.0355139 0) (0.148498 -0.0217337 0) (0.0800569 0.00739997 0) (0.00299402 0.010248 0) (-0.0727217 0.00632486 0) (-0.141829 -0.0205326 0) (-0.207224 -0.0351747 0) (-0.281079 -0.0526951 0) (-0.347624 -0.0677046 0) (-0.387197 -0.086886 0) (-0.398125 -0.111674 0) (-0.376816 -0.136502 0) (-0.34078 -0.17742 0) (-0.268278 -0.218833 0) (-0.167178 -0.261468 0) (-0.120261 -0.296034 0) (0.0420711 -0.401063 0) (0.089192 -0.267909 0) (0.124367 -0.171022 0) (0.138927 -0.085911 0) (0.186411 -0.000301218 0) (0.128679 0.0660474 0) (0.115793 0.174697 0) (0.115063 0.23859 0) (0.0588759 0.252018 0) (0.047953 0.225047 0) (0.032143 0.211683 0) (0.0189038 0.214914 0) (0.00126914 0.22243 0) (-0.0155654 0.214805 0) (-0.0303077 0.211775 0) (-0.0448586 0.22265 0) (-0.0562237 0.250924 0) (-0.109272 0.244403 0) (-0.115169 0.179038 0) (-0.122282 0.0727709 0) (-0.183465 0.0034789 0) (-0.140859 -0.0812715 0) (-0.123451 -0.171219 0) (-0.0903178 -0.273034 0) (-0.0450228 -0.405414 0) (0.0170645 -0.456342 0) (-0.0407265 -0.261129 0) (-0.0979243 -0.187554 0) (-0.135339 -0.0835657 0) (-0.148304 0.00565853 0) (-0.140282 0.101445 0) (-0.12819 0.159787 0) (-0.0951349 0.195826 0) (-0.0478555 0.181066 0) (-0.0333394 0.150699 0) (-0.0122945 0.16165 0) (-0.00781041 0.183007 0) (0.000755116 0.189896 0) (0.0100088 0.183144 0) (0.0131838 0.162702 0) (0.035173 0.150288 0) (0.0495467 0.177827 0) (0.0979771 0.19419 0) (0.131457 0.163191 0) (0.143884 0.109731 0) (0.151867 0.0128572 0) (0.140334 -0.0726276 0) (0.102087 -0.179888 0) (0.0466975 -0.259026 0) (-0.0207052 -0.460318 0) (-0.016133 -0.380388 0) (-0.0686619 -0.103083 0) (-0.151288 -0.0668574 0) (-0.178367 -0.0476197 0) (-0.19419 -0.00405677 0) (-0.177412 0.0248241 0) (-0.160625 0.048476 0) (-0.123464 0.0522766 0) (-0.0947598 0.0657853 0) (-0.0699441 0.100971 0) (-0.0500741 0.122033 0) (-0.0240552 0.131089 0) (-0.000414297 0.138438 0) (0.0242945 0.130816 0) (0.052506 0.124204 0) (0.0715676 0.0972998 0) (0.0967135 0.059473 0) (0.123837 0.0560741 0) (0.159356 0.0524228 0) (0.179068 0.0296748 0) (0.197808 0.001279 0) (0.182879 -0.0407816 0) (0.154122 -0.0581689 0) (0.0713037 -0.0951504 0) (0.0111487 -0.38429 0) (-0.0137693 -0.347326 0) (-0.0395634 -0.0361766 0) (-0.0979496 0.0133573 0) (-0.124156 0.0106395 0) (-0.139947 0.0177078 0) (-0.146139 0.0283419 0) (-0.140998 0.039158 0) (-0.130755 0.0404419 0) (-0.119863 0.0474422 0) (-0.0921135 0.0626228 0) (-0.0683122 0.0660229 0) (-0.0298606 0.0720052 0) (0.000253202 0.0933705 0) (0.0321623 0.06551 0) (0.0696227 0.0626348 0) (0.0984688 0.0643963 0) (0.122707 0.049266 0) (0.133721 0.0443314 0) (0.145841 0.0365704 0) (0.154303 0.0236524 0) (0.150686 0.0189489 0) (0.13983 0.0211939 0) (0.111789 0.0247329 0) (0.0458189 -0.0239591 0) (0.00765879 -0.352513 0) (-0.029305 -0.293277 0) (-0.0179486 0.0773796 0) (-0.070255 0.0936799 0) (-0.0933414 0.0568405 0) (-0.119533 0.0448903 0) (-0.135807 0.0434587 0) (-0.140422 0.0224561 0) (-0.136804 0.0118714 0) (-0.116781 -0.0100961 0) (-0.102894 -0.0135896 0) (-0.0713862 -0.0199256 0) (-0.042815 -0.0336245 0) (0.00243438 -0.00321216 0) (0.0423879 -0.0393296 0) (0.0741956 -0.0270075 0) (0.101909 -0.0227819 0) (0.121004 -0.0142574 0) (0.144916 0.00554455 0) (0.143892 0.0151715 0) (0.140829 0.0279408 0) (0.122455 0.0350652 0) (0.0989214 0.0615094 0) (0.0690583 0.128194 0) (0.0140978 0.111798 0) (0.0256396 -0.30667 0) (-0.0380394 -0.279866 0) (0.0343079 0.0738572 0) (0.0252784 0.177622 0) (0.0148684 0.132661 0) (-0.049306 0.123047 0) (-0.065466 0.0703112 0) (-0.0847566 0.0421634 0) (-0.0867007 -0.0114072 0) (-0.0915955 -0.0373024 0) (-0.0762061 -0.0536307 0) (-0.0661642 -0.0755914 0) (-0.0416204 -0.111724 0) (-0.00744463 -0.119946 0) (0.0241146 -0.109227 0) (0.0481953 -0.0762021 0) (0.0580696 -0.0602324 0) (0.0699731 -0.0431752 0) (0.0671733 -0.000530865 0) (0.0676224 0.0465127 0) (0.0488461 0.0661989 0) (0.0378066 0.12092 0) (-0.0160971 0.164058 0) (-0.021763 0.187697 0) (-0.0299157 0.0971936 0) (0.0383997 -0.295404 0) (-0.0111781 -0.256062 0) (0.0238418 -0.124899 0) (0.118758 0.157557 0) (0.117415 0.243974 0) (0.0794782 0.221172 0) (0.0207228 0.145998 0) (-0.01119 0.0759523 0) (-0.0214874 0.0372581 0) (-0.0402543 -0.015891 0) (-0.0468473 -0.0656989 0) (-0.0437796 -0.0961384 0) (-0.030064 -0.151012 0) (-0.0135275 -0.166166 0) (0.00690807 -0.153523 0) (0.0230052 -0.101035 0) (0.0306888 -0.0670748 0) (0.0200422 -0.0236635 0) (0.00446629 0.0293593 0) (-0.00163224 0.0580805 0) (-0.0285251 0.114646 0) (-0.0710404 0.190205 0) (-0.106637 0.227512 0) (-0.108017 0.18215 0) (-0.0275917 -0.0630683 0) (0.0225178 -0.27061 0) (0.0400425 -0.316069 0) (0.0625199 -0.255441 0) (0.100549 -0.0473486 0) (0.16425 0.233638 0) (0.131445 0.319468 0) (0.0847533 0.28017 0) (0.0190385 0.139076 0) (-0.0100582 0.0626402 0) (-0.0176716 0.00744021 0) (-0.0373862 -0.0447847 0) (-0.0392225 -0.108077 0) (-0.0252625 -0.177823 0) (-0.00567686 -0.210254 0) (0.0122727 -0.185086 0) (0.0285241 -0.128506 0) (0.0297176 -0.047503 0) (0.0123694 0.00493394 0) (-0.00150827 0.0551689 0) (-0.0205781 0.109738 0) (-0.0796913 0.230337 0) (-0.127621 0.294972 0) (-0.162697 0.252411 0) (-0.110684 0.00823979 0) (-0.0494613 -0.243194 0) (-0.031189 -0.296656 0) (0.0266528 -0.49747 0) (0.076178 -0.323699 0) (0.0588375 -0.155726 0) (0.122608 0.204481 0) (0.0999512 0.37861 0) (0.076514 0.379508 0) (0.0246873 0.266001 0) (-0.0143866 0.115634 0) (-0.0199781 0.0431167 0) (-0.0441921 -0.020004 0) (-0.0327025 -0.124365 0) (-0.0151213 -0.224665 0) (0.00980907 -0.260048 0) (0.0278364 -0.233777 0) (0.0422366 -0.151601 0) (0.0455121 -0.0330976 0) (0.0266084 0.0415883 0) (0.00463096 0.104733 0) (-0.0177262 0.215418 0) (-0.078824 0.342301 0) (-0.108094 0.355532 0) (-0.128059 0.22389 0) (-0.0669234 -0.144227 0) (-0.071875 -0.312025 0) (-0.0327613 -0.469726 0) (0.00100337 -0.55829 0) (0.0289625 -0.338621 0) (-0.0157091 -0.123303 0) (0.0304614 0.198725 0) (0.0173473 0.417319 0) (0.013975 0.43806 0) (-0.0103868 0.33286 0) (-0.0394745 0.143879 0) (-0.0332044 0.0752989 0) (-0.0414185 -0.0188679 0) (-0.0215717 -0.176361 0) (-0.00450509 -0.277904 0) (0.0127196 -0.314823 0) (0.0265061 -0.27645 0) (0.0394811 -0.171775 0) (0.0474883 -0.0265593 0) (0.0335227 0.0902841 0) (0.0367658 0.136587 0) (0.01815 0.269555 0) (-0.0226217 0.41294 0) (-0.0311653 0.3982 0) (-0.0491798 0.206235 0) (0.00673144 -0.12392 0) (-0.0417015 -0.332009 0) (-0.00245128 -0.546636 0) (-0.0109939 -0.562471 0) (-0.0273732 -0.277926 0) (-0.0550873 -0.0812256 0) (-0.033621 0.257214 0) (-0.0450097 0.417274 0) (-0.0325435 0.439037 0) (-0.032508 0.347599 0) (-0.0438761 0.148367 0) (-0.0283264 0.0494778 0) (-0.026068 -0.0403036 0) (-0.00599278 -0.210776 0) (-0.00469845 -0.302163 0) (0.00671735 -0.338136 0) (0.00955416 -0.295507 0) (0.0115777 -0.183034 0) (0.0219482 -0.0159769 0) (0.020956 0.0651534 0) (0.0462857 0.136673 0) (0.0299768 0.310609 0) (0.021293 0.439028 0) (0.0302168 0.4199 0) (0.0121769 0.256879 0) (0.0469129 -0.0890341 0) (0.0172542 -0.282196 0) (0.00899002 -0.560786 0) (-0.0281992 -0.488848 0) (-0.0315382 -0.245206 0) (-0.0624707 -0.0655318 0) (-0.0443271 0.25372 0) (-0.0435528 0.397919 0) (-0.0243313 0.424079 0) (-0.0163553 0.341831 0) (-0.0204904 0.148765 0) (0.0003166 0.0274312 0) (-0.00286869 -0.0405786 0) (0.0165741 -0.217618 0) (-0.00148716 -0.306479 0) (0.000138993 -0.342802 0) (-0.0169993 -0.284852 0) (-0.0195609 -0.173374 0) (-0.00759087 -0.0218201 0) (8.36299e-05 0.0308122 0) (0.0205933 0.136709 0) (0.0141371 0.311635 0) (0.0171732 0.427673 0) (0.0326605 0.406146 0) (0.0310671 0.244497 0) (0.0568965 -0.0848648 0) (0.0270595 -0.256844 0) (0.0294381 -0.499971 0) (-0.0140856 -0.455585 0) (-0.0198369 -0.216882 0) (-0.0494335 -0.0492926 0) (-0.0395344 0.229191 0) (-0.0306068 0.34987 0) (-0.00873434 0.383241 0) (0.00824899 0.322644 0) (0.00755822 0.144283 0) (0.0204024 0.0022318 0) (0.0186631 -0.0577684 0) (0.0303972 -0.204253 0) (0.0110938 -0.266327 0) (-0.00507726 -0.302921 0) (-0.019048 -0.260054 0) (-0.0329517 -0.183508 0) (-0.0187497 -0.0545528 0) (-0.0185209 -0.00230371 0) (-0.00573049 0.128667 0) (-0.0057025 0.303904 0) (0.00531914 0.398495 0) (0.0303926 0.368254 0) (0.0391305 0.224808 0) (0.0513478 -0.0675508 0) (0.0198298 -0.234992 0) (0.0154275 -0.458656 0) (-0.0269323 -0.407917 0) (-0.00348683 -0.189561 0) (-0.041142 -0.0132962 0) (-0.0415605 0.214102 0) (-0.0226463 0.31473 0) (-0.00814139 0.341716 0) (0.0177826 0.291461 0) (0.0180327 0.12947 0) (0.0250501 -0.00169312 0) (0.0193255 -0.0789145 0) (0.0290124 -0.19099 0) (0.00307106 -0.245629 0) (0.000465479 -0.285466 0) (-0.017865 -0.226427 0) (-0.0358825 -0.175413 0) (-0.020036 -0.0628402 0) (-0.0284521 -0.00282313 0) (-0.0171589 0.115583 0) (-0.0178711 0.278351 0) (0.0070585 0.34918 0) (0.0294064 0.321443 0) (0.04916 0.210697 0) (0.0493578 -0.0219185 0) (0.00686661 -0.199613 0) (0.02505 -0.416112 0) (-0.0198732 -0.367257 0) (0.00370576 -0.18594 0) (-0.0227415 0.0487169 0) (-0.0290657 0.198745 0) (-0.0207182 0.271539 0) (-0.00389403 0.289881 0) (0.00959124 0.264099 0) (0.0378348 0.106834 0) (0.0326716 0.0220399 0) (0.0459545 -0.0947448 0) (0.0203728 -0.157987 0) (0.0131622 -0.224124 0) (-0.0046367 -0.25077 0) (-0.0120576 -0.203628 0) (-0.0259583 -0.164989 0) (-0.0415222 -0.0944124 0) (-0.0299526 0.0110693 0) (-0.0340222 0.083375 0) (-0.00782639 0.250623 0) (0.00745643 0.285891 0) (0.0276494 0.267535 0) (0.0373217 0.194836 0) (0.0303188 0.0438435 0) (-3.87761e-05 -0.19057 0) (0.0198796 -0.369909 0) (0.00902022 -0.359298 0) (0.014318 -0.224325 0) (0.0122865 0.0739089 0) (-0.0157946 0.20564 0) (-0.0141074 0.260434 0) (-0.0145939 0.26979 0) (0.00645884 0.216532 0) (0.0448484 0.062465 0) (0.0477189 0.0168429 0) (0.05999 -0.0520598 0) (0.0366475 -0.10603 0) (0.0198273 -0.17763 0) (0.00420426 -0.223675 0) (-0.0100351 -0.167638 0) (-0.0277008 -0.102782 0) (-0.0537009 -0.056007 0) (-0.0418867 0.0113937 0) (-0.041917 0.0493271 0) (-0.00738874 0.199378 0) (0.0172444 0.262249 0) (0.0164613 0.253987 0) (0.0197063 0.200234 0) (-0.00984922 0.0748273 0) (-0.0139594 -0.222833 0) (-0.00778125 -0.360225 0) (0.0399546 -0.417304 0) (0.0132115 -0.240101 0) (0.0246516 0.112196 0) (-0.0195018 0.238943 0) (-0.0240602 0.271893 0) (-0.0268003 0.244451 0) (0.0119208 0.126526 0) (0.0157762 0.0184988 0) (0.021775 -0.0136212 0) (0.00994069 -0.0561845 0) (0.015465 -0.0841244 0) (0.00737221 -0.150078 0) (0.00115458 -0.193724 0) (-0.00289517 -0.135439 0) (-0.0136818 -0.0796992 0) (-0.00944208 -0.0542519 0) (-0.0206614 -0.015433 0) (-0.0159611 0.0124686 0) (-0.0140271 0.114108 0) (0.0242589 0.233329 0) (0.024093 0.265551 0) (0.0186286 0.235826 0) (-0.0249078 0.11178 0) (-0.0129134 -0.239537 0) (-0.039944 -0.416724 0) (0.0247126 -0.472941 0) (0.00229763 -0.207236 0) (-0.00774267 0.150414 0) (-0.0393127 0.295101 0) (-0.0453931 0.287809 0) (-0.0513455 0.193968 0) (-0.0273789 0.104012 0) (-0.0583717 0.0619616 0) (-0.0633234 0.0160742 0) (-0.061132 -0.0408549 0) (-0.0367551 -0.0973991 0) (-0.0154961 -0.146455 0) (-0.00263662 -0.187953 0) (0.00988111 -0.129298 0) (0.0330598 -0.0852539 0) (0.0576271 -0.038851 0) (0.0622942 0.0131537 0) (0.059619 0.0572804 0) (0.0267726 0.0956605 0) (0.0505544 0.180196 0) (0.0440638 0.280104 0) (0.0394661 0.290699 0) (0.00775352 0.148755 0) (-0.00217875 -0.205782 0) (-0.024306 -0.471972 0) (0.010335 -0.484569 0) (-0.012176 -0.105084 0) (-0.034672 0.231357 0) (-0.0587739 0.326104 0) (-0.0629889 0.312291 0) (-0.068418 0.197259 0) (-0.0899248 0.144429 0) (-0.115216 0.0771678 0) (-0.118094 -0.0152762 0) (-0.104193 -0.117968 0) (-0.0841549 -0.197663 0) (-0.0375953 -0.225209 0) (-0.00698663 -0.255485 0) (0.0301163 -0.215805 0) (0.0780508 -0.194415 0) (0.10283 -0.123871 0) (0.119879 -0.0238146 0) (0.118028 0.067222 0) (0.0948278 0.137408 0) (0.0695347 0.187122 0) (0.0640095 0.301591 0) (0.0596206 0.321219 0) (0.0356752 0.230071 0) (0.0118479 -0.103346 0) (-0.00975893 -0.483117 0) (0.00229013 -0.476315 0) (-0.0139279 -0.0950686 0) (0.0085444 0.24903 0) (-0.0299368 0.365897 0) (-0.0288074 0.312784 0) (-0.0417695 0.21601 0) (-0.0690385 0.182266 0) (-0.0763934 0.0945162 0) (-0.104999 -0.0331218 0) (-0.0865044 -0.158147 0) (-0.0839619 -0.279981 0) (-0.0353105 -0.346096 0) (-0.00310631 -0.373029 0) (0.0295124 -0.344869 0) (0.08115 -0.287658 0) (0.0849684 -0.172858 0) (0.11132 -0.0483306 0) (0.0793106 0.0820869 0) (0.0736592 0.176253 0) (0.044066 0.208814 0) (0.0294185 0.303455 0) (0.0302653 0.361904 0) (-0.00893871 0.249484 0) (0.0130495 -0.0942729 0) (-0.00224564 -0.474996 0) (0.000485785 -0.476598 0) (0.00154875 -0.123844 0) (0.0327707 0.216182 0) (0.0637752 0.403946 0) (0.0451976 0.376155 0) (0.0452657 0.266823 0) (0.00755506 0.227306 0) (0.0275144 0.145621 0) (0.0105085 0.0581663 0) (0.016305 -0.122149 0) (-0.00791134 -0.29827 0) (-0.0160229 -0.382534 0) (-0.000184555 -0.415761 0) (0.0164726 -0.383962 0) (0.0145604 -0.313842 0) (-0.0100446 -0.146033 0) (-0.00837512 0.0476553 0) (-0.0263466 0.138259 0) (-0.00604917 0.223958 0) (-0.0448889 0.263407 0) (-0.046166 0.371092 0) (-0.0654806 0.400674 0) (-0.0338264 0.217007 0) (-0.00276783 -0.125259 0) (-0.000203994 -0.476467 0) (-0.0046173 -0.492746 0) (0.0103148 -0.143566 0) (0.0228724 0.0389094 0) (0.0927762 0.356176 0) (0.0857471 0.362667 0) (0.0958336 0.314782 0) (0.0755247 0.255638 0) (0.0819402 0.144896 0) (0.0930335 0.044956 0) (0.0825346 -0.0434972 0) (0.0548104 -0.214219 0) (0.0307167 -0.359936 0) (0.00231896 -0.417549 0) (-0.0183953 -0.370928 0) (-0.049968 -0.239562 0) (-0.073889 -0.0530834 0) (-0.0921583 0.0413273 0) (-0.0797123 0.138461 0) (-0.0749865 0.252333 0) (-0.0945685 0.311754 0) (-0.0851025 0.358443 0) (-0.092284 0.354424 0) (-0.0231896 0.0387848 0) (-0.0103484 -0.145422 0) (0.00451405 -0.492643 0) (-0.00899693 -0.498516 0) (0.0142787 -0.149613 0) (-0.0222645 -0.0304419 0) (0.0554115 0.326916 0) (0.06421 0.34313 0) (0.0821754 0.309434 0) (0.0869262 0.245391 0) (0.091074 0.138695 0) (0.0909912 0.0462417 0) (0.0779583 -0.0264799 0) (0.0607637 -0.178294 0) (0.0306522 -0.291085 0) (0.00649178 -0.338989 0) (-0.0228003 -0.294217 0) (-0.050658 -0.194921 0) (-0.0731899 -0.0337858 0) (-0.0861586 0.0461724 0) (-0.0892285 0.135417 0) (-0.0851471 0.243375 0) (-0.0810637 0.306414 0) (-0.0626684 0.339539 0) (-0.054271 0.32573 0) (0.0230564 -0.0279349 0) (-0.0141784 -0.151595 0) (0.00887361 -0.498434 0) (-0.00738988 -0.476518 0) (-0.00843417 -0.123553 0) (-0.0502106 -0.018323 0) (-0.00524432 0.212671 0) (0.0320003 0.274377 0) (0.0650704 0.268938 0) (0.0783111 0.231145 0) (0.0853265 0.14501 0) (0.0783558 0.0727343 0) (0.062533 0.0145561 0) (0.0471276 -0.125731 0) (0.0269757 -0.248885 0) (0.00522288 -0.306527 0) (-0.0152246 -0.256913 0) (-0.0383552 -0.143233 0) (-0.0580036 0.00807972 0) (-0.0749744 0.0780652 0) (-0.0833809 0.143919 0) (-0.0766409 0.229233 0) (-0.0626017 0.265491 0) (-0.0307703 0.270316 0) (0.00663683 0.211703 0) (0.0501609 -0.0140028 0) (0.00937943 -0.123192 0) (0.0070881 -0.476787 0) (-0.00804718 -0.465083 0) (-0.00665476 -0.0887671 0) (-0.0464108 0.00966988 0) (-0.0423975 0.122984 0) (-0.0080876 0.185236 0) (0.0161614 0.199428 0) (0.0393769 0.191017 0) (0.050167 0.14063 0) (0.0361451 0.101294 0) (0.0345891 0.0286205 0) (0.0319075 -0.106453 0) (0.0163383 -0.207175 0) (0.00074756 -0.251571 0) (-0.0182856 -0.201099 0) (-0.0339589 -0.110202 0) (-0.0387433 0.0369001 0) (-0.0419149 0.103828 0) (-0.0521858 0.140418 0) (-0.0415639 0.189006 0) (-0.0180464 0.198527 0) (0.00662679 0.183105 0) (0.0411675 0.123703 0) (0.0454495 0.0125701 0) (0.005574 -0.0898358 0) (0.00777158 -0.466125 0) (-0.0071113 -0.449397 0) (-0.000507422 -0.0561237 0) (-0.0320863 0.0657478 0) (-0.0475155 0.112364 0) (-0.0346303 0.137427 0) (-0.0198395 0.15528 0) (-0.0038383 0.153129 0) (0.00565209 0.137062 0) (0.00737931 0.103464 0) (0.0193223 0.0150436 0) (0.0174512 -0.0941316 0) (0.00682265 -0.178085 0) (-0.00217727 -0.230386 0) (-0.00953817 -0.176092 0) (-0.0209576 -0.0997743 0) (-0.0211727 0.0217522 0) (-0.00899373 0.105716 0) (-0.00525912 0.135735 0) (0.00175987 0.150864 0) (0.0197704 0.150996 0) (0.0342971 0.131008 0) (0.0465859 0.111172 0) (0.0301653 0.0690484 0) (0.000771473 -0.0586532 0) (0.00589004 -0.451411 0) (-0.00344511 -0.443296 0) (0.00060873 -0.0479158 0) (-0.0171146 0.117718 0) (-0.0435763 0.121434 0) (-0.0372208 0.123072 0) (-0.0357753 0.131209 0) (-0.0169663 0.130082 0) (-0.00962973 0.118503 0) (0.00598919 0.0776866 0) (0.019308 0.00388681 0) (0.0167723 -0.0743551 0) (0.00747343 -0.162904 0) (0.00193291 -0.211357 0) (-0.00317161 -0.162752 0) (-0.0125514 -0.0824938 0) (-0.014979 0.000407216 0) (-0.00118169 0.0736806 0) (0.0141454 0.115249 0) (0.0223527 0.127828 0) (0.0390364 0.124483 0) (0.0388851 0.122375 0) (0.044413 0.123444 0) (0.0168394 0.120419 0) (0.00208685 -0.0528857 0) (0.00184334 -0.445671 0) (-0.002533 -0.433864 0) (-0.00257165 -0.0422906 0) (-0.00910232 0.172042 0) (-0.0379032 0.144224 0) (-0.0342952 0.1232 0) (-0.0374445 0.105041 0) (-0.0207183 0.0969821 0) (-0.0083365 0.085974 0) (0.00785387 0.0419021 0) (0.018714 -0.00730743 0) (0.0160773 -0.0626754 0) (0.00744355 -0.14418 0) (0.0013714 -0.202877 0) (-0.00338588 -0.141383 0) (-0.013757 -0.0702225 0) (-0.0162093 -0.00269302 0) (-0.0073582 0.0432879 0) (0.00938504 0.084448 0) (0.0208902 0.0975297 0) (0.0359556 0.108912 0) (0.0332774 0.123463 0) (0.0372983 0.148738 0) (0.0109415 0.169977 0) (0.00369447 -0.036657 0) (0.00385856 -0.433102 0) (-0.00295436 -0.425954 0) (-0.00223413 -0.0399051 0) (-0.000321701 0.20404 0) (-0.0208307 0.171747 0) (-0.0201402 0.128771 0) (-0.022523 0.0965936 0) (-0.0144441 0.0657702 0) (-0.00299563 0.0528755 0) (0.00841203 0.0175867 0) (0.0150384 -0.0158407 0) (0.0125078 -0.0479055 0) (0.00489429 -0.135435 0) (-0.000743828 -0.185827 0) (-0.00551432 -0.131134 0) (-0.0157453 -0.0508804 0) (-0.0185844 -0.0109816 0) (-0.0114625 0.0176075 0) (5.67136e-05 0.0536457 0) (0.00940732 0.0689552 0) (0.0194179 0.0960762 0) (0.0156182 0.124807 0) (0.0179899 0.172354 0) (-0.00128594 0.198615 0) (0.001414 -0.0388743 0) (0.00350435 -0.425757 0) (-0.00135286 -0.422209 0) (-0.00256004 -0.0571442 0) (0.00762457 0.214151 0) (-0.00403613 0.188984 0) (0.00166409 0.130865 0) (-0.00103161 0.0944595 0) (0.00516861 0.0538321 0) (0.00788517 0.0341942 0) (0.0146165 0.00687291 0) (0.0138933 -0.0178523 0) (0.0123744 -0.0382596 0) (0.00556621 -0.116287 0) (-0.00100232 -0.179125 0) (-0.00649077 -0.111262 0) (-0.0141999 -0.0379686 0) (-0.0163719 -0.0167407 0) (-0.0148607 0.0077139 0) (-0.010476 0.0356283 0) (-0.00785443 0.0556319 0) (-0.00318343 0.0947731 0) (-0.00640577 0.130963 0) (0.000435211 0.186376 0) (-0.00876191 0.205337 0) (0.00167278 -0.061015 0) (0.00150054 -0.42226 0) (-0.00104054 -0.416096 0) (-0.00740032 -0.068401 0) (0.00588579 0.21024 0) (0.00902199 0.185976 0) (0.0217505 0.129134 0) (0.0202189 0.0908882 0) (0.0238842 0.0504631 0) (0.022674 0.0298284 0) (0.0221117 0.00999968 0) (0.01814 -0.0129763 0) (0.0144997 -0.0260812 0) (0.00829509 -0.105962 0) (0.000640922 -0.15902 0) (-0.00585466 -0.104147 0) (-0.0132165 -0.0265428 0) (-0.0163628 -0.0126391 0) (-0.022953 0.0100956 0) (-0.0234809 0.0358566 0) (-0.0263984 0.0575753 0) (-0.0233026 0.0938583 0) (-0.025865 0.123929 0) (-0.00986997 0.179366 0) (-0.00593019 0.201143 0) (0.00670469 -0.0684032 0) (0.00176455 -0.41459 0) (-0.00443407 -0.399941 0) (-0.0107144 -0.0597697 0) (0.00259988 0.183325 0) (0.0193927 0.15595 0) (0.0365494 0.114422 0) (0.0332322 0.0899029 0) (0.035399 0.0522853 0) (0.0308819 0.0358209 0) (0.0278148 0.0190979 0) (0.0196538 -0.00497507 0) (0.016291 -0.0155044 0) (0.00820692 -0.0859684 0) (-0.000260369 -0.150476 0) (-0.00924121 -0.0808751 0) (-0.0188772 -0.0131355 0) (-0.0220236 0.00119683 0) (-0.0312809 0.0254394 0) (-0.0333696 0.0413053 0) (-0.0370074 0.0586928 0) (-0.0341949 0.0929123 0) (-0.0370358 0.109549 0) (-0.0208641 0.143623 0) (-0.00334499 0.172456 0) (0.0100451 -0.0664501 0) (0.00382681 -0.402411 0) (-0.00467666 -0.388928 0) (-0.00711617 -0.0716643 0) (0.00592524 0.133248 0) (0.0271546 0.11364 0) (0.0361281 0.102685 0) (0.0348425 0.0902541 0) (0.0393928 0.0579528 0) (0.0338103 0.0446541 0) (0.0304168 0.0343677 0) (0.0213891 0.0115817 0) (0.0179454 -0.00198832 0) (0.0081387 -0.0677961 0) (-0.00118294 -0.124094 0) (-0.0114275 -0.0596515 0) (-0.0210586 0.000885914 0) (-0.0239357 0.013908 0) (-0.0305158 0.0360743 0) (-0.0333773 0.0470531 0) (-0.0385661 0.0626154 0) (-0.0324527 0.091126 0) (-0.0318448 0.0976188 0) (-0.0245478 0.105199 0) (-0.00456471 0.124395 0) (0.00833504 -0.075065 0) (0.00409235 -0.388943 0) (-0.00306028 -0.377347 0) (-0.00461107 -0.0830291 0) (0.00564807 0.0963288 0) (0.0268481 0.0911672 0) (0.0249973 0.0974256 0) (0.027098 0.0813226 0) (0.0365363 0.0574604 0) (0.030109 0.054517 0) (0.027692 0.0463725 0) (0.0214691 0.0244135 0) (0.0204786 0.0112656 0) (0.01019 -0.0409478 0) (0.000484319 -0.112946 0) (-0.0085264 -0.0348567 0) (-0.0191722 0.011922 0) (-0.0176224 0.0237168 0) (-0.0253491 0.0446654 0) (-0.0288142 0.0580217 0) (-0.0337813 0.0599622 0) (-0.0217652 0.0760676 0) (-0.0217778 0.0937662 0) (-0.0234642 0.0849867 0) (-0.00361307 0.0901684 0) (0.00599433 -0.0809139 0) (0.00381121 -0.377435 0) (-0.00353395 -0.368765 0) (-0.0053388 -0.0877422 0) (0.00344584 0.0605605 0) (0.0195443 0.0730457 0) (0.0124894 0.105373 0) (0.0117028 0.0622555 0) (0.029312 0.0569599 0) (0.0220686 0.0643432 0) (0.0207944 0.0497195 0) (0.0159748 0.0313594 0) (0.0176206 0.0178054 0) (0.00911226 -0.0188327 0) (3.04459e-06 -0.0898594 0) (-0.00843704 -0.0123437 0) (-0.0171542 0.0155885 0) (-0.016163 0.031072 0) (-0.0222431 0.0580042 0) (-0.020947 0.0657017 0) (-0.0252634 0.0524755 0) (-0.0105535 0.0622046 0) (-0.012269 0.104106 0) (-0.0211236 0.0689391 0) (-0.000676141 0.0529561 0) (0.00445675 -0.084642 0) (0.00396084 -0.367525 0) (-0.0041939 -0.357845 0) (-0.00491751 -0.0907307 0) (-0.000851869 0.0360632 0) (0.0138646 0.0752044 0) (0.000249 0.123533 0) (0.00621421 0.0306937 0) (0.0194211 0.0470895 0) (0.012413 0.0741415 0) (0.0165474 0.0562923 0) (0.0130396 0.0377831 0) (0.0152488 0.0192027 0) (0.00797195 0.0032828 0) (-0.000342866 -0.0813742 0) (-0.00846134 0.00929215 0) (-0.0146364 0.0208267 0) (-0.0152504 0.0426765 0) (-0.0176001 0.053368 0) (-0.00965561 0.0653783 0) (-0.0191286 0.0475813 0) (-0.00429567 0.0363248 0) (-0.00136472 0.124944 0) (-0.0121729 0.061658 0) (0.00172635 0.0299824 0) (0.00375577 -0.0858249 0) (0.00399175 -0.357971 0) (-0.00412758 -0.347747 0) (-0.00507705 -0.0911898 0) (-0.00351337 0.0203467 0) (0.00840945 0.0699719 0) (-0.000338116 0.131239 0) (0.00599315 0.0126822 0) (0.00846138 0.0519795 0) (0.00367307 0.0718986 0) (0.0120952 0.0475123 0) (0.0114495 0.040477 0) (0.0107706 0.0214589 0) (0.00792308 0.0217363 0) (-0.000606416 -0.0613584 0) (-0.00732713 0.0256263 0) (-0.00947807 0.0216614 0) (-0.00895464 0.04347 0) (-0.00922185 0.0424303 0) (-0.00464194 0.0699741 0) (-0.00953887 0.0499003 0) (-0.0046192 0.0140214 0) (0.000736087 0.131351 0) (-0.00478797 0.0578838 0) (0.000434021 0.0224739 0) (0.0052597 -0.0907621 0) (0.00385354 -0.347549 0) (-0.00432056 -0.336477 0) (-0.00499104 -0.0914934 0) (-0.00431247 0.00859715 0) (0.00291409 0.0658778 0) (-0.0014123 0.133673 0) (0.00492949 0.0059002 0) (0.00370673 0.0587252 0) (0.00246934 0.0653087 0) (0.00940882 0.0380037 0) (0.00648952 0.0435642 0) (0.00448068 0.0212867 0) (0.00583916 0.0328268 0) (-0.00112438 -0.0551026 0) (-0.0068459 0.0337834 0) (-0.00554115 0.0198559 0) (-0.00667402 0.0441172 0) (-0.0102295 0.0453107 0) (-0.00295236 0.0652547 0) (-0.00192134 0.0542256 0) (-0.00639954 0.00904523 0) (0.00192605 0.131069 0) (-0.00289804 0.0611643 0) (0.00349356 0.0105725 0) (0.00569631 -0.0923146 0) (0.00433509 -0.336739 0) (-0.00457279 -0.325711 0) (-0.00560966 -0.0911676 0) (-0.0061597 0.00679757 0) (-0.00156093 0.0618106 0) (-0.00194085 0.132683 0) (0.00468767 -0.00488698 0) (0.000931849 0.0648815 0) (0.00267873 0.0546524 0) (0.00917656 0.0434902 0) (0.00517166 0.0514103 0) (0.00355725 0.0213238 0) (0.00583467 0.0368709 0) (-8.14655e-05 -0.0360624 0) (-0.00691555 0.03834 0) (-0.00382594 0.0198846 0) (-0.00634247 0.0543365 0) (-0.00838921 0.0383427 0) (-0.00147078 0.0475046 0) (-0.00203142 0.0634266 0) (-0.00571376 -0.000280804 0) (0.00114966 0.129301 0) (0.000527174 0.0542955 0) (0.00697745 0.00413469 0) (0.00535004 -0.089485 0) (0.00472655 -0.325547 0) (-0.00430121 -0.311025 0) (-0.0079123 -0.0900141 0) (-0.00497273 0.00597798 0) (-0.00312459 0.0547413 0) (-0.00299994 0.124964 0) (0.00292143 -0.00380356 0) (-0.000487131 0.0689841 0) (0.000509193 0.0419677 0) (0.00444092 0.0384882 0) (0.00458861 0.054283 0) (0.00322062 0.0217372 0) (0.00537864 0.0409567 0) (-0.000322467 -0.0263397 0) (-0.00582599 0.0422057 0) (-0.00366946 0.0198831 0) (-0.00447642 0.0535637 0) (-0.00380615 0.0375976 0) (-0.00271477 0.0480553 0) (-0.000735319 0.068476 0) (-0.00293074 -0.00096562 0) (0.00257665 0.1209 0) (0.00466841 0.0461503 0) (0.0045021 0.00596133 0) (0.00789826 -0.0890002 0) (0.00417164 -0.311362 0) (-0.00430719 -0.297147 0) (-0.00821495 -0.0873567 0) (-0.00725903 -0.00335673 0) (-0.00257636 0.059175 0) (-0.00412158 0.120271 0) (0.0025233 -0.0131542 0) (-0.00100372 0.0747091 0) (0.00253083 0.0414711 0) (0.00352935 0.0377512 0) (0.00409865 0.0527155 0) (0.00167302 0.0224538 0) (0.00498995 0.0431287 0) (-0.000502758 -0.00926486 0) (-0.00583515 0.0438994 0) (-0.0027135 0.0209662 0) (-0.00505794 0.0514202 0) (-0.00553178 0.0408494 0) (-0.00279978 0.0368441 0) (0.00193604 0.0696229 0) (-0.00277373 -0.00985114 0) (0.00499128 0.112898 0) (0.00341583 0.0534795 0) (0.00689706 -0.00227017 0) (0.00848886 -0.0863632 0) (0.00440929 -0.296695 0) (-0.00460262 -0.282932 0) (-0.0075033 -0.0801524 0) (-0.00991625 -0.00565242 0) (-0.00331844 0.0486914 0) (-0.0013897 0.118343 0) (0.000143571 -0.0132347 0) (-0.00309105 0.073781 0) (0.0034654 0.0293116 0) (0.00399704 0.04169 0) (0.00449365 0.0560406 0) (0.00268609 0.0248245 0) (0.00481746 0.0430327 0) (0.000424843 0.00215181 0) (-0.00467105 0.0442437 0) (-0.00177076 0.0233199 0) (-0.00432247 0.0568976 0) (-0.00223025 0.0394549 0) (-0.00227454 0.0263714 0) (0.0018043 0.0731667 0) (-0.000929971 -0.0114472 0) (0.00135347 0.111897 0) (0.00283431 0.0429061 0) (0.00904231 -0.00522749 0) (0.00724874 -0.0806754 0) (0.00453772 -0.283104 0) (-0.00443468 -0.268656 0) (-0.00796634 -0.0768483 0) (-0.00766264 -0.00592188 0) (-0.00501151 0.0376451 0) (-0.00292819 0.115812 0) (-0.00166349 -0.00961944 0) (-0.00262351 0.0712712 0) (0.00185315 0.0221527 0) (-0.000131768 0.0424374 0) (0.00359955 0.0513863 0) (0.00316788 0.028586 0) (0.00448613 0.0442741 0) (0.000280698 0.017481 0) (-0.00428978 0.0456579 0) (-0.00292019 0.0265417 0) (-0.0032859 0.0503982 0) (0.000909949 0.0419211 0) (-0.00222995 0.0288629 0) (0.00274905 0.0703371 0) (0.0021815 -0.00705974 0) (0.00308676 0.108017 0) (0.00575925 0.0342802 0) (0.007383 -0.00565747 0) (0.0081563 -0.0770217 0) (0.00444723 -0.268683 0) (-0.00438859 -0.252668 0) (-0.00918202 -0.0701446 0) (-0.0099167 -0.00873532 0) (-0.00674196 0.0412264 0) (-0.0039497 0.112934 0) (-0.000218786 -0.0139695 0) (-0.00214755 0.0717838 0) (0.00218711 0.0242638 0) (-2.95318e-05 0.0436014 0) (0.00303257 0.0456363 0) (0.00181895 0.0316682 0) (0.00344134 0.0449936 0) (0.000181587 0.0291206 0) (-0.0033338 0.0467929 0) (-0.00118214 0.0297313 0) (-0.0031309 0.0450131 0) (-0.0010775 0.0425734 0) (-0.00192079 0.0214471 0) (0.00303057 0.0682526 0) (0.00102036 -0.010635 0) (0.00478144 0.103446 0) (0.00720604 0.0393301 0) (0.00991975 -0.00841537 0) (0.00932806 -0.0701748 0) (0.00443889 -0.25235 0) (-0.00430798 -0.237311 0) (-0.00883113 -0.0607658 0) (-0.0112288 -0.00841185 0) (-0.00717059 0.0267129 0) (-0.00173154 0.107065 0) (-0.000753617 -0.0131632 0) (-0.00234201 0.0709321 0) (0.00235919 0.0187372 0) (0.000996804 0.0463491 0) (0.00252184 0.0469588 0) (0.00149704 0.0352805 0) (0.00267914 0.0450934 0) (0.000426673 0.0393103 0) (-0.00199304 0.0463613 0) (-0.00037564 0.0328316 0) (-0.00180566 0.0501353 0) (-0.000111285 0.0442271 0) (-0.00146889 0.0196842 0) (0.00222262 0.0688089 0) (0.00110446 -0.0102291 0) (0.00207604 0.0983702 0) (0.00690378 0.0260395 0) (0.0109249 -0.00856529 0) (0.00865695 -0.0611801 0) (0.00421701 -0.237376 0) (-0.00403643 -0.223051 0) (-0.00806713 -0.0532968 0) (-0.00927599 -0.00842631 0) (-0.00787329 0.0193798 0) (-0.00292178 0.104476 0) (-0.00153357 -0.0114283 0) (-0.00282011 0.0694763 0) (0.000563149 0.0173549 0) (-0.000707912 0.0492814 0) (0.000911542 0.0442849 0) (0.000261904 0.0382938 0) (0.00115023 0.0452996 0) (5.12698e-05 0.0457181 0) (-0.000725902 0.047737 0) (-0.00105141 0.0356384 0) (-0.000511227 0.0455963 0) (0.0025002 0.0477032 0) (6.76006e-05 0.0194366 0) (0.00338594 0.0670004 0) (0.00244951 -0.00854193 0) (0.00358929 0.0962416 0) (0.00804948 0.0193861 0) (0.00930007 -0.0083613 0) (0.0080837 -0.0536128 0) (0.00404991 -0.223094 0) (-0.00402505 -0.208168 0) (-0.00843877 -0.0449106 0) (-0.0101661 -0.00607301 0) (-0.0105667 0.0193889 0) (-0.0026958 0.0954692 0) (0.000493914 -0.00880031 0) (-0.00335862 0.0701795 0) (-3.41336e-05 0.0171082 0) (-0.00178895 0.0510962 0) (-1.40381e-05 0.0457679 0) (-3.29806e-05 0.0406842 0) (1.85849e-05 0.0450374 0) (0.000472964 0.0481078 0) (0.000732607 0.0483612 0) (0.000984645 0.0383908 0) (0.000819043 0.0414372 0) (0.00173202 0.0497345 0) (0.000143745 0.0183326 0) (0.00347342 0.0679158 0) (0.000532561 -0.00643483 0) (0.00354511 0.0880415 0) (0.0101486 0.0202112 0) (0.0103573 -0.00619138 0) (0.0084196 -0.0451372 0) (0.00405417 -0.208115 0) (-0.00383597 -0.194222 0) (-0.00780851 -0.0355435 0) (-0.0100369 -0.00221454 0) (-0.0100488 0.0106828 0) (-0.00286764 0.0796837 0) (-0.00167412 -0.00296108 0) (-0.00411677 0.0719272 0) (-0.000846413 0.0171128 0) (-0.0034439 0.0543132 0) (-0.000817877 0.0420943 0) (5.13086e-05 0.0433379 0) (-0.000735863 0.045382 0) (0.000752998 0.0481067 0) (0.00179995 0.0473691 0) (0.00200713 0.0408837 0) (0.00181631 0.0462653 0) (0.00292734 0.0536433 0) (0.00169664 0.0188008 0) (0.00413848 0.0684617 0) (0.00189091 -0.00240984 0) (0.00306214 0.0752572 0) (0.00928687 0.0108682 0) (0.00998653 -0.00252567 0) (0.00770101 -0.035882 0) (0.00385645 -0.194385 0) (-0.00366953 -0.181166 0) (-0.00691988 -0.0282382 0) (-0.00845862 0.00196716 0) (-0.00878181 0.00846039 0) (-0.00429438 0.0777575 0) (-0.00311271 2.69603e-05 0) (-0.00457222 0.0710938 0) (-0.00233802 0.0176555 0) (-0.00351149 0.0569493 0) (-0.00170554 0.0384537 0) (-0.00155794 0.0456305 0) (-0.00119732 0.0451714 0) (-2.53391e-05 0.0472199 0) (0.00184922 0.0471156 0) (0.00123133 0.0434997 0) (0.00226796 0.0411775 0) (0.00504138 0.0553411 0) (0.00324455 0.0184164 0) (0.00544903 0.0705361 0) (0.00376647 0.00162604 0) (0.00456053 0.0739158 0) (0.00885341 0.00836418 0) (0.00847772 0.00122224 0) (0.00697195 -0.0288062 0) (0.00368367 -0.181106 0) (-0.0035784 -0.16834 0) (-0.00678236 -0.021652 0) (-0.00820648 0.00583226 0) (-0.00955564 0.00751326 0) (-0.00442819 0.0701516 0) (-0.00246382 0.00270326 0) (-0.00499455 0.0745159 0) (-0.00273837 0.0171298 0) (-0.00381076 0.0586317 0) (-0.00176585 0.0402949 0) (-0.00166879 0.0472463 0) (-0.000831536 0.0448445 0) (0.000115134 0.046457 0) (0.0013852 0.0468621 0) (0.00181116 0.045756 0) (0.00195179 0.0374594 0) (0.00424528 0.0580292 0) (0.002383 0.0191556 0) (0.00525892 0.0717762 0) (0.00368427 0.00468605 0) (0.00512018 0.0667011 0) (0.00978956 0.00856049 0) (0.00846762 0.00541886 0) (0.00682294 -0.0218156 0) (0.00353292 -0.168275 0) (-0.00339364 -0.156276 0) (-0.00627815 -0.0153172 0) (-0.00761848 0.0107293 0) (-0.00874611 0.00618749 0) (-0.00504903 0.0618489 0) (-0.00491977 0.00728052 0) (-0.00522645 0.0753439 0) (-0.00238514 0.0167555 0) (-0.00438755 0.0607607 0) (-0.00123821 0.0354388 0) (-0.00104384 0.0489493 0) (-0.000406189 0.0445682 0) (0.00032999 0.0471289 0) (0.00108162 0.0471558 0) (0.00209572 0.0475055 0) (0.0018879 0.038205 0) (0.00429739 0.0605714 0) (0.0033909 0.0180605 0) (0.00537166 0.0710384 0) (0.00463509 0.00707728 0) (0.00518679 0.0605 0) (0.00820013 0.00645044 0) (0.00754555 0.0105161 0) (0.00611778 -0.0154719 0) (0.00335696 -0.156515 0) (-0.00327449 -0.14487 0) (-0.00573467 -0.00998336 0) (-0.00673222 0.0149641 0) (-0.00758068 0.00620759 0) (-0.00534286 0.0631261 0) (-0.00512329 0.0083033 0) (-0.00479991 0.0724017 0) (-0.0028807 0.0170545 0) (-0.00396461 0.0623046 0) (-0.00129897 0.0334896 0) (-0.00161243 0.0512028 0) (-0.000567197 0.044121 0) (-0.00022291 0.0479364 0) (0.000842704 0.0448748 0) (0.00190976 0.0498276 0) (0.00172327 0.0341637 0) (0.00459029 0.060725 0) (0.00382984 0.0183276 0) (0.00544227 0.073949 0) (0.00509997 0.00886076 0) (0.00540106 0.0622127 0) (0.00760128 0.00641047 0) (0.00675953 0.0143716 0) (0.00579126 -0.0103849 0) (0.00328099 -0.145078 0) (-0.00313237 -0.133893 0) (-0.00540329 -0.00516755 0) (-0.0061193 0.0188899 0) (-0.00742496 0.00686257 0) (-0.00507469 0.0600445 0) (-0.00438698 0.00985204 0) (-0.00445957 0.0740662 0) (-0.0026751 0.0176232 0) (-0.00371984 0.062486 0) (-0.00182377 0.0327905 0) (-0.00179582 0.0529396 0) (-0.000559158 0.0435567 0) (-5.86058e-05 0.0486526 0) (0.000800032 0.0434463 0) (0.00189785 0.0519336 0) (0.00170123 0.0327776 0) (0.00389674 0.0616271 0) (0.0019419 0.0179488 0) (0.00481746 0.0730152 0) (0.00526771 0.011087 0) (0.00550469 0.0585102 0) (0.00805995 0.00750663 0) (0.0064938 0.0186012 0) (0.00561217 -0.0051306 0) (0.0031662 -0.133792 0) (-0.00279209 -0.123643 0) (-0.00490783 -0.00110386 0) (-0.00549546 0.0227383 0) (-0.00687604 0.00826613 0) (-0.00492246 0.0578752 0) (-0.00557184 0.0121832 0) (-0.00415742 0.0715112 0) (-0.00189683 0.0184011 0) (-0.00353198 0.0656467 0) (-0.00144078 0.0309188 0) (-0.00169393 0.0534206 0) (-0.000426036 0.0425554 0) (0.000137319 0.0493066 0) (0.000913487 0.0431935 0) (0.00201004 0.0531251 0) (0.00184099 0.0318111 0) (0.00367703 0.0656789 0) (0.00262781 0.0190246 0) (0.00416176 0.0683511 0) (0.00514541 0.0123382 0) (0.00491608 0.0565655 0) (0.00653701 0.00833615 0) (0.00545105 0.0228151 0) (0.00482671 -0.000941257 0) (0.0027846 -0.123628 0) (-0.00233971 -0.114232 0) (-0.00424876 0.00291108 0) (-0.00462023 0.0267764 0) (-0.00600595 0.00978027 0) (-0.00453727 0.0586211 0) (-0.00501605 0.0138838 0) (-0.00374606 0.067067 0) (-0.00293087 0.0208592 0) (-0.00327185 0.0651054 0) (-0.000840133 0.030915 0) (-0.00172451 0.0552309 0) (-0.000533275 0.0419434 0) (1.29189e-05 0.0498052 0) (0.000821159 0.0416967 0) (0.00192736 0.0546501 0) (0.00120677 0.0311278 0) (0.00351931 0.0645668 0) (0.00351814 0.0209349 0) (0.00404283 0.0701291 0) (0.00493731 0.0141144 0) (0.0045076 0.0585958 0) (0.00574276 0.00978238 0) (0.00451194 0.0265004 0) (0.00417599 0.00287232 0) (0.0023771 -0.114282 0) (-0.00172012 -0.106204 0) (-0.0032718 0.00561441 0) (-0.00354673 0.0307728 0) (-0.00527953 0.0114393 0) (-0.00378741 0.0578869 0) (-0.00410388 0.0158674 0) (-0.00325219 0.0676286 0) (-0.00257754 0.0228168 0) (-0.00273351 0.062217 0) (-0.0013164 0.0316758 0) (-0.00166209 0.055885 0) (-0.000588761 0.0417758 0) (1.01015e-05 0.0495534 0) (0.00065207 0.0415533 0) (0.00167313 0.0556599 0) (0.0011983 0.0319371 0) (0.00279645 0.0620418 0) (0.00191778 0.022769 0) (0.00339942 0.0672477 0) (0.00476274 0.0163329 0) (0.00404595 0.0575025 0) (0.00560779 0.0117118 0) (0.00371427 0.0304984 0) (0.00331714 0.00558923 0) (0.00176555 -0.106158 0) (-0.00127157 -0.100605 0) (-0.00240585 0.0080163 0) (-0.00237963 0.0353688 0) (-0.00473249 0.0133173 0) (-0.00298788 0.0580911 0) (-0.00400404 0.0181204 0) (-0.00282737 0.0652001 0) (-0.00219121 0.0250398 0) (-0.00240723 0.0641429 0) (-0.00113213 0.0333463 0) (-0.001495 0.0555653 0) (-0.000481185 0.0422389 0) (6.75269e-06 0.0501512 0) (0.00044663 0.041995 0) (0.00151421 0.0557852 0) (0.00132024 0.0332819 0) (0.00250066 0.0642581 0) (0.00230824 0.0253037 0) (0.00280545 0.0636221 0) (0.00387953 0.0184487 0) (0.00311953 0.0576927 0) (0.00471503 0.0136256 0) (0.00243132 0.0353863 0) (0.00237284 0.00811436 0) (0.00126794 -0.100563 0) (-0.00135551 -0.0948178 0) (-0.00245988 0.00994761 0) (-0.00185662 0.0401565 0) (-0.0043771 0.0167039 0) (-0.00287641 0.0575595 0) (-0.00396044 0.0218682 0) (-0.00294264 0.0645892 0) (-0.00269714 0.0283655 0) (-0.00227052 0.0611554 0) (-0.000519798 0.0354125 0) (-0.00134256 0.0566659 0) (-0.000184951 0.0433739 0) (2.09338e-05 0.0507111 0) (0.000273023 0.0432846 0) (0.00141807 0.0555446 0) (0.000644622 0.0356856 0) (0.00235221 0.061309 0) (0.00292798 0.0285204 0) (0.00299442 0.0648732 0) (0.00374592 0.0219808 0) (0.00283307 0.0576034 0) (0.00427619 0.0168673 0) (0.00182348 0.0401923 0) (0.00242262 0.00998821 0) (0.00135955 -0.0948063 0) (-0.00175882 -0.0896122 0) (-0.00298755 0.011697 0) (-0.00230118 0.0424163 0) (-0.00452966 0.0198708 0) (-0.00341158 0.0576476 0) (-0.0041403 0.0248842 0) (-0.00341853 0.061343 0) (-0.00211075 0.0308478 0) (-0.00284293 0.0580934 0) (-0.00141073 0.0372552 0) (-0.00155105 0.0553201 0) (-0.00023083 0.0439935 0) (4.78938e-05 0.0502763 0) (0.00044501 0.0438221 0) (0.00163372 0.0553167 0) (0.00127413 0.0372125 0) (0.00285165 0.0582068 0) (0.00208338 0.03089 0) (0.00339964 0.0616366 0) (0.00417331 0.0249282 0) (0.00335257 0.0573549 0) (0.00451689 0.0199665 0) (0.00228056 0.0424384 0) (0.00297434 0.0116995 0) (0.00177428 -0.0896026 0) (-0.00314681 -0.0832522 0) (-0.00357273 0.0142288 0) (-0.00405208 0.0437999 0) (-0.00496004 0.0242977 0) (-0.00447493 0.0564439 0) (-0.00409268 0.0287654 0) (-0.0042588 0.058339 0) (-0.00257826 0.033955 0) (-0.00324522 0.0591161 0) (-0.00167669 0.0387822 0) (-0.00181698 0.0538035 0) (-0.000426599 0.0444386 0) (5.01838e-05 0.0503547 0) (0.000412585 0.0444179 0) (0.00181731 0.0540866 0) (0.00169687 0.0388032 0) (0.00324099 0.0592122 0) (0.00259386 0.0340004 0) (0.00423514 0.0586699 0) (0.00409617 0.0288417 0) (0.0044129 0.0565666 0) (0.00495222 0.024366 0) (0.00400637 0.0438413 0) (0.0035635 0.0141403 0) (0.00313775 -0.0832249 0) (-0.00533044 -0.0700915 0) (-0.00555311 0.0217765 0) (-0.00536059 0.047438 0) (-0.00633095 0.0293665 0) (-0.005644 0.0568573 0) (-0.00537839 0.0333717 0) (-0.00504475 0.0588768 0) (-0.00416524 0.0374462 0) (-0.00353174 0.0571829 0) (-0.00180574 0.0422994 0) (-0.00193602 0.0546236 0) (-0.000574905 0.0464645 0) (2.38646e-05 0.0517487 0) (0.000518004 0.0466246 0) (0.00191088 0.0541748 0) (0.00182078 0.0423348 0) (0.00352859 0.0572908 0) (0.00415874 0.0374929 0) (0.00504879 0.0591504 0) (0.0054065 0.0334634 0) (0.00566777 0.0567144 0) (0.00631163 0.0294368 0) (0.00532483 0.0475022 0) (0.00554769 0.0216563 0) (0.00531408 -0.0701178 0) (-0.00403825 -0.0604566 0) (-0.00509314 0.0163419 0) (-0.00469413 0.043736 0) (-0.0070571 0.0283357 0) (-0.00696317 0.05137 0) (-0.00660578 0.0318887 0) (-0.00650623 0.0524779 0) (-0.00498949 0.0355148 0) (-0.00495607 0.0504107 0) (-0.00305054 0.0395495 0) (-0.00265008 0.0494827 0) (-0.000986952 0.0429546 0) (-5.50957e-06 0.0474538 0) (0.000981447 0.0431036 0) (0.00262385 0.0495177 0) (0.00298327 0.0395833 0) (0.00492329 0.0505265 0) (0.00495171 0.0355551 0) (0.0064851 0.0526782 0) (0.00662689 0.0319634 0) (0.00694983 0.0513962 0) (0.00703813 0.0284306 0) (0.00466288 0.0438181 0) (0.00508884 0.0161732 0) (0.00403194 -0.0604484 0) (-0.00713672 -0.0446624 0) (-0.00323393 0.0277187 0) (-0.00689222 0.055716 0) (-0.00749826 0.0442095 0) (-0.00835359 0.0571188 0) (-0.00723894 0.0433944 0) (-0.00733169 0.0562336 0) (-0.0053769 0.0447297 0) (-0.00533587 0.0554243 0) (-0.00343853 0.0465716 0) (-0.00284052 0.0537407 0) (-0.00111671 0.0488394 0) (-3.62041e-05 0.0522282 0) (0.00105389 0.0489379 0) (0.00279031 0.0536633 0) (0.00338561 0.0465721 0) (0.00530474 0.0555099 0) (0.00533949 0.0447483 0) (0.00730815 0.0563757 0) (0.00724183 0.0434456 0) (0.00834465 0.0571433 0) (0.00750205 0.0442898 0) (0.0068867 0.0557769 0) (0.00323144 0.0275206 0) (0.00710865 -0.0447008 0) (-0.0200818 -0.0407713 0) (-0.0191655 0.0232815 0) (-0.0200238 0.045839 0) (-0.0179972 0.0379287 0) (-0.01526 0.0443198 0) (-0.0125668 0.036215 0) (-0.0102016 0.0429687 0) (-0.00776356 0.036185 0) (-0.00614873 0.0421431 0) (-0.00411908 0.0370451 0) (-0.00289559 0.0413974 0) (-0.00128621 0.0381705 0) (-4.54884e-05 0.0405631 0) (0.00119786 0.0382328 0) (0.00281201 0.0413355 0) (0.00401589 0.0370278 0) (0.00606814 0.0422263 0) (0.00769647 0.0362201 0) (0.0101638 0.0430935 0) (0.0125723 0.0362803 0) (0.0152689 0.0443719 0) (0.0180257 0.0380209 0) (0.0200576 0.0459197 0) (0.019209 0.0231964 0) (0.020065 -0.0408293 0) (-0.0194087 -0.0283977 0) (-0.0343617 -0.0133344 0) (-0.02701 -0.010273 0) (-0.0232513 -0.0174633 0) (-0.0181401 -0.0132171 0) (-0.0141708 -0.0176482 0) (-0.0110318 -0.0109321 0) (-0.00800323 -0.0141245 0) (-0.00606098 -0.00843033 0) (-0.00387272 -0.0107009 0) (-0.00268604 -0.00719398 0) (-0.00112931 -0.00844581 0) (-5.4667e-05 -0.00705399 0) (0.00103447 -0.00840006 0) (0.0025923 -0.0072106 0) (0.00374189 -0.0106849 0) (0.00595772 -0.0084269 0) (0.00792704 -0.0141913 0) (0.0109974 -0.0109665 0) (0.0141936 -0.0176796 0) (0.0181729 -0.0132404 0) (0.0233017 -0.0174553 0) (0.0271096 -0.0102369 0) (0.0344339 -0.0133608 0) (0.0194257 -0.0283994 0) (0.0157469 -0.24031 0) (-0.0169403 -0.346614 0) (-0.00723496 -0.370293 0) (-0.0122939 -0.368726 0) (-0.011696 -0.357693 0) (-0.0111192 -0.348997 0) (-0.0100594 -0.339048 0) (-0.00828565 -0.335117 0) (-0.00689646 -0.328418 0) (-0.00502844 -0.325691 0) (-0.00362246 -0.323813 0) (-0.00175569 -0.322521 0) (-3.36586e-05 -0.32264 0) (0.00169821 -0.322497 0) (0.00356728 -0.323718 0) (0.00495757 -0.325575 0) (0.00684265 -0.328403 0) (0.0082438 -0.335243 0) (0.0100324 -0.339174 0) (0.0111177 -0.349081 0) (0.0116977 -0.357699 0) (0.0122816 -0.368705 0) (0.00728128 -0.370252 0) (0.0169255 -0.346292 0) (-0.0157167 -0.240076 0) (0.0938364 -0.162722 0) (0.00429997 -0.162333 0) (-0.0147301 -0.143745 0) (-0.0258111 -0.151182 0) (-0.0292001 -0.156964 0) (-0.0331733 -0.160632 0) (-0.0359718 -0.164768 0) (-0.0369695 -0.16543 0) (-0.034266 -0.169346 0) (-0.0278868 -0.168212 0) (-0.0201508 -0.167844 0) (-0.0104341 -0.16688 0) (-7.1167e-05 -0.16706 0) (0.010329 -0.166882 0) (0.0200902 -0.167884 0) (0.0278384 -0.168268 0) (0.0342435 -0.169368 0) (0.0369802 -0.165417 0) (0.035983 -0.164745 0) (0.0331533 -0.160598 0) (0.0291298 -0.157002 0) (0.0257105 -0.15127 0) (0.0147402 -0.143769 0) (-0.00460339 -0.162531 0) (-0.094162 -0.162731 0) (0.308791 -0.113697 0) (-0.00567456 -0.104081 0) (-0.0453817 -0.112182 0) (-0.0586734 -0.124947 0) (-0.0635976 -0.132619 0) (-0.0718579 -0.130927 0) (-0.0766486 -0.133825 0) (-0.0807218 -0.145814 0) (-0.0809248 -0.168183 0) (-0.0684824 -0.179302 0) (-0.0516147 -0.180816 0) (-0.0295149 -0.182763 0) (-0.000136077 -0.18181 0) (0.0293689 -0.182798 0) (0.0514284 -0.180859 0) (0.0685473 -0.179384 0) (0.0810012 -0.168287 0) (0.0808685 -0.145962 0) (0.0767679 -0.13376 0) (0.0718961 -0.130695 0) (0.0635819 -0.13249 0) (0.0586018 -0.12502 0) (0.0454247 -0.112278 0) (0.00541051 -0.104508 0) (-0.30964 -0.113392 0) (-0.0118559 0.127915 0) (-0.0344543 0.158025 0) (-0.0356647 0.115178 0) (-0.0434508 0.102088 0) (-0.0447551 0.0925824 0) (-0.0491368 0.0896583 0) (-0.0500463 0.0866775 0) (-0.052824 0.0816745 0) (-0.0565179 0.0760181 0) (-0.0642032 0.0626497 0) (-0.0504835 -0.0141178 0) (-0.0282973 -0.0979438 0) (-8.95693e-05 -0.129155 0) (0.0282314 -0.0984464 0) (0.0502819 -0.0156004 0) (0.0643431 0.0621863 0) (0.0568247 0.0759077 0) (0.0531129 0.0816437 0) (0.0503115 0.0868141 0) (0.0493826 0.0898736 0) (0.0449774 0.0926566 0) (0.0436067 0.101946 0) (0.0358151 0.115033 0) (0.034512 0.158043 0) (0.0119135 0.127962 0) (-0.0214071 0.215756 0) (-0.0344365 0.192851 0) (-0.0309566 0.136143 0) (-0.0377796 0.115232 0) (-0.0361138 0.101334 0) (-0.0383167 0.0920718 0) (-0.0386415 0.0867507 0) (-0.0403288 0.074582 0) (-0.0384762 0.045962 0) (-0.0288403 -0.00651012 0) (-0.00500695 -0.0959946 0) (-0.0084503 -0.148505 0) (0.000264966 -0.192035 0) (0.00883214 -0.149377 0) (0.00553064 -0.0968073 0) (0.0290555 -0.00752243 0) (0.0388682 0.045494 0) (0.0407346 0.0745344 0) (0.039011 0.0870572 0) (0.0386507 0.0924259 0) (0.036392 0.101521 0) (0.037988 0.115212 0) (0.0311324 0.136127 0) (0.0345513 0.192938 0) (0.0214869 0.215962 0) (-0.00154804 0.252687 0) (-0.0221977 0.21273 0) (-0.0194535 0.132762 0) (-0.0253596 0.104641 0) (-0.0190469 0.0900637 0) (-0.0120162 0.0836065 0) (-0.000681456 0.0757354 0) (0.0104807 0.0613899 0) (0.0220421 0.0321556 0) (0.0309483 -0.00754279 0) (0.0190109 -0.0730243 0) (0.00561846 -0.143233 0) (0.000598687 -0.198429 0) (-0.00439012 -0.144346 0) (-0.0179257 -0.0741491 0) (-0.0301018 -0.00823697 0) (-0.0214234 0.0318576 0) (-0.00994205 0.0614439 0) (0.00115949 0.0760336 0) (0.0124645 0.0839682 0) (0.0194184 0.0903415 0) (0.0256431 0.104791 0) (0.0196512 0.132842 0) (0.0223362 0.213035 0) (0.00157416 0.253134 0) (0.00899644 0.249289 0) (0.0163027 0.224679 0) (0.0215542 0.154887 0) (0.0255848 0.108544 0) (0.0346236 0.0857693 0) (0.0512124 0.0598971 0) (0.0716104 0.0503904 0) (0.0901758 0.0483208 0) (0.0999432 0.0397752 0) (0.105226 0.0178525 0) (0.0863394 -0.00088571 0) (0.0529196 -0.0543313 0) (0.000968525 -0.112198 0) (-0.0514691 -0.055195 0) (-0.085194 -0.00103801 0) (-0.104413 0.017858 0) (-0.0992259 0.0400022 0) (-0.0896341 0.0487437 0) (-0.0711825 0.0510465 0) (-0.0508349 0.0603741 0) (-0.0343335 0.0861896 0) (-0.0253655 0.108973 0) (-0.0215135 0.155281 0) (-0.016306 0.225207 0) (-0.00901825 0.249775 0) (0.0125128 0.206855 0) (0.0307606 0.197835 0) (0.0395411 0.148308 0) (0.0569137 0.083152 0) (0.0699327 0.0424633 0) (0.090142 0.00338368 0) (0.106509 -0.0117852 0) (0.128835 -0.0121643 0) (0.148306 0.00188528 0) (0.149141 0.0367167 0) (0.120609 0.0499255 0) (0.0901973 0.0207102 0) (0.000237971 -0.028643 0) (-0.0900776 0.0205411 0) (-0.120502 0.0500171 0) (-0.148931 0.0370257 0) (-0.148228 0.00254962 0) (-0.128706 -0.0113706 0) (-0.106415 -0.0109629 0) (-0.0900254 0.00415973 0) (-0.0698768 0.0433945 0) (-0.0569413 0.0839866 0) (-0.0396462 0.148884 0) (-0.0309051 0.198369 0) (-0.0125235 0.207315 0) (0.00637921 0.145871 0) (0.0189892 0.135943 0) (0.032149 0.0927026 0) (0.0435597 0.0323414 0) (0.0522758 -0.00829572 0) (0.0591247 -0.0382772 0) (0.06967 -0.0523356 0) (0.0794137 -0.048543 0) (0.0957634 -0.0128111 0) (0.100814 0.0609414 0) (0.0854353 0.145051 0) (0.0596138 0.201353 0) (-0.00013415 0.215585 0) (-0.0599978 0.2015 0) (-0.0858743 0.144943 0) (-0.101149 0.0609442 0) (-0.09613 -0.0124948 0) (-0.0797377 -0.0480697 0) (-0.0698906 -0.0518204 0) (-0.0593363 -0.0376862 0) (-0.0524741 -0.00762934 0) (-0.0436966 0.0331253 0) (-0.0322451 0.0933648 0) (-0.0191049 0.136273 0) (-0.00640358 0.145988 0) ) ; boundaryField { inlet { type fixedValue; value uniform (0 0 0); } outlet { type pressureInletOutletVelocity; phi phi.water; value nonuniform List<vector> 25 ( (0.00637921 0.145871 0) (0.0189892 0.135943 0) (0.032149 0.0927026 0) (0.0435597 0.0323414 0) (0 -0.00705676 0) (0 -0.0373034 0) (0 -0.0520842 0) (0 -0.0492049 0) (0 -0.014232 0) (0.100814 0.0609414 0) (0.0854353 0.145051 0) (0.0596138 0.201353 0) (-0.00013415 0.215585 0) (-0.0599978 0.2015 0) (-0.0858743 0.144943 0) (-0.101149 0.0609442 0) (-0 -0.0139063 0) (-0 -0.0487185 0) (-0 -0.0515586 0) (-0 -0.0367072 0) (-0 -0.006395 0) (-0.0436966 0.0331253 0) (-0.0322451 0.0933648 0) (-0.0191049 0.136273 0) (-0.00640358 0.145988 0) ) ; } walls { type fixedValue; value uniform (0 0 0); } defaultFaces { type empty; } } // ************************************************************************* //
324dad42c648b980ec549d79def9fe49833a7d63
feff2c95a1a4a4f0b8ffa68340428557ff234fe8
/cpp2c/bd.cpp
8b62c6d2a97a9cc9d9cebc4abb8f070ee44aa0bc
[]
no_license
ShaiHoresh/experis
e836966efcd7f559c768ed4b7f28c96e2817c49c
d2982bf9560fd0ff651deefdaf56fe9f9e861fc6
refs/heads/master
2021-09-03T01:09:16.911055
2018-01-04T12:56:11
2018-01-04T12:56:11
116,258,477
0
0
null
null
null
null
UTF-8
C++
false
false
721
cpp
bd.cpp
#include <iostream> class B { public: inline virtual void foo() {std::cout << "B's foo" << std::endl;} void baz() {std::cout << "B's baz" << std::endl;} // int a; }; class D: public B { public: inline virtual void foo() {std::cout << "D's foo" << std::endl;} void baz() {std::cout << "D's baz" << std::endl;} }; int main() { B b, *pb1, *pb2; D d, *pd1, *pd2; pb1 = &b; pb2 = &d; pd1 = &d; b.foo(); pb1->foo(); pb2->foo(); ((B)d).foo(); b.baz(); pb2->baz(); std::cout << ((pb2 == pd1) ? "true" : "false") << std::endl; std::cout << &pb2 << std::endl; std::cout << &pd1 << std::endl; return 0; }
d845f4bd1a223d90aac6670ca4be49e520cc3b81
11426005738c6f8f3efc5f5ff1d29e52f4ca847f
/15.三数之和.cpp
8caf642cfb1cac9910a78238d5a2959a6392b3d6
[]
no_license
Chaosame/leetcode_cpp
9f4075c7e859b5a2636036e2fa6272bec2113e25
1ce8ab198b18248d39168f7c8419626e8cd94b39
refs/heads/main
2023-04-05T07:03:08.996209
2021-04-09T13:34:02
2021-04-09T13:34:02
344,394,080
0
0
null
null
null
null
UTF-8
C++
false
false
1,289
cpp
15.三数之和.cpp
/* * @lc app=leetcode.cn id=15 lang=cpp * * [15] 三数之和 */ // @lc code=start //回溯不行得双指针 class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> res; vector<int> tmp_res; if (nums.size()<3){ return res; } sort(nums.begin(),nums.end()); // 排序防重复 dfs(0,nums,tmp_res,res,0); // set<vector<int>> s(res.begin(),res.end()); // res.assign(s.begin(),s.end()); return res; } void dfs(int cur,vector<int>& nums,vector<int> &tmp_res,vector<vector<int>> &res,int target){ int n = nums.size(); if(tmp_res.size()>=3){ if(target == 0){ res.push_back(tmp_res); } return; //深度到3说明已经到底直接返回 } if(cur>=n){ return; } for(int i=cur;i<n;i++){ //选取元素 tmp_res.push_back(nums[i]); //递归 dfs(i+1,nums,tmp_res,res,target-nums[i]); //回溯 tmp_res.pop_back(); //去重 while(i<n-1&&nums[i+1]==nums[i]){ i++; } } } }; // @lc code=end
7ed39fd347404794033cbeebbcf317e8c731da42
f8fcec0fb4284bc6c12cba19c54f83a74ea26f19
/GameOfLife3D/stdafx.h
7c4742638726536e41c1df8d175ffbdec73252d1
[ "MIT" ]
permissive
Crawping/GameOfLife3D
4efc7bbb41e3254f3bb19bf0a94b88f8b628ae95
c4c1e9efdcf26d4c028509bd252aba1d23c636a1
refs/heads/master
2023-05-23T06:22:00.634530
2019-01-10T11:18:18
2019-01-10T11:18:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,490
h
stdafx.h
#pragma once #include "targetver.h" #ifdef DEBUG #define DEBUG_RESOURCE #endif #include <cstdlib> #include <ctime> #include <cwchar> #include <cmath> #include <cstdint> #include <cassert> #include <string> #include <iostream> #include <fstream> #include <vector> #include <queue> #include <stack> #include <array> #include <map> #include <unordered_map> #include <tuple> #include <regex> /* #ifdef INT8_MIN #undef INT8_MIN #endif #ifdef INT8_MAX #undef INT8_MAX #endif #ifdef INT16_MIN #undef INT16_MIN #endif #ifdef INT16_MAX #undef INT16_MAX #endif #ifdef INT32_MIN #undef INT32_MIN #endif #ifdef INT32_MAX #undef INT32_MAX #endif #ifdef INT64_MIN #undef INT64_MIN #endif #ifdef INT64_MAX #undef INT64_MAX #endif #ifdef UINT8_MIN #undef UINT8_MIN #endif #ifdef UINT8_MAX #undef UINT8_MAX #endif #ifdef UINT16_MIN #undef UINT16_MIN #endif #ifdef UINT16_MAX #undef UINT16_MAX #endif #ifdef UINT32_MIN #undef UINT32_MIN #endif #ifdef UINT32_MAX #undef UINT32_MAX #endif #ifdef UINT64_MIN #undef UINT64_MIN #endif #ifdef UINT64_MAX #undef UINT64_MAX #endif */ #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <ppl.h> #include <d3d11.h> #include <d3d11.h> #include <d3d10_1.h> //#include <dxerr.h> #include <DirectXMath.h> #include <d3dcompiler.h> //#include <xnamath.h> #include <d2d1.h> #include <d2d1helper.h> #include <dwrite.h> #include <wincodec.h> #include <atlbase.h> #include <atlcom.h> #include <atlwin.h> #include <initguid.h> #include <uiribbon.h> #include <mshtmcid.h> #include <msctf.h> #include <OleCtl.h> #include <initguid.h> #include <tsattrs.h> #include <shlobj.h> #include <shobjidl.h> #include <shellapi.h> #include <knownfolders.h> #include <UIAutomationCore.h> #include <UIAnimation.h> #ifndef Assert #if defined(DEBUG) || defined(_DEBUG) #define Assert(b) \ do { \ if (!(b)) { \ OutputDebugStringA("Assert: " #b "\n"); \ } \ } while (0) #else #define Assert(b) #endif // DEBUG || _DEBUG #endif #define ASSERT assert #ifndef HINST_THISCOMPONENT EXTERN_C IMAGE_DOS_HEADER __ImageBase; #define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase) #endif #import "MSXML6.dll" rename_namespace(_T("MSXML")) #include <msxml6.h> #undef min #undef max #include "logging/Logging.h" // SafeAcquire template <typename InterfaceType> inline InterfaceType *SafeAcquire(InterfaceType *newObject) { if (newObject != nullptr) { #ifdef DEBUG_RESOURCE LOG(SEVERITY_LEVEL_INFO) << L"[RESOURCE] Acquire [" << std::hex << newObject << L"]" << std::dec; #endif newObject->AddRef(); } return newObject; } // SafeRelease template <class Interface> inline void SafeRelease(Interface **ppInterfaceToRelease) { if (*ppInterfaceToRelease != nullptr) { #ifdef DEBUG_RESOURCE LOG(SEVERITY_LEVEL_INFO) << L"[RESOURCE] Release [" << std::hex << *ppInterfaceToRelease << L"]" << std::dec; #endif (*ppInterfaceToRelease)->Release(); (*ppInterfaceToRelease) = nullptr; } } #pragma warning(disable : 4714) #pragma warning(disable : 4503)
5135ee2b372f9b38efb79076aaf456ae1909afe8
4f4eb5c1ad154db2d3d4e8c3aeb3e1525711785a
/main.cpp
b1be5cec9db81b5273aa171820e9edc81cce2d0f
[]
no_license
alexseles/Countdown
ec7e4ed6e45b8e2e2fe120f7ef292a15765a60f9
557c0d9f8624e5b900f9ae98e28f289f2775340b
refs/heads/main
2023-01-08T21:10:51.966455
2020-11-07T12:58:06
2020-11-07T12:58:06
310,844,822
0
0
null
null
null
null
UTF-8
C++
false
false
332
cpp
main.cpp
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std; int main() { int num, counter, countdown, resp; cout <<" What is the number of the countdown? "; cin >>countdown; for (counter=countdown;counter>=0;counter--) { cout <<counter<<"\n"; } }
cc5dff40970f476da7c982ac96be05568be751a3
47cb37f9ed234aa12b6da1be459649b799b6cbec
/MegaManX3/StageBoss.h
5dfdb8850d828c2cbdcde6411a553cf353646aef
[ "MIT" ]
permissive
sd2017/Mega-Man-X3
3dc1ba64172050297abd834726259029e2c9af13
bd42d11926a071e67ea554761933ee47802225f6
refs/heads/master
2022-10-02T22:25:43.787913
2020-06-06T11:09:44
2020-06-06T11:09:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
785
h
StageBoss.h
#pragma once #include "Stage.h" #include "BlastHornet.h" class StageBoss : public Stage { private: Gate* gateLeft; BlastHornet* boss; HPBar* hpBarBoss; bool ready = false; bool gateLeftClose = false; public: StageBoss(); ~StageBoss(); public: void getStaticObjects(unordered_map<int, GameObject*> *saticObjects); void getDynamicObjects(unordered_map<int, GameObject*> *dynamicObjects); public: void update(DWORD dt, unordered_map<int, GameObject*>* staticObjects); void render(DWORD dt, D3DCOLOR colorBrush = WHITE(255)); void reset(); public: HPBar* getHPBar() { if (ready && !main->isRevivaling) return hpBarBoss; else return null; } HornetPoint* getHornetPoint() { if (boss->isDeath() && !main->isRevivaling) return null; else return boss->getHoretPoint(); } };
767bb5d68f99138552186a6bfa3a80ec816ab8f9
ba75d803f40a52e080ca1f7657025c7c59f87b21
/network_api_cc/include/nta/ntypes/ObjectModel.hpp
25f763803f84af792b1039af077e7e0c69e874b9
[]
no_license
kokukuma/nupic_tutorials
8c010e8f5391c470f543036a041e0e064e7b1f9b
b92c39038f9757f658d32e9875075f2c85287ced
refs/heads/master
2016-09-10T08:18:22.062350
2014-08-17T08:08:48
2015-11-12T05:48:01
22,003,882
0
1
null
null
null
null
UTF-8
C++
false
false
43,725
hpp
ObjectModel.hpp
/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * 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. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ /** @file * Interfaces for C++ runtime objects used by INode */ /* * TEMPORARY for NUPIC 2 development * Included because IWriteBuffer/IReadBuffer */ #ifndef NTA_OBJECT_MODEL_HPP #define NTA_OBJECT_MODEL_HPP #include <nta/types/Types.hpp> #include <nta/ntypes/ObjectModel.h> #include <string> #include <stdexcept> namespace nta { //--------------------------------------------------------------------------- // // I R E A D B U F F E R // //--------------------------------------------------------------------------- /** * @b Responsibility: * Interface for reading values from a binary buffer */ //--------------------------------------------------------------------------- struct IReadBuffer { /** * Virtual destructor. Required for abstract classes. */ virtual ~IReadBuffer() {} /** * Reset the internal pointer to point to the beginning of the buffer. * * This is necessary if you want to read from the same buffer multiple * times. */ virtual void reset() const = 0; /** * Returns the size in bytes of the buffer's contents * * This is useful if you want to copy the entire buffer * as a byte array. * * @retval number of bytes in the buffer */ virtual Size getSize() const = 0; /** * Returns a pointer to the buffer's contents * * This is useful if you want to access the bytes directly. * The returned buffer is not related in any way to the * internal advancing pointer used in the read() methods. * * @retval pointer to beginning of the buffer */ virtual const Byte * getData() const = 0; /** * Read a single byte into 'value' and advance the internal pointer. * * @param value the output byte. * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(Byte & value) const = 0; /** * Read 'size' bytes into the 'value' array and advance * the internal pointer. * If the buffer contains less than 'size' bytes it will read * as much as possible and write the number of bytes actually read * into the 'size' argument. * * @param value the output buffer. Must not be NULL * @param size the size of the output buffer. Must be >0. Receives * the actual number of bytes read if success or 0 * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(Byte * value, Size & size) const = 0; /** * Read a string into the string object provided in 'value'. * The string object should be empty before begin passed in, * or the result will be undefined. * The string must have been written to the buffer using the * IWriteBuffer::write(const std::string &) interface. * The value of the string upon completion will be undefined on failure. * Note that reading and writing a string is slightly different from * reading or writing an arbitrary binary structure in the * the following ways: * * Reading/writing a 0-length string is a sensible operation. * * The length of the string is almost never known ahead of time. * * @retval value A reference to a character array pointer (initially null). * This array will point to a new buffer allocated with the * provided allocator upon success. * The caller is responsible for this memory. * @retval size A reference to a size that will be filled in with the * string length. * @param fAlloc A function pointer that will be called to * perform necessary allocation of value buffer. * @param fDealloc A function pointer that will be called if a failure * occurs after the value array has been allocated to * cleanup allocated memory. * @return 0 for success, -1 for failure */ virtual NTA_Int32 readString( NTA_Byte * &value, NTA_UInt32 &size, NTA_Byte *(fAlloc)(NTA_UInt32 size), void (fDealloc)(NTA_Byte *) ) const = 0; /** * Read a single integer (32 bits) into 'value' * and advance the internal pointer. * * @param value the output integer. * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(Int32 & value) const = 0; /** * Read 'size' Int32 elements into the 'value' array and advance * the internal pointer. * If the buffer contains less than 'size' bytes it will read * as much as possible and write the number of elements actually read * into the 'size' argument. * * @param value the output buffer. Must not be NULL * @param size the size of the output buffer. Must be >0. * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(Int32 * value, Size size) const = 0; /** * Read a single unsigned integer (32 bits) into 'value' * and advance the internal pointer. * * @param value the output unsigned integer. * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(UInt32 & value) const = 0; /** * Read 'size' UInt32 elements into the 'value' array and advance * the internal pointer. * If the buffer contains less than 'size' bytes it will read * as much as possible and write the number of elements actually read * into the 'size' argument. * * @param value the output buffer. Must not be NULL * @param size the size of the output buffer. Must be >0. Receives * the actual number of elements read if success or 0 * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(UInt32 * value, Size size) const = 0; /** * Read a single integer (64 bits) into 'value' * and advance the internal pointer. * * @param value the output integer. * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(Int64 & value) const = 0; /** * Read 'size' Int64 elements into the 'value' array and advance * the internal pointer. * If the buffer contains less than 'size' bytes it will read * as much as possible and write the number of elements actually read * into the 'size' argument. * * @param value the output buffer. Must not be NULL * @param size the size of the output buffer. Must be >0. Receives * the actual number of elements read if success or 0 * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(Int64 * value, Size size) const = 0; /** * Read a single unsigned integer (64 bits) into 'value' * and advance the internal pointer. * * @param value the output unsigned integer. * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(UInt64 & value) const = 0; /** * Read 'size' UInt64 elements into the 'value' array and advance * the internal pointer. * If the buffer contains less than 'size' bytes it will read * as much as possible and write the number of elements actually read * into the 'size' argument. * * @param value the output buffer. Must not be NULL * @param size the size of the output buffer. Must be >0. Receives * the actual number of elements read if success or 0 * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(UInt64 * value, Size size) const = 0; /** * Read a single 32-bit real number (float) * into 'value' and advance the internal pointer. * * @param value the output real number. * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(Real32 & value) const = 0; /** * Read 'size' Real32 elements into the 'value' array and advance * the internal pointer. * If the buffer contains less than 'size' bytes it will read * as much as possible and write the number of elements actually read * into the 'size' argument. * * @param value the output buffer. Must not be NULL * @param size the size of the output buffer. Must be >0. Receives * the actual number of elements read if success or 0 * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(Real32 * value, Size size) const = 0; /** * Read a single 64-bit real number (double) * into 'value' and advance the internal pointer. * * @param value the output real number. * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(Real64 & value) const = 0; /** * Read 'size' Real64 elements into the 'value' array and advance * the internal pointer. * If the buffer contains less than 'size' bytes it will read * as much as possible and write the number of elements actually read * into the 'size' argument. * * @param value the output buffer. Must not be NULL * @param size the size of the output buffer. Must be >0. Receives * the actual number of elements read if success or 0 * @retval 0 for success, -1 for failure, 1 for EOF */ virtual Int32 read(Real64 * value, Size size) const = 0; }; //--------------------------------------------------------------------------- // // I R E A D B U F F E R I T E R A T O R // //--------------------------------------------------------------------------- /** * @b Responsibility: * Interface for iterating over a collection of IReadBuffer objects */ //--------------------------------------------------------------------------- struct IReadBufferIterator { /** * Virtual destructor. Required for abstract classes. */ virtual ~IReadBufferIterator() {} /** * Reset the internal pointer to point to the beginning of the iterator. * * The following next() will return the first IReadBuffer in the collection * or NULL if the collection is empty. Multiple consecutive calls are allowed * but have no effect. */ virtual void reset() = 0; /** * Get the next buffer in the collection * * This method returns the buffer pointed to by the internal pointer and advances * the pointer to the next buffer in the collection. If the collection is empty * or previous call to next() returned the last buffer, further calls to next() * will return NULL. * * @retval [IReadBuffer *] next buffer or NULL */ virtual const IReadBuffer * next() = 0; }; //--------------------------------------------------------------------------- // // I W R I T E B U F F E R // //--------------------------------------------------------------------------- /** * @b Responsibility: * Interface for writing values to a binary buffer */ //--------------------------------------------------------------------------- struct IWriteBuffer { /** * Virtual destructor. Required for abstract classes. */ virtual ~IWriteBuffer() {} /** * Write a single byte into * the internal buffer. * * @param value the input byte. * @retval 0 for success, -1 for failure */ virtual Int32 write(Byte value) = 0; /** * Write a byte array into * the internal buffer. * * @param value the input array. * @param size how many bytes to write * @retval 0 for success, -1 for failure */ virtual Int32 write(const Byte * value, Size size) = 0; /** * Write the contents of a string into the stream. * The string may be of 0 length and may contain any 8-bit characters * (the string must be 1-byte encoded). * Note that reading and writing a string is slightly different from * reading or writing an arbitrary binary structure in the * the following ways: * * Reading/writing a 0-length string is a sensible operation. * * @param value the input array. * @retval 0 for success, -1 for failure */ virtual Int32 writeString(const Byte * value, Size size) = 0; /** * Write a single integer (32 bits) into * the internal buffer. * * @param value the input integer. * @retval 0 for success, -1 for failure */ virtual Int32 write(Int32 value) = 0; /** * Write array of Int32 elements into * the internal buffer. * * @param value the input array. * @param size how many bytes to write * @retval 0 for success, -1 for failure */ virtual Int32 write(const Int32 * value, Size size) = 0; /** * Write a single unsigned integer (32 bits) into * the internal buffer. * * @param value the input unsigned integer. * @retval 0 for success, -1 for failure */ virtual Int32 write(UInt32 value) = 0; /** * Write array of UInt32 elements into * the internal buffer. * * @param value the input array. * @param size how many bytes to write * @retval 0 for success, -1 for failure */ virtual Int32 write(const UInt32 * value, Size size) = 0; /** * Write a single integer (64 bits) into * the internal buffer. * * @param value the input integer. * @retval 0 for success, -1 for failure */ virtual Int32 write(Int64 value) = 0; /** * Write array of Int64 elements into * the internal buffer. * * @param value the input array. * @param size how many bytes to write * @retval 0 for success, -1 for failure */ virtual Int32 write(const Int64 * value, Size size) = 0; /** * Write a single unsigned integer (64 bits) into * the internal buffer. * * @param value the input unsigned integer. * @retval 0 for success, -1 for failure */ virtual Int32 write(UInt64 value) = 0; /** * Write array of UInt64 elements into * the internal buffer. * * @param value the input array. * @param size how many bytes to write * @retval 0 for success, -1 for failure */ virtual Int32 write(const UInt64 * value, Size size) = 0; /** * Write a single precision real (32 bits) into * the internal buffer. * * @param value the input real number. * @retval 0 for success, -1 for failure */ virtual Int32 write(Real32 value) = 0; /** * Write array of Real32 elements into * the internal buffer. * * @param value the input array. * @param size how many bytes to write * @retval 0 for success, -1 for failure */ virtual Int32 write(const Real32 * value, Size size) = 0; /** * Write a double precision real (64 bits) into * the internal buffer. * * @param value the input real number. * @retval 0 for success, -1 for failure */ virtual Int32 write(Real64 value) = 0; /** * Write array of Real64 elements into * the internal buffer. * * @param value the input array. * @param size how many bytes to write * @retval 0 for success, -1 for failure */ virtual Int32 write(const Real64 * value, Size size) = 0; /** * Get the size in bytes of the contents of the internal * buffer. * * @retval [Size] size in bytes of the buffer contents */ virtual Size getSize() = 0; /** * A pointer to the internal buffer. * * The buffer is guarantueed to be contiguous. * * @retval [Byte *] internal buffer */ virtual const Byte * getData() = 0; }; //--------------------------------------------------------------------------- // // I R A N G E // //--------------------------------------------------------------------------- /** * * @b Responsibility * A base interface that defines the common operations for input * and output ranges. Exposes the numer of elements (elementCount) * and the size of each element in bytes (elementSize). * * @b Rationale * Plain old reuse. both IInputRange and IOutputRange are derived * from IRange. * */ //--------------------------------------------------------------------------- struct IRange { /** * Virtual destructor. Required for abstract classes. */ virtual ~IRange() {} /** * Get the number of elements in a range * * @retval [Size] number of elements */ virtual Size getElementCount() const = 0; /** * Get the size of a single element in a range * * All elements in a range have the same size * * @retval [Size] size in bytes of a range element. */ virtual Size getElementSize() const = 0; }; //--------------------------------------------------------------------------- // // I I N P U T R A N G E // //--------------------------------------------------------------------------- /** * * @b Responsibility * The input range interface. Provides access to a couple of iterator-like * pointers to the beginning and end of the raange. The lag argument * controls the offset (from which buffer to extract the pointers). * @b Note * begin() and end() return a const Byte *. It is the responsibility of the * caller to cast it to te correct type. The memory is not suppposed to * be modified only read. */ //--------------------------------------------------------------------------- struct IInputRange : public IRange { /** * Get the beginning pointer to the range's byte array * * @retval [Byte *] pointer to internal byte array. */ virtual const Byte * begin() const = 0; /** * Get the end pointer to the range's byte array * * The end pointer is pointing to the byte immediately * following the last byte in the internal byte array * * @retval [Byte *] the end pointer of the internal byte array. */ virtual const Byte * end() const = 0; }; //--------------------------------------------------------------------------- // // I O U T P U T R A N G E // //--------------------------------------------------------------------------- /** * @b Responsibility * The output range interface. Provides access to a couple of iterator-like * pointers to the beginning and end of the raange. * * @b Note * begin() and end() return a Byte *. It is the responsibility of the * caller to cast it to te correct type. The memory can be written to of course. */ //--------------------------------------------------------------------------- struct IOutputRange : public IRange { /** * Get the beginning pointer to the range's byte array * * @retval [Byte *] pointer to internal byte array. */ virtual Byte * begin() = 0; /** * Get the end pointer to the range's byte array * * The end pointer is pointing to the byte immediately * following the last byte in the internal byte array * * @retval [Byte *] the end pointer of the internal byte array. */ virtual Byte * end() = 0; }; //--------------------------------------------------------------------------- // // I I N P U T R A N G E M A P E N T R Y // //--------------------------------------------------------------------------- /** * @b Responsibility * The input range map entry interface. Each entry has a name and an input * range iterator. That means that a whole collection on input ranges are * accessible via the same name. */ //--------------------------------------------------------------------------- struct IInputRangeMapEntry { /** * Virtual destructor. Required for abstract classes. */ virtual ~IInputRangeMapEntry() {} /** * Reset the internal pointer to point to the beginning of the input range iterator. * * The following next() will return the first IReadBuffer in the collection * or NULL if the collection is empty. Multiple consecutive calls are allowed * but have no effect. */ virtual void reset() const = 0; /** * Get the next input range in the map entry * * This method returns the input range pointed to by the internal pointer and advances * the pointer to the next input range in the map entry. If the collection is empty * or previous call to next() returned the last input range, further calls to next() * will return NULL. * * @retval [const IInputRange *] next input range or NULL */ virtual const IInputRange * next() const = 0; /** * The name of the input range */ const Byte * name; }; //--------------------------------------------------------------------------- // // I I N P U T R A N G E M A P // //--------------------------------------------------------------------------- /** * @b Responsibility * The input range map interface. Stores a collection of IInputMapRangeEntry * objects. It provides lookup by name as well an iterator * to iterate over all the entries. */ //--------------------------------------------------------------------------- struct IInputRangeMap { /** * Virtual destructor. Required for abstract classes. */ virtual ~IInputRangeMap() {} /** * Reset the internal pointer to point to the first InputRangeMap entry. * * The following next() will return the first entry in the map or NULL * if the collection is empty. Multiple consecutive calls are allowed * but have no effect. */ virtual void reset() const = 0; /** * Get the next InputRangeMap entry * * This method returns the InputRangeMap entry pointed to by the internal pointer * and advances the pointer to the next entry. If the collection is empty * or previous call to next() returned the last entry, further calls to next() * will return NULL. * * @retval [const IInputRangeMapEntry *] next map entry or NULL */ virtual const IInputRangeMapEntry * next() const = 0; /** * Get an InputRangeMap entry by name * * This method returns the InputRangeMap entry whose name matches the input name * or NULL if an entry with this name is not in the map. lookup() calls * don't affect the internal iterator pointer. * * @param [const Byte *] entry name to lookup. * @retval [const IInputRangeMapEntry *] map entry or NULL */ virtual const IInputRangeMapEntry * lookup(const Byte * name) const = 0; }; //--------------------------------------------------------------------------- // // I O U T P U T R A N G E M A P E N T R Y // //--------------------------------------------------------------------------- /** * @b Responsibility * The output range map entry is just a named output range */ //--------------------------------------------------------------------------- struct IOutputRangeMapEntry { /** * The name of the output range */ const Byte * name; /** * The output range */ IOutputRange * range; }; //--------------------------------------------------------------------------- // // I O U T P U T R A N G E M A P // //--------------------------------------------------------------------------- /** * @b Responsibility * The output range map interface. Stores pairs of output [name, range]. * It provides lookup by name as well as iterator-like * methods (begin(), end()) to iterate over all entries */ //--------------------------------------------------------------------------- struct IOutputRangeMap { /** * Virtual destructor. Required for abstract classes. */ virtual ~IOutputRangeMap() {} /** * Reset the internal pointer to point to the first OutputRangeMap entry. * * The following next() will return the first entry in the map or NULL * if the collection is empty. Multiple consecutive calls are allowed * but have no effect. */ virtual void reset() = 0; /** * Get the next OutputRangeMap entry * * This method returns the OutputRangeMap entry pointed to by the internal pointer * and advances the pointer to the next entry. If the collection is empty * or previous call to next() returned the last entry, further calls to next() * will return NULL. * * @retval [const IOutputRangeMapEntry *] next map entry or NULL */ virtual IOutputRangeMapEntry * next() = 0; /** * Get an OutputRangeMap entry by name * * This method returns the OutputRangeMap entry whose name matches the * requested name or NULL if an entry with this name is not in the map. * lookup() calls don't affect the internal iterator pointer. * * @param [const Byte *] entry name to lookup. * @retval [const IOutputRangeMapEntry *] map entry or NULL */ virtual IOutputRange * lookup(const Byte * name) = 0; }; //--------------------------------------------------------------------------- // // I I N P U T // //--------------------------------------------------------------------------- /** * @b Responsibility * The flattened input accessor. Provides easy access to the flattened input * of a node or a specific baby node within a multi-node. */ //--------------------------------------------------------------------------- struct IInput { enum {allNodes = -1}; /** * Virtual destructor. Required for abstract classes. */ virtual ~IInput() {} /** * Get the beginning pointer to the input's byte array * * @param nodeIdx [Int32] baby node index, or allNodes for entire input * @param sentinelP [Byte*] pointer to default value to insert for elements of * the node input that are outside the actual input bounds. * @retval [Byte *] pointer to internal byte array. */ virtual const Byte * begin(Int32 nodeIdx=allNodes, const Byte* sentinelP=0) = 0; /** * Get the end pointer to the input's byte array * * The end pointer is pointing to the byte immediately * following the last byte in the internal byte array * * @param nodeIdx [Int32] baby node index, or allNodes for entire input * @retval [Byte *] the end pointer of the internal byte array. */ virtual const Byte * end(Int32 nodeIdx=allNodes) = 0; /** * Get the number of elements in an input * * @param nodeIdx [Int32] baby node index, or allNodes for entire input * @retval [Size] number of elements */ virtual Size getElementCount(Int32 nodeIdx=allNodes) = 0; /** * Get the size of a single element in an input * * All elements in a range have the same size * * @retval [Size] size in bytes of a range element. */ virtual Size getElementSize() = 0; /** * Get the number of links into a specific node * * @param nodeIdx [Int32] baby node index, or allNodes for entire input * @retval [Size] number of links */ virtual Size getLinkCount(Int32 nodeIdx=allNodes) = 0; /** * Get pointer to the link boundaries * * @param nodeIdx [Int32] baby node index, or allNodes for entire input * @retval [Size] pointer to array of link boundaries */ virtual Size * getLinkBoundaries(Int32 nodeIdx=allNodes) = 0; }; //--------------------------------------------------------------------------- // // I O U T P U T // //--------------------------------------------------------------------------- /** * @b Responsibility * The easy output accessor. Provides easy access to the output * of a node or a specific baby node within a multi-node. */ //--------------------------------------------------------------------------- struct IOutput { enum {allNodes = -1}; /** * Virtual destructor. Required for abstract classes. */ virtual ~IOutput() {} /** * Get the beginning pointer to the input's byte array * * @param nodeIdx [Int32] baby node index, or allNodes for entire input * @retval [Byte *] pointer to internal byte array. */ virtual Byte * begin(Int32 nodeIdx=allNodes) = 0; /** * Get the end pointer to the input's byte array * * The end pointer is pointing to the byte immediately * following the last byte in the internal byte array * * @param nodeIdx [Int32] baby node index, or allNodes for entire input * @retval [Byte *] the end pointer of the internal byte array. */ virtual Byte * end(Int32 nodeIdx=allNodes) = 0; /** * Get the number of elements in a range * * @param nodeIdx [Int32] baby node index, or allNodes for entire input * @retval [Size] number of elements */ virtual Size getElementCount(Int32 nodeIdx=allNodes) = 0; /** * Get the size of a single element in a range * * All elements in a range have the same size * * @retval [Size] size in bytes of a range element. */ virtual Size getElementSize() = 0; }; //--------------------------------------------------------------------------- /** * @b Responsibility * Aggregate all the information a node needs for initialization. It includes * id, name, logLevel, inputs, outputs and state. This struct is passed to * INode::init() during the initialization of nodes. Note that multi-nodes * (nodes that represent multiple "baby" nodes require additional information * that is provided by the IMultiNodeInfo interface (see bellow). */ //--------------------------------------------------------------------------- struct INodeInfo { /** * Virtual destructor. Required for abstract classes. */ virtual ~INodeInfo() {} /** * Return the type of the node * * A node is created dynamically by the runtime engine based on * its type (used when registering a node type with the plugin manager). * Making this type available to the node via INodeInfo * saves the node from storing its type internally. It also ensures * that there will not be a conflict between the registered type of * a node and what the node thinks its type is. * * @retval [const Byte *] node type */ virtual const Byte * getType() = 0; /** * Return the current log level of the node * * The node should take into account the log level every time * it is about to log something. The log level can be modified * externally by the user. The node should exercise judgment * and call INodeInfo->getLogLevel() frequently * (before every log statement or at the beginning of each compute()) * * @retval [const Byte *] node type */ virtual LogLevel getLogLevel() = 0; /** * Return an object used to access the flattened input of a node. * * This method can be used to get easy access to a flattened version of any node input. * It is much easier to use than the more primitive getInputs() call which can potentially * return multiple input ranges that comprise the input. * * In addition, the IInput object allows you to easily get a pointer to the portion of * the flattened input that corresponds to any particular baby node. * * @retval [IInput *] flattened node input object */ virtual IInput * getInput(const NTA_Byte* varName) = 0; /** * Return an object used to access the output of a node. * * This method can be used to get easy access to any node output. * It is much easier to use than the more primitive getOutputs() call for multi-nodes * since it allows you to easily get a pointer to the portion of the output that * corresponds to any particular baby node. * * @retval [IOutput *] node output object */ virtual IOutput * getOutput(const NTA_Byte* varName) = 0; /** * Return the inputs of the node * * The inputs are garantueed to be persistent over the lifetime * of the node. That means that the node may call getInputs() * multiple times and will always get the same answer. * The contents of the inputs may change of course between * calls to compute(), but the number of inputs, names and all * other structural properties (including the memory area) * are all fixed. * * @retval [IInputRangeMap &] node inputs */ virtual IInputRangeMap & getInputs() = 0; /** * Return the outputs of the node * * The outputs are garantueed to be persistent over the lifetime * of the node. That means that the node may call getOutputs() * multiple times and will always get the same answer. * The contents of the outputs may change of course as the node * modifies them in compute(), but the number of outputs, names * and all other structural properties (including the memory area) * are all fixed. * * @retval [IOutputRangeMap &] node outputs */ virtual IOutputRangeMap & getOutputs() = 0; /** * Return the serialized state of the node * * The state is used to initialize a node on the runtime side * to an initial state. The initial state is created on the tools * side and stored in serialized form in the network file. * * @retval [IReadBuffer &] initial node state */ virtual IReadBuffer & getState() = 0; /** * Return the number of baby nodes in a multi-node. * * This method is only used for multi-nodes. * It returns the number of baby nodes for this multi-node. * * @retval [NTA_Size] number of baby nodes in this multi-node. */ virtual NTA_Size getMNNodeCount() = 0; /** * Return the Multi-node input list for a given input variable in a multi-node * * This method is only used for multi-nodes. * It returns a pointer to an array of NTA_IndexRangeLists's, one per baby node. Each * NTA_IndexRangeList contains a count and an array of NTA_IndexRange's. * Each NTA_IndexRange has an offset and size, specifying the offset within the * input variable 'varName', and the number of elements. * * @retval [NTA_IndexRangeList *] array of NTA_IndexRangeLists, one for each baby node */ virtual const NTA_IndexRangeList * getMNInputLists(const NTA_Byte* varName) = 0; /** * Return the Multi-node output sizes for a given output variable of a multi-node * * This method is only used for multi-nodes. * It returns a pointer to an array of sizes, one per baby node of the multi-node. * * @retval [IReadBuffer &] serialized SparseMatrix01 */ virtual const NTA_Size * getMNOutputSizes(const NTA_Byte* varName) = 0; }; //--------------------------------------------------------------------------- // // I I N P U T S I Z E M A P // //--------------------------------------------------------------------------- /** * This interface provides access to the input sizes of a node. * It contains entries and provides iterator-like accessor * as well as lookup by name accessor. */ //--------------------------------------------------------------------------- struct IInputSizeMap { virtual ~IInputSizeMap() {} virtual void reset()= 0; virtual const NTA_InputSizeMapEntry * next() = 0; virtual const NTA_InputSizeMapEntry * lookup(const Byte * name) = 0; }; //--------------------------------------------------------------------------- // // I O U T P U T S I Z E M A P // //--------------------------------------------------------------------------- /** * This interface provides access to the output sizes of a node. * It contains entries and provides iterator-like accessor * as well as lookup by name accessor. */ //--------------------------------------------------------------------------- struct IOutputSizeMap { virtual ~IOutputSizeMap() {} virtual void reset()= 0; virtual const NTA_OutputSizeMapEntry * next() = 0; virtual const NTA_OutputSizeMapEntry * lookup(const Byte * name) = 0; }; //--------------------------------------------------------------------------- // // I P A R A M E T E R M A P E N T R Y // //--------------------------------------------------------------------------- /** * @b Responsibility * The parameter map entry interface. Each entry has a name and read buffer * that contains the value of the parameter. */ //--------------------------------------------------------------------------- struct IParameterMapEntry { /** * The parameter name */ const Byte * name; /** * The parameter value */ const IReadBuffer * value; }; //--------------------------------------------------------------------------- // // I P A R A M E T E R M A P // //--------------------------------------------------------------------------- /** * @b Responsibility * The parameter map interface. Stores pairs of [name, parameter] * It provides lookup by name as well as iterator-like * methods (begin(), end()) to iterate over all entries */ //--------------------------------------------------------------------------- struct IParameterMap { /** * Virtual destructor. Required for abstract classes. */ virtual ~IParameterMap() {} /** * Reset the internal pointer to point to the first parameter entry. * * The following next() will return the first entry in the map or NULL * if the map is empty. Multiple consecutive calls are allowed * but have no effect. */ virtual void reset() const = 0; /** * Get the next parameter entry * * This method returns the parameter entry pointed to by the internal pointer * and advances the pointer to the next entry. If the collection is empty * or previous call to next() returned the last entry, further calls to next() * will return NULL. * * @retval [const IParameterMapEntry *] next map entry or NULL */ virtual const IParameterMapEntry * next() const = 0; /** * Get a parameter by name * * This method returns the parameter whose name matches the * requested name or NULL if an entry with this name is not in the map. * lookup() calls don't affect the internal iterator pointer. * * @param [const Byte *] parameter name to lookup. * @retval [const IReadBuffer *] map entry or NULL */ virtual const IReadBuffer * lookup(const Byte * name) const = 0; }; /** ------------------------------------ * * I N I T I A L S T A T E I N F O * * ------------------------------------- * * This struct contains all the Information that * NTA_CreateInitialState needs: input sizes, output sizes * and a map of the initial parameters. */ struct IInitialStateInfo { virtual ~IInitialStateInfo() {} virtual const Byte * getNodeType() = 0; virtual const IInputSizeMap & getInputSizes() = 0; virtual const IOutputSizeMap & getOutputSizes() = 0; virtual const IParameterMap & getParameters() = 0; }; // //--------------------------------------------------------------------------- // /** // * @b Responsibility // * Aggregate the additional information a multi-node needs for initialization. // * It includes the number of baby nodes and index ranges of each baby node into // * the multi-node inputs and outputs. This struct is passed to // * INode::init() during the initialization of nodes. // */ // //--------------------------------------------------------------------------- // struct IMultiNodeInfo // { // /** // * Virtual destructor. Required for abstract classes. // */ // virtual ~IMultiNodeInfo() {} // // /** // * Return the number of baby nodes in a multi-node. // * // * This method is only used for multi-nodes. // * It returns the number of baby nodes for this multi-node. // * // * @retval [NTA_Size] number of baby nodes in this multi-node. // */ // virtual NTA_Size getNodeCount() = 0; // // /** // * Return the Multi-node input list for a given input variable in a multi-node // * // * This method is only used for multi-nodes. // * It returns a pointer to an array of NTA_IndexRangeLists's, one per baby node. Each // * NTA_IndexRangeList contains a count and an array of NTA_IndexRange's. // * Each NTA_IndexRange has an offset and size, specifying the offset within the // * input variable 'varName', and the number of elements. // * // * @retval [NTA_IndexRangeList *] array of NTA_IndexRangeLists, one for each baby node // */ // virtual const NTA_IndexRangeList * getInputList(const NTA_Byte* varName) = 0; // // /** // * Return the Multi-node output sizes for a given output variable of a multi-node // * // * This method is only used for multi-nodes. // * It returns a pointer to an array of sizes, one per baby node of the multi-node. // * // * @retval [IReadBuffer &] serialized SparseMatrix01 // */ // virtual const NTA_Size * getOutputSizes(const NTA_Byte* varName) = 0; // }; inline NTA_Byte *_ReadString_alloc(NTA_UInt32 size) { return new NTA_Byte[size]; } inline void _ReadString_dealloc(NTA_Byte *p) { delete[] p; } inline std::string ReadStringFromBuffer(const IReadBuffer &buf) { NTA_Byte *value = 0; NTA_UInt32 size = 0; NTA_Int32 result = buf.readString(value, size, _ReadString_alloc, _ReadString_dealloc); if(result != 0) throw std::runtime_error("Failed to read string from stream."); std::string toReturn(value, size); // Real fps must be provided to use delete here. delete[] value; return toReturn; } } // end namespace nta #endif // NTA_OBJECT_MODEL_HPP
86d7e91ba452390e6e779aba856a949efad2689e
02847e4a028fa921751a2372e21ee55e79dcec39
/test-core/src/unittest_transaction.cpp
aef52e90f55432faafdd20ea35b3ffc464034a8f
[ "BSL-1.0" ]
permissive
KouOuchi/ObjectGenoise
369c6b831980372fc0638cee114868f944b5d71a
aac02e7677d9db201e291ae284684cfc849d06d8
refs/heads/master
2023-06-25T17:51:49.192757
2023-06-10T13:55:31
2023-06-10T13:55:31
33,002,868
2
0
null
null
null
null
UTF-8
C++
false
false
11,050
cpp
unittest_transaction.cpp
#include "fixtures.h" #include "utility.h" #ifdef TEST_OG_TRAN BOOST_FIXTURE_TEST_SUITE(tran, fixture_clean_session); BOOST_AUTO_TEST_CASE( transaction_1000 ) { #ifdef _WINDOWS og::core::CrtCheckMemory __check__; #endif // initialize db og::og_session cleaned_session_; cleaned_session_.open(DBPATH); cleaned_session_.purge(); cleaned_session_.schema()->purge(); string OTYPE1 = "type_session_1002_1"; string ONAME1 = "name_session_1002_1"; string OTYPE2 = "type_session_1002_2"; string ONAME2 = "name_session_1002_2"; string RELTYPE = "reltype_session_1002"; string RELNAME = "relnamee_session_1002"; list<string> otype_list1; otype_list1.push_back(OTYPE1); list<string> oname_list1; oname_list1.push_back(ONAME1); list<string> otype_list2; otype_list2.push_back(OTYPE2); list<string> oname_list2; oname_list2.push_back(ONAME2); list<string> reltype_list; reltype_list.push_back(RELTYPE); list<string> relname_list; relname_list.push_back(RELNAME); string id; { // create transaction og::og_transaction tran(cleaned_session_); // create schema obj og::og_schema_object_ptr schm_obj1 = cleaned_session_.schema()->create_object(OTYPE1, ONAME1); id = schm_obj1->get_id(); schm_obj1->set_comment("aaa"); og::og_schema_object_ptr schm_obj2 = cleaned_session_.schema()->create_object(OTYPE2, ONAME2); // connect schm_obj1->connect_to(schm_obj2, RELTYPE); tran.commit(); } { // check optional<og::og_schema_object_ptr> schm_obj1 = cleaned_session_.schema()->get_object( id); BOOST_REQUIRE(schm_obj1.is_initialized()); list<og::og_schema_object_ptr> schm_children; schm_obj1.get()->get_connected_object_to(reltype_list, &schm_children); BOOST_REQUIRE(schm_children.size() == 1); BOOST_REQUIRE_EQUAL(schm_obj1->get()->get_comment(), "aaa"); } } BOOST_AUTO_TEST_CASE( transaction_1001 ) { #ifdef _WINDOWS og::core::CrtCheckMemory __check__; #endif // initialize db og::og_session cleaned_session_; cleaned_session_.open(DBPATH); cleaned_session_.purge(); cleaned_session_.schema()->purge(); string OTYPE1 = "type_session_1002_1"; string ONAME1 = "name_session_1002_1"; string OTYPE2 = "type_session_1002_2"; string ONAME2 = "name_session_1002_2"; string RELTYPE = "reltype_session_1002"; string RELNAME = "relnamee_session_1002"; list<string> otype_list1; otype_list1.push_back(OTYPE1); list<string> oname_list1; oname_list1.push_back(ONAME1); list<string> otype_list2; otype_list2.push_back(OTYPE2); list<string> oname_list2; oname_list2.push_back(ONAME2); list<string> reltype_list; reltype_list.push_back(RELTYPE); list<string> relname_list; relname_list.push_back(RELNAME); string id; string child_id; { // create transaction og::og_transaction tran(cleaned_session_); // create schema obj og::og_schema_object_ptr schm_obj1 = cleaned_session_.schema()->create_object(OTYPE1, ONAME1); schm_obj1->set_comment("aaa"); id = schm_obj1->get_id(); og::og_schema_object_ptr schm_obj2 = cleaned_session_.schema()->create_object(OTYPE2, ONAME2); // connect schm_obj1->connect_to(schm_obj2, RELTYPE); child_id = schm_obj2->get_id(); } { // check optional<og::og_schema_object_ptr> schm_obj1 = cleaned_session_.schema()->get_object( id); BOOST_REQUIRE(!schm_obj1.is_initialized()); optional<og::og_schema_object_ptr> schm_obj2 = cleaned_session_.schema()->get_object( child_id); BOOST_REQUIRE(!schm_obj2.is_initialized()); } } // parameter and transaction BOOST_AUTO_TEST_CASE(transaction_1002) { #ifdef _WINDOWS og::core::CrtCheckMemory __check__; #endif // initialize db og::og_session cleaned_session_; cleaned_session_.open(DBPATH); cleaned_session_.purge(); cleaned_session_.schema()->purge(); string OTYPE1 = "Document2002from"; string OTYPE2 = "Document2002to"; string RELTYPE = "Document2002rel"; string ONAME = "Dcument-Name2002"; list<string> otype_list; otype_list.push_back(OTYPE1); otype_list.push_back(OTYPE2); list<string> rel_type_list; rel_type_list.push_back(RELTYPE); og::og_schema_object_ptr p1 = cleaned_session_.schema()->create_object(OTYPE1, ONAME); og::og_schema_object_ptr p2 = cleaned_session_.schema()->create_object(OTYPE2, ONAME); og::og_schema_relation_ptr rel_ptr = p1->connect_to(p2, RELTYPE); og::core::parameter_basetype_real type1; type1.default_value_ = 1.414; type1.warn_max_ = 3; type1.system_max_ = 3; type1.warn_min_ = 1; type1.system_min_ = 1; og::core::parameter_basetype_real type2; type2.default_value_ = 2.236; type2.warn_max_ = 3; type2.system_max_ = 3; type2.warn_min_ = 1; type2.system_min_ = 1; og::og_schema_parameter_ptr ptest1 = cleaned_session_.schema()->create_parameter("hoge_type1", "comment1", &type1); og::og_schema_parameter_ptr ptest2 = cleaned_session_.schema()->create_parameter("hoge_type2", "comment2", &type2, 3, 2, 4); BOOST_REQUIRE_EQUAL(ptest1->get_comment(), "comment1"); BOOST_REQUIRE_EQUAL(ptest1->get_type(), "hoge_type1"); BOOST_REQUIRE_EQUAL(ptest2->get_comment(), "comment2"); BOOST_REQUIRE_EQUAL(ptest2->get_type(), "hoge_type2"); list<boost::tuple<string, og::og_schema_parameter_ptr>> param_name_types0; p1->get_parameters(&param_name_types0); BOOST_REQUIRE_EQUAL(param_name_types0.size(), 0); // apply parameter to schema_object p1->add_parameter_definition("H1", ptest1); p1->add_parameter_definition("H2", ptest2); // apply parameter to schema_relation rel_ptr->add_parameter_definition("H3", ptest1); rel_ptr->add_parameter_definition("H4", ptest2); // session object test (explicit) { og::og_transaction tran(cleaned_session_); og::og_session_object_ptr o1 = cleaned_session_.create_object(p1); //o1->sync(); std::string oid = o1->get_id(); tran.rollback(); optional<og::og_session_object_ptr> o1_2 = cleaned_session_.get_object(oid); // confirm rollback(discard object creation) BOOST_REQUIRE_EQUAL(o1_2.is_initialized(), false); } // session object test (implicit) { og::og_session_object_ptr o1 = cleaned_session_.create_object(p1); string oid(o1->get_id()); { og::og_transaction tran(cleaned_session_); o1->set_parameter_value<double>("H1", 1.1234); o1->set_comment("aaa"); } // rollback { optional<og::og_session_object_ptr> o1_2 = cleaned_session_.get_object(oid); BOOST_REQUIRE_EQUAL(o1_2.is_initialized(), true); double h1; o1_2.get()->get_parameter_value<double>("H2", &h1); // confirm rollback BOOST_REQUIRE_EQUAL(h1, 2.236); BOOST_REQUIRE_EQUAL(o1_2.get()->get_comment(), ""); } } // session object test (commit) { og::og_session_object_ptr o1 = cleaned_session_.create_object(p1); string oid(o1->get_id()); { og::og_transaction tran(cleaned_session_); o1->set_parameter_value<double>("H1", 1.1234); o1->set_comment("aaa"); tran.commit(); } // commit; { optional<og::og_session_object_ptr> o1_2 = cleaned_session_.get_object(oid); BOOST_REQUIRE_EQUAL(o1_2.is_initialized(), true); double h1; o1_2.get()->get_parameter_value<double>("H2", &h1); // confirm commit BOOST_REQUIRE_EQUAL(h1, 2.236); BOOST_REQUIRE_EQUAL(o1_2.get()->get_comment(), "aaa"); } } // session relation test (explicit) { og::og_session_object_ptr o1 = cleaned_session_.create_object(p1); og::og_session_object_ptr o2 = cleaned_session_.create_object(p2); og::og_transaction tran(cleaned_session_); og::og_session_relation_ptr o1o2 = o1->connect_to(o2, RELTYPE); string relid(o1o2->get_id()); tran.rollback(); list<og::og_session_object_ptr> connected; o1->get_connected_object(&connected); BOOST_REQUIRE_EQUAL(connected.size(), 0); } // session relation test (implicit) { og::og_session_object_ptr o1 = cleaned_session_.create_object(p1); og::og_session_object_ptr o2 = cleaned_session_.create_object(p2); { og::og_transaction tran(cleaned_session_); og::og_session_relation_ptr o1o2 = o1->connect_to(o2, RELTYPE); string relid(o1o2->get_id()); } //implicit rollback; list<og::og_session_object_ptr> connected; o1->get_connected_object(&connected); BOOST_REQUIRE_EQUAL(connected.size(), 0); } // session relation test (explicit) { og::og_session_object_ptr o1 = cleaned_session_.create_object(p1); og::og_session_object_ptr o2 = cleaned_session_.create_object(p2); og::og_transaction tran(cleaned_session_); og::og_session_relation_ptr o1o2 = o1->connect_to(o2, RELTYPE); string relid(o1o2->get_id()); o1o2->set_comment("aaa"); //o1o2->sync(); tran.commit(); list<og::og_session_object_ptr> connected; o1->get_connected_object(&connected); BOOST_REQUIRE_EQUAL(connected.size(), 1); BOOST_REQUIRE_EQUAL(o1o2.get()->get_comment(), "aaa"); } // session object test (implicit) { og::og_session_object_ptr o1 = cleaned_session_.create_object(p1); og::og_session_object_ptr o2 = cleaned_session_.create_object(p2); og::og_session_relation_ptr o1o2 = o1->connect_to(o2, RELTYPE); string relid(o1o2->get_id()); { og::og_transaction tran(cleaned_session_); o1o2->set_parameter_value<double>("H3", 2.2345); //o1o2->sync(); tran.rollback(); } // explicit rollback { double h1; optional<og::og_session_relation_ptr> o1o2_2 = cleaned_session_.get_relation(relid); o1o2_2.get()->get_parameter_value<double>("H3", &h1); // confirm rollback BOOST_REQUIRE_EQUAL(h1, 1.414); } { og::og_transaction tran(cleaned_session_); o1o2->set_parameter_value<double>("H3", 2.2345); //o1o2->sync(); } // implicit rollback { double h1; optional<og::og_session_relation_ptr> o1o2_2 = cleaned_session_.get_relation(relid); o1o2_2.get()->get_parameter_value<double>("H3", &h1); // confirm rollback BOOST_REQUIRE_EQUAL(h1, 1.414); } { og::og_transaction tran(cleaned_session_); o1o2->set_parameter_value<double>("H3", 1.1234); //o1o2->sync(); tran.commit(); } // commit; { double h1; o1o2.get()->get_parameter_value<double>("H3", &h1); // confirm commit BOOST_REQUIRE_EQUAL(h1, 1.1234); } } } BOOST_AUTO_TEST_SUITE_END() #endif
65a2acd653a46351b8f9daf70fdb75630229815c
c5a7ebf02eb2c4d6064670f0e490df64a8a0e7d4
/Omnibot/include/Threads/pthread_PooledThread.h
184d380b7538a8133b34565796b5547231187402
[]
no_license
thechairman/Omnibot
7e7bc20ada2ce13706dcbef833b66987163a862e
2088fe11072d4d064cca49e47493a6e78aa5a2c2
refs/heads/master
2021-01-17T15:37:43.358876
2015-04-02T02:13:54
2015-04-02T02:13:54
2,949,138
2
3
null
2014-08-17T21:31:01
2011-12-09T18:29:36
C++
UTF-8
C++
false
false
878
h
pthread_PooledThread.h
#ifndef _H_PTHREAD_POOLEDTHREAD_ #define _H_PTHREAD_POOLEDTHREAD_ #include <pthread.h> #include <semaphore.h> #include <deque> #include "OmniPooledThread.h" #include "OmniThreadTypes.h" class pthread_PooledThread: public OmniPooledThread { public: pthread_PooledThread(); ~pthread_PooledThread(); int start(); int stop(); int join(); int addTask(OmniThreadedClass*, OmniThreadedClass::Mode); bool isHeld(); int id(); OmniThreadStatus status(); private: void* workFucntion(void*); static const unsigned int POLL_INTERVAL = 5000; OmniThreadMode _mode; bool _started; bool _running; bool _idle; bool _held; int _id; sem_t _taskSem; pthread_t _thread; std::deque<std::pair<OmniThreadedClass*, OmniThreadedClass::Mode>* > _tasks; static void* workFunction(void*); bool initThread(); friend class pthread_ThreadPool; }; #endif
b5e9c19ede026e9fa03664e82ba6036479597c46
a0b0eb383ecfeaeed3d2b0271657a0c32472bf8e
/codeforces/1427B.cpp
867bd654a7283b5d255ea051be59639086c1606f
[ "Apache-2.0" ]
permissive
tangjz/acm-icpc
45764d717611d545976309f10bebf79c81182b57
f1f3f15f7ed12c0ece39ad0dd044bfe35df9136d
refs/heads/master
2023-04-07T10:23:07.075717
2022-12-24T15:30:19
2022-12-26T06:22:53
13,367,317
53
20
Apache-2.0
2022-12-26T06:22:54
2013-10-06T18:57:09
C++
UTF-8
C++
false
false
1,519
cpp
1427B.cpp
#include <bits/stdc++.h> using namespace std; typedef unsigned int UL; typedef long long LL; typedef unsigned long long ULL; typedef double DB; typedef long double LD; const int mod = (int)1e9 + 7, maxd = 10, maxc = 26; const int maxn = (int)3e5 + 1, maxm = (int)2e6 + 1; const DB eps = 1e-9, pi = acos((DB)-1); inline int sgn(DB x) { return (x > eps) - (x < -eps); } void solve() { int n, m; static char buf[maxn]; scanf("%d%d%s", &n, &m, buf); int ans = 0, tot = 0; static pair<int, int> arr[maxn]; for(int i = 0, j; i < n; ) { if(buf[i] == 'W') { ++ans; if(i > 0 && buf[i - 1] == 'W') ++ans; ++i; continue; } for(j = i; j < n && buf[j] != 'W'; ++j); int fir = (i > 0) + (j < n); int sec = j - i; // printf("%d %d: %d %d\n", i, j, fir, sec); arr[tot++] = {-fir, sec}; i = j; } // full: 2t+1 // half: 2t // none: 2t-1 if(tot == 1 && !arr[0].first) { // none int adt = min(arr[0].second, m); if(adt > 0) ans += adt + adt - 1; } else { sort(arr, arr + tot); int rem = 0; for(int i = 0; i < tot; ++i) { int fir = -arr[i].first; int sec = arr[i].second; if(m >= sec) { // full or half // printf("%d %d\n", fir, sec); ans += sec + sec - 1 + fir; m -= sec; } else { rem += sec; } } // half int adt = min(rem, m); if(adt > 0) ans += adt + adt; } printf("%d\n", ans); } int main() { int T = 1; scanf("%d", &T); for(int Case = 1; Case <= T; ++Case) { // printf("Case #%d: ", Case); solve(); } return 0; }
2e5a89096d0455654ad297fc166749206b4e9a7a
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/odephysics/nodebodynode_cmds.cc
f8f4f8e0395b2ff8e916c4f495507ee8bcb389f3
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
38,530
cc
nodebodynode_cmds.cc
#define N_IMPLEMENTS nOdeBodyNode //------------------------------------------------------------------------------ // (c) 2003 Vadim Macagon // // nOdeBodyNode is licensed under the terms of the Nebula License. //------------------------------------------------------------------------------ #include "odephysics/nodebodynode.h" #include "kernel/npersistserver.h" #include "mathlib/vector.h" static void n_initbody( void* slf, nCmd* cmd ); static void n_setautocleanup( void* slf, nCmd* cmd ); static void n_getautocleanup( void* slf, nCmd* cmd ); static void n_setrotation( void* slf, nCmd* cmd ); static void n_getrotation( void* slf, nCmd* cmd ); static void n_setposition( void* slf, nCmd* cmd ); static void n_getposition( void* slf, nCmd* cmd ); static void n_setlinearvel( void* slf, nCmd* cmd ); static void n_getlinearvel( void* slf, nCmd* cmd ); static void n_setangularvel( void* slf, nCmd* cmd ); static void n_getangularvel( void* slf, nCmd* cmd ); static void n_addforce( void* slf, nCmd* cmd ); static void n_addtorque( void* slf, nCmd* cmd ); static void n_addrelforce( void* slf, nCmd* cmd ); static void n_addreltorque( void* slf, nCmd* cmd ); static void n_addforceatpos( void* slf, nCmd* cmd ); static void n_addforceatrelpos( void* slf, nCmd* cmd ); static void n_addrelforceatpos( void* slf, nCmd* cmd ); static void n_addrelforceatrelpos( void* slf, nCmd* cmd ); static void n_getforce( void* slf, nCmd* cmd ); static void n_gettorque( void* slf, nCmd* cmd ); static void n_setforce( void* slf, nCmd* cmd ); static void n_settorque( void* slf, nCmd* cmd ); static void n_getrelpointpos( void* slf, nCmd* cmd ); static void n_getrelpointvel( void* slf, nCmd* cmd ); static void n_getpointvel( void* slf, nCmd* cmd ); static void n_getposrelpoint( void* slf, nCmd* cmd ); static void n_vectortoworld( void* slf, nCmd* cmd ); static void n_vectorfromworld( void* slf, nCmd* cmd ); static void n_enable( void* slf, nCmd* cmd ); static void n_isenabled( void* slf, nCmd* cmd ); static void n_setfiniterotationmode( void* slf, nCmd* cmd ); static void n_getfiniterotationmode( void* slf, nCmd* cmd ); static void n_setfiniterotationaxis( void* slf, nCmd* cmd ); static void n_getfiniterotationaxis( void* slf, nCmd* cmd ); static void n_getnumjoints( void* slf, nCmd* cmd ); static void n_enablegravity( void* slf, nCmd* cmd ); static void n_isgravityenabled( void* slf, nCmd* cmd ); static void n_connectedto( void* slf, nCmd* cmd ); static void n_connectedtoex( void* slf, nCmd* cmd ); static void n_setmasstotal( void* slf, nCmd* cmd ); static void n_getmasstotal( void* slf, nCmd* cmd ); static void n_setmasscog( void* slf, nCmd* cmd ); static void n_getmasscog( void* slf, nCmd* cmd ); static void n_setmassinertia( void* slf, nCmd* cmd ); static void n_getmassinertia( void* slf, nCmd* cmd ); static void n_copymass( void* slf, nCmd* cmd ); #ifdef ODE_STEPFAST_AUTO_DISABLE static void n_setautodisablethreshold( void* slf, nCmd* cmd ); static void n_getautodisablethreshold( void* slf, nCmd* cmd ); static void n_setautodisablesteps( void* slf, nCmd* cmd ); static void n_getautodisablesteps( void* slf, nCmd* cmd ); static void n_setautodisable( void* slf, nCmd* cmd ); static void n_getautodisable( void* slf, nCmd* cmd ); #endif // ODE_STEPFAST_AUTO_DISABLE //------------------------------------------------------------------------------ /** @scriptclass nodebodynode @superclass nroot @classinfo Provides script access to ODE bodies. */ void n_initcmds( nClass* clazz ) { clazz->BeginCmds(); clazz->AddCmd( "v_initbody_s", 'IB__', n_initbody ); clazz->AddCmd( "v_setautocleanup_b", 'SAC_', n_setautocleanup ); clazz->AddCmd( "b_getautocleanup_v", 'GAC_', n_getautocleanup ); clazz->AddCmd( "v_setrotation_ffff", 'SRQ_', n_setrotation ); clazz->AddCmd( "ffff_getrotation_v", 'GRQ_', n_getrotation ); clazz->AddCmd( "v_setposition_fff", 'SP__', n_setposition ); clazz->AddCmd( "fff_getposition_v", 'GP__', n_getposition ); clazz->AddCmd( "v_setlinearvel_fff", 'SLV_', n_setlinearvel ); clazz->AddCmd( "fff_getlinearvel_v", 'GLV_', n_getlinearvel ); clazz->AddCmd( "v_setangularvel_fff", 'SAV_', n_setangularvel ); clazz->AddCmd( "fff_getangularvel_v", 'GAV_', n_getangularvel ); clazz->AddCmd( "v_addforce_fff", 'AF__', n_addforce ); clazz->AddCmd( "v_addtorque_fff", 'AT__', n_addtorque ); clazz->AddCmd( "v_addrelforce_fff", 'ARF_', n_addrelforce ); clazz->AddCmd( "v_addreltorque_fff", 'ART_', n_addreltorque ); clazz->AddCmd( "v_addforceatpos_ffffff", 'AFAP', n_addforceatpos ); clazz->AddCmd( "v_addforceatrelpos_ffffff", 'AFRP', n_addforceatrelpos ); clazz->AddCmd( "v_addrelforceatpos_ffffff", 'ARFP', n_addrelforceatpos ); clazz->AddCmd( "v_addrelforceatrelpos_ffffff", 'RFRP', n_addrelforceatrelpos ); clazz->AddCmd( "fff_getforce_v", 'GF__', n_getforce ); clazz->AddCmd( "fff_gettorque_v", 'GT__', n_gettorque ); clazz->AddCmd( "v_setforce_fff", 'SF__', n_setforce ); clazz->AddCmd( "v_settorque_fff", 'ST__', n_settorque ); clazz->AddCmd( "fff_getrelpointpos_fff", 'GRPP', n_getrelpointpos ); clazz->AddCmd( "fff_getrelpointvel_fff", 'GRPV', n_getrelpointvel ); clazz->AddCmd( "fff_getpointvel_fff", 'GPV_', n_getpointvel ); clazz->AddCmd( "fff_getposrelpoint_fff", 'GPRP', n_getposrelpoint ); clazz->AddCmd( "fff_vectortoworld_fff", 'VTW_', n_vectortoworld ); clazz->AddCmd( "fff_vectorfromworld_fff", 'VFW_', n_vectorfromworld ); clazz->AddCmd( "v_enable_b", 'E___', n_enable ); clazz->AddCmd( "b_isenabled_v", 'IE__', n_isenabled ); clazz->AddCmd( "v_setfiniterotationmode_i", 'SFRM', n_setfiniterotationmode ); clazz->AddCmd( "i_getfiniterotationmode_v", 'GFRM', n_getfiniterotationmode ); clazz->AddCmd( "v_setfiniterotationaxis_fff", 'SFRA', n_setfiniterotationaxis ); clazz->AddCmd( "fff_getfiniterotationaxis_v", 'GFRA', n_getfiniterotationaxis ); clazz->AddCmd( "i_getnumjoints_v", 'GNJ_', n_getnumjoints ); clazz->AddCmd( "v_enablegravity_b", 'EG__', n_enablegravity ); clazz->AddCmd( "b_isgravityenabled_v", 'IGE_', n_isgravityenabled ); clazz->AddCmd( "b_connectedto_s", 'CT__', n_connectedto ); clazz->AddCmd( "b_connectedtoex_si", 'CTE_', n_connectedtoex ); clazz->AddCmd( "v_setmasstotal_f", 'SMT_', n_setmasstotal ); clazz->AddCmd( "f_getmasstotal_v", 'GMT_', n_getmasstotal ); clazz->AddCmd( "v_setmasscog_fff", 'SMCG', n_setmasscog ); clazz->AddCmd( "fff_getmasscog_v", 'GMCG', n_getmasscog ); clazz->AddCmd( "v_setmassinertia_ffffff", 'SMI_', n_setmassinertia ); clazz->AddCmd( "ffffff_getmassinertia_v", 'GMI_', n_getmassinertia ); clazz->AddCmd( "v_copymass_s", 'CPYM', n_copymass ); #ifdef ODE_STEPFAST_AUTO_DISABLE clazz->AddCmd( "v_setautodisablethreshold_f", 'SADT', n_setautodisablethreshold ); clazz->AddCmd( "f_getautodisablethreshold_v", 'GADT', n_getautodisablethreshold ); clazz->AddCmd( "v_setautodisablesteps_i", 'SADS', n_setautodisablesteps ); clazz->AddCmd( "i_getautodisablesteps_v", 'GADS', n_getautodisablesteps ); clazz->AddCmd( "v_setautodisable_b", 'SAD_', n_setautodisable ); clazz->AddCmd( "b_getautodisable_v", 'GAD_', n_getautodisable ); #endif // ODE_STEPFAST_AUTO_DISABLE clazz->EndCmds(); } //------------------------------------------------------------------------------ /** @cmd initbody @input s(PhysicsContext) @output v @info Initialise the body, must be called before trying to use any of the other commands. */ static void n_initbody( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; self->InitBody( cmd->In()->GetS() ); } //------------------------------------------------------------------------------ /** @cmd setautocleanup @input b(True/False) @output v @info If enabled the lightweight C++ body will be destroyed along with the node. This is enabled by default. */ static void n_setautocleanup( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; self->SetAutoCleanup( cmd->In()->GetB() ); } //------------------------------------------------------------------------------ /** @cmd getautocleanup @input v @output b(True/False) @info Check if the lightweight C++ instance will be destroyed along with the node. */ static void n_getautocleanup( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; cmd->Out()->SetB( self->GetAutoCleanup() ); } //------------------------------------------------------------------------------ /** @cmd setrotation @input f(q.x), f(q.y), f(q.z), f(q.w) @output v @info Set the rotation of the body to the provided quaternion. */ static void n_setrotation( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); float w = cmd->In()->GetF(); self->GetBody()->SetRotation( quaternion(x, y, z, w) ); } //------------------------------------------------------------------------------ /** @cmd getrotation @input v @output f(q.x), f(q.y), f(q.z), f(q.w) @info Get rotation of the body as a quaternion. */ static void n_getrotation( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; quaternion q; self->GetBody()->GetRotation( &q ); cmd->Out()->SetF( q.x ); cmd->Out()->SetF( q.y ); cmd->Out()->SetF( q.z ); cmd->Out()->SetF( q.w ); } //------------------------------------------------------------------------------ /** @cmd setposition @input f(x), f(y), f(z) @output v @info Set the position of the body. */ static void n_setposition( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); self->GetBody()->SetPosition( vector3(x, y, z) ); } //------------------------------------------------------------------------------ /** @cmd getposition @input v @output f(x), f(y), f(z) @info Get the position of the body. */ static void n_getposition( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; vector3 pos; self->GetBody()->GetPosition( &pos ); cmd->Out()->SetF( pos.x ); cmd->Out()->SetF( pos.y ); cmd->Out()->SetF( pos.z ); } //------------------------------------------------------------------------------ /** @cmd setlinearvel @input f(x), f(y), f(z) @output v @info Set linear velocity of the body. */ static void n_setlinearvel( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); self->GetBody()->SetLinearVel( vector3(x, y, z) ); } //------------------------------------------------------------------------------ /** @cmd getlinearvel @input v @output f(x), f(y), f(z) @info Get the linear velocity of the body. */ static void n_getlinearvel( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; vector3 vel; self->GetBody()->GetLinearVel( &vel ); cmd->Out()->SetF( vel.x ); cmd->Out()->SetF( vel.y ); cmd->Out()->SetF( vel.z ); } //------------------------------------------------------------------------------ /** @cmd setangularvel @input f(x), f(y), f(z) @output v @info Set the angular velocity of the body. */ static void n_setangularvel( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); self->GetBody()->SetAngularVel( vector3(x, y, z) ); } //------------------------------------------------------------------------------ /** @cmd getangularvel @input v @output f(x), f(y), f(z) @info Get the angular velocity of the body. */ static void n_getangularvel( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; vector3 vel; self->GetBody()->GetAngularVel( &vel ); cmd->Out()->SetF( vel.x ); cmd->Out()->SetF( vel.y ); cmd->Out()->SetF( vel.z ); } //------------------------------------------------------------------------------ /** @cmd addforce @input f(fx), f(fy), f(fz) @output v @info See ODE manual. (dBodyAddForce) */ static void n_addforce( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); self->GetBody()->AddForce( vector3(x, y, z) ); } //------------------------------------------------------------------------------ /** @cmd addtorque @input f(fx), f(fy), f(fz) @output v @info See ODE manual. (dBodyAddTorque) */ static void n_addtorque( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); self->GetBody()->AddTorque( vector3(x, y, z) ); } //------------------------------------------------------------------------------ /** @cmd addrelforce @input f(fx), f(fy), f(fz) @output v @info See ODE manual. (dBodyAddRelForce) */ static void n_addrelforce( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); self->GetBody()->AddRelForce( vector3(x, y, z) ); } //------------------------------------------------------------------------------ /** @cmd addreltorque @input f(fx), f(fy), f(fz) @output v @info See ODE manual. (dBodyAddRelTorque) */ static void n_addreltorque( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); self->GetBody()->AddRelTorque( vector3(x, y, z) ); } //------------------------------------------------------------------------------ /** @cmd addforceatpos @input f(fx), f(fy), f(fz), f(px), f(py), f(pz) @output v @info See ODE manual. (dBodyAddForceAtPos) */ static void n_addforceatpos( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float fx = cmd->In()->GetF(); float fy = cmd->In()->GetF(); float fz = cmd->In()->GetF(); float px = cmd->In()->GetF(); float py = cmd->In()->GetF(); float pz = cmd->In()->GetF(); self->GetBody()->AddForceAtPos( vector3(fx, fy, fz), vector3( px, py, pz ) ); } //------------------------------------------------------------------------------ /** @cmd addforceatrelpos @input f(fx), f(fy), f(fz), f(px), f(py), f(pz) @output v @info See ODE manual. (dBodyAddForceAtRelPos) */ static void n_addforceatrelpos( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float fx = cmd->In()->GetF(); float fy = cmd->In()->GetF(); float fz = cmd->In()->GetF(); float px = cmd->In()->GetF(); float py = cmd->In()->GetF(); float pz = cmd->In()->GetF(); self->GetBody()->AddForceAtRelPos( vector3(fx, fy, fz), vector3(px, py, pz) ); } //------------------------------------------------------------------------------ /** @cmd addrelforceatpos @input f(fx), f(fy), f(fz), f(px), f(py), f(pz) @output v @info See ODE manual. (dBodyAddRelForceAtPos) */ static void n_addrelforceatpos( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float fx = cmd->In()->GetF(); float fy = cmd->In()->GetF(); float fz = cmd->In()->GetF(); float px = cmd->In()->GetF(); float py = cmd->In()->GetF(); float pz = cmd->In()->GetF(); self->GetBody()->AddRelForceAtPos( vector3(fx, fy, fz), vector3(px, py, pz) ); } //------------------------------------------------------------------------------ /** @cmd addrelforceatrelpos @input f(fx), f(fy), f(fz), f(px), f(py), f(pz) @output v @info See ODE manual. (dBodyAddRelForceAtRelPos) */ static void n_addrelforceatrelpos( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float fx = cmd->In()->GetF(); float fy = cmd->In()->GetF(); float fz = cmd->In()->GetF(); float px = cmd->In()->GetF(); float py = cmd->In()->GetF(); float pz = cmd->In()->GetF(); self->GetBody()->AddRelForceAtRelPos( vector3(fx, fy, fz), vector3(px, py, pz) ); } //------------------------------------------------------------------------------ /** @cmd getforce @input v @output f(fx), f(fy), f(fz) @info Get the accumulated force vector for the body. */ static void n_getforce( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; vector3 f; self->GetBody()->GetForce( &f ); cmd->Out()->SetF( f.x ); cmd->Out()->SetF( f.y ); cmd->Out()->SetF( f.z ); } //------------------------------------------------------------------------------ /** @cmd gettorque @input v @output f(fx), f(fy), f(fz) @info Get the accumulated torque vector for the body. */ static void n_gettorque( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; vector3 f; self->GetBody()->GetTorque( &f ); cmd->Out()->SetF( f.x ); cmd->Out()->SetF( f.y ); cmd->Out()->SetF( f.z ); } //------------------------------------------------------------------------------ /** @cmd setforce @input f(fx), f(fy), f(fz) @output v @info Set the accumulated force vector for the body. */ static void n_setforce( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float fx = cmd->In()->GetF(); float fy = cmd->In()->GetF(); float fz = cmd->In()->GetF(); self->GetBody()->SetForce( vector3(fx, fy, fz) ); } //------------------------------------------------------------------------------ /** @cmd settorque @input f(fx), f(fy), f(fz) @output v @info Set the accumulated torque vector for the body. */ static void n_settorque( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float fx = cmd->In()->GetF(); float fy = cmd->In()->GetF(); float fz = cmd->In()->GetF(); self->GetBody()->SetTorque( vector3(fx, fy, fz) ); } //------------------------------------------------------------------------------ /** @cmd getrelpointpos @input f(BodyRelativeX), f(BodyRelativeY), f(BodyRelativeZ) @output f(GlobalX), f(GlobalY), f(GlobalZ) @info See ODE manual. (dBodyGetRelPointPos) */ static void n_getrelpointpos( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float brx = cmd->In()->GetF(); float bry = cmd->In()->GetF(); float brz = cmd->In()->GetF(); vector3 res; self->GetBody()->GetRelPointPos( vector3(brx, bry, brz), &res ); cmd->Out()->SetF( res.x ); cmd->Out()->SetF( res.y ); cmd->Out()->SetF( res.z ); } //------------------------------------------------------------------------------ /** @cmd getrelpointvel @input f(BodyRelativeX), f(BodyRelativeY), f(BodyRelativeZ) @output f(GlobalVelX), f(GlobalVelY), f(GlobalVelZ) @info See ODE manual. (dBodyGetRelPointVel) */ static void n_getrelpointvel( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float brx = cmd->In()->GetF(); float bry = cmd->In()->GetF(); float brz = cmd->In()->GetF(); vector3 res; self->GetBody()->GetRelPointVel( vector3(brx, bry, brz), &res ); cmd->Out()->SetF( res.x ); cmd->Out()->SetF( res.y ); cmd->Out()->SetF( res.z ); } //------------------------------------------------------------------------------ /** @cmd getpointvel @input f(GlobalX), f(GlobalY), f(GlobalZ) @output f(GlobalVelX), f(GlobalVelY), f(GlobalVelZ) @info See ODE manual. (dBodyGetPointVel) */ static void n_getpointvel( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float gx = cmd->In()->GetF(); float gy = cmd->In()->GetF(); float gz = cmd->In()->GetF(); vector3 res; self->GetBody()->GetPointVel( vector3(gx, gy, gz), &res ); cmd->Out()->SetF( res.x ); cmd->Out()->SetF( res.y ); cmd->Out()->SetF( res.z ); } //------------------------------------------------------------------------------ /** @cmd getposrelpoint @input f(GlobalX), f(GlobalY), f(GlobalZ) @output f(BodyRelativeX), f(BodyRelativeY), f(BodyRelativeZ) @info See ODE manual. (dBodyGetPosRelPoint) */ static void n_getposrelpoint( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float gx = cmd->In()->GetF(); float gy = cmd->In()->GetF(); float gz = cmd->In()->GetF(); vector3 res; self->GetBody()->GetPosRelPoint( vector3(gx, gy, gz), &res ); cmd->Out()->SetF( res.x ); cmd->Out()->SetF( res.y ); cmd->Out()->SetF( res.z ); } //------------------------------------------------------------------------------ /** @cmd vectortoworld @input f(BodyRelativeX), f(BodyRelativeY), f(BodyRelativeZ) @output f(GlobalX), f(GlobalY), f(GlobalZ) @info Transform a vector expressed in the body coordinate system to the global/world coordinate system. */ static void n_vectortoworld( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float brx = cmd->In()->GetF(); float bry = cmd->In()->GetF(); float brz = cmd->In()->GetF(); vector3 res; self->GetBody()->VectorToWorld( vector3(brx, bry, brz), &res ); cmd->Out()->SetF( res.x ); cmd->Out()->SetF( res.y ); cmd->Out()->SetF( res.z ); } //------------------------------------------------------------------------------ /** @cmd vectorfromworld @input f(GlobalX), f(GlobalY), f(GlobalZ) @output f(BodyRelativeX), f(BodyRelativeY), f(BodyRelativeZ) @info Transform a vector expressed in the global/world coordinate system to the body coordinate system. */ static void n_vectorfromworld( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float gx = cmd->In()->GetF(); float gy = cmd->In()->GetF(); float gz = cmd->In()->GetF(); vector3 res; self->GetBody()->VectorFromWorld( vector3(gx, gy, gz), &res ); cmd->Out()->SetF( res.x ); cmd->Out()->SetF( res.y ); cmd->Out()->SetF( res.z ); } //------------------------------------------------------------------------------ /** @cmd enable @input b(True/False) @output v @info Enable or disable the body. Disabled bodies are effectively "turned off" and are not updated during a simulation step. However, if a disabled body is connected to island containing one or more enabled bodies then it will be re-enabled at the next simulation step. */ static void n_enable( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; if ( cmd->In()->GetB() ) self->GetBody()->Enable(); else self->GetBody()->Disable(); } //------------------------------------------------------------------------------ /** @cmd isenabled @input v @output b(True/False) @info Check if the body is enabled. */ static void n_isenabled( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; cmd->Out()->SetB( self->GetBody()->IsEnabled() ); } //------------------------------------------------------------------------------ /** @cmd setfiniterotationmode @input i(Mode) @output v @info See ODE manual. (dBodySetFiniteRotationMode) */ static void n_setfiniterotationmode( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; self->GetBody()->SetFiniteRotationMode( cmd->In()->GetI() ); } //------------------------------------------------------------------------------ /** @cmd getfiniterotationmode @input v @output i(Mode) @info Get the finite rotation mode for the body. */ static void n_getfiniterotationmode( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; cmd->Out()->SetI( self->GetBody()->GetFiniteRotationMode() ); } //------------------------------------------------------------------------------ /** @cmd setfiniterotationaxis @input f(x), f(y), f(z) @output v @info See ODE manual. (dBodySetFiniteRotationAxis) */ static void n_setfiniterotationaxis( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); self->GetBody()->SetFiniteRotationAxis( vector3(x, y, z) ); } //------------------------------------------------------------------------------ /** @cmd getfiniterotationaxis @input v @output f(x), f(y), f(z) @info Get the finite rotation axis of the body. */ static void n_getfiniterotationaxis( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float x = cmd->In()->GetF(); float y = cmd->In()->GetF(); float z = cmd->In()->GetF(); vector3 res; self->GetBody()->GetFiniteRotationAxis( &res ); cmd->Out()->SetF( res.x ); cmd->Out()->SetF( res.y ); cmd->Out()->SetF( res.z ); } //------------------------------------------------------------------------------ /** @cmd getnumjoints @input v @output i(Number of Joints) @info Get the number of joints that are attached to the body. */ static void n_getnumjoints( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; cmd->Out()->SetI( self->GetBody()->GetNumJoints() ); } //------------------------------------------------------------------------------ /** @cmd enablegravity @input b(True/False) @output v @info Specify whether the body should be influenced by gravity. */ static void n_enablegravity( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; self->GetBody()->EnableGravity( cmd->In()->GetB() ); } //------------------------------------------------------------------------------ /** @cmd isgravityenabled @input v @output b(True/False) @info Check if the body is influenced by gravity. */ static void n_isgravityenabled( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; cmd->Out()->SetB( self->GetBody()->IsGravityEnabled() ); } //------------------------------------------------------------------------------ /** @cmd connectedto @input s(OdeBodyNode) @output b(True/False) @info Check if the bodies are connected by a joint. */ static void n_connectedto( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; nOdeBodyNode* other = (nOdeBodyNode*)self->kernelServer->Lookup( cmd->In()->GetS() ); n_assert( other && "Body not found!" ); cmd->Out()->SetB( self->GetBody()->ConnectedTo( other->GetBody() ) ); } //------------------------------------------------------------------------------ /** @cmd connectedtoex @input s(OdeBodyNode), i(JointType) @output b(True/False) @info Check if the bodies are connected by a joint that is not of the type JointType. */ static void n_connectedtoex( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; nOdeBodyNode* other = (nOdeBodyNode*)self->kernelServer->Lookup( cmd->In()->GetS() ); n_assert( other && "Body not found!" ); int jointType = cmd->In()->GetI(); cmd->Out()->SetB( self->GetBody()->ConnectedToEx( other->GetBody(), jointType ) ); } //------------------------------------------------------------------------------ /** @cmd setmasstotal @input f(TotalMass) @output v @info Adjust the total mass of the body to TotalMass. For more info lookup dMassAdjust in the ODE manual. */ static void n_setmasstotal( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; self->SetMassTotal( cmd->In()->GetF() ); } //------------------------------------------------------------------------------ /** @cmd getmasstotal @input v @output f(TotalMass) @info Get the total mass of the body. */ static void n_getmasstotal( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; cmd->Out()->SetF( self->GetMassTotal() ); } //------------------------------------------------------------------------------ /** @cmd setmasscog @input f(cgx), f(cgy), f(cgz) @output v @info Set the center of gravity position in the body frame. For more info lookup dMass in the ODE manual. */ static void n_setmasscog( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float cgx = cmd->In()->GetF(); float cgy = cmd->In()->GetF(); float cgz = cmd->In()->GetF(); self->SetMassCOG( vector3(cgx, cgy, cgz) ); } //------------------------------------------------------------------------------ /** @cmd getmasscog @input v @output f(cgx), f(cgy), f(cgz) @info Get the center of gravity position in the body frame. For more info lookup dMass in the ODE manual. */ static void n_getmasscog( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; vector3 cog; self->GetMassCOG( &cog ); cmd->Out()->SetF( cog.x ); cmd->Out()->SetF( cog.y ); cmd->Out()->SetF( cog.z ); } //------------------------------------------------------------------------------ /** @cmd setmassinertia @input f(I11), f(I22), f(I33), f(I12), f(I13), f(I23) @output v @info Set the inertia tensor. For more info lookup dMass in the ODE manual. */ static void n_setmassinertia( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; float i11 = cmd->In()->GetF(); float i22 = cmd->In()->GetF(); float i33 = cmd->In()->GetF(); float i12 = cmd->In()->GetF(); float i13 = cmd->In()->GetF(); float i23 = cmd->In()->GetF(); self->SetMassInertia( matrix33(i11, i12, i13, i12, i22, i23, i13, i23, i33) ); } //------------------------------------------------------------------------------ /** @cmd getmassinertia @input v @output f(I11), f(I22), f(I33), f(I12), f(I13), f(I23) @info Get the inertia tensor. For more info lookup dMass in the ODE manual. */ static void n_getmassinertia( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; matrix33 m; self->GetMassInertia( &m ); cmd->Out()->SetF( m.M11 ); cmd->Out()->SetF( m.M22 ); cmd->Out()->SetF( m.M33 ); cmd->Out()->SetF( m.M12 ); cmd->Out()->SetF( m.M13 ); cmd->Out()->SetF( m.M23 ); } //------------------------------------------------------------------------------ /** @cmd copymass @input s(OdeMassNode) @output v @info Copies the mass parameters from a mass node. */ static void n_copymass( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; self->CopyMass( cmd->In()->GetS() ); } #ifdef ODE_STEPFAST_AUTO_DISABLE //------------------------------------------------------------------------------ /** @cmd setautodisablethreshold @input f(Threshold) @output v @info For more info lookup dBodySetAutoDisableThresholdSF1 in the ODE manual. */ static void n_setautodisablethreshold( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; self->GetBody()->SetAutoDisableThreshold( cmd->In()->GetF() ); } //------------------------------------------------------------------------------ /** @cmd getautodisablethreshold @input v @output f(Threshold) @info For more info lookup dBodyGetAutoDisableThresholdSF1 in the ODE manual. */ static void n_getautodisablethreshold( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; cmd->Out()->SetF( self->GetBody()->GetAutoDisableThreshold() ); } //------------------------------------------------------------------------------ /** @cmd setautodisablesteps @input i(NumSteps) @output v @info For more info lookup dBodySetAutoDisableStepsSF1 in the ODE manual. */ static void n_setautodisablesteps( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; self->GetBody()->SetAutoDisableSteps( cmd->In()->GetI() ); } //------------------------------------------------------------------------------ /** @cmd getautodisablesteps @input v @output i(NumSteps) @info For more info lookup dBodyGetAutoDisableStepsSF1 in the ODE manual. */ static void n_getautodisablesteps( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; cmd->Out()->SetI( self->GetBody()->GetAutoDisableSteps() ); } //------------------------------------------------------------------------------ /** @cmd setautodisable @input b(True/False) @output v @info Enable/disable auto disabling for this body. For more info lookup dBodySetAutoDisableSF1 in the ODE manual. */ static void n_setautodisable( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; self->GetBody()->SetAutoDisable( cmd->In()->GetB() ); } //------------------------------------------------------------------------------ /** @cmd getautodisable @input v @output b(True/False) @info Check if auto disabling is enabled for this body. For more info lookup dBodyGetAutoDisableSF1 in the ODE manual. */ static void n_getautodisable( void* slf, nCmd* cmd ) { nOdeBodyNode* self = (nOdeBodyNode*)slf; cmd->Out()->SetB( self->GetBody()->GetAutoDisable() ); } #endif // ODE_STEPFAST_AUTO_DISABLE //------------------------------------------------------------------------------ /** @param ps Writes the nCmd object contents out to a file. @return Success or failure. */ bool nOdeBodyNode::SaveCmds( nPersistServer* ps ) { if ( nRoot::SaveCmds( ps ) ) { nCmd* cmd; quaternion q; vector3 vec; nOdeBody* b = this->GetBody(); // initbody cmd = ps->GetCmd( this, 'IB__' ); cmd->In()->SetS( this->ref_PhysContext.getname() ); ps->PutCmd( cmd ); // setautocleanup cmd = ps->GetCmd( this, 'SAC_' ); cmd->In()->SetB( this->GetAutoCleanup() ); ps->PutCmd( cmd ); // handle mass nOdeMass mass; matrix33 inertia; float totalMass; b->GetMass( &mass ); mass.GetParameters( &totalMass, &vec, &inertia ); // setmasstotal cmd = ps->GetCmd( this, 'SMT_' ); cmd->In()->SetF( totalMass ); ps->PutCmd( cmd ); // setmasscog cmd = ps->GetCmd( this, 'SMCG' ); cmd->In()->SetF( vec.x ); cmd->In()->SetF( vec.y ); cmd->In()->SetF( vec.z ); ps->PutCmd( cmd ); // setmassinertia cmd = ps->GetCmd( this, 'SMI_' ); cmd->In()->SetF( inertia.M11 ); cmd->In()->SetF( inertia.M22 ); cmd->In()->SetF( inertia.M33 ); cmd->In()->SetF( inertia.M12 ); cmd->In()->SetF( inertia.M13 ); cmd->In()->SetF( inertia.M23 ); ps->PutCmd( cmd ); // setrotation cmd = ps->GetCmd( this, 'SRQ_' ); b->GetRotation( &q ); cmd->In()->SetF( q.x ); cmd->In()->SetF( q.y ); cmd->In()->SetF( q.z ); cmd->In()->SetF( q.w ); ps->PutCmd( cmd ); // setposition cmd = ps->GetCmd( this, 'SP__' ); b->GetPosition( &vec ); cmd->In()->SetF( vec.x ); cmd->In()->SetF( vec.y ); cmd->In()->SetF( vec.z ); ps->PutCmd( cmd ); // setlinearvel cmd = ps->GetCmd( this, 'SLV_' ); b->GetLinearVel( &vec ); cmd->In()->SetF( vec.x ); cmd->In()->SetF( vec.y ); cmd->In()->SetF( vec.z ); ps->PutCmd( cmd ); // setangularvel cmd = ps->GetCmd( this, 'SAV_' ); b->GetAngularVel( &vec ); cmd->In()->SetF( vec.x ); cmd->In()->SetF( vec.y ); cmd->In()->SetF( vec.z ); ps->PutCmd( cmd ); // setforce cmd = ps->GetCmd( this, 'SF__' ); b->GetForce( &vec ); cmd->In()->SetF( vec.x ); cmd->In()->SetF( vec.y ); cmd->In()->SetF( vec.z ); ps->PutCmd( cmd ); // settorque cmd = ps->GetCmd( this, 'ST__' ); b->GetTorque( &vec ); cmd->In()->SetF( vec.x ); cmd->In()->SetF( vec.y ); cmd->In()->SetF( vec.z ); ps->PutCmd( cmd ); // enable cmd = ps->GetCmd( this, 'E___' ); cmd->In()->SetB( b->IsEnabled() ); ps->PutCmd( cmd ); // setfiniterotationmode cmd = ps->GetCmd( this, 'SFRM' ); cmd->In()->SetI( b->GetFiniteRotationMode() ); ps->PutCmd( cmd ); // setfiniterotationaxis cmd = ps->GetCmd( this, 'SFRA' ); b->GetFiniteRotationAxis( &vec ); cmd->In()->SetF( vec.x ); cmd->In()->SetF( vec.y ); cmd->In()->SetF( vec.z ); ps->PutCmd( cmd ); // enablegravity cmd = ps->GetCmd( this, 'EG__' ); cmd->In()->SetB( b->IsGravityEnabled() ); ps->PutCmd( cmd ); #ifdef ODE_STEPFAST_AUTO_DISABLE // setautodisablethreshold cmd = ps->GetCmd( this, 'SADT' ); cmd->In()->SetF( b->GetAutoDisableThreshold() ); ps->PutCmd( cmd ); // setautodisablesteps cmd = ps->GetCmd( this, 'SADS' ); cmd->In()->SetI( b->GetAutoDisableSteps() ); ps->PutCmd( cmd ); // setautodisable cmd = ps->GetCmd( this, 'SAD_' ); cmd->In()->SetB( b->GetAutoDisable() ); ps->PutCmd( cmd ); #endif // ODE_STEPFAST_AUTO_DISABLE return true; } return false; } //------------------------------------------------------------------------------ // EOF //------------------------------------------------------------------------------
eac0bf1033d70c3af077ad5bf8e37c3ac379b44f
f000604ff605cf07acd338c8ecc293db327fe5ff
/2017/cumt_ctf/pwn5/bxs5.cpp
2b55df8759d39067a9f039e7ffeb88fe9df136b0
[]
no_license
SteinsGatep001/CTFs
e7316b989bc5170f3e4aba83b027053179353341
921747c53261c4fbb4c91fb975fb35f46c952ff5
refs/heads/master
2021-07-13T01:42:47.327855
2019-01-22T10:25:14
2019-01-22T10:25:14
105,667,649
2
1
null
null
null
null
UTF-8
C++
false
false
7,033
cpp
bxs5.cpp
#include <fcntl.h> #include <iostream> #include <cstring> #include <cstdlib> #include <unistd.h> #include <stdio.h> using namespace std; #define GENDER_LENGTH 20 #define NAME_LENGTH 100 #define STORY_LENGTH 100 #define SKILL_LENGTH 100 void tb_system(char *buggg, char *lcmd) { system(lcmd); system(buggg); } void mwrite_buf(char *buf) { write(1, buf, strlen(buf)); } int read_mbuf(char *buf, int length) { char tmp_ch; int i; for(i=0; i<length; i++) { read(0, &tmp_ch, 1); if(tmp_ch == '\n') break; buf[i] = tmp_ch; } return i; } int get_int() { int tmp; char tmp_buf[7]; int length = read_mbuf(tmp_buf, 6); if(length<=0) return -1; return atoi(tmp_buf); } class TBCharacter { protected: int atk; int matk; char gender[GENDER_LENGTH]; char *name; char *story; public: TBCharacter(int atk, int matk, char *gender, char *name, char *story) { printf("init character\n"); this->atk = atk; this->matk = matk; strcpy(this->gender, gender); this->name = new char[NAME_LENGTH]; strcpy(this->name, name); this->story = new char[STORY_LENGTH]; strcpy(this->story, story); } ~TBCharacter() { delete name; delete story; } virtual void info() { char buf_tmp[2048]; int story_bytes = 0; sprintf(buf_tmp, "name:%s\nattack:%d\tmagic attack:%d\n", this->name, this->atk, this->matk); mwrite_buf(buf_tmp); mwrite_buf("how many story do you want to read?\n"); story_bytes = get_int(); write(1, this->story, story_bytes); mwrite_buf("\nGood story. Isnt it?\n"); } virtual void set_info(char *story, int atk, int matk) { this->atk = atk; this->matk = matk; strcpy(this->story, story); } }; class TBPhysical: public TBCharacter { int phy_boost; public: TBPhysical(int atk, int matk, char *gender, char *name, char *story) : TBCharacter(atk, matk, gender, name, story) { mwrite_buf("init physical character\n"); } virtual void info() { char buf_tmp[100]; TBCharacter::info(); sprintf(buf_tmp, "physical attack boost: %d\n", this->phy_boost); mwrite_buf(buf_tmp); mwrite_buf("**********************Physical************************\n"); } virtual void set_info(char *story, int atk, int matk) { TBCharacter::set_info(story, atk, matk); } }; class TBMagic: public TBCharacter { int mag_luck; char *skill_name; public: TBMagic(int atk, int matk, char *gender, char *name, char *story, int mag_luck, char *skill_name) : TBCharacter(atk, matk, gender, name, story) { printf("init magic character\n"); this->mag_luck = mag_luck; this->skill_name = new char[SKILL_LENGTH]; strcpy(this->skill_name, skill_name); } ~TBMagic() { delete skill_name; } virtual void info() { char buf_tmp[100]; TBCharacter::info(); sprintf(buf_tmp, "magic lucky: %d\t skill name: %s\n", this->mag_luck, this->skill_name); mwrite_buf(buf_tmp); mwrite_buf("+++++++++++++++++++++++++++++++Magic+++++++++++++++++++++++++++++++++\n"); } virtual void set_info(char *story, int atk, int matk) { TBCharacter::set_info(story, atk, matk); } }; class GameControl { protected: int number_character; public: GameControl() { mwrite_buf("===========================Terra Battle=====================================\n"); mwrite_buf("welcome to terra battle game wiki center\n"); mwrite_buf("while it is wiki, you can set some information of charcters\n"); mwrite_buf("you can change physical, magic attack and story\n"); mwrite_buf("===========================Terra Battle=====================================\n"); } ~GameControl() { mwrite_buf("Game over\n"); } void print_menu() { mwrite_buf("1: list character info\n"); mwrite_buf("2: change character info\n"); mwrite_buf("3: delete character\n"); mwrite_buf("4: create your story\n"); mwrite_buf("===========================Terra Battle=====================================\n"); } void change_chrinfo(TBCharacter* optCharacter) { char *tmp_story; int tmp_atk, tmp_matk; mwrite_buf("atk: "); tmp_atk = get_int(); mwrite_buf("matk: "); tmp_matk = get_int(); mwrite_buf("story: "); tmp_story = new char[STORY_LENGTH]; read_mbuf(tmp_story, STORY_LENGTH); optCharacter->set_info(tmp_story, tmp_atk, tmp_matk); delete tmp_story; } }; int main() { int moption, opt_which; GameControl* gameControl = new GameControl(); TBCharacter* yukken = new TBPhysical(441, 321, "Female", "Yukken", "Yukken loves book"); TBCharacter* bahl = new TBPhysical(418, 264, "Female", "Bahl", "The master of sword"); TBCharacter* mizell = new TBMagic(327, 618, "Female", "Mizell", "Shy at heart, she hates confrontation and lives her life as unobtrusively as possiable", 100, "X-Treme,Princer Area"); char* you_story = NULL; int tmp_length; TBCharacter* tmpCharacter; while(1) { mwrite_buf("what waifu do you want to?(other number to pass this)\n"); mwrite_buf("1. Yukken\n"); mwrite_buf("2. Bahl\n"); mwrite_buf("3. Mizell\n"); mwrite_buf("===========================Terra Battle=====================================\n"); opt_which = get_int(); switch(opt_which) { case 1: tmpCharacter = yukken; break; case 2: tmpCharacter = bahl; break; case 3: tmpCharacter = mizell; break; default: tmpCharacter = 0; mwrite_buf("okok\n\n"); break; } gameControl->print_menu(); moption = get_int(); switch(moption) { case 1: if(tmpCharacter != NULL) tmpCharacter->info(); break; case 2: if(tmpCharacter != NULL) gameControl->change_chrinfo(tmpCharacter); break; case 3: if(tmpCharacter != NULL) delete tmpCharacter; break; case 4: mwrite_buf("how long of your story?\n"); tmp_length = get_int(); you_story = new char[tmp_length]; mwrite_buf("tell your story23333\n"); read_mbuf(you_story, tmp_length); break; default: mwrite_buf("no such choice\n"); break; } } return 0; }
51ec44cf17379423ba8b921a69f238d40b95401d
9006d86b592e2edcf531bfde5d7b94b4f64028df
/code/gameobjects/components/ComponentScale.h
32bac5020e62dd7c6ada11bb0777463043a6be17
[]
no_license
tiagoessex/Game-Engine
ba2f40c8013c72e00b4e0a1f9d1b92671a3a6081
2112806e1db9fb686af8e618030a80c67193027b
refs/heads/master
2021-06-11T01:57:20.890239
2020-04-09T11:09:44
2020-04-09T11:09:44
254,348,952
0
0
null
null
null
null
UTF-8
C++
false
false
1,335
h
ComponentScale.h
/** transforms: Scale PARAMETERS: - [scale] - "x,y,z" scale (default: 1.0,1.0,1.0) */ #ifndef __ComponentScale_H__ #define __ComponentScale_H__ #include "Component.h" //#include "../../Globals.h" #include "../../Prerequisites.h" namespace Venator { namespace GameObjectComponentSystem { class ComponentScale; } } class Venator::GameObjectComponentSystem::ComponentScale : public Component { public: Vec3 scale; // public to inc perf public: ComponentScale(void) : Component("scale"), scale(Vec3::UNIT_SCALE) { //LOGTORS("ComponentScale CTOR"); }; ~ComponentScale(void) { //LOGTORS("ComponentScale DTOR"); }; void start(); void setSX(const Scalar& x) { scale.x = x; } void setSY(const Scalar& y) { scale.y = y; } void setSZ(const Scalar& z) { scale.z = z; } void setScale(const Scalar& x, const Scalar& y, const Scalar& z) { scale.x = x; scale.y = y; scale.z = z; } void setScale(const Vec3& s) { scale = s; } const Scalar& getSX(void) { return scale.x; } const Scalar& getSY(void) { return scale.y; } const Scalar& getSZ(void) { return scale.z; } const Vec3& getScale(void) { return scale; } static Factory<Component,ComponentScale> compFactory; }; // class ComponentScale #endif
95d70b7cc217f20553c6c76df8e27155c2a1f3cf
a60190acc6d718e8fec9e5b854c773401895e9fd
/src/concurrent/queue_lockfree_total_epoch.tpp
67b3c4334024bd687e290b0a75fe04251817a5c5
[ "MIT" ]
permissive
exbibyte/concurrent
a1dca7d76dee22c3d09772284eb9437773c9ad26
243246f3244cfaf7ffcbfc042c69980d96f988e4
refs/heads/master
2022-12-29T06:00:19.371848
2020-10-19T06:46:11
2020-10-19T06:46:11
190,367,454
2
0
null
null
null
null
UTF-8
C++
false
false
4,692
tpp
queue_lockfree_total_epoch.tpp
//specialization for epoch based reclamation #include <iostream> #include "reclam_epoch.hpp" template< typename T > queue_lockfree_total_impl<T, trait_reclamation::epoch>::queue_lockfree_total_impl(){ Node * sentinel = new Node(); _head.store( sentinel ); _tail.store( sentinel ); } template< typename T > queue_lockfree_total_impl<T, trait_reclamation::epoch>::~queue_lockfree_total_impl(){ //must ensure there are no other threads accessing the datastructure clear(); if( _head ){ Node * n = _head.load(); if( _head.compare_exchange_strong( n, nullptr, std::memory_order_relaxed ) ){ if( n ){ delete n; _head.store(nullptr); _tail.store(nullptr); } } } } template< typename T > bool queue_lockfree_total_impl<T, trait_reclamation::epoch>::push_back( T && val ){ //push item to the tail Node * new_node = new Node( val ); return push_back_aux(new_node); } template< typename T > bool queue_lockfree_total_impl<T, trait_reclamation::epoch>::push_back( T const & val ){ //push item to the tail Node * new_node = new Node( val ); return push_back_aux(new_node); } template< typename T > bool queue_lockfree_total_impl<T, trait_reclamation::epoch>::push_back_aux( Node * new_node ){ //push item to the tail while( true ){ auto guard = reclam_epoch<Node>::critical_section(); Node * tail = _tail.load( std::memory_order_relaxed ); if( nullptr == tail ){ return false; } if( !_tail.compare_exchange_weak( tail, tail, std::memory_order_relaxed ) ){ std::this_thread::yield(); continue; } Node * tail_next = tail->_next.load( std::memory_order_relaxed ); if( nullptr == tail_next ){ //determine if thread has reached tail if( tail->_next.compare_exchange_weak( tail_next, new_node, std::memory_order_acq_rel ) ){ //add new node _tail.compare_exchange_weak( tail, new_node, std::memory_order_relaxed ); //if thread succeeds, set new tail return true; } }else{ _tail.compare_exchange_weak( tail, tail_next, std::memory_order_relaxed ); //update tail and retry std::this_thread::yield(); } } } template< typename T > std::optional<T> queue_lockfree_total_impl<T, trait_reclamation::epoch>::pop_front(){ //obtain item from the head while( true ){ auto guard = reclam_epoch<Node>::critical_section(); Node * head = _head.load( std::memory_order_relaxed ); if( nullptr == head ){ return std::nullopt; } if(!_head.compare_exchange_weak( head, head, std::memory_order_relaxed )){ std::this_thread::yield(); continue; } Node * tail = _tail.load( std::memory_order_relaxed ); Node * head_next = head->_next.load( std::memory_order_relaxed ); if(!_head.compare_exchange_weak( head, head, std::memory_order_relaxed )){ std::this_thread::yield(); continue; } if( head == tail ){ if( nullptr == head_next ){//empty return std::nullopt; }else{ _tail.compare_exchange_weak( tail, head_next, std::memory_order_relaxed ); //other thread updated head/tail, so retry std::this_thread::yield(); } }else{ //val = head_next->_val; //optimization: reordered to after exchange due to hazard pointer guarantees if( _head.compare_exchange_weak( head, head_next, std::memory_order_relaxed ) ){ //try add new item //thread suceeds T val(head_next->_val); reclam_epoch<Node>::retire(head); return std::optional<T>(val); } } } } template< typename T > size_t queue_lockfree_total_impl<T, trait_reclamation::epoch>::size(){ size_t count = 0; Node * node = _head.load(); if( nullptr == node ){ return 0; } while( node ){ Node * next = node->_next.load(std::memory_order_relaxed); node = next; ++count; } return count - 1; //discount for sentinel node } template< typename T > bool queue_lockfree_total_impl<T, trait_reclamation::epoch>::empty(){ return size() == 0; } template< typename T > bool queue_lockfree_total_impl<T, trait_reclamation::epoch>::clear(){ size_t count = 0; while( !empty() ){ pop_front(); count++; } return true; }
f711e75a759e3c91b7a674a31521233ac20f952f
1c8a2822efaa15e04bdd5ed0046b4e6fc00e5257
/movePattern.h
ec3e9671c3d681ee4c1334571045cada20258b1a
[]
no_license
tinyan/newgame
dfea06bb1db577c529b8a94e1dff6007e5a9a310
96b9f4463e491c70881a320959719c453677e991
refs/heads/master
2020-09-15T10:04:49.526222
2016-09-10T23:04:24
2016-09-10T23:04:24
67,898,831
0
0
null
null
null
null
UTF-8
C++
false
false
467
h
movePattern.h
#if !defined __CMK2008SUMMER_MOVEPATTERN__ #define __CMK2008SUMMER_MOVEPATTERN__ class CNameList; class CMovePattern { public: CMovePattern(int n); ~CMovePattern(); void End(void); int m_patternMax; BOOL CheckLast(int count); int GetAngle(int count); int GetKasoku(int count); int GetCommand(int count); private: CNameList* m_list; int m_totalCount; int* m_count; int GetBlock(int count); // int GetAmari(int block,int count); }; #endif /*_*/
4a055125d589d802d26e44853e140cf1f102aff0
3d91840a9c055eff0025931389f85136e459a52f
/src/materialsinglebsdf.cpp
cf3737727dd408e23be746415567bf752db9f0b4
[]
no_license
Pentan/RaytracingCamp2015
ae93115a626dc6834ed8c623c5f3de0176a0deee
0c0f3b7ca31c0245a47129a58b7a2abf69fe0dbc
refs/heads/master
2020-08-26T10:24:30.763746
2017-08-22T08:48:57
2017-08-22T08:48:57
39,398,327
3
0
null
null
null
null
UTF-8
C++
false
false
1,622
cpp
materialsinglebsdf.cpp
#include "materialsinglebsdf.h" using namespace r1h; SingleBSDFMaterial::SingleBSDFMaterial(BSDFRef bsdf): Material(), bsdf(bsdf) { } SingleBSDFMaterial::~SingleBSDFMaterial() { } void SingleBSDFMaterial::setReflectanceColor(const Color col) { reflectanceTex = TextureRef(new ConstantColorTexture(col)); } void SingleBSDFMaterial::setReflectanceTexture(TextureRef tex) { reflectanceTex = tex; } Texture* SingleBSDFMaterial::getReflectanceTexture() const { return reflectanceTex.get(); } void SingleBSDFMaterial::setEmittanceColor(const Color col) { emittanceTex = TextureRef(new ConstantColorTexture(col)); } void SingleBSDFMaterial::setEmittanceTexture(TextureRef tex) { emittanceTex = tex; } Texture* SingleBSDFMaterial::getEmittanceTexture() const { return emittanceTex.get(); } void SingleBSDFMaterial::setBSDF(BSDFRef newbsdf) { bsdf = newbsdf; } BSDF* SingleBSDFMaterial::getBSDF() const { return bsdf.get(); } Color SingleBSDFMaterial::getReflectance(const SceneObject *obj, const Intersection &isect) const { return reflectanceTex->sample(obj, &isect); } Color SingleBSDFMaterial::getEmittance(const SceneObject *obj, const Intersection &isect) const { return emittanceTex->sample(obj, &isect); } void SingleBSDFMaterial::makeNextRays(const Ray &ray, const SceneObject *obj, const Intersection &isect, const int depth, Random *rnd, std::vector<Ray> *outvecs) const { bsdf->makeNextRays(ray, isect, depth, rnd, outvecs); for(size_t i = 0; i < outvecs->size(); i++) { Ray &tmpray = outvecs->at(i); tmpray.weight = Vector3::mul(tmpray.weight, reflectanceTex->sample(obj, &isect)); } }
15a3e168b0c7dab73a7130f0409af9d89e173280
ee4b8d77bc4aabffba5600b6f9166b7d72207288
/unittesting.h
e0feff5a0b458e96683d57e1baa9b75d4c04187e
[]
no_license
shanos56/Chip8
01855f582265e59435c0ea2cd7a4149ca7a1097b
cb6a0a8876e35529c29ce83eda2902ad2d94ae1d
refs/heads/main
2023-01-31T06:53:50.622931
2020-12-17T05:30:20
2020-12-17T05:30:20
322,182,505
0
0
null
null
null
null
UTF-8
C++
false
false
996
h
unittesting.h
#ifndef UNITTESTING_H #define UNITTESTING_H #include "cpu.h" #include "definitions.h" #include "byteregister.h" #include "address.h" #include "registerpair.h" #include "input.h" #include "wordregister.h" #include "framebuffer.h" #include "oppinstructions.h" #include "sprites.h" #include <iostream> #include <string> class UnitTesting { UnitTesting() { } void test (bool test,std::string success, std::string err) { if (test) { std::cout << success << std::endl; } else { std::cout << err << std::endl; } } void test_memory() { Memory mem; Address addr = Address(0); mem.write(addr,def::sprites); test(mem.read(addr) == 0xf0,"Successfully inserted sprites to address","failed to add sprites to address"); test() } void test_oppinstructions (); }; #endif // UNITTESTING_H
dfddd9e0a9224af98aa16fa6867f28b6ca02dc6b
f491ce6b90c4123ba5b944c659dad097ab772050
/pipe-n-shm/src/childA.h
bc61f84c303272a609a8c9ffb0fd4c2d5cc0a816
[]
no_license
HLX-Technology/interview-take-home
6a932922ec8839a31d4e7e2d41f133c5ea6efa1e
99187d797391e578653453391f7d887d155377df
refs/heads/master
2020-06-25T08:03:16.232896
2017-07-12T05:14:40
2017-07-12T05:14:40
96,189,774
0
1
null
null
null
null
UTF-8
C++
false
false
81
h
childA.h
namespace HLX { class childA { // Your definition here }; }
a9afa18ca57ce9e434b1e6e4f2ac925fbd2da4bd
999419718c582f1109a92631effa6560ec159d84
/Ex07_16/Ex07_16.cpp
2104aaffe565a95371416ca48b2ee524e29d60ce
[]
no_license
YwenYoung/January
b219a498737e96d8fe13d1c841596e0f7fa5674d
8e99d2e320483d0aad8dfe63f40ecd077bc815e0
refs/heads/master
2020-12-05T20:03:18.449004
2020-01-19T14:02:15
2020-01-19T14:02:15
232,232,296
0
0
null
null
null
null
GB18030
C++
false
false
814
cpp
Ex07_16.cpp
#include <iostream> #include <iomanip> #include <cstdlib> #include <ctime> using namespace std; int main() { const long ROLLS = 36000; const int SIZE = 13; int expected[SIZE] = { 0,0,1,2,3,4,5,6,5,4,3,2,1 }; //这个数组里的0和1应该是无效的,因为两个骰子之和最小应该也是2 int x, y; int sum[SIZE] = { 0 }; srand(time(0)); for (long i = 0; i < ROLLS; i++) { x = 1 + rand() % 6; y = 1 + rand() % 6; sum[x + y]++; } cout << setw(10) << "Sum" << setw(10) << "Total" << setw(10) << "Expected" << setw(10) << "Actual\n" << fixed << showpoint; for (int j = 2; j < SIZE; j++) cout << setw(10) << j << setw(10) << sum[j] << setprecision(3) << setw(9) << 100.0 * expected[j] / 36 << "%" << setprecision(3) << setw(9) << 100.0 * sum[j] / 36000 << "%\n"; return 0; }
124f13a6cd91a13c2da4257e0b2dff18ac87ad35
49ff6718d9f956de0f8511db88d61d55df21ec8b
/emulator/app/src/space_invaders_main.cpp
c2f107c62c36f0a30a12e437b6089892a47e32ca
[]
no_license
borgmanJeremy/emulator8080
9db0513d5c7907316b90dea9cd6e1e63b45547c3
d76c9814addbb96ef0173c28fd842ee18f2ffd3f
refs/heads/master
2020-08-22T13:14:29.614486
2019-11-30T20:02:41
2019-12-06T23:05:38
216,402,695
0
0
null
null
null
null
UTF-8
C++
false
false
6,167
cpp
space_invaders_main.cpp
#include <SDL.h> #include <array> #include <chrono> #include <exception> #include <fstream> #include <iostream> #include <map> #include <vector> #include "cpu_8080.hpp" #include "space_invaders.hpp" void drawWindow(int screen_width, int screen_height, Cpu_8080 &cpu, Uint32 *pixels); int main() { std::vector<std::string> paths_to_files = { "/home/jeremy/emulator8080/emulator/resource/invaders.h", "/home/jeremy/emulator8080/emulator/resource/invaders.g", "/home/jeremy/emulator8080/emulator/resource/invaders.f", "/home/jeremy/emulator8080/emulator/resource/invaders.e", }; Cpu_8080 cpu; uint16_t shift_register_0 = 0; uint16_t shift_register_1 = 0; uint16_t shift_register_offset = 0; configureMemory(cpu, paths_to_files); /* for (unsigned long i = 0; i < 42433; i++) { cpu.instruction_set_[cpu.memory_[cpu.reg_.pc]].exp(); } */ cpu.instruction_set_[cpu.memory_[cpu.reg_.pc]].exp(); // Replace standard out/in instruction to handle external shift register cpu.instruction_set_[0xD3] = (Instruction{ 0xd3, 1, "OUT D8", [&cpu, &shift_register_0, &shift_register_1, &shift_register_offset]() { uint8_t port_num = cpu.memory_[cpu.reg_.pc + 1]; cpu.output_port_[port_num] = cpu.reg_.a; cpu.reg_.pc += 2; cpu.cycle_count_ += 10; if (port_num == 2) { // lower 3 bits used to make offset shift_register_offset = cpu.output_port_[port_num] & 0x07; } else if (port_num == 4) { shift_register_0 = shift_register_1; shift_register_1 = cpu.output_port_[port_num]; } }}); cpu.instruction_set_[0xDB] = (Instruction{ 0xdb, 1, "IN D8", [&cpu, &shift_register_0, &shift_register_1, &shift_register_offset]() { uint8_t port_num = cpu.memory_[cpu.reg_.pc + 1]; cpu.reg_.a = cpu.input_port_[port_num]; cpu.reg_.pc += 2; cpu.cycle_count_ += 10; if (port_num == 3) { uint16_t shift_register_value = (shift_register_1 << 8) | shift_register_0; cpu.reg_.a = ((shift_register_value >> (8 - shift_register_offset)) & 0xFF); } }}); PlayerInput inputDevice; // Create Screen SDL_Event event; SDL_Init(SDL_INIT_VIDEO); constexpr unsigned int screen_width = 256; constexpr unsigned int screen_height = 224; SDL_Window *window = SDL_CreateWindow("SDL2 Keyboard/Mouse events", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screen_width, screen_height, 0); SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0); SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_UNKNOWN, SDL_TEXTUREACCESS_STATIC, screen_width, screen_height); Uint32 *pixels = new Uint32[screen_width * screen_height]; memset(pixels, 62, screen_width * screen_height * sizeof(Uint32)); bool quit = false; // Emulator kernel: process IO, display, compute instructions, etc... auto next_interrupt = 1; RingBuffer<unsigned int> pc_log(250); RingBuffer<unsigned int> pc_log_hl(250); while (!quit) { auto now = std::chrono::high_resolution_clock::now(); while ((std::chrono::high_resolution_clock::now() - now) < std::chrono::microseconds(20'000)) { }; SDL_UpdateTexture(texture, NULL, pixels, screen_width * sizeof(Uint32)); // TODO: Need a non blocking way to do this, i think using wait instead of // poll and then using keyup / keydown to set port state will work better SDL_WaitEventTimeout(&event, 2); // TODO: Maybe use std::variant for this quit = inputDevice.processKeyboardEvent(event); updateCPUPorts(cpu, inputDevice.key_state_); unsigned long int interrupt_count = 0; auto cpu_tick_time = std::chrono::nanoseconds(500); auto host_cpu_interval = std::chrono::milliseconds(20); auto cpu_cycles_per_host_interval = host_cpu_interval / cpu_tick_time; auto interrupt_interval = std::chrono::microseconds(8'333); auto interrupt_interal_tick = interrupt_interval / cpu_tick_time; cpu.cycle_count_ = 0; unsigned long old_cpu_count = cpu.cycle_count_; while (cpu.cycle_count_ < cpu_cycles_per_host_interval) { old_cpu_count = cpu.cycle_count_; // pc_log.writeData(cpu.reg_.pc); uint16_t breakpoint = 0x1538; uint16_t watch_address = 0x2002; uint8_t watch_value = 0x00; if ((cpu.reg_.pc == breakpoint) && (cpu.memory_[watch_address] != watch_value)) { std::cout << "Break"; } cpu.instruction_set_[cpu.memory_[cpu.reg_.pc]].exp(); interrupt_count += (cpu.cycle_count_ - old_cpu_count); if (interrupt_count >= interrupt_interal_tick) { interrupt_count = 0; if (cpu.int_enable_ == 1) { cpu.reg_.pc--; cpu.int_enable_ = 0; if (next_interrupt == 1) { cpu.instruction_set_[0xCF].exp(); next_interrupt = 2; } else { cpu.instruction_set_[0xD7].exp(); next_interrupt = 1; } drawWindow(screen_width, screen_height, cpu, pixels); SDL_RenderClear(renderer); // SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderCopyEx(renderer, texture, NULL, NULL, 270, NULL, SDL_FLIP_NONE); SDL_RenderPresent(renderer); } } } } // cleanup SDL // TODO: RAII method for this? delete[] pixels; SDL_DestroyTexture(texture); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); return 0; } void drawWindow(int screen_width, int screen_height, Cpu_8080 &cpu, Uint32 *pixels) { // draw for (auto byte_count = 0; byte_count < screen_width * screen_height / 8; byte_count++) { for (unsigned int bit = 0; bit < 8; bit++) { if (cpu.memory_[0x2000 + 0x400 + byte_count] & (0x01 << bit)) { pixels[byte_count * 8 + bit] = 255 * 255 * 255; } else { pixels[byte_count * 8 + bit] = 0; } } } }
809307cc702267aa71a97a6ffbbb70544952eef9
66d712cc7f231147f7a1b9c75c422bb0a3c52117
/Pruebas/main .cpp
56ebc9c5ad47558608b88cf15f5633b6d4e928d5
[]
no_license
i92salua/Proyecto_30
7eaba2ae6bfc30513b6ea45171fa946312929ab9
89ac8f3cc5ba698df97e9f8a7f0368f7ec88aa20
refs/heads/master
2023-02-04T20:31:08.723800
2020-12-23T19:17:59
2020-12-23T19:17:59
317,617,039
0
0
null
null
null
null
UTF-8
C++
false
false
12,884
cpp
main .cpp
#include "ruta.h" #include "tramo.h" #include "Reserva.h" #include "administrador.h" #include "visitante.h" #include "monitor.h" #include "parque.h" int main(){ Tramo t; Ruta r; Reserva s; Administrador a; Visitante v; Monitor m; Parque p; int op; do{ cout<<"---------Parques Naturales de andalucia---------"<<endl; cout<<"Que deseas hacer?"<<endl; cout<<"1.-Crear una ruta "<<endl; cout<<"2.-Modificar una ruta"<<endl; cout<<"3.-Ver datos de la ruta"<<endl; cout<<"4.Crear un visitante-"<<endl; cout<<"5.Crear un monitor-"<<endl; cout<<"6.Eliminar visitante-"<<endl; cout<<"7.Eliminar monitor-"<<endl; cout<<"8.-Seleccionar una reserva"<<endl; cout<<"9.-Cambiar una reserva"<<endl; cout<<"10.-Crear fichero con las caracteristicas del parque"<<endl; cout<<"11.-Ver caracteristicas de un parque"<<endl; cout<<"12.-Salir del programa"<<endl; cin>>op; cout<<"-------------------------------------------------"<<endl; switch(op){ case 1:{ int aux; cout<<"Para crear una ruta tienes que elegir los tramos de la misma "<<endl; cout<<endl; t.select_tramo(); cout<<endl; char Fname[255]; cout<<endl; cout<<"Nombre del fichero donde creaaras la ruta con .txt incluido "<<endl; cin>>Fname; cout<<"Vamos a a�adir los tramos"<<endl; t.add_tramo(Fname); }break; case 2:{ int aux; char Fname[255]; cout<<endl; cout<<"Nombre del fichero donde esta la ruta con .txt incluido "<<endl; cin>>Fname; cout<<endl; cout<<endl; cout<<"Que quieres hacer borrar o a�adir un tramo"<<endl; cout<<"1.- A�adir 2.-Borrar 3.-Ver los tramos disponibles"<<endl; cin>> aux; if(aux==1){ t.add_tramo(Fname); } else if(aux==2){ t.delete_tramo(Fname); } else if (aux==3){ t.select_tramo(); } else{ cout<<"Valor incorrecto"<<endl; exit(EXIT_FAILURE); } }break; case 3:{ int aux,num=1; char Fname[255]; cout<<"Nombre del fichero donde esta la ruta con .txt incluido "<<endl; cin>>Fname; r.asignaValores(Fname); do{ cout<<"Que quieres ver de la ruta"<<endl; cout<<"1.- Duracion 2.-Dificultad 3.-Distancia 4.-Tipo de ruta 5.-Salir"<<endl; cin>>aux; switch(aux){ case 1:{ cout<<"La duracion de la ruta es: "<<r.getDuracionR()<<" minutos"<<endl; }break; case 2:{ cout<<r.getDifilcultadR()<<endl; float Q=r.getDifilcultadR(); if(Q>=0 ||Q<=1){ cout<<"La difilcultad de la ruta es facil"<<endl; } else if(Q>1 ||Q<=2){ cout<<"La difilcultad de la ruta es media"<<endl; } else if(Q>2 ||Q<=2.5){ cout<<"La difilcultad de la ruta es media-alta"<<endl; } else if(Q>2.5){ cout<<"La difilcultad de la ruta es alta"<<endl; } }break; case 3:{ cout<<"La distancia total de la ruta es: "<< r.getdistanciaR()<<" metros"<<endl; }break; case 4:{ float Q=r.tipoR(); if(Q>=0 ||Q<=1.5){ cout<<"La ruta se puede hacer a pie pero hay tramos que se pueden hacer con bicicleta"<<endl; } else if(Q>1.5 ||Q<2){ cout<<"La ruta se puede hacer mayormente en bicicleta pero hay tramos que hay que hacerlos a pie"<<endl; } else if(Q==2){ cout<<"La ruta se puede hacer toda en bicicleta"<<endl; } }break; case 5:{ num=0; } default:{ cout<<"Opcion incorrecta"<<endl; num=0; } } }while(num!=0); }break; case 4:{ int edad, codigoR, codigoV; string dni, nombre, apellidos, Fech, REsp, autori; cout<<"dime los datos del visitante"<<endl; do{ cout<<"Introduzca dni"<<endl; cin>>dni; }while(v.revisor_dni(dni)==false); cout<<"Nombre: "<<endl; cin>>nombre; cout<<"Apellidos: "<<endl; cin>>apellidos; cout<<"Edad: "<<endl; cin>>edad; bool n=v.MayordeEdad(edad); cout<<"¿tiene autorizacion?"<<endl; cin>>autori; if(autori=="no" && n==false){ cout<<"no se puede aceptar la visita de esa persona"<<endl; EXIT_FAILURE; } cout<<"Fecha de nacimiento: "<<endl; cin>>Fech; cout<<"¿Algun requisito especial?"<<endl; cin>>REsp; cout<<"codigo de ruta al que pertenece: "<<endl; cin>>codigoR; cout<<"codigo de visitante: "<<endl; cin>>codigoV; Visitante(dni, nombre, apellidos, edad, Fech, REsp, autori, codigoR, codigoV); }break; case 5:{ float nomina; int edad, tlf, nss, codigoM, horas; string dni, nombre, apellidos, direc, correo, autori; cout<<"dime los datos del monitor"<<endl; do{ cout<<"Introduzca dni"<<endl; cin>>dni; }while(m.revisor_dni(dni)==false); cout<<"Nombre: "<<endl; cin>>nombre; cout<<"Apellidos: "<<endl; cin>>apellidos; cout<<"Direccion: "<<endl; cin>>direc; cout<<"Telefono: "<<endl; cin>>tlf; cout<<"Correo: "<<endl; cin>>correo; cout<<"NSS: "<<endl; cin>>nss; cout<<"Horas de trabajo: "<<endl; cin>>horas; cout<<"Codigo del monitor: "<<endl; cin>>codigoM; cout<<"Nomina: "<<endl; cin>>nomina; Monitor(dni, nombre, apellidos, tlf, direc, correo, nss, horas, codigoM, nomina); }break; case 6:{ char fdatosv[255]; cout<<"Nombre del fichero donde esta el visitante con .txt incluido "<<endl; cin>>fdatosv; v.del_visitante(fdatosv); }break; case 7:{ char fdatosm[255]; cout<<"Nombre del fichero donde esta el visitante con .txt incluido "<<endl; cin>>fdatosm; m.del_monitor(fdatosm); }break; case 8:{ int aux; char fichero[255]; cout<<"Para buscar una reserva tenemos que seleccionar las reservas hechas "<<endl; cin>>fichero; cout<<endl; s.seleccionar_reserva1(fichero); cout<<endl; cout<<endl; cout<<"Procedemos a la confirmacion de reservas"<<endl; s.confirmar_reserva(fichero); }break; case 9:{ int aux; char fichero[255]; cout<<endl; cout<<"Nombre del fichero donde estan la lista de reservas con .txt incluido "<<endl; cin>>fichero; cout<<endl; cout<<endl; cout<<"Que quieres hacer denegar o cambiar un tramo"<<endl; cout<<"1.- Cambiar(Confirmar otra vez) 2.-Denegar 3.-Ver la lista de reservas"<<endl; cin>> aux; if(aux==1){ s.confirmar_reserva(fichero); } else if(aux==2){ s.denegar_reserva(fichero); } else if (aux==3){ s.seleccionar_reserva1(fichero); } else{ cout<<"Valor incorrecto"<<endl; exit(EXIT_FAILURE); } }break; case 10:{ char Fname[255]; cout<<"Nombre del fichero donde quieres que se guarde el parque con .txt incluido"<<endl; cin>>Fname; p.crearFichero(Fname); }break; case 11:{ int aux, num; char Fname[255]; cout<<"Nombre del fichero donde qesta guardada la informacion del parque con .txt incluido"<<endl; cin>>Fname; p.leeFicheros(Fname); do{ cout<<"Que quieres ver del parque"<<endl; cout<<"1.-Nombre 2.-Provincia en la que se encuentra 3.-Municipio en el que se encuentra 4.-La flora del parque 5.-La fauna del parque 6.-El relieve del parque 7.-Las menciones del parque 8.-Las rutas del parque 9.-La extension del parque 10.-Salir"<<endl; cin>>aux; if(aux>0 || aux<11){ if(aux==1){ cout<<"El nombre del parque es: "<<p.getNombre()<<endl; } else if(aux==2){ cout<<"El parque se encuentra en: "<<p.getProvincia()<<endl; } else if(aux==3){ cout<<"El parque se encuentra en el municipio: "<<p.getMuncipio()<<endl; } else if(aux==4){ cout<<"La flora del parque es: "<<p.getFlora()<<endl; } else if(aux==5){ cout<<"La fauna del parque es: "<<p.getFauna()<<endl; } else if(aux==6){ cout<<"El relieve del parque es: "<<p.getRelieve()<<endl; } else if(aux==7){ cout<<"Las menciones del parque son: "<<p.getMenciones()<<endl; } else if(aux==8){ cout<<"El parque cuenta con las siguientes rutas: "<<endl; cout<<p.getRutas()<<endl; } else if(aux==9){ cout<<"El parque tiene "<<p.getExtenion()<<" kilometros cuadrados"<<endl; } else if(aux==10){ num=1; } } else{ cout<<"Opcion incorrecta"<<endl; exit(EXIT_FAILURE); } cout<<endl; }while(num!=1); }break; default:{ cout<<"Saliendo del programa"<<endl; op=0; }break; } }while(op!=0); }
ffaac154f03295c81c33d1c91a3612e8b87bb07f
508ca425a965615f67af8fc4f731fb3a29f4665a
/Codeforces/429/B[ Working out ].cpp
642bac062b3a47e87d4221b8d78bd186885700f4
[]
no_license
knakul853/ProgrammingContests
2a1b216dfc20ef81fb666267d78be355400549e9
3366b6a4447dd4df117217734880199e006db5b4
refs/heads/master
2020-04-14T23:37:02.641774
2015-09-06T09:49:12
2015-09-06T09:49:12
164,209,133
1
0
null
2019-01-05T11:34:11
2019-01-05T11:34:10
null
UTF-8
C++
false
false
1,680
cpp
B[ Working out ].cpp
// Alfonso2 Peterssen (mukel) #include <bits/stdc++.h> using namespace std; const int MAXC = 1 << 10; int R, C; int a[MAXC][MAXC]; int upRight[MAXC][MAXC]; int upLeft[MAXC][MAXC]; int downRight[MAXC][MAXC]; int downLeft[MAXC][MAXC]; int main(int argc, char * argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); cin >> R >> C; for (int i = 1; i <= R; ++i) for (int j = 1; j <= C; ++j) cin >> a[i][j]; for (int i = 1; i <= R; ++i) for (int j = 1; j <= C; ++j) downRight[i][j] = max(downRight[i - 1][j], downRight[i][j - 1]) + a[i][j]; for (int i = R; i >= 1; --i) for (int j = 1; j <= C; ++j) upRight[i][j] = max(upRight[i + 1][j], upRight[i][j - 1]) + a[i][j]; for (int i = 1; i <= R; ++i) for (int j = C; j >= 1; --j) downLeft[i][j] = max(downLeft[i - 1][j], downLeft[i][j + 1]) + a[i][j]; for (int i = R; i >= 1; --i) for (int j = C; j >= 1; --j) upLeft[i][j] = max(upLeft[i + 1][j], upLeft[i][j + 1]) + a[i][j]; int ans = 0; for (int i = 2; i < R; ++i) for (int j = 2; j < C; ++j) { int r0 = i - 1; int c0 = j; int r1 = i + 1; int c1 = j; int r2 = i; int c2 = j - 1; int r3 = i; int c3 = j + 1; int t1 = downRight[r0][c0] + upLeft[r1][c1]; int t2 = upRight[r2][c2] + downLeft[r3][c3]; ans = max(ans, t1 + t2); t1 = downRight[r2][c2] + upLeft[r3][c3]; t2 = upRight[r1][c1] + downLeft[r0][c0]; ans = max(ans, t1 + t2); } cout << ans << endl; return 0; }